// Generate VAPID keys and write them into an env file without printing the // private key: `node apps/server/src/gen-vapid.ts deploy/.env`. // Existing VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY lines are kept unless // --force is given (rotating keys invalidates every push subscription). import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; import { generateVapidKeys } from './push.ts'; const file = process.argv[2]; const force = process.argv.includes('--force'); if (!file) { console.error('usage: node gen-vapid.ts [--force]'); process.exit(2); } const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n') : []; const has = (k: string) => lines.some((l) => l.startsWith(`${k}=`) && l.length > k.length + 1); if (has('VAPID_PUBLIC_KEY') && has('VAPID_PRIVATE_KEY') && !force) { console.error(`${file} already has VAPID keys; leaving them alone (use --force to rotate).`); process.exit(0); } const { publicKey, privateKey } = generateVapidKeys(); const kept = lines.filter((l) => !l.startsWith('VAPID_PUBLIC_KEY=') && !l.startsWith('VAPID_PRIVATE_KEY=')); while (kept.length && kept[kept.length - 1] === '') kept.pop(); kept.push(`VAPID_PUBLIC_KEY=${publicKey}`, `VAPID_PRIVATE_KEY=${privateKey}`, ''); writeFileSync(file, kept.join('\n'), { mode: 0o600 }); chmodSync(file, 0o600); console.error(`Wrote VAPID keys to ${file} (private key ${privateKey.length} chars, not shown).`);