import { randomBytes, createHash, timingSafeEqual } from "node:crypto"; import { chmod, readFile, writeFile, unlink } from "node:fs/promises"; import { join } from "node:path"; export const setupTokenPath = (dataDir: string) => join(dataDir, "setup-token"); export async function ensureSetupToken(dataDir: string): Promise { const path = setupTokenPath(dataDir); try { await writeFile(path, randomBytes(32).toString("hex") + "\n", { flag: "wx", mode: 0o600, }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } await chmod(path, 0o600); } export async function matchesSetupToken( dataDir: string, candidate: unknown, ): Promise { if (typeof candidate !== "string" || candidate.length > 4096) return false; try { const expected = (await readFile(setupTokenPath(dataDir), "utf8")).trim(); const digest = (value: string) => createHash("sha256").update(value).digest(); return timingSafeEqual(digest(candidate), digest(expected)); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } } export async function removeSetupToken(dataDir: string): Promise { await unlink(setupTokenPath(dataDir)).catch((error) => { if (error.code !== "ENOENT") throw error; }); } export function validNewPassword(value: unknown): value is string { return ( typeof value === "string" && value.length >= 12 && Buffer.byteLength(value) <= 4096 ); }