Make the deploy panel-friendly: zero-config compose, env vars with defaults
- compose.yaml runs only the app by default; Caddy moved to the
'standalone' profile (the panel brings its own Caddy and routes).
- No env_file: every setting is ${VAR:-default} in compose.yaml, so it
can be set from the panel's Environment tab (or .env standalone).
- VAPID keys are generated on first start and kept in the data volume;
the push subject defaults to https://<site domain>. gen-vapid.ts removed.
- PUSH_DISABLED=1 turns push off.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
This commit is contained in:
parent
1382e53359
commit
04d952872d
11 changed files with 191 additions and 152 deletions
|
|
@ -6,7 +6,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
|
|||
import { extname, join, normalize, sep } from 'node:path';
|
||||
import type { Config } from './config.ts';
|
||||
import type { Store } from './db.ts';
|
||||
import { isAllowedEndpoint, sendPush, type Vapid } from './push.ts';
|
||||
import { isAllowedEndpoint, loadVapidKeys, sendPush, type Vapid } from './push.ts';
|
||||
|
||||
const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url
|
||||
const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/;
|
||||
|
|
@ -114,10 +114,9 @@ export function createApp(cfg: Config, store: Store) {
|
|||
const streams = new Map<string, Set<ServerResponse>>();
|
||||
const createLimiter = new RateLimiter(cfg.groupCreatePerHour, 3600_000);
|
||||
const pushLimiter = new RateLimiter(60, 3600_000);
|
||||
const vapid: Vapid | null =
|
||||
cfg.vapidPublicKey && cfg.vapidPrivateKey && cfg.vapidSubject
|
||||
? { publicKey: cfg.vapidPublicKey, privateKey: cfg.vapidPrivateKey, subject: cfg.vapidSubject }
|
||||
: null;
|
||||
const keys = cfg.pushEnabled ? loadVapidKeys(cfg.dataDir, cfg.vapidPublicKey, cfg.vapidPrivateKey) : null;
|
||||
if (keys) console.log(`push: VAPID keys from ${keys.source}`);
|
||||
const vapid: Vapid | null = keys ? { publicKey: keys.publicKey, privateKey: keys.privateKey, subject: cfg.vapidSubject } : null;
|
||||
const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g);
|
||||
|
||||
function clientIp(req: IncomingMessage): string {
|
||||
|
|
@ -141,9 +140,18 @@ export function createApp(cfg: Config, store: Store) {
|
|||
return g;
|
||||
}
|
||||
|
||||
// Push services want a contact URL in the VAPID token. Without
|
||||
// VAPID_SUBJECT, use the public site address the requests arrive on.
|
||||
function rememberOrigin(req: IncomingMessage) {
|
||||
if (!vapid || cfg.vapidSubject) return;
|
||||
const fwd = cfg.trustProxy ? req.headers['x-forwarded-host'] : undefined;
|
||||
const host = String(fwd ?? req.headers.host ?? '').split(',')[0].trim().toLowerCase();
|
||||
if (/^[a-z0-9.-]+\.[a-z]{2,}(:\d+)?$/.test(host) && !host.startsWith('localhost')) vapid.subject = `https://${host}`;
|
||||
}
|
||||
|
||||
function notify(groupId: string, seq: number, deviceId: string): void {
|
||||
for (const res of streams.get(groupId) ?? []) res.write(`data: ${seq}\n\n`);
|
||||
if (!vapid) return;
|
||||
if (!vapid?.subject) return;
|
||||
for (const sub of store.pushSubs(groupId)) {
|
||||
if (sub.deviceId === deviceId) continue;
|
||||
void sendPush(sub, { g: groupId }, vapid).then((r) => {
|
||||
|
|
@ -336,6 +344,7 @@ export function createApp(cfg: Config, store: Store) {
|
|||
return send(res, 200, { vapidPublicKey: vapid?.publicKey ?? null, maxPhotoBytes: cfg.maxPhotoBytes, maxGroupBytes: cfg.maxGroupBytes });
|
||||
if (p === '/api/rates' && m === 'GET') return rates(res, url);
|
||||
if (p === '/api/groups' && m === 'POST') return createGroup(req, res);
|
||||
rememberOrigin(req);
|
||||
|
||||
const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p);
|
||||
if (g) {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export interface Config {
|
|||
vapidPublicKey: string;
|
||||
vapidPrivateKey: string;
|
||||
vapidSubject: string;
|
||||
pushEnabled: boolean;
|
||||
ratesEnabled: boolean;
|
||||
ratesBaseUrl: string;
|
||||
}
|
||||
|
|
@ -41,6 +42,7 @@ export function loadConfig(env = process.env): Config {
|
|||
vapidPublicKey: env.VAPID_PUBLIC_KEY || '',
|
||||
vapidPrivateKey: env.VAPID_PRIVATE_KEY || '',
|
||||
vapidSubject: env.VAPID_SUBJECT || '',
|
||||
pushEnabled: env.PUSH_DISABLED !== '1',
|
||||
ratesEnabled: env.RATES_DISABLED !== '1',
|
||||
ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref',
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
// Generate VAPID keys and write them into an env file without printing the
|
||||
// private key: `node apps/server/src/gen-vapid.ts .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).`);
|
||||
|
|
@ -16,7 +16,7 @@ if (cfg.ratesEnabled) rates.start();
|
|||
|
||||
server.listen(cfg.port, cfg.host, () => {
|
||||
console.log(`oweme server on http://${cfg.host}:${cfg.port}` + (cfg.staticDir ? ` serving ${cfg.staticDir}` : ' (API only)'));
|
||||
if (!cfg.vapidPublicKey) console.log('push notifications disabled: VAPID_* not set');
|
||||
if (!cfg.pushEnabled) console.log('push notifications disabled (PUSH_DISABLED=1)');
|
||||
});
|
||||
|
||||
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
// the service worker fetches and decrypts the actual events itself, so the
|
||||
// push service never sees content (SPEC.md §7.7).
|
||||
import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { PushSub } from './db.ts';
|
||||
|
||||
const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url');
|
||||
|
|
@ -35,6 +37,23 @@ export function generateVapidKeys(): { publicKey: string; privateKey: string } {
|
|||
return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) };
|
||||
}
|
||||
|
||||
/**
|
||||
* VAPID keys from the environment if both are set, otherwise generated once
|
||||
* and kept in the data directory, so push works without any configuration.
|
||||
* Deleting vapid.json rotates them (and invalidates every subscription).
|
||||
*/
|
||||
export function loadVapidKeys(dataDir: string, envPublic: string, envPrivate: string): { publicKey: string; privateKey: string; source: string } {
|
||||
if (envPublic && envPrivate) return { publicKey: envPublic, privateKey: envPrivate, source: 'environment' };
|
||||
const file = join(dataDir, 'vapid.json');
|
||||
if (existsSync(file)) {
|
||||
const k = JSON.parse(readFileSync(file, 'utf8'));
|
||||
if (typeof k.publicKey === 'string' && typeof k.privateKey === 'string') return { ...k, source: file };
|
||||
}
|
||||
const k = generateVapidKeys();
|
||||
writeFileSync(file, JSON.stringify(k), { mode: 0o600, flag: 'wx' });
|
||||
return { ...k, source: `${file} (new)` };
|
||||
}
|
||||
|
||||
export interface Vapid {
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { after, before, describe, it } from 'node:test';
|
|||
import { createApp } from '../src/app.ts';
|
||||
import { loadConfig } from '../src/config.ts';
|
||||
import { Store } from '../src/db.ts';
|
||||
import { encryptPayload, isAllowedEndpoint } from '../src/push.ts';
|
||||
import { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.ts';
|
||||
import { parseEcbXml } from '../src/rates.ts';
|
||||
|
||||
const b64u = (b: Buffer) => b.toString('base64url');
|
||||
|
|
@ -161,6 +161,23 @@ describe('rates and static', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('vapid keys', () => {
|
||||
it('generates keys once and keeps them in the data dir', () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'oweme-vapid-'));
|
||||
const a = loadVapidKeys(d, '', '');
|
||||
const b = loadVapidKeys(d, '', '');
|
||||
assert.equal(a.publicKey, b.publicKey);
|
||||
assert.match(a.publicKey, /^[A-Za-z0-9_-]{87}$/);
|
||||
assert.equal(loadVapidKeys(d, 'pub', 'priv').publicKey, 'pub'); // env wins
|
||||
rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('exposes the public key without any configuration', async () => {
|
||||
const r = await api('GET', '/api/config');
|
||||
assert.match(r.data.vapidPublicKey, /^[A-Za-z0-9_-]{87}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('web push encryption', () => {
|
||||
it('produces an RFC 8291 payload the browser side can decrypt', () => {
|
||||
// Play the browser: generate a subscription key pair and auth secret.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue