Merge branch 'dev' into refactor/show-product-updates-conditionnally

This commit is contained in:
Milo Schwartz
2025-12-06 09:38:39 -08:00
committed by GitHub
21 changed files with 24601 additions and 22234 deletions

View File

@@ -36,7 +36,7 @@ jobs:
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
@@ -56,7 +56,7 @@ jobs:
shell: bash shell: bash
- name: Install Go - name: Install Go
uses: actions/setup-go@44694675825211faa026b3c33043df3e48a5fa00 # v6.0.0 uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0
with: with:
go-version: 1.24 go-version: 1.24
@@ -135,6 +135,13 @@ jobs:
docker://$DOCKERHUB_IMAGE:$TAG \ docker://$DOCKERHUB_IMAGE:$TAG \
docker://$GHCR_IMAGE:$TAG docker://$GHCR_IMAGE:$TAG
shell: bash shell: bash
- name: Login to GitHub Container Registry (for cosign)
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Install cosign - name: Install cosign
# cosign is used to sign and verify container images (key and keyless) # cosign is used to sign and verify container images (key and keyless)

View File

@@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
- name: Set up Node.js - name: Set up Node.js
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0

View File

@@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
- uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 - uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
with: with:

View File

@@ -2053,7 +2053,7 @@
"pathRewriteStripLabel": "strip", "pathRewriteStripLabel": "strip",
"sidebarEnableEnterpriseLicense": "Enable Enterprise License", "sidebarEnableEnterpriseLicense": "Enable Enterprise License",
"cannotbeUndone": "This can not be undone.", "cannotbeUndone": "This can not be undone.",
"toConfirm": "to confirm", "toConfirm": "to confirm.",
"deleteClientQuestion": "Are you sure you want to remove the client from the site and organization?", "deleteClientQuestion": "Are you sure you want to remove the client from the site and organization?",
"clientMessageRemove": "Once removed, the client will no longer be able to connect to the site.", "clientMessageRemove": "Once removed, the client will no longer be able to connect to the site.",
"sidebarLogs": "Logs", "sidebarLogs": "Logs",
@@ -2220,8 +2220,8 @@
"regenerate": "Regenerate", "regenerate": "Regenerate",
"credentials": "Credentials", "credentials": "Credentials",
"savecredentials": "Save Credentials", "savecredentials": "Save Credentials",
"regeneratecredentials": "Re-key", "regenerateCredentialsButton": "Regenerate Credentials",
"regenerateCredentials": "Regenerate and save your credentials", "regenerateCredentials": "Regenerate Credentials",
"generatedcredentials": "Generated Credentials", "generatedcredentials": "Generated Credentials",
"copyandsavethesecredentials": "Copy and save these credentials", "copyandsavethesecredentials": "Copy and save these credentials",
"copyandsavethesecredentialsdescription": "These credentials will not be shown again after you leave this page. Save them securely now.", "copyandsavethesecredentialsdescription": "These credentials will not be shown again after you leave this page. Save them securely now.",
@@ -2229,7 +2229,7 @@
"credentialsSavedDescription": "Credentials have been regenerated and saved successfully.", "credentialsSavedDescription": "Credentials have been regenerated and saved successfully.",
"credentialsSaveError": "Credentials Save Error", "credentialsSaveError": "Credentials Save Error",
"credentialsSaveErrorDescription": "An error occurred while regenerating and saving the credentials.", "credentialsSaveErrorDescription": "An error occurred while regenerating and saving the credentials.",
"regenerateCredentialsWarning": "Regenerating credentials will invalidate the previous ones. Make sure to update any configurations that use these credentials.", "regenerateCredentialsWarning": "Regenerating credentials will invalidate the previous ones and cause a disconnection. Make sure to update any configurations that use these credentials.",
"confirm": "Confirm", "confirm": "Confirm",
"regenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials?", "regenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials?",
"endpoint": "Endpoint", "endpoint": "Endpoint",
@@ -2253,5 +2253,20 @@
"clientAddress": "Client Address (Advanced)", "clientAddress": "Client Address (Advanced)",
"setupFailedToFetchSubnet": "Failed to fetch default subnet", "setupFailedToFetchSubnet": "Failed to fetch default subnet",
"setupSubnetAdvanced": "Subnet (Advanced)", "setupSubnetAdvanced": "Subnet (Advanced)",
"setupSubnetDescription": "The subnet for this organization's internal network." "setupSubnetDescription": "The subnet for this organization's internal network.",
"siteRegenerateAndDisconnect": "Regenerate and Disconnect",
"siteRegenerateAndDisconnectConfirmation": "Are you sure you want to regenerate the credentials and disconnect this site?",
"siteRegenerateAndDisconnectWarning": "This will regenerate the credentials and immediately disconnect the site. The site will need to be restarted with the new credentials.",
"siteRegenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials for this site?",
"siteRegenerateCredentialsWarning": "This will regenerate the credentials. The site will stay connected until you manually restart it and use the new credentials.",
"clientRegenerateAndDisconnect": "Regenerate and Disconnect",
"clientRegenerateAndDisconnectConfirmation": "Are you sure you want to regenerate the credentials and disconnect this client?",
"clientRegenerateAndDisconnectWarning": "This will regenerate the credentials and immediately disconnect the client. The client will need to be restarted with the new credentials.",
"clientRegenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials for this client?",
"clientRegenerateCredentialsWarning": "This will regenerate the credentials. The client will stay connected until you manually restart it and use the new credentials.",
"remoteExitNodeRegenerateAndDisconnect": "Regenerate and Disconnect",
"remoteExitNodeRegenerateAndDisconnectConfirmation": "Are you sure you want to regenerate the credentials and disconnect this remote exit node?",
"remoteExitNodeRegenerateAndDisconnectWarning": "This will regenerate the credentials and immediately disconnect the remote exit node. The remote exit node will need to be restarted with the new credentials.",
"remoteExitNodeRegenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials for this remote exit node?",
"remoteExitNodeRegenerateCredentialsWarning": "This will regenerate the credentials. The remote exit node will stay connected until you manually restart it and use the new credentials."
} }

