Merge branch 'dev' into feat/update-popup

This commit is contained in:
Milo Schwartz
2025-11-14 09:12:11 -08:00
committed by GitHub
71 changed files with 2562 additions and 935 deletions

View File

@@ -19,6 +19,7 @@ export enum ActionsEnum {
getSite = "getSite",
listSites = "listSites",
updateSite = "updateSite",
reGenerateSecret = "reGenerateSecret",
createResource = "createResource",
deleteResource = "deleteResource",
getResource = "getResource",

View File

@@ -30,6 +30,7 @@ import { pickPort } from "@server/routers/target/helpers";
import { resourcePassword } from "@server/db";
import { hashPassword } from "@server/auth/password";
import { isValidCIDR, isValidIP, isValidUrlGlobPattern } from "../validators";
import { get } from "http";
export type ProxyResourcesResults = {
proxyResource: Resource;
@@ -544,7 +545,7 @@ export async function updateProxyResources(
if (
existingRule.action !== getRuleAction(rule.action) ||
existingRule.match !== rule.match.toUpperCase() ||
existingRule.value !== rule.value.toUpperCase()
existingRule.value !== getRuleValue(rule.match.toUpperCase(), rule.value)
) {
validateRule(rule);
await trx
@@ -552,7 +553,7 @@ export async function updateProxyResources(
.set({
action: getRuleAction(rule.action),
match: rule.match.toUpperCase(),
value: rule.value.toUpperCase()
value: getRuleValue(rule.match.toUpperCase(), rule.value),
})
.where(
eq(resourceRules.ruleId, existingRule.ruleId)
@@ -564,7 +565,7 @@ export async function updateProxyResources(
resourceId: existingResource.resourceId,
action: getRuleAction(rule.action),
match: rule.match.toUpperCase(),
value: rule.value.toUpperCase(),
value: getRuleValue(rule.match.toUpperCase(), rule.value),
priority: index + 1 // start priorities at 1
});
}
@@ -722,7 +723,7 @@ export async function updateProxyResources(
resourceId: newResource.resourceId,
action: getRuleAction(rule.action),
match: rule.match.toUpperCase(),
value: rule.value.toUpperCase(),
value: getRuleValue(rule.match.toUpperCase(), rule.value),
priority: index + 1 // start priorities at 1
});
}
@@ -752,6 +753,14 @@ function getRuleAction(input: string) {
return action;
}
function getRuleValue(match: string, value: string) {
// if the match is a country, uppercase the value
if (match == "COUNTRY") {
return value.toUpperCase();
}
return value;
}
function validateRule(rule: any) {
if (rule.match === "cidr") {
if (!isValidCIDR(rule.value)) {

View File

@@ -80,7 +80,8 @@ export async function getTraefikConfig(
subnet: sites.subnet,
exitNodeId: sites.exitNodeId,
// Domain cert resolver fields
domainCertResolver: domains.certResolver
domainCertResolver: domains.certResolver,
preferWildcardCert: domains.preferWildcardCert
})
.from(sites)
.innerJoin(targets, eq(targets.siteId, sites.siteId))
@@ -178,7 +179,8 @@ export async function getTraefikConfig(
rewritePathType: row.rewritePathType,
priority: priority,
// Store domain cert resolver fields
domainCertResolver: row.domainCertResolver
domainCertResolver: row.domainCertResolver,
preferWildcardCert: row.preferWildcardCert
});
}

View File

@@ -1,4 +1,5 @@
import z from "zod";
import ipaddr from "ipaddr.js";
export function isValidCIDR(cidr: string): boolean {
return z.string().cidr().safeParse(cidr).success;
@@ -68,11 +69,11 @@ export function isUrlValid(url: string | undefined) {
if (!url) return true; // the link is optional in the schema so if it's empty it's valid
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
);
return !!pattern.test(url);
@@ -83,12 +84,15 @@ export function isTargetValid(value: string | undefined) {
const DOMAIN_REGEX =
/^[a-zA-Z0-9_](?:[a-zA-Z0-9-_]{0,61}[a-zA-Z0-9_])?(?:\.[a-zA-Z0-9_](?:[a-zA-Z0-9-_]{0,61}[a-zA-Z0-9_])?)*$/;
const IPV4_REGEX =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
// const IPV4_REGEX =
// /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
// const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
if (IPV4_REGEX.test(value) || IPV6_REGEX.test(value)) {
return true;
try {
const addr = ipaddr.parse(value);
return addr.kind() === "ipv4" || addr.kind() === "ipv6";
} catch {
// fall through to domain regex check
}
return DOMAIN_REGEX.test(value);
@@ -169,10 +173,10 @@ export function isSecondLevelDomain(domain: string): boolean {
}
const trimmedDomain = domain.trim().toLowerCase();
// Split into parts
const parts = trimmedDomain.split('.');
// Should have exactly 2 parts for a second-level domain (e.g., "example.com")
if (parts.length !== 2) {
return false;

View File

@@ -111,7 +111,8 @@ export async function getTraefikConfig(
domainNamespaceId: domainNamespaces.domainNamespaceId,
// Certificate
certificateStatus: certificates.status,
domainCertResolver: domains.certResolver
domainCertResolver: domains.certResolver,
preferWildcardCert: domains.preferWildcardCert
})
.from(sites)
.innerJoin(targets, eq(targets.siteId, sites.siteId))
@@ -218,7 +219,8 @@ export async function getTraefikConfig(
rewritePath: row.rewritePath,
rewritePathType: row.rewritePathType,
priority: priority, // may be null, we fallback later
domainCertResolver: row.domainCertResolver
domainCertResolver: row.domainCertResolver,
preferWildcardCert: row.preferWildcardCert
});
}

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

@@ -1 +1,14 @@
/*
* 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 "./sendSupportEmail";

View File

@@ -68,7 +68,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

@@ -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,143 @@
/*
* 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
.object({
clientId: z.string().transform(Number).pipe(z.number().int().positive())
})
.strict();
const reGenerateSecretBodySchema = z
.object({
olmId: z.string().min(1).optional(),
secret: z.string().min(1).optional(),
})
.strict();
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,129 @@
/*
* 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
.object({
remoteExitNodeId: z.string().length(15),
secret: z.string().length(48)
})
.strict();
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,168 @@
/*
* 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
.object({
siteId: z.string().transform(Number).pipe(z.number().int().positive())
})
.strict();
const updateSiteBodySchema = z
.object({
type: z.enum(["newt", "wireguard"]),
newtId: z.string().min(1).max(255).optional(),
newtSecret: z.string().min(1).max(255).optional(),
exitNodeId: z.number().int().positive().optional(),
pubKey: z.string().optional(),
subnet: z.string().optional(),
})
.strict();
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

@@ -60,6 +60,7 @@ type BasicUserData = {
username: string;
email: string | null;
name: string | null;
role: string | null;
};
export type VerifyUserResponse = {
@@ -883,7 +884,8 @@ async function isUserAllowedToAccessResource(
return {
username: user.username,
email: user.email,
name: user.name
name: user.name,
role: user.role
};
}
@@ -896,7 +898,8 @@ async function isUserAllowedToAccessResource(
return {
username: user.username,
email: user.email,
name: user.name
name: user.name,
role: user.role
};
}

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { Client, db, exitNodes, sites } from "@server/db";
import { Client, db, exitNodes, olms, sites } from "@server/db";
import { clients, clientSites } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -18,6 +18,7 @@ import {
deletePeer as olmDeletePeer
} from "../olm/peers";
import { sendToExitNode } from "#dynamic/lib/exitNodes";
import { hashPassword } from "@server/auth/password";
const updateClientParamsSchema = z
.object({
@@ -30,7 +31,7 @@ const updateClientSchema = z
name: z.string().min(1).max(255).optional(),
siteIds: z
.array(z.number().int().positive())
.optional()
.optional(),
})
.strict();
@@ -89,6 +90,7 @@ export async function updateClient(
const { clientId } = parsedParams.data;
// Fetch the client to make sure it exists and the user has access to it
const [client] = await db
.select()

View File

@@ -178,6 +178,7 @@ authenticated.post(
client.updateClient,
);
// authenticated.get(
// "/site/:siteId/roles",
// verifySiteAccess,
@@ -191,6 +192,7 @@ authenticated.post(
logActionAudit(ActionsEnum.updateSite),
site.updateSite,
);
authenticated.delete(
"/site/:siteId",
verifySiteAccess,

View File

@@ -365,9 +365,9 @@ export async function validateOidcCallback(
if (!existingUserOrgs.length) {
// delete the user
await db
.delete(users)
.where(eq(users.userId, existingUser.userId));
// await db
// .delete(users)
// .where(eq(users.userId, existingUser.userId));
return next(
createHttpError(
HttpCode.UNAUTHORIZED,

View File

@@ -6,6 +6,11 @@ export type CreateRemoteExitNodeResponse = {
secret: string;
};
export type UpdateRemoteExitNodeResponse = {
remoteExitNodeId: string;
secret: string;
}
export type PickRemoteExitNodeDefaultsResponse = {
remoteExitNodeId: string;
secret: string;

View File

@@ -37,6 +37,7 @@ const updateResourceParamsSchema = z
const updateHttpResourceBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
subdomain: subdomainSchema.nullable().optional(),
ssl: z.boolean().optional(),
sso: z.boolean().optional(),
@@ -97,6 +98,7 @@ export type UpdateResourceResponse = Resource;
const updateRawResourceBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
proxyPort: z.number().int().min(1).max(65535).optional(),
stickySession: z.boolean().optional(),
enabled: z.boolean().optional(),
@@ -236,6 +238,30 @@ async function updateHttpResource(
const updateData = parsedBody.data;
if (updateData.niceId) {
const [existingResource] = await db
.select()
.from(resources)
.where(
and(
eq(resources.niceId, updateData.niceId),
eq(resources.orgId, resource.orgId)
)
);
if (
existingResource &&
existingResource.resourceId !== resource.resourceId
) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A resource with niceId "${updateData.niceId}" already exists`
)
);
}
}
if (updateData.domainId) {
const domainId = updateData.domainId;
@@ -362,6 +388,30 @@ async function updateRawResource(
const updateData = parsedBody.data;
if (updateData.niceId) {
const [existingResource] = await db
.select()
.from(resources)
.where(
and(
eq(resources.niceId, updateData.niceId),
eq(resources.orgId, resource.orgId)
)
);
if (
existingResource &&
existingResource.resourceId !== resource.resourceId
) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A resource with niceId "${updateData.niceId}" already exists`
)
);
}
}
const updatedResource = await db
.update(resources)
.set(updateData)

View File

@@ -5,4 +5,4 @@ export * from "./updateSite";
export * from "./listSites";
export * from "./listSiteRoles";
export * from "./pickSiteDefaults";
export * from "./socketIntegration";
export * from "./socketIntegration";

View File

@@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { sites } from "@server/db";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
@@ -20,6 +20,7 @@ const updateSiteParamsSchema = z
const updateSiteBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
niceId: z.string().min(1).max(255).optional(),
dockerSocketEnabled: z.boolean().optional(),
remoteSubnets: z
.string()
@@ -89,6 +90,29 @@ export async function updateSite(
const { siteId } = parsedParams.data;
const updateData = parsedBody.data;
// if niceId is provided, check if it's already in use by another site
if (updateData.niceId) {
const existingSite = await db
.select()
.from(sites)
.where(
and(
eq(sites.niceId, updateData.niceId),
eq(sites.orgId, sites.orgId)
)
)
.limit(1);
if (existingSite.length > 0 && existingSite[0].siteId !== siteId) {
return next(
createHttpError(
HttpCode.CONFLICT,
`A site with niceId "${updateData.niceId}" already exists`
)
);
}
}
// if remoteSubnets is provided, ensure it's a valid comma-separated list of cidrs
if (updateData.remoteSubnets) {
const subnets = updateData.remoteSubnets.split(",").map((s) => s.trim());

View File

@@ -163,12 +163,8 @@ export async function createTarget(
);
if (existingTarget) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
`Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${resourceId}`
)
);
// log a warning
logger.warn(`Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${resourceId}`);
}
let newTarget: Target[] = [];

View File

@@ -48,12 +48,10 @@ export async function deleteTarget(
const { targetId } = parsedParams.data;
const [deletedTarget] = await db.transaction(async (tx) => {
return await tx
.delete(targets)
.where(eq(targets.targetId, targetId))
.returning();
});
const [deletedTarget] = await db
.delete(targets)
.where(eq(targets.targetId, targetId))
.returning();
if (!deletedTarget) {
return next(

View File

@@ -170,12 +170,8 @@ export async function updateTarget(
);
if (foundTarget) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
`Target with IP ${targetData.ip}, port ${targetData.port}, and method ${targetData.method} already exists on the same site.`
)
);
// log a warning
logger.warn(`Target with IP ${targetData.ip}, port ${targetData.port}, method ${targetData.method} already exists for resource ID ${target.resourceId}`);
}
const { internalPort, targetIps } = await pickPort(site.siteId!, db);