// Tooling only; no Node imports are used by the capsule. import { generateKeyPairSync } from "node:crypto"; import { readFileSync, writeFileSync } from "node:fs"; const subject = process.argv[2]; if (!subject || !/^(mailto:[^\s@]+@[^\s@]+|https:\/\/[^\s]+)$/.test(subject)) { throw new Error("Usage: node scripts/setup-push.mjs "); } const path = new URL("../.env.lakebed.server", import.meta.url); let existing = ""; try { existing = readFileSync(path, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; } if (/^\s*(?:export\s+)?PUSH_VAPID_/m.test(existing)) throw new Error("Push keys already exist. Keep them: rotating keys invalidates existing subscriptions."); const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); const publicJwk = publicKey.export({ format: "jwk" }); const rawPublic = Buffer.concat([Buffer.from([4]), Buffer.from(publicJwk.x, "base64url"), Buffer.from(publicJwk.y, "base64url")]); writeFileSync(path, `${existing}${existing.endsWith("\n") || !existing ? "" : "\n"}PUSH_VAPID_SUBJECT=${subject}\nPUSH_VAPID_PUBLIC_KEY=${rawPublic.toString("base64url")}\nPUSH_VAPID_PRIVATE_JWK=${JSON.stringify(privateKey.export({ format: "jwk" }))}\n`, { mode: 0o600 }); console.log("Push keys saved to .env.lakebed.server (gitignored). Keep a secure backup and use the same keys for future deployments.");