Node 24 standard library only (node:http, node:sqlite, node:crypto). Push uses VAPID + RFC 8291 encryption with an allowlist of push services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
28 lines
1.4 KiB
TypeScript
28 lines
1.4 KiB
TypeScript
// 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 <env-file> [--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).`);
|