Merge branch 'dev' into clients-user

This commit is contained in:
Owen
2025-11-17 11:28:47 -05:00
251 changed files with 3872 additions and 1666 deletions

View File

@@ -50,14 +50,14 @@ export const privateConfigSchema = z.object({
host: z.string(),
port: portSchema,
password: z.string().optional(),
db: z.number().int().nonnegative().optional().default(0),
db: z.int().nonnegative().optional().default(0),
replicas: z
.array(
z.object({
host: z.string(),
port: portSchema,
password: z.string().optional(),
db: z.number().int().nonnegative().optional().default(0)
db: z.int().nonnegative().optional().default(0)
})
)
.optional()
@@ -79,14 +79,14 @@ export const privateConfigSchema = z.object({
.default("http://gerbil:3004")
})
.optional()
.default({}),
.prefault({}),
flags: z
.object({
enable_redis: z.boolean().optional().default(false),
use_pangolin_dns: z.boolean().optional().default(false)
})
.optional()
.default({}),
.prefault({}),
branding: z
.object({
app_name: z.string().optional(),

View File

@@ -30,17 +30,17 @@ export const queryAccessAuditLogsQuery = z.object({
timeStart: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
message: "timeStart must be a valid ISO date string"
error: "timeStart must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000)),
timeEnd: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
message: "timeEnd must be a valid ISO date string"
error: "timeEnd must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
.optional()
.default(new Date().toISOString()),
.prefault(new Date().toISOString()),
action: z
.union([z.boolean(), z.string()])
.transform((val) => (typeof val === "string" ? val === "true" : val))
@@ -51,7 +51,7 @@ export const queryAccessAuditLogsQuery = z.object({
.string()
.optional()
.transform(Number)
.pipe(z.number().int().positive())
.pipe(z.int().positive())
.optional(),
actor: z.string().optional(),
type: z.string().optional(),
@@ -61,13 +61,13 @@ export const queryAccessAuditLogsQuery = z.object({
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
.pipe(z.int().nonnegative())
});
export const queryAccessAuditLogsParams = z.object({

View File

@@ -30,17 +30,17 @@ export const queryActionAuditLogsQuery = z.object({
timeStart: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
message: "timeStart must be a valid ISO date string"
error: "timeStart must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000)),
timeEnd: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
message: "timeEnd must be a valid ISO date string"
error: "timeEnd must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
.optional()
.default(new Date().toISOString()),
.prefault(new Date().toISOString()),
action: z.string().optional(),
actorType: z.string().optional(),
actorId: z.string().optional(),
@@ -50,13 +50,13 @@ export const queryActionAuditLogsQuery = z.object({
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
.pipe(z.int().nonnegative())
});
export const queryActionAuditLogsParams = z.object({

View File

@@ -28,7 +28,7 @@ import { response } from "@server/lib/response";
import { encrypt } from "@server/lib/crypto";
import config from "@server/lib/config";
const paramsSchema = z.object({}).strict();
const paramsSchema = z.strictObject({});
export type GetSessionTransferTokenRenponse = {
token: string;

View File

@@ -62,10 +62,10 @@ import { isTargetValid } from "@server/lib/validators";
import { listExitNodes } from "#private/lib/exitNodes";
const bodySchema = z.object({
email: z.string().toLowerCase().email(),
email: z.email().toLowerCase(),
ip: z.string().refine(isTargetValid),
method: z.enum(["http", "https"]),
port: z.number().int().min(1).max(65535),
port: z.int().min(1).max(65535),
pincode: z
.string()
.regex(/^\d{6}$/)

View File

@@ -25,11 +25,9 @@ import stripe from "#private/lib/stripe";
import { getLineItems, getStandardFeaturePriceSet } from "@server/lib/billing";
import { getTierPriceSet, TierId } from "@server/lib/billing/tiers";
const createCheckoutSessionSchema = z
.object({
const createCheckoutSessionSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
export async function createCheckoutSession(
req: Request,

View File

@@ -23,11 +23,9 @@ import config from "@server/lib/config";
import { fromError } from "zod-validation-error";
import stripe from "#private/lib/stripe";
const createPortalSessionSchema = z
.object({
const createPortalSessionSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
export async function createPortalSession(
req: Request,

View File

@@ -33,11 +33,9 @@ import {
SubscriptionItem
} from "@server/db";
const getOrgSchema = z
.object({
const getOrgSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
registry.registerPath({
method: "get",

View File

@@ -27,11 +27,9 @@ import { usageService } from "@server/lib/billing/usageService";
import { FeatureId } from "@server/lib/billing";
import { GetOrgUsageResponse } from "@server/routers/billing/types";
const getOrgSchema = z
.object({
const getOrgSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
registry.registerPath({
method: "get",

View File

@@ -21,11 +21,9 @@ import { fromZodError } from "zod-validation-error";
import { getOrgTierData } from "#private/lib/billing";
import { GetOrgTierResponse } from "@server/routers/billing/types";
const getOrgSchema = z
.object({
const getOrgSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
export async function getOrgTier(
req: Request,

View File

@@ -23,13 +23,11 @@ import { fromError } from "zod-validation-error";
import { registry } from "@server/openApi";
import { GetCertificateResponse } from "@server/routers/certificates/types";
const getCertificateSchema = z
.object({
const getCertificateSchema = z.strictObject({
domainId: z.string(),
domain: z.string().min(1).max(255),
orgId: z.string()
})
.strict();
});
async function query(domainId: string, domain: string) {
const [domainRecord] = await db

View File

@@ -24,12 +24,10 @@ import stoi from "@server/lib/stoi";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
const restartCertificateParamsSchema = z
.object({
certId: z.string().transform(stoi).pipe(z.number().int().positive()),
const restartCertificateParamsSchema = z.strictObject({
certId: z.string().transform(stoi).pipe(z.int().positive()),
orgId: z.string()
})
.strict();
});
registry.registerPath({
method: "post",
@@ -41,7 +39,7 @@ registry.registerPath({
certId: z
.string()
.transform(stoi)
.pipe(z.number().int().positive()),
.pipe(z.int().positive()),
orgId: z.string()
})
},

View File

@@ -23,13 +23,11 @@ import { db, domainNamespaces, resources } from "@server/db";
import { inArray } from "drizzle-orm";
import { CheckDomainAvailabilityResponse } from "@server/routers/domain/types";
const paramsSchema = z.object({}).strict();
const paramsSchema = z.strictObject({});
const querySchema = z
.object({
const querySchema = z.strictObject({
subdomain: z.string()
})
.strict();
});
registry.registerPath({
method: "get",

View File

@@ -23,24 +23,22 @@ import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
const paramsSchema = z.object({}).strict();
const paramsSchema = z.strictObject({});
const querySchema = z
.object({
const querySchema = z.strictObject({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().nonnegative()),
.pipe(z.int().nonnegative()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
})
.strict();
.pipe(z.int().nonnegative())
});
async function query(limit: number, offset: number) {
const res = await db

View File

@@ -23,11 +23,15 @@ import * as license from "#private/routers/license";
import * as generateLicense from "./generatedLicense";
import * as logs from "#private/routers/auditLogs";
import * as misc from "#private/routers/misc";
import * as reKey from "#private/routers/re-key";
import {
verifyOrgAccess,
verifyUserHasAction,
verifyUserIsServerAdmin
verifyUserIsServerAdmin,
verifySiteAccess,
verifyClientAccess,
verifyClientsEnabled,
} from "@server/middlewares";
import { ActionsEnum } from "@server/auth/actions";
import {
@@ -403,3 +407,26 @@ authenticated.get(
logActionAudit(ActionsEnum.exportLogs),
logs.exportAccessAuditLogs
);
authenticated.post(
"/re-key/:clientId/regenerate-client-secret",
verifyClientsEnabled,
verifyClientAccess,
verifyUserHasAction(ActionsEnum.reGenerateSecret),
reKey.reGenerateClientSecret
);
authenticated.post(
"/re-key/:siteId/regenerate-site-secret",
verifySiteAccess,
verifyUserHasAction(ActionsEnum.reGenerateSecret),
reKey.reGenerateSiteSecret
);
authenticated.put(
"/re-key/:orgId/reGenerate-remote-exit-node-secret",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.updateRemoteExitNode),
reKey.reGenerateExitNodeSecret
);

View File

@@ -37,7 +37,7 @@ async function createNewLicense(orgId: string, licenseData: any): Promise<any> {
const data = await response.json();
logger.debug("Fossorial API response:", {data});
logger.debug("Fossorial API response:", { data });
return data;
} catch (error) {
console.error("Error creating new license:", error);

View File

@@ -17,7 +17,10 @@ import createHttpError from "http-errors";
import logger from "@server/logger";
import { response as sendResponse } from "@server/lib/response";
import privateConfig from "#private/lib/config";
import { GeneratedLicenseKey, ListGeneratedLicenseKeysResponse } from "@server/routers/generatedLicense/types";
import {
GeneratedLicenseKey,
ListGeneratedLicenseKeysResponse
} from "@server/routers/generatedLicense/types";
async function fetchLicenseKeys(orgId: string): Promise<any> {
try {

View File

@@ -78,105 +78,78 @@ import { verifyResourceAccessToken } from "@server/auth/verifyResourceAccessToke
import semver from "semver";
// Zod schemas for request validation
const getResourceByDomainParamsSchema = z
.object({
const getResourceByDomainParamsSchema = z.strictObject({
domain: z.string().min(1, "Domain is required")
})
.strict();
});
const getUserSessionParamsSchema = z
.object({
const getUserSessionParamsSchema = z.strictObject({
userSessionId: z.string().min(1, "User session ID is required")
})
.strict();
});
const getUserOrgRoleParamsSchema = z
.object({
const getUserOrgRoleParamsSchema = z.strictObject({
userId: z.string().min(1, "User ID is required"),
orgId: z.string().min(1, "Organization ID is required")
})
.strict();
});
const getRoleResourceAccessParamsSchema = z
.object({
const getRoleResourceAccessParamsSchema = z.strictObject({
roleId: z
.string()
.transform(Number)
.pipe(
z.number().int().positive("Role ID must be a positive integer")
z.int().positive("Role ID must be a positive integer")
),
resourceId: z
.string()
.transform(Number)
.pipe(
z
.number()
.int()
z.int()
.positive("Resource ID must be a positive integer")
)
})
.strict();
});
const getUserResourceAccessParamsSchema = z
.object({
const getUserResourceAccessParamsSchema = z.strictObject({
userId: z.string().min(1, "User ID is required"),
resourceId: z
.string()
.transform(Number)
.pipe(
z
.number()
.int()
z.int()
.positive("Resource ID must be a positive integer")
)
})
.strict();
});
const getResourceRulesParamsSchema = z
.object({
const getResourceRulesParamsSchema = z.strictObject({
resourceId: z
.string()
.transform(Number)
.pipe(
z
.number()
.int()
z.int()
.positive("Resource ID must be a positive integer")
)
})
.strict();
});
const validateResourceSessionTokenParamsSchema = z
.object({
const validateResourceSessionTokenParamsSchema = z.strictObject({
resourceId: z
.string()
.transform(Number)
.pipe(
z
.number()
.int()
z.int()
.positive("Resource ID must be a positive integer")
)
})
.strict();
});
const validateResourceSessionTokenBodySchema = z
.object({
const validateResourceSessionTokenBodySchema = z.strictObject({
token: z.string().min(1, "Token is required")
})
.strict();
});
const validateResourceAccessTokenBodySchema = z
.object({
const validateResourceAccessTokenBodySchema = z.strictObject({
accessTokenId: z.string().optional(),
resourceId: z.number().optional(),
accessToken: z.string()
})
.strict();
});
// Certificates by domains query validation
const getCertificatesByDomainsQuerySchema = z
.object({
const getCertificatesByDomainsQuerySchema = z.strictObject({
// Accept domains as string or array (domains or domains[])
domains: z
.union([z.array(z.string().min(1)), z.string().min(1)])
@@ -185,8 +158,7 @@ const getCertificatesByDomainsQuerySchema = z
"domains[]": z
.union([z.array(z.string().min(1)), z.string().min(1)])
.optional()
})
.strict();
});
// Type exports for request schemas
export type GetResourceByDomainParams = z.infer<
@@ -591,11 +563,9 @@ hybridRouter.get(
}
);
const getOrgLoginPageParamsSchema = z
.object({
const getOrgLoginPageParamsSchema = z.strictObject({
orgId: z.string().min(1)
})
.strict();
});
hybridRouter.get(
"/org/:orgId/login-page",
@@ -1217,7 +1187,7 @@ hybridRouter.post(
);
const geoIpLookupParamsSchema = z.object({
ip: z.string().ip()
ip: z.union([z.ipv4(), z.ipv6()])
});
hybridRouter.get(
"/geoip/:ip",

View File

@@ -20,11 +20,9 @@ import license from "#private/license/license";
import { z } from "zod";
import { fromError } from "zod-validation-error";
const bodySchema = z
.object({
const bodySchema = z.strictObject({
licenseKey: z.string().min(1).max(255)
})
.strict();
});
export async function activateLicense(
req: Request,

View File

@@ -23,11 +23,9 @@ import { eq } from "drizzle-orm";
import { licenseKey } from "@server/db";
import license from "#private/license/license";
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
licenseKey: z.string().min(1).max(255)
})
.strict();
});
export async function deleteLicenseKey(
req: Request,

View File

@@ -35,18 +35,14 @@ import { TierId } from "@server/lib/billing/tiers";
import { build } from "@server/build";
import { CreateLoginPageResponse } from "@server/routers/loginPage/types";
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
const bodySchema = z
.object({
const bodySchema = z.strictObject({
subdomain: z.string().nullable().optional(),
domainId: z.string()
})
.strict();
});
export type CreateLoginPageBody = z.infer<typeof bodySchema>;

View File

@@ -25,7 +25,7 @@ import { DeleteLoginPageResponse } from "@server/routers/loginPage/types";
const paramsSchema = z
.object({
orgId: z.string(),
loginPageId: z.coerce.number()
loginPageId: z.coerce.number<number>()
})
.strict();

View File

@@ -22,11 +22,9 @@ import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { GetLoginPageResponse } from "@server/routers/loginPage/types";
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
async function query(orgId: string) {
const [res] = await db

View File

@@ -23,8 +23,8 @@ import { fromError } from "zod-validation-error";
import { LoadLoginPageResponse } from "@server/routers/loginPage/types";
const querySchema = z.object({
resourceId: z.coerce.number().int().positive().optional(),
idpId: z.coerce.number().int().positive().optional(),
resourceId: z.coerce.number<number>().int().positive().optional(),
idpId: z.coerce.number<number>().int().positive().optional(),
orgId: z.string().min(1).optional(),
fullDomain: z.string().min(1)
});

View File

@@ -31,18 +31,16 @@ import { UpdateLoginPageResponse } from "@server/routers/loginPage/types";
const paramsSchema = z
.object({
orgId: z.string(),
loginPageId: z.coerce.number()
loginPageId: z.coerce.number<number>()
})
.strict();
const bodySchema = z
.object({
const bodySchema = z.strictObject({
subdomain: subdomainSchema.nullable().optional(),
domainId: z.string().optional()
})
.strict()
.refine((data) => Object.keys(data).length > 0, {
message: "At least one field must be provided for update"
error: "At least one field must be provided for update"
})
.refine(
(data) => {
@@ -51,7 +49,9 @@ const bodySchema = z
}
return true;
},
{ message: "Invalid subdomain" }
{
error: "Invalid subdomain"
}
);
export type UpdateLoginPageBody = z.infer<typeof bodySchema>;

View File

@@ -22,12 +22,10 @@ import { sendEmail } from "@server/emails";
import SupportEmail from "@server/emails/templates/SupportEmail";
import config from "@server/lib/config";
const bodySchema = z
.object({
const bodySchema = z.strictObject({
body: z.string().min(1),
subject: z.string().min(1).max(255)
})
.strict();
});
export async function sendSupportEmail(
req: Request,
@@ -68,7 +66,7 @@ export async function sendSupportEmail(
{
name: req.user?.email || "Support User",
to: "support@pangolin.net",
from: req.user?.email || config.getNoReplyEmail(),
from: config.getNoReplyEmail(),
subject: `Support Request: ${subject}`
}
);

View File

@@ -29,15 +29,14 @@ import { getOrgTierData } from "#private/lib/billing";
import { TierId } from "@server/lib/billing/tiers";
import { CreateOrgIdpResponse } from "@server/routers/orgIdp/types";
const paramsSchema = z.object({ orgId: z.string().nonempty() }).strict();
const paramsSchema = z.strictObject({ orgId: z.string().nonempty() });
const bodySchema = z
.object({
const bodySchema = z.strictObject({
name: z.string().nonempty(),
clientId: z.string().nonempty(),
clientSecret: z.string().nonempty(),
authUrl: z.string().url(),
tokenUrl: z.string().url(),
authUrl: z.url(),
tokenUrl: z.url(),
identifierPath: z.string().nonempty(),
emailPath: z.string().optional(),
namePath: z.string().optional(),
@@ -45,8 +44,7 @@ const bodySchema = z
autoProvision: z.boolean().optional(),
variant: z.enum(["oidc", "google", "azure"]).optional().default("oidc"),
roleMapping: z.string().optional()
})
.strict();
});
// registry.registerPath({
// method: "put",

View File

@@ -26,7 +26,7 @@ import { OpenAPITags, registry } from "@server/openApi";
const paramsSchema = z
.object({
orgId: z.string().optional(), // Optional; used with org idp in saas
idpId: z.coerce.number()
idpId: z.coerce.number<number>()
})
.strict();

View File

@@ -30,7 +30,7 @@ import { GetOrgIdpResponse } from "@server/routers/orgIdp/types";
const paramsSchema = z
.object({
orgId: z.string().nonempty(),
idpId: z.coerce.number()
idpId: z.coerce.number<number>()
})
.strict();

View File

@@ -24,28 +24,24 @@ import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { ListOrgIdpsResponse } from "@server/routers/orgIdp/types";
const querySchema = z
.object({
const querySchema = z.strictObject({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().nonnegative()),
.pipe(z.int().nonnegative()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
})
.strict();
.pipe(z.int().nonnegative())
});
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
orgId: z.string().nonempty()
})
.strict();
});
async function query(orgId: string, limit: number, offset: number) {
const res = await db

View File

@@ -31,12 +31,11 @@ import { TierId } from "@server/lib/billing/tiers";
const paramsSchema = z
.object({
orgId: z.string().nonempty(),
idpId: z.coerce.number()
idpId: z.coerce.number<number>()
})
.strict();
const bodySchema = z
.object({
const bodySchema = z.strictObject({
name: z.string().optional(),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
@@ -48,8 +47,7 @@ const bodySchema = z
scopes: z.string().optional(),
autoProvision: z.boolean().optional(),
roleMapping: z.string().optional()
})
.strict();
});
export type UpdateOrgIdpResponse = {
idpId: number;

View File

@@ -0,0 +1,16 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
export * from "./reGenerateClientSecret";
export * from "./reGenerateSiteSecret";
export * from "./reGenerateExitNodeSecret";

View File

@@ -0,0 +1,139 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, olms, } from "@server/db";
import { clients } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { eq, and } from "drizzle-orm";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password";
const reGenerateSecretParamsSchema = z.strictObject({
clientId: z.string().transform(Number).pipe(z.int().positive())
});
const reGenerateSecretBodySchema = z.strictObject({
olmId: z.string().min(1).optional(),
secret: z.string().min(1).optional(),
});
export type ReGenerateSecretBody = z.infer<typeof reGenerateSecretBodySchema>;
registry.registerPath({
method: "post",
path: "/re-key/{clientId}/regenerate-client-secret",
description: "Regenerate a client's OLM credentials by its client ID.",
tags: [OpenAPITags.Client],
request: {
params: reGenerateSecretParamsSchema,
body: {
content: {
"application/json": {
schema: reGenerateSecretBodySchema
}
}
}
},
responses: {}
});
export async function reGenerateClientSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = reGenerateSecretBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { olmId, secret } = parsedBody.data;
const parsedParams = reGenerateSecretParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { clientId } = parsedParams.data;
let secretHash = undefined;
if (secret) {
secretHash = await hashPassword(secret);
}
// Fetch the client to make sure it exists and the user has access to it
const [client] = await db
.select()
.from(clients)
.where(eq(clients.clientId, clientId))
.limit(1);
if (!client) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Client with ID ${clientId} not found`
)
);
}
const [existingOlm] = await db
.select()
.from(olms)
.where(eq(olms.clientId, clientId))
.limit(1);
if (existingOlm && olmId && secretHash) {
await db
.update(olms)
.set({
olmId,
secretHash
})
.where(eq(olms.clientId, clientId));
}
return response(res, {
data: existingOlm,
success: true,
error: false,
message: "Credentials regenerated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -0,0 +1,127 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { NextFunction, Request, Response } from "express";
import { db, exitNodes, exitNodeOrgs, ExitNode, ExitNodeOrg } from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { remoteExitNodes } from "@server/db";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import { fromError } from "zod-validation-error";
import { hashPassword } from "@server/auth/password";
import logger from "@server/logger";
import { and, eq } from "drizzle-orm";
import { UpdateRemoteExitNodeResponse } from "@server/routers/remoteExitNode/types";
import { OpenAPITags, registry } from "@server/openApi";
export const paramsSchema = z.object({
orgId: z.string()
});
const bodySchema = z.strictObject({
remoteExitNodeId: z.string().length(15),
secret: z.string().length(48)
});
registry.registerPath({
method: "post",
path: "/re-key/{orgId}/regenerate-secret",
description: "Regenerate a exit node credentials by its org ID.",
tags: [OpenAPITags.Org],
request: {
params: paramsSchema,
body: {
content: {
"application/json": {
schema: bodySchema
}
}
}
},
responses: {}
});
export async function reGenerateExitNodeSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { remoteExitNodeId, secret } = parsedBody.data;
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);
}
const [existingRemoteExitNode] = await db
.select()
.from(remoteExitNodes)
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId));
if (!existingRemoteExitNode) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Remote Exit Node does not exist")
);
}
const secretHash = await hashPassword(secret);
await db
.update(remoteExitNodes)
.set({ secretHash })
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId));
return response<UpdateRemoteExitNodeResponse>(res, {
data: {
remoteExitNodeId,
secret,
},
success: true,
error: false,
message: "Remote Exit Node secret updated successfully",
status: HttpCode.OK,
});
} catch (e) {
logger.error("Failed to update remoteExitNode", e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to update remoteExitNode"
)
);
}
}

View File

@@ -0,0 +1,164 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, newts, sites } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password";
import { addPeer } from "@server/routers/gerbil/peers";
const updateSiteParamsSchema = z.strictObject({
siteId: z.string().transform(Number).pipe(z.int().positive())
});
const updateSiteBodySchema = z.strictObject({
type: z.enum(["newt", "wireguard"]),
newtId: z.string().min(1).max(255).optional(),
newtSecret: z.string().min(1).max(255).optional(),
exitNodeId: z.int().positive().optional(),
pubKey: z.string().optional(),
subnet: z.string().optional(),
});
registry.registerPath({
method: "post",
path: "/re-key/{siteId}/regenerate-site-secret",
description: "Regenerate a site's Newt or WireGuard credentials by its site ID.",
tags: [OpenAPITags.Site],
request: {
params: updateSiteParamsSchema,
body: {
content: {
"application/json": {
schema: updateSiteBodySchema,
},
},
},
},
responses: {},
});
export async function reGenerateSiteSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = updateSiteParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(HttpCode.BAD_REQUEST, fromError(parsedParams.error).toString())
);
}
const parsedBody = updateSiteBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(HttpCode.BAD_REQUEST, fromError(parsedBody.error).toString())
);
}
const { siteId } = parsedParams.data;
const { type, exitNodeId, pubKey, subnet, newtId, newtSecret } = parsedBody.data;
let updatedSite = undefined;
if (type === "newt") {
if (!newtSecret) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "newtSecret is required for newt sites")
);
}
const secretHash = await hashPassword(newtSecret);
updatedSite = await db
.update(newts)
.set({
newtId,
secretHash,
})
.where(eq(newts.siteId, siteId))
.returning();
logger.info(`Regenerated Newt credentials for site ${siteId}`);
} else if (type === "wireguard") {
if (!pubKey) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Public key is required for wireguard sites")
);
}
if (!exitNodeId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Exit node ID is required for wireguard sites"
)
);
}
try {
updatedSite = await db.transaction(async (tx) => {
await addPeer(exitNodeId, {
publicKey: pubKey,
allowedIps: subnet ? [subnet] : [],
});
const result = await tx
.update(sites)
.set({ pubKey })
.where(eq(sites.siteId, siteId))
.returning();
return result;
});
logger.info(`Regenerated WireGuard credentials for site ${siteId}`);
} catch (err) {
logger.error(
`Transaction failed while regenerating WireGuard secret for site ${siteId}`,
err
);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to regenerate WireGuard credentials. Rolled back transaction."
)
);
}
}
return response(res, {
data: updatedSite,
success: true,
error: false,
message: "Credentials regenerated successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error("Unexpected error in reGenerateSiteSecret", error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An unexpected error occurred")
);
}
}

View File

@@ -35,12 +35,10 @@ export const paramsSchema = z.object({
orgId: z.string()
});
const bodySchema = z
.object({
const bodySchema = z.strictObject({
remoteExitNodeId: z.string().length(15),
secret: z.string().length(48)
})
.strict();
});
export type CreateRemoteExitNodeBody = z.infer<typeof bodySchema>;

View File

@@ -24,12 +24,10 @@ import { fromError } from "zod-validation-error";
import { usageService } from "@server/lib/billing/usageService";
import { FeatureId } from "@server/lib/billing";
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
orgId: z.string().min(1),
remoteExitNodeId: z.string().min(1)
})
.strict();
});
export async function deleteRemoteExitNode(
req: Request,

View File

@@ -23,12 +23,10 @@ import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { GetRemoteExitNodeResponse } from "@server/routers/remoteExitNode/types";
const getRemoteExitNodeSchema = z
.object({
const getRemoteExitNodeSchema = z.strictObject({
orgId: z.string().min(1),
remoteExitNodeId: z.string().min(1)
})
.strict();
});
async function query(remoteExitNodeId: string) {
const [remoteExitNode] = await db

View File

@@ -23,11 +23,9 @@ import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { ListRemoteExitNodesResponse } from "@server/routers/remoteExitNode/types";
const listRemoteExitNodesParamsSchema = z
.object({
const listRemoteExitNodesParamsSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
const listRemoteExitNodesSchema = z.object({
limit: z
@@ -35,13 +33,13 @@ const listRemoteExitNodesSchema = z.object({
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
.pipe(z.int().nonnegative())
});
export function queryRemoteExitNodes(orgId: string) {

View File

@@ -21,11 +21,9 @@ import { fromError } from "zod-validation-error";
import { z } from "zod";
import { PickRemoteExitNodeDefaultsResponse } from "@server/routers/remoteExitNode/types";
const paramsSchema = z
.object({
const paramsSchema = z.strictObject({
orgId: z.string()
})
.strict();
});
export async function pickRemoteExitNodeDefaults(
req: Request,