diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts new file mode 100644 index 0000000..d58137d --- /dev/null +++ b/apps/server/src/app.ts @@ -0,0 +1,365 @@ +// HTTP API and static file server (SPEC.md §8.1). Plain node:http with a +// small hand-written router; no dependencies. +import { createHash, timingSafeEqual } from 'node:crypto'; +import { createReadStream, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'; +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'; + +const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url +const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/; +const BLOB_ID_RE = /^[A-Za-z0-9_-]{16,64}$/; +const DEVICE_RE = /^[A-Za-z0-9_-]{8,64}$/; +const B64U_RE = /^[A-Za-z0-9_-]+$/; +const HEX64_RE = /^[0-9a-f]{64}$/; + +class HttpError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +const SECURITY_HEADERS: Record = { + 'Content-Security-Policy': [ + "default-src 'self'", + "script-src 'self'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' blob: data:", + "connect-src 'self'", + "worker-src 'self'", + "manifest-src 'self'", + "object-src 'none'", + "base-uri 'none'", + "form-action 'self'", + "frame-ancestors 'none'", + ].join('; '), + 'Referrer-Policy': 'no-referrer', + 'X-Content-Type-Options': 'nosniff', + 'X-Frame-Options': 'DENY', + 'Permissions-Policy': 'camera=(self), geolocation=(), microphone=()', + 'Cross-Origin-Opener-Policy': 'same-origin', +}; + +const MIME: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json', + '.webmanifest': 'application/manifest+json', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', +}; + +function send(res: ServerResponse, status: number, body: unknown, headers: Record = {}): void { + const json = JSON.stringify(body); + res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers }); + res.end(json); +} + +async function readBody(req: IncomingMessage, limit: number): Promise { + const declared = Number(req.headers['content-length'] ?? 0); + if (declared > limit) throw new HttpError(413, 'too large'); + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + size += (chunk as Buffer).length; + if (size > limit) throw new HttpError(413, 'too large'); + chunks.push(chunk as Buffer); + } + return Buffer.concat(chunks); +} + +async function readJson(req: IncomingMessage, limit: number): Promise { + if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new HttpError(415, 'expected JSON'); + try { + return JSON.parse((await readBody(req, limit)).toString('utf8')); + } catch (e) { + if (e instanceof HttpError) throw e; + throw new HttpError(400, 'bad JSON'); + } +} + +const sha256hex = (s: string) => createHash('sha256').update(s).digest('hex'); + +/** Fixed-window rate limiter keyed by client IP. */ +class RateLimiter { + private hits = new Map(); + private readonly max: number; + private readonly windowMs: number; + constructor(max: number, windowMs: number) { + this.max = max; + this.windowMs = windowMs; + } + allow(key: string): boolean { + const now = Date.now(); + if (this.hits.size > 10_000) for (const [k, v] of this.hits) if (v.reset < now) this.hits.delete(k); + const h = this.hits.get(key); + if (!h || h.reset < now) { + this.hits.set(key, { n: 1, reset: now + this.windowMs }); + return true; + } + h.n += 1; + return h.n <= this.max; + } +} + +export function createApp(cfg: Config, store: Store) { + const streams = new Map>(); + 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 blobDir = (g: string) => join(cfg.dataDir, 'blobs', g); + + function clientIp(req: IncomingMessage): string { + if (cfg.trustProxy) { + // Caddy appends the real client address as the last entry. + const xff = String(req.headers['x-forwarded-for'] ?? '').split(',').map((s) => s.trim()).filter(Boolean); + if (xff.length) return xff[xff.length - 1]; + } + return req.socket.remoteAddress ?? '?'; + } + + /** Check the bearer token for a group. Unknown group and wrong token both + * give 404, so the API doesn't reveal which group ids exist. */ + function authorize(req: IncomingMessage, groupId: string) { + if (!ID_RE.test(groupId)) throw new HttpError(404, 'not found'); + const g = store.getGroup(groupId); + const m = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(String(req.headers.authorization ?? '')); + const given = Buffer.from(sha256hex(m?.[1] ?? ''), 'hex'); + const expected = Buffer.from(g?.authHash ?? '0'.repeat(64), 'hex'); + if (!g || !m || !timingSafeEqual(given, expected)) throw new HttpError(404, 'not found'); + return g; + } + + 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; + for (const sub of store.pushSubs(groupId)) { + if (sub.deviceId === deviceId) continue; + void sendPush(sub, { g: groupId }, vapid).then((r) => { + if (r === 'gone') store.deletePush(groupId, sub.endpoint); + }); + } + } + + // ---- route handlers -------------------------------------------------- + + async function createGroup(req: IncomingMessage, res: ServerResponse) { + if (!createLimiter.allow(clientIp(req))) throw new HttpError(429, 'too many groups created, try later'); + const body = await readJson(req, 1024); + if (!ID_RE.test(body?.id) || !HEX64_RE.test(body?.authHash)) throw new HttpError(400, 'bad group'); + if (!store.createGroup(body.id, body.authHash)) throw new HttpError(409, 'exists'); + send(res, 201, { id: body.id }); + } + + function getEvents(req: IncomingMessage, res: ServerResponse, groupId: string, url: URL) { + authorize(req, groupId); + const after = Math.max(0, Number(url.searchParams.get('after') ?? 0) || 0); + const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get('limit') ?? 500) || 500)); + send(res, 200, { events: store.eventsAfter(groupId, after, limit), latest: store.latestSeq(groupId) }); + } + + async function postEvents(req: IncomingMessage, res: ServerResponse, groupId: string) { + const g = authorize(req, groupId); + const body = await readJson(req, 200 * (cfg.maxEventBytes * 1.4 + 512)); + const events = body?.events; + if (!Array.isArray(events) || events.length === 0 || events.length > 200) throw new HttpError(400, 'events must be 1..200'); + let bytes = 0; + for (const e of events) { + if (!EVENT_ID_RE.test(e?.id) || !DEVICE_RE.test(e?.deviceId) || !B64U_RE.test(e?.iv) || !B64U_RE.test(e?.ct) || e.iv.length !== 16) + throw new HttpError(400, 'bad event'); + const size = Math.floor((e.ct.length * 3) / 4); + if (size > cfg.maxEventBytes) throw new HttpError(413, 'event too large'); + bytes += size; + } + if (g.bytes + bytes > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); + const seqs = store.tx(() => { + let next = store.latestSeq(groupId); + const out: number[] = []; + for (const e of events) { + const existing = store.seqOf(groupId, e.id); + if (existing !== undefined) { + out.push(existing); + continue; + } + next += 1; + store.insertEvent(groupId, next, { id: e.id, deviceId: e.deviceId, iv: e.iv, ct: e.ct }); + out.push(next); + } + store.addBytes(groupId, bytes); + return out; + }); + send(res, 200, { seqs }); + notify(groupId, Math.max(...seqs), events[0].deviceId); + } + + function stream(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-store', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', + }); + res.write(`data: ${store.latestSeq(groupId)}\n\n`); + let set = streams.get(groupId); + if (!set) streams.set(groupId, (set = new Set())); + set.add(res); + const ping = setInterval(() => res.write(': ping\n\n'), 25_000); + req.on('close', () => { + clearInterval(ping); + set!.delete(res); + if (set!.size === 0) streams.delete(groupId); + }); + } + + async function putBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) { + const g = authorize(req, groupId); + if (!BLOB_ID_RE.test(blobId)) throw new HttpError(400, 'bad blob id'); + if (store.hasBlob(groupId, blobId)) return send(res, 200, { ok: true }); // immutable; retries are fine + const data = await readBody(req, cfg.maxPhotoBytes); + if (data.length === 0) throw new HttpError(400, 'empty'); + if (g.bytes + data.length > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); + mkdirSync(blobDir(groupId), { recursive: true }); + writeFileSync(join(blobDir(groupId), blobId), data, { flag: 'wx' }); + store.tx(() => { + store.insertBlob(groupId, blobId, data.length); + store.addBytes(groupId, data.length); + }); + send(res, 201, { ok: true }); + } + + function getBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) { + authorize(req, groupId); + if (!BLOB_ID_RE.test(blobId) || !store.hasBlob(groupId, blobId)) throw new HttpError(404, 'not found'); + const path = join(blobDir(groupId), blobId); + res.writeHead(200, { + 'Content-Type': 'application/octet-stream', + 'Content-Length': String(statSync(path).size), + 'Cache-Control': 'private, max-age=31536000, immutable', + }); + createReadStream(path).pipe(res); + } + + async function postPush(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + if (!vapid) throw new HttpError(501, 'push not configured'); + if (!pushLimiter.allow(clientIp(req))) throw new HttpError(429, 'slow down'); + const b = await readJson(req, 4096); + if (!isAllowedEndpoint(b?.endpoint) || b.endpoint.length > 1000) throw new HttpError(400, 'unsupported push service'); + if (!B64U_RE.test(b?.keys?.p256dh) || !B64U_RE.test(b?.keys?.auth) || !DEVICE_RE.test(b?.deviceId)) + throw new HttpError(400, 'bad subscription'); + store.upsertPush(groupId, { endpoint: b.endpoint, p256dh: b.keys.p256dh, auth: b.keys.auth, deviceId: b.deviceId }); + send(res, 200, { ok: true }); + } + + async function deletePush(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + const b = await readJson(req, 4096); + if (typeof b?.endpoint !== 'string') throw new HttpError(400, 'bad endpoint'); + store.deletePush(groupId, b.endpoint); + send(res, 200, { ok: true }); + } + + function deleteGroup(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + store.deleteGroup(groupId); + rmSync(blobDir(groupId), { recursive: true, force: true }); + for (const s of streams.get(groupId) ?? []) s.end(); + streams.delete(groupId); + send(res, 200, { ok: true }); + } + + function rates(res: ServerResponse, url: URL) { + const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpError(400, 'bad date'); + const r = store.ratesOn(date); + if (!r) throw new HttpError(404, 'no rates'); + // Past dates never change; today's may still be published later. + const final = r.date < date || date < new Date().toISOString().slice(0, 10); + send(res, 200, { base: 'EUR', ...r }, { 'Cache-Control': final ? 'public, max-age=86400' : 'public, max-age=900' }); + } + + function serveStatic(req: IncomingMessage, res: ServerResponse, url: URL) { + if (!cfg.staticDir) throw new HttpError(404, 'not found'); + let rel: string; + try { + rel = decodeURIComponent(url.pathname); + } catch { + throw new HttpError(400, 'bad path'); + } + let path = normalize(join(cfg.staticDir, rel)); + if (!path.startsWith(cfg.staticDir + sep) && path !== cfg.staticDir) throw new HttpError(404, 'not found'); + let isFile = existsSync(path) && statSync(path).isFile(); + if (!isFile) { + // SPA fallback for app routes; real missing assets stay 404. + if (extname(rel) !== '') throw new HttpError(404, 'not found'); + rel = '/index.html'; + path = join(cfg.staticDir, 'index.html'); + isFile = true; + } + const cache = rel.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache'; + res.writeHead(200, { + 'Content-Type': MIME[extname(path)] ?? 'application/octet-stream', + 'Content-Length': String(statSync(path).size), + 'Cache-Control': cache, + ...(rel === '/sw.js' ? { 'Service-Worker-Allowed': '/' } : {}), + }); + if (req.method === 'HEAD') return res.end(); + createReadStream(path).pipe(res); + } + + // ---- router ---------------------------------------------------------- + + async function route(req: IncomingMessage, res: ServerResponse) { + const url = new URL(req.url ?? '/', 'http://x'); + const p = url.pathname; + const m = req.method ?? 'GET'; + if (!p.startsWith('/api/')) { + if (m !== 'GET' && m !== 'HEAD') throw new HttpError(405, 'method not allowed'); + return serveStatic(req, res, url); + } + if (p === '/api/health' && m === 'GET') return send(res, 200, { ok: true }); + if (p === '/api/config' && m === 'GET') + 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); + + const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p); + if (g) { + const [, id, rest = ''] = g; + if (rest === '' && m === 'DELETE') return deleteGroup(req, res, id); + if (rest === '/events' && m === 'GET') return getEvents(req, res, id, url); + if (rest === '/events' && m === 'POST') return postEvents(req, res, id); + if (rest === '/stream' && m === 'GET') return stream(req, res, id); + if (rest === '/push' && m === 'POST') return postPush(req, res, id); + if (rest === '/push' && m === 'DELETE') return deletePush(req, res, id); + const b = /^\/blobs\/([^/]+)$/.exec(rest); + if (b && m === 'PUT') return putBlob(req, res, id, b[1]); + if (b && m === 'GET') return getBlob(req, res, id, b[1]); + } + throw new HttpError(404, 'not found'); + } + + return async function handler(req: IncomingMessage, res: ServerResponse) { + for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v); + try { + await route(req, res); + } catch (e) { + const status = e instanceof HttpError ? e.status : 500; + if (status === 500) console.error(`${req.method} ${new URL(req.url ?? '/', 'http://x').pathname}:`, e); + if (!res.headersSent) send(res, status, { error: e instanceof HttpError ? e.message : 'internal error' }); + else res.end(); + } + }; +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts new file mode 100644 index 0000000..c50144e --- /dev/null +++ b/apps/server/src/config.ts @@ -0,0 +1,47 @@ +// All configuration comes from environment variables (see deploy/.env.example). +import { resolve } from 'node:path'; + +function int(env: NodeJS.ProcessEnv, name: string, def: number): number { + const raw = env[name]; + if (raw === undefined || raw === '') return def; + const n = Number(raw); + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`${name} must be a non-negative integer, got "${raw}"`); + return n; +} + +export interface Config { + host: string; + port: number; + dataDir: string; + /** built web client; empty = API only (dev, where Vite serves the client) */ + staticDir: string; + trustProxy: boolean; + maxPhotoBytes: number; + maxEventBytes: number; + maxGroupBytes: number; + groupCreatePerHour: number; + vapidPublicKey: string; + vapidPrivateKey: string; + vapidSubject: string; + ratesEnabled: boolean; + ratesBaseUrl: string; +} + +export function loadConfig(env = process.env): Config { + return { + host: env.HOST || '127.0.0.1', + port: int(env, 'PORT', 8481), + dataDir: resolve(env.DATA_DIR || './data'), + staticDir: env.STATIC_DIR ? resolve(env.STATIC_DIR) : '', + trustProxy: env.TRUST_PROXY === '1', + maxPhotoBytes: int(env, 'MAX_PHOTO_BYTES', 2 * 1024 * 1024), + maxEventBytes: int(env, 'MAX_EVENT_BYTES', 64 * 1024), + maxGroupBytes: int(env, 'MAX_GROUP_BYTES', 200 * 1024 * 1024), + groupCreatePerHour: int(env, 'GROUP_CREATE_PER_HOUR', 10), + vapidPublicKey: env.VAPID_PUBLIC_KEY || '', + vapidPrivateKey: env.VAPID_PRIVATE_KEY || '', + vapidSubject: env.VAPID_SUBJECT || '', + ratesEnabled: env.RATES_DISABLED !== '1', + ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', + }; +} diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts new file mode 100644 index 0000000..c550794 --- /dev/null +++ b/apps/server/src/db.ts @@ -0,0 +1,175 @@ +// SQLite storage. Everything group-related is ciphertext the server cannot +// read; the only plaintext is ids, sizes, timestamps and push endpoints. +import { DatabaseSync } from 'node:sqlite'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; + +export interface StoredEvent { + seq: number; + id: string; + deviceId: string; + iv: string; + ct: string; +} + +export interface PushSub { + endpoint: string; + p256dh: string; + auth: string; + deviceId: string; +} + +export class Store { + readonly db: DatabaseSync; + + constructor(dataDir: string) { + mkdirSync(dataDir, { recursive: true }); + this.db = new DatabaseSync(join(dataDir, 'oweme.sqlite')); + this.db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + CREATE TABLE IF NOT EXISTS groups ( + id TEXT PRIMARY KEY, + auth_hash TEXT NOT NULL, + bytes INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS events ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + id TEXT NOT NULL, + device_id TEXT NOT NULL, + iv TEXT NOT NULL, + ct TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, seq), + UNIQUE (group_id, id) + ); + CREATE TABLE IF NOT EXISTS blobs ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + id TEXT NOT NULL, + size INTEGER NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, id) + ); + CREATE TABLE IF NOT EXISTS push_subs ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + endpoint TEXT NOT NULL, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + device_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, endpoint) + ); + CREATE TABLE IF NOT EXISTS rates ( + date TEXT PRIMARY KEY, + json TEXT NOT NULL + ); + `); + } + + tx(fn: () => T): T { + this.db.exec('BEGIN IMMEDIATE'); + try { + const r = fn(); + this.db.exec('COMMIT'); + return r; + } catch (e) { + this.db.exec('ROLLBACK'); + throw e; + } + } + + createGroup(id: string, authHash: string): boolean { + const r = this.db + .prepare('INSERT OR IGNORE INTO groups (id, auth_hash, created_at) VALUES (?, ?, ?)') + .run(id, authHash, Date.now()); + return r.changes === 1; + } + + getGroup(id: string): { authHash: string; bytes: number } | undefined { + const r = this.db.prepare('SELECT auth_hash, bytes FROM groups WHERE id = ?').get(id) as + | { auth_hash: string; bytes: number } + | undefined; + return r && { authHash: r.auth_hash, bytes: r.bytes }; + } + + deleteGroup(id: string): void { + this.db.prepare('DELETE FROM groups WHERE id = ?').run(id); + } + + addBytes(id: string, n: number): void { + this.db.prepare('UPDATE groups SET bytes = bytes + ? WHERE id = ?').run(n, id); + } + + latestSeq(groupId: string): number { + const r = this.db.prepare('SELECT MAX(seq) AS s FROM events WHERE group_id = ?').get(groupId) as { s: number | null }; + return r.s ?? 0; + } + + eventsAfter(groupId: string, after: number, limit: number): StoredEvent[] { + return this.db + .prepare('SELECT seq, id, device_id AS deviceId, iv, ct FROM events WHERE group_id = ? AND seq > ? ORDER BY seq LIMIT ?') + .all(groupId, after, limit) as unknown as StoredEvent[]; + } + + /** Existing seq for an event id (idempotent retries), if any. */ + seqOf(groupId: string, id: string): number | undefined { + const r = this.db.prepare('SELECT seq FROM events WHERE group_id = ? AND id = ?').get(groupId, id) as { seq: number } | undefined; + return r?.seq; + } + + insertEvent(groupId: string, seq: number, e: Omit): void { + this.db + .prepare('INSERT INTO events (group_id, seq, id, device_id, iv, ct, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)') + .run(groupId, seq, e.id, e.deviceId, e.iv, e.ct, Date.now()); + } + + hasBlob(groupId: string, id: string): boolean { + return !!this.db.prepare('SELECT 1 FROM blobs WHERE group_id = ? AND id = ?').get(groupId, id); + } + + insertBlob(groupId: string, id: string, size: number): void { + this.db.prepare('INSERT INTO blobs (group_id, id, size, created_at) VALUES (?, ?, ?, ?)').run(groupId, id, size, Date.now()); + } + + upsertPush(groupId: string, s: PushSub): void { + this.db + .prepare( + `INSERT INTO push_subs (group_id, endpoint, p256dh, auth, device_id, created_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (group_id, endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, device_id = excluded.device_id`, + ) + .run(groupId, s.endpoint, s.p256dh, s.auth, s.deviceId, Date.now()); + } + + deletePush(groupId: string, endpoint: string): void { + this.db.prepare('DELETE FROM push_subs WHERE group_id = ? AND endpoint = ?').run(groupId, endpoint); + } + + deletePushEverywhere(endpoint: string): void { + this.db.prepare('DELETE FROM push_subs WHERE endpoint = ?').run(endpoint); + } + + pushSubs(groupId: string): PushSub[] { + return this.db + .prepare('SELECT endpoint, p256dh, auth, device_id AS deviceId FROM push_subs WHERE group_id = ?') + .all(groupId) as unknown as PushSub[]; + } + + saveRates(date: string, rates: Record): void { + this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates)); + } + + /** Rates for the latest published date on or before `date`. */ + ratesOn(date: string): { date: string; rates: Record } | undefined { + const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as + | { date: string; json: string } + | undefined; + return r && { date: r.date, rates: JSON.parse(r.json) }; + } + + latestRatesDate(): string | undefined { + const r = this.db.prepare('SELECT MAX(date) AS d FROM rates').get() as { d: string | null }; + return r.d ?? undefined; + } +} diff --git a/apps/server/src/gen-vapid.ts b/apps/server/src/gen-vapid.ts new file mode 100644 index 0000000..091d1e7 --- /dev/null +++ b/apps/server/src/gen-vapid.ts @@ -0,0 +1,28 @@ +// 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).`); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts new file mode 100644 index 0000000..f06049e --- /dev/null +++ b/apps/server/src/main.ts @@ -0,0 +1,30 @@ +import { createServer } from 'node:http'; +import { createApp } from './app.ts'; +import { loadConfig } from './config.ts'; +import { Store } from './db.ts'; +import { RatesService } from './rates.ts'; + +const cfg = loadConfig(); +const store = new Store(cfg.dataDir); +const server = createServer(createApp(cfg, store)); +// SSE connections are long-lived; don't let the default timeouts cut them. +server.requestTimeout = 0; +server.headersTimeout = 30_000; + +const rates = new RatesService(store, cfg.ratesBaseUrl); +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'); +}); + +for (const sig of ['SIGINT', 'SIGTERM'] as const) { + process.on(sig, () => { + rates.stop(); + server.close(); + server.closeAllConnections(); + store.db.close(); + process.exit(0); + }); +} diff --git a/apps/server/src/push.ts b/apps/server/src/push.ts new file mode 100644 index 0000000..c37b77f --- /dev/null +++ b/apps/server/src/push.ts @@ -0,0 +1,105 @@ +// Web Push sender: VAPID (RFC 8292) + aes128gcm payload encryption +// (RFC 8291), using only node:crypto. The payload is just { g: groupId }; +// 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 type { PushSub } from './db.ts'; + +const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url'); +const fromB64u = (s: string) => Buffer.from(s, 'base64url'); + +/** Push services we deliver to. Anything else is refused, so a registered + * "endpoint" can't make the server send requests to arbitrary hosts. */ +const ALLOWED_PUSH_HOSTS = [ + 'fcm.googleapis.com', + 'updates.push.services.mozilla.com', + 'push.services.mozilla.com', + 'web.push.apple.com', + 'notify.windows.com', +]; + +export function isAllowedEndpoint(endpoint: string): boolean { + let u: URL; + try { + u = new URL(endpoint); + } catch { + return false; + } + if (u.protocol !== 'https:' || u.port !== '') return false; + return ALLOWED_PUSH_HOSTS.some((h) => u.hostname === h || u.hostname.endsWith(`.${h}`)); +} + +export function generateVapidKeys(): { publicKey: string; privateKey: string } { + const ecdh = createECDH('prime256v1'); + ecdh.generateKeys(); + return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) }; +} + +export interface Vapid { + publicKey: string; + privateKey: string; + subject: string; +} + +function vapidAuthHeader(endpoint: string, v: Vapid): string { + const pub = fromB64u(v.publicKey); + const key = createPrivateKey({ + key: { kty: 'EC', crv: 'P-256', d: v.privateKey, x: b64u(pub.subarray(1, 33)), y: b64u(pub.subarray(33, 65)) }, + format: 'jwk', + }); + const header = b64u(Buffer.from(JSON.stringify({ typ: 'JWT', alg: 'ES256' }))); + const claims = b64u( + Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: v.subject })), + ); + const sig = sign('sha256', Buffer.from(`${header}.${claims}`), { key, dsaEncoding: 'ieee-p1363' }); + return `vapid t=${header}.${claims}.${b64u(sig)}, k=${v.publicKey}`; +} + +/** RFC 8291 aes128gcm encryption of `plaintext` for one subscription. */ +export function encryptPayload(sub: Pick, plaintext: Buffer): Buffer { + const uaPublic = fromB64u(sub.p256dh); + const authSecret = fromB64u(sub.auth); + const ecdh = createECDH('prime256v1'); + const asPublic = ecdh.generateKeys(); + const shared = ecdh.computeSecret(uaPublic); + const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]); + const ikm = Buffer.from(hkdfSync('sha256', shared, authSecret, keyInfo, 32)); + const salt = randomBytes(16); + const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16)); + const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12)); + const cipher = createCipheriv('aes-128-gcm', cek, nonce); + // 0x02 = padding delimiter for the last (only) record. + const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]); + const rs = Buffer.alloc(4); + rs.writeUInt32BE(4096); + return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]); +} + +/** Send one push. Returns 'gone' if the subscription should be deleted. */ +export async function sendPush(sub: PushSub, payload: object, v: Vapid): Promise<'ok' | 'gone' | 'error'> { + if (!isAllowedEndpoint(sub.endpoint)) return 'gone'; + try { + const res = await fetch(sub.endpoint, { + method: 'POST', + headers: { + Authorization: vapidAuthHeader(sub.endpoint, v), + 'Content-Encoding': 'aes128gcm', + 'Content-Type': 'application/octet-stream', + TTL: String(24 * 3600), + Urgency: 'normal', + }, + body: encryptPayload(sub, Buffer.from(JSON.stringify(payload))), + redirect: 'error', + signal: AbortSignal.timeout(15_000), + }); + if (res.status === 404 || res.status === 410) return 'gone'; + if (!res.ok) { + console.error(`push: ${new URL(sub.endpoint).hostname} HTTP ${res.status}`); + return 'error'; + } + return 'ok'; + } catch (e) { + console.error(`push: ${(e as Error).message}`); + return 'error'; + } +} diff --git a/apps/server/src/rates.ts b/apps/server/src/rates.ts new file mode 100644 index 0000000..e0bc450 --- /dev/null +++ b/apps/server/src/rates.ts @@ -0,0 +1,52 @@ +// ECB daily reference rates (EUR-based). Fetched by the server so that +// clients never contact a third party (SPEC.md §8.2). +import type { Store } from './db.ts'; + +/** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ +export function parseEcbXml(xml: string): Map> { + const out = new Map>(); + const dayRe = /([\s\S]*?)<\/Cube>/g; + const rateRe = //g; + for (const day of xml.matchAll(dayRe)) { + const rates: Record = { EUR: '1' }; + for (const r of day[2].matchAll(rateRe)) rates[r[1]] = r[2]; + out.set(day[1], rates); + } + return out; +} + +export class RatesService { + private timer: NodeJS.Timeout | undefined; + private readonly store: Store; + private readonly baseUrl: string; + + constructor(store: Store, baseUrl: string) { + this.store = store; + this.baseUrl = baseUrl; + } + + async refresh(): Promise { + // Full history the first time (≈8 MB), the last 90 days afterwards. + const file = this.store.latestRatesDate() ? 'eurofxref-hist-90d.xml' : 'eurofxref-hist.xml'; + const res = await fetch(`${this.baseUrl}/${file}`, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) throw new Error(`ECB ${file}: HTTP ${res.status}`); + const days = parseEcbXml(await res.text()); + if (days.size === 0) throw new Error(`ECB ${file}: no rates parsed`); + this.store.tx(() => { + for (const [date, rates] of days) this.store.saveRates(date, rates); + }); + console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); + } + + /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */ + start(): void { + const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`)); + void run(); + this.timer = setInterval(run, 6 * 3600_000); + this.timer.unref(); + } + + stop(): void { + clearInterval(this.timer); + } +} diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts new file mode 100644 index 0000000..e8bfe0c --- /dev/null +++ b/apps/server/test/server.test.ts @@ -0,0 +1,186 @@ +import assert from 'node:assert/strict'; +import { createDecipheriv, createECDH, createHash, hkdfSync, randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +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 { parseEcbXml } from '../src/rates.ts'; + +const b64u = (b: Buffer) => b.toString('base64url'); +const newGroup = () => { + const id = b64u(randomBytes(16)); + const token = b64u(randomBytes(32)); + return { id, token, authHash: createHash('sha256').update(token).digest('hex') }; +}; + +let server: Server; +let base: string; +let dir: string; +let store: Store; + +before(async () => { + dir = mkdtempSync(join(tmpdir(), 'oweme-test-')); + const web = join(dir, 'web'); + mkdirSync(join(web, 'assets'), { recursive: true }); + writeFileSync(join(web, 'index.html'), 'OweMe'); + writeFileSync(join(web, 'assets', 'app-abc.js'), 'console.log(1)'); + const cfg = loadConfig({ + DATA_DIR: join(dir, 'data'), STATIC_DIR: web, MAX_PHOTO_BYTES: '1000', MAX_EVENT_BYTES: '300', + MAX_GROUP_BYTES: '5000', GROUP_CREATE_PER_HOUR: '50', + }); + store = new Store(cfg.dataDir); + store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); + server = createServer(createApp(cfg, store)); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const addr = server.address() as { port: number }; + base = `http://127.0.0.1:${addr.port}`; +}); + +after(() => { + server.closeAllConnections(); + server.close(); + store.db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +async function api(method: string, path: string, opts: { token?: string; json?: unknown; body?: Buffer } = {}) { + const headers: Record = {}; + if (opts.token) headers.Authorization = `Bearer ${opts.token}`; + if (opts.json !== undefined) headers['Content-Type'] = 'application/json'; + const res = await fetch(base + path, { method, headers, body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body }); + const text = await res.text(); + let data: any = text; + try { data = JSON.parse(text); } catch { /* not JSON */ } + return { status: res.status, data, headers: res.headers }; +} + +const event = (id: string, size = 20) => ({ id, deviceId: 'device-123', iv: b64u(randomBytes(12)), ct: b64u(randomBytes(size)) }); + +describe('groups and events', () => { + it('creates a group, rejects duplicates and bad input', async () => { + const g = newGroup(); + assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 201); + assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 409); + assert.equal((await api('POST', '/api/groups', { json: { id: 'short', authHash: g.authHash } })).status, 400); + }); + + it('requires the right token, answering 404 either way', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + assert.equal((await api('GET', `/api/groups/${g.id}/events`)).status, 404); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: newGroup().token })).status, 404); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 200); + }); + + it('appends idempotently and pages by seq', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const r1 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-aaaa'), event('evt-bbbb')] } }); + assert.deepEqual(r1.data.seqs, [1, 2]); + const r2 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-bbbb'), event('evt-cccc')] } }); + assert.deepEqual(r2.data.seqs, [2, 3]); + const r3 = await api('GET', `/api/groups/${g.id}/events?after=1`, { token: g.token }); + assert.deepEqual(r3.data.events.map((e: any) => e.id), ['evt-bbbb', 'evt-cccc']); + assert.equal(r3.data.latest, 3); + }); + + it('enforces event and group size limits', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + assert.equal((await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-big1', 400)] } })).status, 413); + for (let i = 0; i < 17; i++) await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event(`evt-fill${i}`, 290)] } }); + const r = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-over', 290)] } }); + assert.equal(r.status, 507); + }); + + it('streams new seqs over SSE', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const ac = new AbortController(); + const res = await fetch(`${base}/api/groups/${g.id}/stream`, { headers: { Authorization: `Bearer ${g.token}` }, signal: ac.signal }); + const reader = res.body!.getReader(); + const first = new TextDecoder().decode((await reader.read()).value); + assert.match(first, /data: 0/); + await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-live')] } }); + const next = new TextDecoder().decode((await reader.read()).value); + assert.match(next, /data: 1/); + ac.abort(); + }); + + it('stores immutable blobs with a size cap, and deletes everything with the group', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const blob = randomBytes(500); + assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { token: g.token, body: blob })).status, 201); + assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdee`, { token: g.token, body: randomBytes(1001) })).status, 413); + const res = await fetch(`${base}/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { headers: { Authorization: `Bearer ${g.token}` } }); + assert.deepEqual(Buffer.from(await res.arrayBuffer()), blob); + assert.equal((await api('DELETE', `/api/groups/${g.id}`, { token: g.token })).status, 200); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 404); + }); + + it('refuses push endpoints outside known push services', async () => { + assert.equal(isAllowedEndpoint('https://fcm.googleapis.com/fcm/send/abc'), true); + assert.equal(isAllowedEndpoint('https://web.push.apple.com/xyz'), true); + assert.equal(isAllowedEndpoint('https://169.254.169.254/latest'), false); + assert.equal(isAllowedEndpoint('http://fcm.googleapis.com/x'), false); + assert.equal(isAllowedEndpoint('https://fcm.googleapis.com.evil.example/x'), false); + }); +}); + +describe('rates and static', () => { + it('returns the latest rates on or before a date', async () => { + const r = await api('GET', '/api/rates?date=2026-10-11'); + assert.equal(r.status, 200); + assert.equal(r.data.date, '2026-10-08'); + assert.equal(r.data.rates.CZK, '24.4'); + assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404); + }); + + it('parses ECB XML', () => { + const xml = ''; + assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); + }); + + it('serves the SPA with security headers and blocks traversal', async () => { + const r = await api('GET', '/g/abc'); + assert.equal(r.status, 200); + assert.match(r.data, /OweMe/); + assert.match(r.headers.get('content-security-policy')!, /default-src 'self'/); + assert.equal(r.headers.get('referrer-policy'), 'no-referrer'); + assert.equal((await api('GET', '/assets/app-abc.js')).headers.get('cache-control'), 'public, max-age=31536000, immutable'); + assert.equal((await api('GET', '/assets/missing.js')).status, 404); + assert.equal((await api('GET', '/assets/..%2f..%2f..%2f..%2fetc%2fpasswd')).status, 404); + const dots = await api('GET', '/%2e%2e/%2e%2e/etc/passwd'); // URL parser collapses these → SPA fallback + assert.match(dots.data, /OweMe/); + }); +}); + +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. + const ua = createECDH('prime256v1'); + const uaPublic = ua.generateKeys(); + const auth = randomBytes(16); + const body = encryptPayload({ p256dh: b64u(uaPublic), auth: b64u(auth) }, Buffer.from('{"g":"x"}')); + + const salt = body.subarray(0, 16); + const idlen = body[20]; + const asPublic = body.subarray(21, 21 + idlen); + const ct = body.subarray(21 + idlen); + const shared = ua.computeSecret(asPublic); + const ikm = Buffer.from(hkdfSync('sha256', shared, auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]), 32)); + const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16)); + const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12)); + const d = createDecipheriv('aes-128-gcm', cek, nonce); + d.setAuthTag(ct.subarray(ct.length - 16)); + const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]); + assert.equal(plain.subarray(0, -1).toString(), '{"g":"x"}'); + assert.equal(plain[plain.length - 1], 2); + }); +}); diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json new file mode 100644 index 0000000..20153cf --- /dev/null +++ b/apps/server/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023"], + "types": ["node"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "test"] +} diff --git a/package.json b/package.json index 0a43455..4975d5b 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "build": "npm run build -w apps/web", "test": "npm run test:core && npm run test:server", "test:core": "vitest run --root packages/core", - "test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/", + "test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/*.test.ts", "test:e2e": "playwright test", "check": "tsc -p packages/core && tsc -p apps/server && npm run check -w apps/web" },