45442
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -33,9 +33,9 @@
}, },
"dependencies": { "dependencies": {
"@asteasolutions/zod-to-openapi": "8.1.0", "@asteasolutions/zod-to-openapi": "8.1.0",
"@aws-sdk/client-s3": "3.922.0",
"@faker-js/faker": "^10.1.0", "@faker-js/faker": "^10.1.0",
"@headlessui/react": "^2.2.9", "@headlessui/react": "^2.2.9",
"@aws-sdk/client-s3": "3.943.0",
"@hookform/resolvers": "5.2.2", "@hookform/resolvers": "5.2.2",
"@monaco-editor/react": "^4.7.0", "@monaco-editor/react": "^4.7.0",
"@node-rs/argon2": "^2.0.2", "@node-rs/argon2": "^2.0.2",
@@ -81,10 +81,10 @@
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"d3": "^7.9.0", "d3": "^7.9.0",
"date-fns": "4.1.0", "date-fns": "4.1.0",
"drizzle-orm": "0.44.7", "drizzle-orm": "0.45.0",
"eslint": "9.39.1", "eslint": "9.39.1",
"eslint-config-next": "16.0.3", "eslint-config-next": "16.0.3",
"express": "5.1.0", "express": "5.2.1",
"express-rate-limit": "8.2.1", "express-rate-limit": "8.2.1",
"glob": "11.1.0", "glob": "11.1.0",
"helmet": "8.1.0", "helmet": "8.1.0",
@@ -95,7 +95,7 @@
"jmespath": "^0.16.0", "jmespath": "^0.16.0",
"js-yaml": "4.1.1", "js-yaml": "4.1.1",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"lucide-react": "^0.552.0", "lucide-react": "^0.556.0",
"maxmind": "5.0.1", "maxmind": "5.0.1",
"moment": "2.30.1", "moment": "2.30.1",
"next": "15.5.7", "next": "15.5.7",
@@ -104,7 +104,7 @@
"nextjs-toploader": "^3.9.17", "nextjs-toploader": "^3.9.17",
"node-cache": "5.1.2", "node-cache": "5.1.2",
"node-fetch": "3.3.2", "node-fetch": "3.3.2",
"nodemailer": "7.0.10", "nodemailer": "7.0.11",
"npm": "^11.6.4", "npm": "^11.6.4",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"oslo": "1.2.1", "oslo": "1.2.1",
@@ -115,7 +115,7 @@
"react-day-picker": "9.11.1", "react-day-picker": "9.11.1",
"react-dom": "19.2.1", "react-dom": "19.2.1",
"react-easy-sort": "^1.8.0", "react-easy-sort": "^1.8.0",
"react-hook-form": "7.66.0", "react-hook-form": "7.68.0",
"react-icons": "^5.5.0", "react-icons": "^5.5.0",
"rebuild": "0.1.2", "rebuild": "0.1.2",
"recharts": "^2.15.4", "recharts": "^2.15.4",
@@ -124,8 +124,8 @@
"semver": "^7.7.3", "semver": "^7.7.3",
"stripe": "18.2.1", "stripe": "18.2.1",
"swagger-ui-express": "^5.0.1", "swagger-ui-express": "^5.0.1",
"tailwind-merge": "3.3.1",
"topojson-client": "^3.1.0", "topojson-client": "^3.1.0",
"tailwind-merge": "3.4.0",
"tw-animate-css": "^1.3.8", "tw-animate-css": "^1.3.8",
"uuid": "^13.0.0", "uuid": "^13.0.0",
"vaul": "1.1.2", "vaul": "1.1.2",
@@ -149,14 +149,14 @@
"@types/cors": "2.8.19", "@types/cors": "2.8.19",
"@types/crypto-js": "^4.2.2", "@types/crypto-js": "^4.2.2",
"@types/d3": "^7.4.3", "@types/d3": "^7.4.3",
"@types/express": "5.0.5", "@types/express": "5.0.6",
"@types/express-session": "^1.18.2", "@types/express-session": "^1.18.2",
"@types/jmespath": "^0.15.2", "@types/jmespath": "^0.15.2",
"@types/js-yaml": "4.0.9", "@types/js-yaml": "4.0.9",
"@types/jsonwebtoken": "^9.0.10", "@types/jsonwebtoken": "^9.0.10",
"@types/node": "24.10.1", "@types/node": "24.10.1",
"@types/nodemailer": "7.0.3",
"@types/nprogress": "^0.2.3", "@types/nprogress": "^0.2.3",
"@types/nodemailer": "7.0.4",
"@types/pg": "8.15.6", "@types/pg": "8.15.6",
"@types/react": "19.2.2", "@types/react": "19.2.2",
"@types/react-dom": "19.2.2", "@types/react-dom": "19.2.2",
@@ -164,16 +164,16 @@
"@types/swagger-ui-express": "^4.1.8", "@types/swagger-ui-express": "^4.1.8",
"@types/topojson-client": "^3.1.5", "@types/topojson-client": "^3.1.5",
"@types/ws": "8.18.1", "@types/ws": "8.18.1",
"@types/yargs": "17.0.34",
"babel-plugin-react-compiler": "^1.0.0", "babel-plugin-react-compiler": "^1.0.0",
"drizzle-kit": "0.31.6", "@types/yargs": "17.0.35",
"esbuild": "0.27.0", "drizzle-kit": "0.31.8",
"esbuild-node-externals": "1.19.1", "esbuild": "0.27.1",
"esbuild-node-externals": "1.20.1",
"postcss": "^8", "postcss": "^8",
"react-email": "4.3.2", "react-email": "4.3.2",
"tailwindcss": "^4.1.4", "tailwindcss": "^4.1.4",
"tsc-alias": "1.8.16", "tsc-alias": "1.8.16",
"tsx": "4.20.6", "tsx": "4.21.0",
"typescript": "^5", "typescript": "^5",
"typescript-eslint": "^8.46.3" "typescript-eslint": "^8.46.3"
}, },
@@ -183,4 +183,4 @@
"react-dom": "19.0.0" "react-dom": "19.0.0"
} }
} }
} }

View File

