Add server: encrypted event log API, blobs, SSE, ECB rates, Web Push
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
This commit is contained in:
parent
c2043b86bc
commit
8dd25b93b0
10 changed files with 1005 additions and 1 deletions
365
apps/server/src/app.ts
Normal file
365
apps/server/src/app.ts
Normal file
|
|
@ -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<string, string> = {
|
||||
'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<string, string> = {
|
||||
'.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<string, string> = {}): 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<Buffer> {
|
||||
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<any> {
|
||||
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<string, { n: number; reset: number }>();
|
||||
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<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 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();
|
||||
}
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue