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, loadVapidKeys } from '../src/push.ts'; import { parseEcbXml, parseExtraRates } 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' }); store.saveExtraRates('2026-10-09', 'xr', { EUR: '1', CZK: '24.9', ALL: '98.38' }); 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('fills in currencies the ECB lacks from the extra source, ECB first', async () => { const r = await api('GET', '/api/rates?date=2026-10-11'); assert.equal(r.data.rates.ALL, '98.38'); assert.equal(r.data.rates.CZK, '24.4'); assert.deepEqual(r.data.sources, { ALL: 'xr:2026-10-09' }); // A snapshot more than a week old is not used; ECB rates still are. const late = await api('GET', '/api/rates?date=2026-10-20'); assert.equal(late.data.rates.ALL, undefined); assert.equal(late.data.rates.CZK, '24.4'); assert.equal((await api('GET', '/api/rates?date=2026-02-30x')).status, 400); assert.equal((await api('GET', '/api/rates?date=2026-13-45')).status, 400); }); it('parses the extra rates feed', () => { const t = Date.UTC(2026, 10, 6, 0, 2) / 1000; const p = parseExtraRates({ result: 'success', base_code: 'EUR', time_last_update_unix: t, rates: { EUR: 1, ALL: 98.38, BAD: -1, XYZ: 1e-9, lower: 2 } }); assert.deepEqual(p, { date: '2026-11-06', rates: { EUR: '1', ALL: '98.38' } }); assert.throws(() => parseExtraRates({ result: 'error' })); assert.throws(() => parseExtraRates({ result: 'success', base_code: 'USD', time_last_update_unix: t, rates: { EUR: 1 } })); }); 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('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. 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); }); });