regenerate secret for wireguard

This commit is contained in:
Pallavi Kumari
2025-10-28 19:26:58 +05:30
parent 18cdf070c7
commit f7e7993fd4
2 changed files with 272 additions and 102 deletions

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, newts } from "@server/db";
import { db, newts, sites } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -9,6 +9,8 @@ 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 "../gerbil/peers";
const updateSiteParamsSchema = z
.object({
@@ -18,28 +20,31 @@ const updateSiteParamsSchema = z
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: "/site/{siteId}/regenerate-secret",
description:
"Regenerate a site's Newt credentials by its site ID.",
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
}
}
}
schema: updateSiteBodySchema,
},
},
},
},
responses: {}
responses: {},
});
export async function reGenerateSiteSecret(
@@ -51,56 +56,100 @@ export async function reGenerateSiteSecret(
const parsedParams = updateSiteParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
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()
)
createHttpError(HttpCode.BAD_REQUEST, fromError(parsedBody.error).toString())
);
}
const { siteId } = parsedParams.data;
const { newtId, newtSecret } = parsedBody.data;
const { type, exitNodeId, pubKey, subnet, newtId, newtSecret } = parsedBody.data;
const secretHash = await hashPassword(newtSecret!);
const updatedSite = await db
.update(newts)
.set({
newtId,
secretHash
})
.where(eq(newts.siteId, siteId))
.returning();
let updatedSite = undefined;
if (updatedSite.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site with ID ${siteId} not found`
)
);
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[0],
data: updatedSite,
success: true,
error: false,
message: "Credentials regenerated successfully",
status: HttpCode.OK
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
logger.error("Unexpected error in reGenerateSiteSecret", error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An unexpected error occurred")
);
}
}

View File

@@ -21,6 +21,9 @@ import { InfoSection, InfoSectionContent, InfoSections, InfoSectionTitle } from
import CopyToClipboard from "@app/components/CopyToClipboard";
import { PickSiteDefaultsResponse } from "@server/routers/site";
import { useSiteContext } from "@app/hooks/useSiteContext";
import CopyTextBox from "@app/components/CopyTextBox";
import { QRCodeCanvas } from "qrcode.react";
import { generateKeypair } from "../wireguardConfig";
export default function CredentialsPage() {
const { env } = useEnvContext();
@@ -31,12 +34,36 @@ export default function CredentialsPage() {
const [newtId, setNewtId] = useState("");
const [newtSecret, setNewtSecret] = useState("");
const { site, updateSite } = useSiteContext();
const [wgConfig, setWgConfig] = useState("");
const [siteDefaults, setSiteDefaults] =
useState<PickSiteDefaultsResponse | null>(null);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [publicKey, setPublicKey] = useState("");
const [privateKey, setPrivateKey] = useState("");
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);
};
// Clear credentials when user leaves/reloads
useEffect(() => {
@@ -49,6 +76,14 @@ export default function CredentialsPage() {
}, []);
const handleRegenerate = async () => {
const generatedKeypair = generateKeypair();
const privateKey = generatedKeypair.privateKey;
const publicKey = generatedKeypair.publicKey;
setPrivateKey(privateKey);
setPublicKey(publicKey);
try {
setLoading(true);
await api
@@ -64,6 +99,15 @@ export default function CredentialsPage() {
setNewtId(newtId);
setNewtSecret(newtSecret);
hydrateWireGuardConfig(
privateKey,
data.publicKey,
data.subnet,
data.address,
data.endpoint,
data.listenPort
);
}
});
} finally {
@@ -74,11 +118,46 @@ export default function CredentialsPage() {
const handleSave = async () => {
setLoading(true);
try {
await api.post(`/site/${site?.siteId}/regenerate-secret`, {
let payload: any = {};
if (site?.type === "wireguard") {
if (!siteDefaults || !wgConfig) {
toast({
variant: "destructive",
title: t("siteErrorCreate"),
description: t("siteErrorCreateKeyPair")
});
setLoading(false);
return;
}
payload = {
type: "wireguard",
subnet: siteDefaults.subnet,
exitNodeId: siteDefaults.exitNodeId,
pubKey: publicKey
};
}
if (site?.type === "newt") {
if (!siteDefaults) {
toast({
variant: "destructive",
title: t("siteErrorCreate"),
description: t("siteErrorCreateDefaults")
});
setLoading(false);
return;
}
payload = {
type: "newt",
newtId: siteDefaults?.newtId,
newtSecret: siteDefaults?.newtSecret,
});
newtSecret: siteDefaults?.newtSecret
};
}
try {
await api.post(`/site/${site?.siteId}/regenerate-secret`, payload);
toast({
title: t("credentialsSaved"),
@@ -100,6 +179,7 @@ export default function CredentialsPage() {
}
};
return (
<SettingsContainer>
<SettingsSection>
@@ -117,73 +197,114 @@ export default function CredentialsPage() {
<Button
onClick={handleRegenerate}
loading={loading}
disabled={site.type != "newt"}
disabled={site.type === "local"}
>
{t("regeneratecredentials")}
</Button>
) : (
<>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("siteNewtCredentials")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t(
"siteNewtCredentialsDescription"
)}
</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>
<CopyToClipboard
text={newtId}
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("newtSecretKey")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard
text={newtSecret}
/>
</InfoSectionContent>
</InfoSection>
</InfoSections>
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("copyandsavethesecredentials")}
</AlertTitle>
<AlertDescription>
{site.type === "wireguard" && (
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("WgConfiguration")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("WgConfigurationDescription")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<div className="flex items-center gap-4">
<CopyTextBox text={wgConfig} />
<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>
<Alert variant="neutral">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("siteCredentialsSave")}
</AlertTitle>
<AlertDescription>
{t(
"siteCredentialsSaveDescription"
)}
</AlertDescription>
</Alert>
</SettingsSectionBody>
</SettingsSection>
)}
{site.type === "newt" && (
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("siteNewtCredentials")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t(
"copyandsavethesecredentialsdescription"
"siteNewtCredentialsDescription"
)}
</AlertDescription>
</Alert>
</SettingsSectionBody>
</SettingsSection>
</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>
<CopyToClipboard
text={newtId}
/>
</InfoSectionContent>
</InfoSection>
<InfoSection>
<InfoSectionTitle>
{t("newtSecretKey")}
</InfoSectionTitle>
<InfoSectionContent>
<CopyToClipboard
text={newtSecret}
/>
</InfoSectionContent>
</InfoSection>
</InfoSections>
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("copyandsavethesecredentials")}
</AlertTitle>
<AlertDescription>
{t(
"copyandsavethesecredentialsdescription"
)}
</AlertDescription>
</Alert>
</SettingsSectionBody>
</SettingsSection>
)}
<div className="flex justify-end mt-6 space-x-2">
<Button