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 { Request, Response, NextFunction } from "express";
import { z } from "zod"; import { z } from "zod";
import { db, newts } from "@server/db"; import { db, newts, sites } from "@server/db";
import { eq } from "drizzle-orm"; import { eq } 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";
@@ -9,6 +9,8 @@ import logger from "@server/logger";
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 { addPeer } from "../gerbil/peers";
const updateSiteParamsSchema = z const updateSiteParamsSchema = z
.object({ .object({
@@ -18,28 +20,31 @@ const updateSiteParamsSchema = z
const updateSiteBodySchema = z const updateSiteBodySchema = z
.object({ .object({
type: z.enum(["newt", "wireguard"]),
newtId: z.string().min(1).max(255).optional(), newtId: z.string().min(1).max(255).optional(),
newtSecret: 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(); .strict();
registry.registerPath({ registry.registerPath({
method: "post", method: "post",
path: "/site/{siteId}/regenerate-secret", path: "/site/{siteId}/regenerate-secret",
description: description: "Regenerate a site's Newt or WireGuard credentials by its site ID.",
"Regenerate a site's Newt credentials by its site ID.",
tags: [OpenAPITags.Site], tags: [OpenAPITags.Site],
request: { request: {
params: updateSiteParamsSchema, params: updateSiteParamsSchema,
body: { body: {
content: { content: {
"application/json": { "application/json": {
schema: updateSiteBodySchema schema: updateSiteBodySchema,
} },
} },
} },
}, },
responses: {} responses: {},
}); });
export async function reGenerateSiteSecret( export async function reGenerateSiteSecret(
@@ -51,56 +56,100 @@ export async function reGenerateSiteSecret(
const parsedParams = updateSiteParamsSchema.safeParse(req.params); const parsedParams = updateSiteParamsSchema.safeParse(req.params);
if (!parsedParams.success) { if (!parsedParams.success) {
return next( return next(
createHttpError( createHttpError(HttpCode.BAD_REQUEST, fromError(parsedParams.error).toString())
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
); );
} }
const parsedBody = updateSiteBodySchema.safeParse(req.body); const parsedBody = updateSiteBodySchema.safeParse(req.body);
if (!parsedBody.success) { if (!parsedBody.success) {
return next( return next(
createHttpError( createHttpError(HttpCode.BAD_REQUEST, fromError(parsedBody.error).toString())
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
); );
} }
const { siteId } = parsedParams.data; const { siteId } = parsedParams.data;
const { newtId, newtSecret } = parsedBody.data; const { type, exitNodeId, pubKey, subnet, newtId, newtSecret } = parsedBody.data;
const secretHash = await hashPassword(newtSecret!); let updatedSite = undefined;
const updatedSite = await db
.update(newts)
.set({
newtId,
secretHash
})
.where(eq(newts.siteId, siteId))
.returning();
if (updatedSite.length === 0) { if (type === "newt") {
return next( if (!newtSecret) {
createHttpError( return next(
HttpCode.NOT_FOUND, createHttpError(HttpCode.BAD_REQUEST, "newtSecret is required for newt sites")
`Site with ID ${siteId} not found` );
) }
);
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, { return response(res, {
data: updatedSite[0], data: updatedSite,
success: true, success: true,
error: false, error: false,
message: "Credentials regenerated successfully", message: "Credentials regenerated successfully",
status: HttpCode.OK status: HttpCode.OK,
}); });
} catch (error) { } catch (error) {
logger.error(error); logger.error("Unexpected error in reGenerateSiteSecret", error);
return next( 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 CopyToClipboard from "@app/components/CopyToClipboard";
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 CopyTextBox from "@app/components/CopyTextBox";
import { QRCodeCanvas } from "qrcode.react";
import { generateKeypair } from "../wireguardConfig";
export default function CredentialsPage() { export default function CredentialsPage() {
const { env } = useEnvContext(); const { env } = useEnvContext();
@@ -31,12 +34,36 @@ export default function CredentialsPage() {
const [newtId, setNewtId] = useState(""); const [newtId, setNewtId] = useState("");
const [newtSecret, setNewtSecret] = useState(""); const [newtSecret, setNewtSecret] = useState("");
const { site, updateSite } = useSiteContext(); const { site, updateSite } = useSiteContext();
const [wgConfig, setWgConfig] = useState("");
const [siteDefaults, setSiteDefaults] = const [siteDefaults, setSiteDefaults] =
useState<PickSiteDefaultsResponse | null>(null); useState<PickSiteDefaultsResponse | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [saving, setSaving] = 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 // Clear credentials when user leaves/reloads
useEffect(() => { useEffect(() => {
@@ -49,6 +76,14 @@ export default function CredentialsPage() {
}, []); }, []);
const handleRegenerate = async () => { const handleRegenerate = async () => {
const generatedKeypair = generateKeypair();
const privateKey = generatedKeypair.privateKey;
const publicKey = generatedKeypair.publicKey;
setPrivateKey(privateKey);
setPublicKey(publicKey);
try { try {
setLoading(true); setLoading(true);
await api await api
@@ -64,6 +99,15 @@ export default function CredentialsPage() {
setNewtId(newtId); setNewtId(newtId);
setNewtSecret(newtSecret); setNewtSecret(newtSecret);
hydrateWireGuardConfig(
privateKey,
data.publicKey,
data.subnet,
data.address,
data.endpoint,
data.listenPort
);
} }
}); });
} finally { } finally {
@@ -74,11 +118,46 @@ export default function CredentialsPage() {
const handleSave = async () => { const handleSave = async () => {
setLoading(true); setLoading(true);
try { let payload: any = {};
await api.post(`/site/${site?.siteId}/regenerate-secret`, {
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, newtId: siteDefaults?.newtId,
newtSecret: siteDefaults?.newtSecret, newtSecret: siteDefaults?.newtSecret
}); };
}
try {
await api.post(`/site/${site?.siteId}/regenerate-secret`, payload);
toast({ toast({
title: t("credentialsSaved"), title: t("credentialsSaved"),
@@ -100,6 +179,7 @@ export default function CredentialsPage() {
} }
}; };
return ( return (
<SettingsContainer> <SettingsContainer>
<SettingsSection> <SettingsSection>
@@ -117,73 +197,114 @@ export default function CredentialsPage() {
<Button <Button
onClick={handleRegenerate} onClick={handleRegenerate}
loading={loading} loading={loading}
disabled={site.type != "newt"} disabled={site.type === "local"}
> >
{t("regeneratecredentials")} {t("regeneratecredentials")}
</Button> </Button>
) : ( ) : (
<> <>
<SettingsSection> {site.type === "wireguard" && (
<SettingsSectionHeader> <SettingsSection>
<SettingsSectionTitle> <SettingsSectionHeader>
{t("siteNewtCredentials")} <SettingsSectionTitle>
</SettingsSectionTitle> {t("WgConfiguration")}
<SettingsSectionDescription> </SettingsSectionTitle>
{t( <SettingsSectionDescription>
"siteNewtCredentialsDescription" {t("WgConfigurationDescription")}
)} </SettingsSectionDescription>
</SettingsSectionDescription> </SettingsSectionHeader>
</SettingsSectionHeader> <SettingsSectionBody>
<SettingsSectionBody> <div className="flex items-center gap-4">
<InfoSections cols={3}> <CopyTextBox text={wgConfig} />
<InfoSection> <div
<InfoSectionTitle> className={`relative w-fit border rounded-md`}
{t("newtEndpoint")} >
</InfoSectionTitle> <div className="bg-white p-6 rounded-md">
<InfoSectionContent> <QRCodeCanvas
<CopyToClipboard value={wgConfig}
text={ size={168}
env.app.dashboardUrl className="mx-auto"
} />
/> </div>
</InfoSectionContent> </div>
</InfoSection> </div>
<InfoSection> <Alert variant="neutral">
<InfoSectionTitle> <InfoIcon className="h-4 w-4" />
{t("newtId")} <AlertTitle className="font-semibold">
</InfoSectionTitle> {t("siteCredentialsSave")}
<InfoSectionContent> </AlertTitle>
<CopyToClipboard <AlertDescription>
text={newtId} {t(
/> "siteCredentialsSaveDescription"
</InfoSectionContent> )}
</InfoSection> </AlertDescription>
<InfoSection> </Alert>
<InfoSectionTitle> </SettingsSectionBody>
{t("newtSecretKey")} </SettingsSection>
</InfoSectionTitle> )}
<InfoSectionContent> {site.type === "newt" && (
<CopyToClipboard <SettingsSection>
text={newtSecret} <SettingsSectionHeader>
/> <SettingsSectionTitle>
</InfoSectionContent> {t("siteNewtCredentials")}
</InfoSection> </SettingsSectionTitle>
</InfoSections> <SettingsSectionDescription>
<Alert variant="neutral" className="mt-4">
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
{t("copyandsavethesecredentials")}
</AlertTitle>
<AlertDescription>
{t( {t(
"copyandsavethesecredentialsdescription" "siteNewtCredentialsDescription"
)} )}
</AlertDescription> </SettingsSectionDescription>
</Alert> </SettingsSectionHeader>
</SettingsSectionBody> <SettingsSectionBody>
</SettingsSection> <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"> <div className="flex justify-end mt-6 space-x-2">
<Button <Button