@@ -1,6 +1,7 @@
import { join } from "path"; import { join } from "path";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import { db, resources, siteResources } from "@server/db"; import { db, resources, siteResources } from "@server/db";
import { randomInt } from "crypto";
import { exitNodes, sites } from "@server/db"; import { exitNodes, sites } from "@server/db";
import { eq, and } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
import { __DIRNAME } from "@server/lib/consts"; import { __DIRNAME } from "@server/lib/consts";
@@ -111,10 +112,10 @@ export async function getUniqueExitNodeEndpointName(): Promise<string> {
export function generateName(): string { export function generateName(): string {
const name = ( const name = (
names.descriptors[ names.descriptors[
Math.floor(Math.random() * names.descriptors.length) randomInt(names.descriptors.length)
] + ] +
"-" + "-" +
names.animals[Math.floor(Math.random() * names.animals.length)] names.animals[randomInt(names.animals.length)]
) )
.toLowerCase() .toLowerCase()
.replace(/\s/g, "-"); .replace(/\s/g, "-");

View File

@@ -13,7 +13,7 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { z } from "zod"; import { z } from "zod";
import { db, olms } from "@server/db"; import { db, Olm, olms } from "@server/db";
import { clients } from "@server/db"; import { clients } from "@server/db";
import response from "@server/lib/response"; import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode"; import HttpCode from "@server/types/HttpCode";
@@ -23,7 +23,7 @@ import { eq, and } from "drizzle-orm";
import { fromError } from "zod-validation-error"; import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi"; import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password"; import { hashPassword } from "@server/auth/password";
import { disconnectClient, sendToClient } from "#dynamic/routers/ws"; import { disconnectClient, sendToClient } from "#private/routers/ws";
const reGenerateSecretParamsSchema = z.strictObject({ const reGenerateSecretParamsSchema = z.strictObject({
clientId: z.string().transform(Number).pipe(z.int().positive()) clientId: z.string().transform(Number).pipe(z.int().positive())
@@ -31,29 +31,12 @@ const reGenerateSecretParamsSchema = z.strictObject({
const reGenerateSecretBodySchema = z.strictObject({ const reGenerateSecretBodySchema = z.strictObject({
// olmId: z.string().min(1).optional(), // olmId: z.string().min(1).optional(),
secret: z.string().min(1) secret: z.string().min(1),
disconnect: z.boolean().optional().default(true)
}); });
export type ReGenerateSecretBody = z.infer<typeof reGenerateSecretBodySchema>; 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( export async function reGenerateClientSecret(
req: Request, req: Request,
res: Response, res: Response,
@@ -70,7 +53,7 @@ export async function reGenerateClientSecret(
); );
} }
const { secret } = parsedBody.data; const { secret, disconnect } = parsedBody.data;
const parsedParams = reGenerateSecretParamsSchema.safeParse(req.params); const parsedParams = reGenerateSecretParamsSchema.safeParse(req.params);
if (!parsedParams.success) { if (!parsedParams.success) {
@@ -132,21 +115,26 @@ export async function reGenerateClientSecret(
}) })
.where(eq(olms.olmId, existingOlms[0].olmId)); .where(eq(olms.olmId, existingOlms[0].olmId));
const payload = { // Only disconnect if explicitly requested
type: `olm/terminate`, if (disconnect) {
data: {} const payload = {
}; type: `olm/terminate`,
// Don't await this to prevent blocking the response data: {}
sendToClient(existingOlms[0].olmId, payload).catch((error) => { };
logger.error("Failed to send termination message to olm:", error); // Don't await this to prevent blocking the response
}); sendToClient(existingOlms[0].olmId, payload).catch((error) => {
logger.error("Failed to send termination message to olm:", error);
});
disconnectClient(existingOlms[0].olmId).catch((error) => { disconnectClient(existingOlms[0].olmId).catch((error) => {
logger.error("Failed to disconnect olm after re-key:", error); logger.error("Failed to disconnect olm after re-key:", error);
}); });
}
return response(res, { return response(res, {
data: existingOlms, data: {
olmId: existingOlms[0].olmId,
},
success: true, success: true,
error: false, error: false,
message: "Credentials regenerated successfully", message: "Credentials regenerated successfully",

View File

@@ -12,7 +12,7 @@
*/ */
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import { db, exitNodes, exitNodeOrgs, ExitNode, ExitNodeOrg } from "@server/db"; import { db, exitNodes, exitNodeOrgs, ExitNode, ExitNodeOrg, RemoteExitNode } from "@server/db";
import HttpCode from "@server/types/HttpCode"; import HttpCode from "@server/types/HttpCode";
import { z } from "zod"; import { z } from "zod";
import { remoteExitNodes } from "@server/db"; import { remoteExitNodes } from "@server/db";
@@ -22,9 +22,8 @@ import { fromError } from "zod-validation-error";
import { hashPassword } from "@server/auth/password"; import { hashPassword } from "@server/auth/password";
import logger from "@server/logger"; import logger from "@server/logger";
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import { UpdateRemoteExitNodeResponse } from "@server/routers/remoteExitNode/types";
import { OpenAPITags, registry } from "@server/openApi"; import { OpenAPITags, registry } from "@server/openApi";
import { disconnectClient } from "@server/routers/ws"; import { disconnectClient, sendToClient } from "#private/routers/ws";
export const paramsSchema = z.object({ export const paramsSchema = z.object({
orgId: z.string() orgId: z.string()
@@ -32,25 +31,8 @@ export const paramsSchema = z.object({
const bodySchema = z.strictObject({ const bodySchema = z.strictObject({
remoteExitNodeId: z.string().length(15), remoteExitNodeId: z.string().length(15),
secret: z.string().length(48) secret: z.string().length(48),
}); disconnect: z.boolean().optional().default(true)
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( export async function reGenerateExitNodeSecret(
@@ -79,7 +61,7 @@ export async function reGenerateExitNodeSecret(
); );
} }
const { remoteExitNodeId, secret } = parsedBody.data; const { remoteExitNodeId, secret, disconnect } = parsedBody.data;
const [existingRemoteExitNode] = await db const [existingRemoteExitNode] = await db
.select() .select()
@@ -102,17 +84,34 @@ export async function reGenerateExitNodeSecret(
.set({ secretHash }) .set({ secretHash })
.where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId)); .where(eq(remoteExitNodes.remoteExitNodeId, remoteExitNodeId));
disconnectClient(existingRemoteExitNode.remoteExitNodeId).catch( // Only disconnect if explicitly requested
(error) => { if (disconnect) {
logger.error("Failed to disconnect newt after re-key:", error); const payload = {
} type: `remoteExitNode/terminate`,
); data: {}
};
// Don't await this to prevent blocking the response
sendToClient(existingRemoteExitNode.remoteExitNodeId, payload).catch(
(error) => {
logger.error(
"Failed to send termination message to remote exit node:",
error
);
}
);
return response<UpdateRemoteExitNodeResponse>(res, { disconnectClient(existingRemoteExitNode.remoteExitNodeId).catch(
data: { (error) => {
remoteExitNodeId, logger.error(
secret "Failed to disconnect remote exit node after re-key:",
}, error
);
}
);
}
return response(res, {
data: null,
success: true, success: true,
error: false, error: false,
message: "Remote Exit Node secret updated successfully", message: "Remote Exit Node secret updated successfully",

View File

@@ -24,7 +24,7 @@ import { OpenAPITags, registry } from "@server/openApi";
import { hashPassword } from "@server/auth/password"; import { hashPassword } from "@server/auth/password";
import { addPeer, deletePeer } from "@server/routers/gerbil/peers"; import { addPeer, deletePeer } from "@server/routers/gerbil/peers";
import { getAllowedIps } from "@server/routers/target/helpers"; import { getAllowedIps } from "@server/routers/target/helpers";
import { disconnectClient, sendToClient } from "#dynamic/routers/ws"; import { disconnectClient, sendToClient } from "#private/routers/ws";
const updateSiteParamsSchema = z.strictObject({ const updateSiteParamsSchema = z.strictObject({
siteId: z.string().transform(Number).pipe(z.int().positive()) siteId: z.string().transform(Number).pipe(z.int().positive())
@@ -33,26 +33,8 @@ const updateSiteParamsSchema = z.strictObject({
const updateSiteBodySchema = z.strictObject({ const updateSiteBodySchema = z.strictObject({
type: z.enum(["newt", "wireguard"]), type: z.enum(["newt", "wireguard"]),
secret: z.string().min(1).max(255).optional(), secret: z.string().min(1).max(255).optional(),
pubKey: z.string().optional() pubKey: z.string().optional(),
}); disconnect: z.boolean().optional().default(true)
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( export async function reGenerateSiteSecret(
@@ -82,7 +64,7 @@ export async function reGenerateSiteSecret(
} }
const { siteId } = parsedParams.data; const { siteId } = parsedParams.data;
const { type, pubKey, secret } = parsedBody.data; const { type, pubKey, secret, disconnect } = parsedBody.data;
let existingNewt: Newt | null = null; let existingNewt: Newt | null = null;
if (type === "newt") { if (type === "newt") {
@@ -131,21 +113,24 @@ export async function reGenerateSiteSecret(
}) })
.where(eq(newts.newtId, existingNewts[0].newtId)); .where(eq(newts.newtId, existingNewts[0].newtId));
const payload = { // Only disconnect if explicitly requested
type: `newt/wg/terminate`, if (disconnect) {
data: {} const payload = {
}; type: `newt/wg/terminate`,
// Don't await this to prevent blocking the response data: {}
sendToClient(existingNewts[0].newtId, payload).catch((error) => { };
logger.error( // Don't await this to prevent blocking the response
"Failed to send termination message to newt:", sendToClient(existingNewts[0].newtId, payload).catch((error) => {
error logger.error(
); "Failed to send termination message to newt:",
}); error
);
});
disconnectClient(existingNewts[0].newtId).catch((error) => { disconnectClient(existingNewts[0].newtId).catch((error) => {
logger.error("Failed to disconnect newt after re-key:", error); logger.error("Failed to disconnect newt after re-key:", error);
}); });
}
logger.info(`Regenerated Newt credentials for site ${siteId}`); logger.info(`Regenerated Newt credentials for site ${siteId}`);
} else if (type === "wireguard") { } else if (type === "wireguard") {
@@ -214,7 +199,9 @@ export async function reGenerateSiteSecret(
} }
return response(res, { return response(res, {
data: existingNewt, data: {
newtId: existingNewt ? existingNewt.newtId : undefined
},
success: true, success: true,
error: false, error: false,
message: "Credentials regenerated successfully", message: "Credentials regenerated successfully",

View File

@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { z } from "zod"; import { z } from "zod";
import { db } from "@server/db"; import { db, olms } from "@server/db";
import { clients, clientSitesAssociationsCache } from "@server/db"; import { clients } from "@server/db";
import { eq, and } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
import response from "@server/lib/response"; import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode"; import HttpCode from "@server/types/HttpCode";
@@ -12,8 +12,8 @@ import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi"; import { OpenAPITags, registry } from "@server/openApi";
const getClientSchema = z.strictObject({ const getClientSchema = z.strictObject({
clientId: z.string().transform(stoi).pipe(z.int().positive()) clientId: z.string().transform(stoi).pipe(z.int().positive())
}); });
async function query(clientId: number) { async function query(clientId: number) {
// Get the client // Get the client
@@ -21,26 +21,20 @@ async function query(clientId: number) {
.select() .select()
.from(clients) .from(clients)
.where(and(eq(clients.clientId, clientId))) .where(and(eq(clients.clientId, clientId)))
.leftJoin(olms, eq(clients.olmId, olms.olmId))
.limit(1); .limit(1);
if (!client) { if (!client) {
return null; return null;
} }
return client;
// Get the siteIds associated with this client
const sites = await db
.select({ siteId: clientSitesAssociationsCache.siteId })
.from(clientSitesAssociationsCache)
.where(eq(clientSitesAssociationsCache.clientId, clientId));
// Add the siteIds to the client object
return {
...client,
siteIds: sites.map((site) => site.siteId)
};
} }
export type GetClientResponse = NonNullable<Awaited<ReturnType<typeof query>>>; export type GetClientResponse = NonNullable<
Awaited<ReturnType<typeof query>>
>["clients"] & {
olmId: string | null;
};
registry.registerPath({ registry.registerPath({
method: "get", method: "get",
@@ -82,8 +76,13 @@ export async function getClient(
); );
} }
const data: GetClientResponse = {
...client.clients,
olmId: client.olms ? client.olms.olmId : null
};
return response<GetClientResponse>(res, { return response<GetClientResponse>(res, {
data: client, data,
success: true, success: true,
error: false, error: false,
message: "Client retrieved successfully", message: "Client retrieved successfully",

View File

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

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { z } from "zod"; import { z } from "zod";
import { db } from "@server/db"; import { db, newts } from "@server/db";
import { sites } from "@server/db"; import { sites } from "@server/db";
import { eq, and } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
import response from "@server/lib/response"; import response from "@server/lib/response";
@@ -12,15 +12,15 @@ import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi"; import { OpenAPITags, registry } from "@server/openApi";
const getSiteSchema = z.strictObject({ const getSiteSchema = z.strictObject({
siteId: z siteId: z
.string() .string()
.optional() .optional()
.transform(stoi) .transform(stoi)
.pipe(z.int().positive().optional()) .pipe(z.int().positive().optional())
.optional(), .optional(),
niceId: z.string().optional(), niceId: z.string().optional(),
orgId: z.string().optional() orgId: z.string().optional()
}); });
async function query(siteId?: number, niceId?: string, orgId?: string) { async function query(siteId?: number, niceId?: string, orgId?: string) {
if (siteId) { if (siteId) {
@@ -28,6 +28,7 @@ async function query(siteId?: number, niceId?: string, orgId?: string) {
.select() .select()
.from(sites) .from(sites)
.where(eq(sites.siteId, siteId)) .where(eq(sites.siteId, siteId))
.leftJoin(newts, eq(sites.siteId, newts.siteId))
.limit(1); .limit(1);
return res; return res;
} else if (niceId && orgId) { } else if (niceId && orgId) {
@@ -35,12 +36,15 @@ async function query(siteId?: number, niceId?: string, orgId?: string) {
.select() .select()
.from(sites) .from(sites)
.where(and(eq(sites.niceId, niceId), eq(sites.orgId, orgId))) .where(and(eq(sites.niceId, niceId), eq(sites.orgId, orgId)))
.leftJoin(newts, eq(sites.siteId, newts.siteId))
.limit(1); .limit(1);
return res; return res;
} }
} }
export type GetSiteResponse = NonNullable<Awaited<ReturnType<typeof query>>>; export type GetSiteResponse = NonNullable<
Awaited<ReturnType<typeof query>>
>["sites"] & { newtId: string | null };
registry.registerPath({ registry.registerPath({
method: "get", method: "get",
@@ -94,8 +98,13 @@ export async function getSite(
return next(createHttpError(HttpCode.NOT_FOUND, "Site not found")); return next(createHttpError(HttpCode.NOT_FOUND, "Site not found"));
} }
const data: GetSiteResponse = {
...site.sites,
newtId: site.newt ? site.newt.newtId : null
};
return response<GetSiteResponse>(res, { return response<GetSiteResponse>(res, {
data: site, data,
success: true, success: true,
error: false, error: false,
message: "Site retrieved successfully", message: "Site retrieved successfully",

View File

@@ -203,6 +203,12 @@ export async function updateTarget(
hcHeaders = JSON.stringify(parsedBody.data.hcHeaders); hcHeaders = JSON.stringify(parsedBody.data.hcHeaders);
} }
// When health check is disabled, reset hcHealth to "unknown"
// to prevent previously unhealthy targets from being excluded
const hcHealthValue = (parsedBody.data.hcEnabled === false || parsedBody.data.hcEnabled === null)
? "unknown"
: undefined;
const [updatedHc] = await db const [updatedHc] = await db
.update(targetHealthCheck) .update(targetHealthCheck)
.set({ .set({
@@ -220,6 +226,7 @@ export async function updateTarget(
hcMethod: parsedBody.data.hcMethod, hcMethod: parsedBody.data.hcMethod,
hcStatus: parsedBody.data.hcStatus, hcStatus: parsedBody.data.hcStatus,
hcTlsServerName: parsedBody.data.hcTlsServerName, hcTlsServerName: parsedBody.data.hcTlsServerName,
...(hcHealthValue !== undefined && { hcHealth: hcHealthValue })
}) })
.where(eq(targetHealthCheck.targetId, targetId)) .where(eq(targetHealthCheck.targetId, targetId))
.returning(); .returning();

View File

@@ -6,6 +6,7 @@ import {
SettingsSection, SettingsSection,
SettingsSectionBody, SettingsSectionBody,
SettingsSectionDescription, SettingsSectionDescription,
SettingsSectionFooter,
SettingsSectionHeader, SettingsSectionHeader,
SettingsSectionTitle SettingsSectionTitle
} from "@app/components/Settings"; } from "@app/components/Settings";
@@ -21,17 +22,20 @@ import {
QuickStartRemoteExitNodeResponse QuickStartRemoteExitNodeResponse
} from "@server/routers/remoteExitNode/types"; } from "@server/routers/remoteExitNode/types";
import { useRemoteExitNodeContext } from "@app/hooks/useRemoteExitNodeContext"; import { useRemoteExitNodeContext } from "@app/hooks/useRemoteExitNodeContext";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext"; import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext"; import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { build } from "@server/build"; import { build } from "@server/build";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@app/components/ui/tooltip";
import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert"; import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert";
import {
InfoSection,
InfoSectionContent,
InfoSections,
InfoSectionTitle
} from "@app/components/InfoSection";
import CopyToClipboard from "@app/components/CopyToClipboard";
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
import { InfoIcon } from "lucide-react";
export default function CredentialsPage() { export default function CredentialsPage() {
const { env } = useEnvContext(); const { env } = useEnvContext();
@@ -44,6 +48,14 @@ export default function CredentialsPage() {
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [credentials, setCredentials] = const [credentials, setCredentials] =
useState<PickRemoteExitNodeDefaultsResponse | null>(null); useState<PickRemoteExitNodeDefaultsResponse | null>(null);
const [currentRemoteExitNodeId, setCurrentRemoteExitNodeId] = useState<
string | null
>(remoteExitNode.remoteExitNodeId);
const [regeneratedSecret, setRegeneratedSecret] = useState<string | null>(
null
);
const [showCredentialsAlert, setShowCredentialsAlert] = useState(false);
const [shouldDisconnect, setShouldDisconnect] = useState(true);
const { licenseStatus, isUnlocked } = useLicenseStatusContext(); const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext(); const subscription = useSubscriptionStatusContext();
@@ -56,39 +68,63 @@ export default function CredentialsPage() {
}; };
const handleConfirmRegenerate = async () => { const handleConfirmRegenerate = async () => {
const response = await api.get< try {
AxiosResponse<PickRemoteExitNodeDefaultsResponse> const response = await api.get<
>(`/org/${orgId}/pick-remote-exit-node-defaults`); AxiosResponse<PickRemoteExitNodeDefaultsResponse>
>(`/org/${orgId}/pick-remote-exit-node-defaults`);
const data = response.data.data; const data = response.data.data;
setCredentials(data); setCredentials(data);
await api.put<AxiosResponse<QuickStartRemoteExitNodeResponse>>( const rekeyRes = await api.put<
`/re-key/${orgId}/regenerate-remote-exit-node-secret`, AxiosResponse<QuickStartRemoteExitNodeResponse>
{ >(`/re-key/${orgId}/regenerate-remote-exit-node-secret`, {
remoteExitNodeId: remoteExitNode.remoteExitNodeId, remoteExitNodeId: remoteExitNode.remoteExitNodeId,
secret: data.secret secret: data.secret,
disconnect: shouldDisconnect
});
if (rekeyRes && rekeyRes.status === 200) {
const rekeyData = rekeyRes.data.data;
if (rekeyData && rekeyData.remoteExitNodeId) {
setCurrentRemoteExitNodeId(rekeyData.remoteExitNodeId);
setRegeneratedSecret(data.secret);
setCredentials({
...data,
remoteExitNodeId: rekeyData.remoteExitNodeId
});
setShowCredentialsAlert(true);
}
} }
);
toast({ toast({
title: t("credentialsSaved"), title: t("credentialsSaved"),
description: t("credentialsSavedDescription") description: t("credentialsSavedDescription")
}); });
} catch (error) {
router.refresh(); toast({
}; variant: "destructive",
title: t("error") || "Error",
const getCredentials = () => { description:
if (credentials) { formatAxiosError(error) ||
return { t("credentialsRegenerateError") ||
Id: remoteExitNode.remoteExitNodeId, "Failed to regenerate credentials"
Secret: credentials.secret });
};
} }
return undefined;
}; };
const getConfirmationString = () => {
return (
remoteExitNode?.name ||
remoteExitNode?.remoteExitNodeId ||
"My remote exit node"
);
};
const displayRemoteExitNodeId =
currentRemoteExitNodeId || remoteExitNode?.remoteExitNodeId || null;
const displaySecret = regeneratedSecret || null;
return ( return (
<> <>
<SettingsContainer> <SettingsContainer>
@@ -101,26 +137,132 @@ export default function CredentialsPage() {
{t("regenerateCredentials")} {t("regenerateCredentials")}
</SettingsSectionDescription> </SettingsSectionDescription>
</SettingsSectionHeader> </SettingsSectionHeader>
<SettingsSectionBody> <SettingsSectionBody>
<SecurityFeaturesAlert /> <InfoSections cols={3}>
<Button <InfoSection>
onClick={() => setModalOpen(true)} <InfoSectionTitle>
disabled={isSecurityFeatureDisabled()} {t("endpoint") || "Endpoint"}
> </InfoSectionTitle>
{t("regeneratecredentials")} <InfoSectionContent>
</Button> <CopyToClipboard
text={env.app.dashboardUrl}
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("remoteExitNodeId") ||
"Remote Exit Node ID"}
</InfoSectionTitle>
<InfoSectionContent>
{displayRemoteExitNodeId ? (
<CopyToClipboard
text={displayRemoteExitNodeId}
/>
) : (
<span>{"••••••••••••••••"}</span>
)}
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("secretKey") || "Secret Key"}
</InfoSectionTitle>
<InfoSectionContent>
{displaySecret ? (
<CopyToClipboard text={displaySecret} />
) : (
<span>
{"••••••••••••••••••••••••••••••••"}
</span>
)}
</InfoSectionContent>
</InfoSection>
</InfoSections>
{showCredentialsAlert && displaySecret && (
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("credentialsSave") ||
"Save the Credentials"}
</AlertTitle>
<AlertDescription>
{t("credentialsSaveDescription") ||
"You will only be able to see this once. Make sure to copy it to a secure place."}
</AlertDescription>
</Alert>
)}
</SettingsSectionBody> </SettingsSectionBody>
<SettingsSectionFooter>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
setShouldDisconnect(false);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("regenerateCredentialsButton")}
</Button>
<Button
onClick={() => {
setShouldDisconnect(true);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("remoteExitNodeRegenerateAndDisconnect")}
</Button>
</div>
</SettingsSectionFooter>
</SettingsSection> </SettingsSection>
</SettingsContainer> </SettingsContainer>
<RegenerateCredentialsModal <ConfirmDeleteDialog
open={modalOpen} open={modalOpen}
onOpenChange={setModalOpen} setOpen={(val) => {
type="remote-exit-node" setModalOpen(val);
onConfirmRegenerate={handleConfirmRegenerate} // Prevent modal from reopening during refresh
dashboardUrl={env.app.dashboardUrl} if (!val) {
credentials={getCredentials()} setTimeout(() => {
router.refresh();
}, 150);
}
}}
dialog={
<div className="space-y-2">
{shouldDisconnect ? (
<>
<p>
{t("remoteExitNodeRegenerateAndDisconnectConfirmation")}
</p>
<p>
{t("remoteExitNodeRegenerateAndDisconnectWarning")}
</p>
</>
) : (
<>
<p>
{t("remoteExitNodeRegenerateCredentialsConfirmation")}
</p>
<p>
{t("remoteExitNodeRegenerateCredentialsWarning")}
</p>
</>
)}
</div>
}
buttonText={
shouldDisconnect
? t("remoteExitNodeRegenerateAndDisconnect")
: t("regenerateCredentialsButton")
}
onConfirm={handleConfirmRegenerate}
string={getConfirmationString()}
title={t("regenerateCredentials")}
warningText={t("cannotbeUndone")}
/> />
</> </>
); );

View File

@@ -1,33 +1,37 @@
"use client"; "use client";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal"; import { useState } from "react";
import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert";
import { import {
SettingsContainer, SettingsContainer,
SettingsSection, SettingsSection,
SettingsSectionBody, SettingsSectionBody,
SettingsSectionDescription, SettingsSectionDescription,
SettingsSectionFooter,
SettingsSectionHeader, SettingsSectionHeader,
SettingsSectionTitle SettingsSectionTitle
} from "@app/components/Settings"; } from "@app/components/Settings";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { import { createApiClient, formatAxiosError } from "@app/lib/api";
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@app/components/ui/tooltip";
import { useClientContext } from "@app/hooks/useClientContext";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import { useParams, useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { PickClientDefaultsResponse } from "@server/routers/client";
import { useClientContext } from "@app/hooks/useClientContext";
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext"; import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext"; import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { toast } from "@app/hooks/useToast";
import { createApiClient } from "@app/lib/api";
import { build } from "@server/build"; import { build } from "@server/build";
import { PickClientDefaultsResponse } from "@server/routers/client"; import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert";
import { useTranslations } from "next-intl"; import {
import { useParams, useRouter } from "next/navigation"; InfoSection,
import { useState } from "react"; InfoSectionContent,
InfoSections,
InfoSectionTitle
} from "@app/components/InfoSection";
import CopyToClipboard from "@app/components/CopyToClipboard";
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
import { InfoIcon } from "lucide-react";
export default function CredentialsPage() { export default function CredentialsPage() {
const { env } = useEnvContext(); const { env } = useEnvContext();
@@ -40,6 +44,12 @@ export default function CredentialsPage() {
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [clientDefaults, setClientDefaults] = const [clientDefaults, setClientDefaults] =
useState<PickClientDefaultsResponse | null>(null); useState<PickClientDefaultsResponse | null>(null);
const [currentOlmId, setCurrentOlmId] = useState<string | null>(client.olmId);
const [regeneratedSecret, setRegeneratedSecret] = useState<string | null>(
null
);
const [showCredentialsAlert, setShowCredentialsAlert] = useState(false);
const [shouldDisconnect, setShouldDisconnect] = useState(true);
const { licenseStatus, isUnlocked } = useLicenseStatusContext(); const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext(); const subscription = useSubscriptionStatusContext();
@@ -52,69 +62,187 @@ export default function CredentialsPage() {
}; };
const handleConfirmRegenerate = async () => { const handleConfirmRegenerate = async () => {
const res = await api.get(`/org/${orgId}/pick-client-defaults`); try {
if (res && res.status === 200) { const res = await api.get(`/org/${orgId}/pick-client-defaults`);
const data = res.data.data; if (res && res.status === 200) {
setClientDefaults(data); const data = res.data.data;
await api.post( const rekeyRes = await api.post(
`/re-key/${client?.clientId}/regenerate-client-secret`, `/re-key/${client?.clientId}/regenerate-client-secret`,
{ {
secret: data.olmSecret secret: data.olmSecret,
disconnect: shouldDisconnect
}
);
if (rekeyRes && rekeyRes.status === 200) {
const rekeyData = rekeyRes.data.data;
if (rekeyData && rekeyData.olmId) {
setCurrentOlmId(rekeyData.olmId);
setRegeneratedSecret(data.olmSecret);
setClientDefaults({
...data,
olmId: rekeyData.olmId
});
setShowCredentialsAlert(true);
}
} }
);
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
}
} catch (error) {
toast({ toast({
title: t("credentialsSaved"), variant: "destructive",
description: t("credentialsSavedDescription") title: t("error") || "Error",
description:
formatAxiosError(error) ||
t("credentialsRegenerateError") ||
"Failed to regenerate credentials"
}); });
router.refresh();
} }
}; };
const getCredentials = () => { const getConfirmationString = () => {
if (clientDefaults) { return client?.name || client?.clientId?.toString() || "My client";
return {
Id: clientDefaults.olmId,
Secret: clientDefaults.olmSecret
};
}
return undefined;
}; };
const displayOlmId = currentOlmId || clientDefaults?.olmId || null;
const displaySecret = regeneratedSecret || null;
return ( return (
<> <>
<SettingsContainer> <SettingsContainer>
<SettingsSection> <SettingsSection>
<SettingsSectionHeader> <SettingsSectionHeader>
<SettingsSectionTitle> <SettingsSectionTitle>
{t("generatedcredentials")} {t("clientOlmCredentials")}
</SettingsSectionTitle> </SettingsSectionTitle>
<SettingsSectionDescription> <SettingsSectionDescription>
{t("regenerateCredentials")} {t("clientOlmCredentialsDescription")}
</SettingsSectionDescription> </SettingsSectionDescription>
</SettingsSectionHeader> </SettingsSectionHeader>
<SettingsSectionBody> <SettingsSectionBody>
<SecurityFeaturesAlert /> <InfoSections cols={3}>
<Button <InfoSection>
onClick={() => setModalOpen(true)} <InfoSectionTitle>
disabled={isSecurityFeatureDisabled()} {t("olmEndpoint")}
> </InfoSectionTitle>
{t("regeneratecredentials")} <InfoSectionContent>
</Button> <CopyToClipboard
text={env.app.dashboardUrl}
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("olmId")}
</InfoSectionTitle>
<InfoSectionContent>
{displayOlmId ? (
<CopyToClipboard text={displayOlmId} />
) : (
<span>{"••••••••••••••••"}</span>
)}
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("olmSecretKey")}
</InfoSectionTitle>
<InfoSectionContent>
{displaySecret ? (
<CopyToClipboard text={displaySecret} />
) : (
<span>{"••••••••••••••••••••••••••••••••"}</span>
)}
</InfoSectionContent>
</InfoSection>
</InfoSections>
{showCredentialsAlert && displaySecret && (
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("clientCredentialsSave")}
</AlertTitle>
<AlertDescription>
{t("clientCredentialsSaveDescription")}
</AlertDescription>
</Alert>
)}
</SettingsSectionBody> </SettingsSectionBody>
<SettingsSectionFooter>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
setShouldDisconnect(false);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("regenerateCredentialsButton")}
</Button>
<Button
onClick={() => {
setShouldDisconnect(true);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("clientRegenerateAndDisconnect")}
</Button>
</div>
</SettingsSectionFooter>
</SettingsSection> </SettingsSection>
</SettingsContainer> </SettingsContainer>
<RegenerateCredentialsModal <ConfirmDeleteDialog
open={modalOpen} open={modalOpen}
onOpenChange={setModalOpen} setOpen={(val) => {
type="client-olm" setModalOpen(val);
onConfirmRegenerate={handleConfirmRegenerate} // Prevent modal from reopening during refresh
dashboardUrl={env.app.dashboardUrl} if (!val) {
credentials={getCredentials()} setTimeout(() => {
router.refresh();
}, 150);
}
}}
dialog={
<div className="space-y-2">
{shouldDisconnect ? (
<>
<p>
{t("clientRegenerateAndDisconnectConfirmation")}
</p>
<p>
{t("clientRegenerateAndDisconnectWarning")}
</p>
</>
) : (
<>
<p>
{t("clientRegenerateCredentialsConfirmation")}
</p>
<p>
{t("clientRegenerateCredentialsWarning")}
</p>
</>
)}
</div>
}
buttonText={
shouldDisconnect
? t("clientRegenerateAndDisconnect")
: t("regenerateCredentialsButton")
}
onConfirm={handleConfirmRegenerate}
string={getConfirmationString()}
title={t("regenerateCredentials")}
warningText={t("cannotbeUndone")}
/> />
</> </>
); );

View File

@@ -1,11 +1,12 @@
"use client"; "use client";
import { useState } from "react"; import { useState, useEffect } from "react";
import { import {
SettingsContainer, SettingsContainer,
SettingsSection, SettingsSection,
SettingsSectionBody, SettingsSectionBody,
SettingsSectionDescription, SettingsSectionDescription,
SettingsSectionFooter,
SettingsSectionHeader, SettingsSectionHeader,
SettingsSectionTitle SettingsSectionTitle
} from "@app/components/Settings"; } from "@app/components/Settings";
@@ -18,17 +19,26 @@ import { useTranslations } from "next-intl";
import { PickSiteDefaultsResponse } from "@server/routers/site"; import { PickSiteDefaultsResponse } from "@server/routers/site";
import { useSiteContext } from "@app/hooks/useSiteContext"; import { useSiteContext } from "@app/hooks/useSiteContext";
import { generateKeypair } from "../wireguardConfig"; import { generateKeypair } from "../wireguardConfig";
import RegenerateCredentialsModal from "@app/components/RegenerateCredentialsModal"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext"; import { useLicenseStatusContext } from "@app/hooks/useLicenseStatusContext";
import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext"; import { useSubscriptionStatusContext } from "@app/hooks/useSubscriptionStatusContext";
import { build } from "@server/build"; import { build } from "@server/build";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@app/components/ui/tooltip";
import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert"; import { SecurityFeaturesAlert } from "@app/components/SecurityFeaturesAlert";
import {
InfoSection,
InfoSectionContent,
InfoSections,
InfoSectionTitle
} from "@app/components/InfoSection";
import CopyToClipboard from "@app/components/CopyToClipboard";
import CopyTextBox from "@app/components/CopyTextBox";
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
import { InfoIcon } from "lucide-react";
import {
generateWireGuardConfig,
generateObfuscatedWireGuardConfig
} from "@app/lib/wireguard";
import { QRCodeCanvas } from "qrcode.react";
export default function CredentialsPage() { export default function CredentialsPage() {
const { env } = useEnvContext(); const { env } = useEnvContext();
@@ -43,6 +53,16 @@ export default function CredentialsPage() {
useState<PickSiteDefaultsResponse | null>(null); useState<PickSiteDefaultsResponse | null>(null);
const [wgConfig, setWgConfig] = useState(""); const [wgConfig, setWgConfig] = useState("");
const [publicKey, setPublicKey] = useState(""); const [publicKey, setPublicKey] = useState("");
const [currentNewtId, setCurrentNewtId] = useState<string | null>(
site.newtId
);
const [regeneratedSecret, setRegeneratedSecret] = useState<string | null>(
null
);
const [showCredentialsAlert, setShowCredentialsAlert] = useState(false);
const [showWireGuardAlert, setShowWireGuardAlert] = useState(false);
const [loadingDefaults, setLoadingDefaults] = useState(false);
const [shouldDisconnect, setShouldDisconnect] = useState(true);
const { licenseStatus, isUnlocked } = useLicenseStatusContext(); const { licenseStatus, isUnlocked } = useLicenseStatusContext();
const subscription = useSubscriptionStatusContext(); const subscription = useSubscriptionStatusContext();
@@ -54,136 +74,389 @@ export default function CredentialsPage() {
return isEnterpriseNotLicensed || isSaasNotSubscribed; return isEnterpriseNotLicensed || isSaasNotSubscribed;
}; };
const hydrateWireGuardConfig = ( // Fetch site defaults for wireguard sites to show in obfuscated config
privateKey: string, useEffect(() => {
publicKey: string, const fetchSiteDefaults = async () => {
subnet: string, if (site?.type === "wireguard" && !siteDefaults && orgId) {
address: string, setLoadingDefaults(true);
endpoint: string, try {
listenPort: string const res = await api.get(
) => { `/org/${orgId}/pick-site-defaults`
const config = `[Interface] );
Address = ${subnet} if (res && res.status === 200) {
ListenPort = 51820 setSiteDefaults(res.data.data);
PrivateKey = ${privateKey} }
} catch (error) {
[Peer] // Silently fail - we'll use site data or obfuscated values
PublicKey = ${publicKey} } finally {
AllowedIPs = ${address.split("/")[0]}/32 setLoadingDefaults(false);
Endpoint = ${endpoint}:${listenPort} }
PersistentKeepalive = 5`; } else {
setWgConfig(config); setLoadingDefaults(false);
return config; }
}; };
fetchSiteDefaults();
}, []);
const handleConfirmRegenerate = async () => { const handleConfirmRegenerate = async () => {
let generatedPublicKey = ""; try {
let generatedWgConfig = ""; let generatedPublicKey = "";
let generatedWgConfig = "";
if (site?.type === "wireguard") { if (site?.type === "wireguard") {
const generatedKeypair = generateKeypair(); const generatedKeypair = generateKeypair();
generatedPublicKey = generatedKeypair.publicKey; generatedPublicKey = generatedKeypair.publicKey;
setPublicKey(generatedPublicKey); setPublicKey(generatedPublicKey);
const res = await api.get(`/org/${orgId}/pick-site-defaults`); const res = await api.get(`/org/${orgId}/pick-site-defaults`);
if (res && res.status === 200) { if (res && res.status === 200) {
const data = res.data.data; const data = res.data.data;
setSiteDefaults(data); setSiteDefaults(data);
// generate config with the fetched data // generate config with the fetched data
generatedWgConfig = hydrateWireGuardConfig( generatedWgConfig = generateWireGuardConfig(
generatedKeypair.privateKey, generatedKeypair.privateKey,
data.publicKey, data.publicKey,
data.subnet, data.subnet,
data.address, data.address,
data.endpoint, data.endpoint,
data.listenPort data.listenPort
); );
} setWgConfig(generatedWgConfig);
setShowWireGuardAlert(true);
await api.post(`/re-key/${site?.siteId}/regenerate-site-secret`, { }
type: "wireguard",
pubKey: generatedPublicKey
});
}
if (site?.type === "newt") {
const res = await api.get(`/org/${orgId}/pick-site-defaults`);
if (res && res.status === 200) {
const data = res.data.data;
setSiteDefaults(data);
await api.post( await api.post(
`/re-key/${site?.siteId}/regenerate-site-secret`, `/re-key/${site?.siteId}/regenerate-site-secret`,
{ {
type: "newt", type: "wireguard",
secret: data.newtSecret pubKey: generatedPublicKey
} }
); );
} }
if (site?.type === "newt") {
const res = await api.get(`/org/${orgId}/pick-site-defaults`);
if (res && res.status === 200) {
const data = res.data.data;
const rekeyRes = await api.post(
`/re-key/${site?.siteId}/regenerate-site-secret`,
{
type: "newt",
secret: data.newtSecret,
disconnect: shouldDisconnect
}
);
if (rekeyRes && rekeyRes.status === 200) {
const rekeyData = rekeyRes.data.data;
if (rekeyData && rekeyData.newtId) {
setCurrentNewtId(rekeyData.newtId);
setRegeneratedSecret(data.newtSecret);
setSiteDefaults({
...data,
newtId: rekeyData.newtId
});
setShowCredentialsAlert(true);
}
}
}
}
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
// ConfirmDeleteDialog handles closing the modal and triggering refresh via setOpen callback
} catch (error) {
toast({
variant: "destructive",
title: t("error") || "Error",
description:
formatAxiosError(error) ||
t("credentialsRegenerateError") ||
"Failed to regenerate credentials"
});
} }
toast({
title: t("credentialsSaved"),
description: t("credentialsSavedDescription")
});
router.refresh();
}; };
const getCredentialType = () => { const getConfirmationString = () => {
if (site?.type === "wireguard") return "site-wireguard"; return site?.name || site?.niceId || "My site";
if (site?.type === "newt") return "site-newt";
return "site-newt";
}; };
const getCredentials = () => { const displayNewtId = currentNewtId || siteDefaults?.newtId || null;
if (site?.type === "wireguard" && wgConfig) { const displaySecret = regeneratedSecret || null;
return { wgConfig };
}
if (site?.type === "newt" && siteDefaults) {
return {
Id: siteDefaults.newtId,
Secret: siteDefaults.newtSecret
};
}
return undefined;
};
return ( return (
<> <>
<SettingsContainer> <SettingsContainer>
<SettingsSection> {site?.type === "newt" && (
<SettingsSectionHeader> <SettingsSection>
<SettingsSectionTitle> <SettingsSectionHeader>
{t("generatedcredentials")} <SettingsSectionTitle>
</SettingsSectionTitle> {t("siteNewtCredentials")}
<SettingsSectionDescription> </SettingsSectionTitle>
{t("regenerateCredentials")} <SettingsSectionDescription>
</SettingsSectionDescription> {t("siteNewtCredentialsDescription")}
</SettingsSectionHeader> </SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<InfoSections cols={3}>
<InfoSection>
<InfoSectionTitle>
{t("newtEndpoint")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard
text={env.app.dashboardUrl}
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("newtId")}
</InfoSectionTitle>
<InfoSectionContent>
{displayNewtId ? (
<CopyToClipboard
text={displayNewtId}
/>
) : (
<span>{"••••••••••••••••"}</span>
)}
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("newtSecretKey")}
</InfoSectionTitle>
<InfoSectionContent>
{displaySecret ? (
<CopyToClipboard
text={displaySecret}
/>
) : (
<span>
{
"••••••••••••••••••••••••••••••••"
}
</span>
)}
</InfoSectionContent>
</InfoSection>
</InfoSections>
<SecurityFeaturesAlert /> {showCredentialsAlert && displaySecret && (
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("siteCredentialsSave")}
</AlertTitle>
<AlertDescription>
{t("siteCredentialsSaveDescription")}
</AlertDescription>
</Alert>
)}
</SettingsSectionBody>
<SettingsSectionFooter>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
setShouldDisconnect(false);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("regenerateCredentialsButton")}
</Button>
<Button
onClick={() => {
setShouldDisconnect(true);
setModalOpen(true);
}}
disabled={isSecurityFeatureDisabled()}
>
{t("siteRegenerateAndDisconnect")}
</Button>
</div>
</SettingsSectionFooter>
</SettingsSection>
)}
<SettingsSectionBody> {site?.type === "wireguard" && (
<Button <SettingsSection>
onClick={() => setModalOpen(true)} <SettingsSectionHeader>
disabled={isSecurityFeatureDisabled()} <SettingsSectionTitle>
> {t("generatedcredentials")}
{t("regeneratecredentials")} </SettingsSectionTitle>
</Button> <SettingsSectionDescription>
</SettingsSectionBody> {t("regenerateCredentials")}
</SettingsSection> </SettingsSectionDescription>
</SettingsSectionHeader>
<SecurityFeaturesAlert />
<SettingsSectionBody>
{!loadingDefaults && (
<>
{wgConfig ? (
<div className="flex items-center gap-4">
<CopyTextBox
text={wgConfig}
outline={true}
/>
<div className="relative w-fit border rounded-md">
<div className="bg-white p-6 rounded-md">
<QRCodeCanvas
value={wgConfig}
size={168}
className="mx-auto"
/>
</div>
</div>
</div>
) : (
<CopyTextBox
text={generateObfuscatedWireGuardConfig(
{
subnet:
siteDefaults?.subnet ||
site?.subnet ||
null,
address:
siteDefaults?.address ||
site?.address ||
null,
endpoint:
siteDefaults?.endpoint ||
site?.endpoint ||
null,
listenPort:
siteDefaults?.listenPort ||
site?.listenPort ||
null,
publicKey:
siteDefaults?.publicKey ||
site?.publicKey ||
site?.pubKey ||
null
}
)}
outline={true}
/>
)}
{showWireGuardAlert && wgConfig && (
<Alert
variant="neutral"
className="mt-4"
>
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("siteCredentialsSave")}
</AlertTitle>
<AlertDescription>
{t(
"siteCredentialsSaveDescription"
)}
</AlertDescription>
</Alert>
)}
</>
)}
</SettingsSectionBody>
<SettingsSectionFooter>
<Button
onClick={() => setModalOpen(true)}
disabled={isSecurityFeatureDisabled()}
>
{t("siteRegenerateAndDisconnect")}
</Button>
</SettingsSectionFooter>
</SettingsSection>
)}
</SettingsContainer> </SettingsContainer>
<RegenerateCredentialsModal {site?.type === "newt" && (
open={modalOpen} <ConfirmDeleteDialog
onOpenChange={setModalOpen} open={modalOpen}
type={getCredentialType()} setOpen={(val) => {
onConfirmRegenerate={handleConfirmRegenerate} setModalOpen(val);
dashboardUrl={env.app.dashboardUrl} // Prevent modal from reopening during refresh
credentials={getCredentials()} if (!val) {
/> setTimeout(() => {
router.refresh();
}, 150);
}
}}
dialog={
<div className="space-y-2">
{shouldDisconnect ? (
<>
<p>
{t(
"siteRegenerateAndDisconnectConfirmation"
)}
</p>
<p>
{t(
"siteRegenerateAndDisconnectWarning"
)}
</p>
</>
) : (
<>
<p>
{t(
"siteRegenerateCredentialsConfirmation"
)}
</p>
<p>
{t("siteRegenerateCredentialsWarning")}
</p>
</>
)}
</div>
}
buttonText={
shouldDisconnect
? t("siteRegenerateAndDisconnect")
: t("regenerateCredentialsButton")
}
onConfirm={handleConfirmRegenerate}
string={getConfirmationString()}
title={t("regenerateCredentials")}
warningText={t("cannotbeUndone")}
/>
)}
{site?.type === "wireguard" && (
<ConfirmDeleteDialog
open={modalOpen}
setOpen={(val) => {
setModalOpen(val);
// Prevent modal from reopening during refresh
if (!val) {
setTimeout(() => {
router.refresh();
}, 150);
}
}}
dialog={
<div className="space-y-2">
<p>{t("regenerateCredentialsConfirmation")}</p>
<p>{t("regenerateCredentialsWarning")}</p>
</div>
}
buttonText={t("regenerateCredentialsButton")}
onConfirm={handleConfirmRegenerate}
string={getConfirmationString()}
title={t("regenerateCredentials")}
warningText={t("cannotbeUndone")}
/>
)}
</> </>
); );
} }

View File

@@ -47,6 +47,7 @@ import { Checkbox, CheckboxWithLabel } from "@app/components/ui/checkbox";
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert"; import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
import { generateKeypair } from "../[niceId]/wireguardConfig"; import { generateKeypair } from "../[niceId]/wireguardConfig";
import { createApiClient, formatAxiosError } from "@app/lib/api"; import { createApiClient, formatAxiosError } from "@app/lib/api";
import { generateWireGuardConfig } from "@app/lib/wireguard";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { import {
CreateSiteBody, CreateSiteBody,
@@ -214,26 +215,6 @@ export default function Page() {
string | undefined string | undefined
>(); >();
const hydrateWireGuardConfig = (
privateKey: string,
publicKey: string,
subnet: string,
address: string,
endpoint: string,
listenPort: string
) => {
const wgConfig = `[Interface]
Address = ${subnet}
ListenPort = 51820
PrivateKey = ${privateKey}
[Peer]
PublicKey = ${publicKey}
AllowedIPs = ${address.split("/")[0]}/32
Endpoint = ${endpoint}:${listenPort}
PersistentKeepalive = 5`;
setWgConfig(wgConfig);
};
const hydrateCommands = ( const hydrateCommands = (
id: string, id: string,
@@ -595,7 +576,7 @@ WantedBy=default.target`
acceptClients acceptClients
); );
hydrateWireGuardConfig( const wgConfig = generateWireGuardConfig(
privateKey, privateKey,
data.publicKey, data.publicKey,
data.subnet, data.subnet,
@@ -603,6 +584,7 @@ WantedBy=default.target`
data.endpoint, data.endpoint,
data.listenPort data.listenPort
); );
setWgConfig(wgConfig);
setTunnelTypes((prev: any) => { setTunnelTypes((prev: any) => {
return prev.map((item: any) => { return prev.map((item: any) => {

View File

@@ -426,7 +426,7 @@ export default function LoginForm({
<div className="text-center"> <div className="text-center">
<Link <Link
href={`${env.app.dashboardUrl}/auth/reset-password${form.getValues().email ? `?email=${form.getValues().email}` : ""}`} href={`${env.app.dashboardUrl}/auth/reset-password${form.getValues().email ? `?email=${encodeURIComponent(form.getValues().email)}` : ""}`}
className="text-sm text-muted-foreground" className="text-sm text-muted-foreground"
> >
{t("passwordForgot")} {t("passwordForgot")}

View File

@@ -273,7 +273,7 @@ export default function SitesTable({ sites, orgId }: SitesTableProps) {
if (originalRow.type === "wireguard") { if (originalRow.type === "wireguard") {
return ( return (
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<span>WireGuard</span> <Badge variant="secondary">WireGuard</Badge>
</div> </div>
); );
} }
@@ -281,7 +281,7 @@ export default function SitesTable({ sites, orgId }: SitesTableProps) {
if (originalRow.type === "local") { if (originalRow.type === "local") {
return ( return (
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<span>{t("local")}</span> <Badge variant="secondary">Local</Badge>
</div> </div>
); );
} }

61
src/lib/wireguard.ts Normal file
View File

@@ -0,0 +1,61 @@
export function generateWireGuardConfig(
privateKey: string,
publicKey: string,
subnet: string,
address: string,
endpoint: string,
listenPort: string | number
): string {
const addressWithoutCidr = address.split("/")[0];
const port = typeof listenPort === "number" ? listenPort : listenPort;
return `[Interface]
Address = ${subnet}
ListenPort = 51820
PrivateKey = ${privateKey}
[Peer]
PublicKey = ${publicKey}
AllowedIPs = ${addressWithoutCidr}/32
Endpoint = ${endpoint}:${port}
PersistentKeepalive = 5`;
}
export function generateObfuscatedWireGuardConfig(options?: {
subnet?: string | null;
address?: string | null;
endpoint?: string | null;
listenPort?: number | string | null;
publicKey?: string | null;
}): string {
const obfuscate = (value: string | null | undefined, length: number = 20): string => {
return value || "•".repeat(length);
};
const obfuscateKey = (value: string | null | undefined): string => {
return value || "•".repeat(44); // Base64 key length
};
const subnet = options?.subnet || obfuscate(null, 20);
const subnetWithCidr = subnet.includes("•")
? `${subnet}/32`
: (subnet.includes("/") ? subnet : `${subnet}/32`);
const address = options?.address ? options.address.split("/")[0] : obfuscate(null, 20);
const endpoint = obfuscate(options?.endpoint, 20);
const listenPort = options?.listenPort
? (typeof options.listenPort === "number" ? options.listenPort : options.listenPort)
: 51820;
const publicKey = obfuscateKey(options?.publicKey);
return `[Interface]
Address = ${subnetWithCidr}
ListenPort = 51820
PrivateKey = ${obfuscateKey(null)}
[Peer]
PublicKey = ${publicKey}
AllowedIPs = ${address}/32
Endpoint = ${endpoint}:${listenPort}
PersistentKeepalive = 5`;
}