/** Largest request body we accept (a settings patch is tiny). */ export const MAX_BODY_BYTES = 64 * 1024; /** Optional diagnostics hook for failed route responses (set by the kernel). */ let routeErrorHook; export function setRouteErrorHook(hook) { routeErrorHook = hook; } /** Collect a request body as UTF-8 text. */ export async function readBody(req, maxBytes = MAX_BODY_BYTES) { const chunks = []; let bytes = 0; for await (const chunk of req) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); bytes += buffer.byteLength; if (bytes > maxBytes) throw new Error('request-too-large'); chunks.push(buffer); } return Buffer.concat(chunks).toString('utf8'); } /** Reject cross-origin browser writes. */ export function sameOrigin(req) { const origin = req.headers.origin; const host = req.headers.host; if (origin === undefined || host === undefined) return true; return origin === `http://${host}` || origin === `https://${host}`; } /** Emit one JSON response with no caching. */ export function json(res, status, body) { const text = JSON.stringify(body); res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(text), }); res.end(text); } /** Emit a plain-text error (page route) or JSON error (API routes). */ export function fail(res, status, message, asHtml = false) { try { routeErrorHook?.('route.error', { status, error: message, html: asHtml }); } catch { /* diagnostics must never change the response */ } const text = asHtml ? `云端记忆${message}` : JSON.stringify({ ok: false, error: message }); res.writeHead(status, { 'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8', 'cache-control': 'no-store', }); res.end(text); } /** * Read one JSON object body, or answer the request and return undefined. * * The method, origin and content-type gates live here so every write route * cannot forget one of them. */ export async function jsonBody(req, res) { if (req.method !== 'POST' && req.method !== 'PUT') { fail(res, 405, 'method-not-allowed'); return undefined; } if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return undefined; } const type = (req.headers['content-type'] ?? '').toLowerCase(); if (!type.startsWith('application/json')) { fail(res, 415, 'json-required'); return undefined; } let parsed; try { parsed = JSON.parse(await readBody(req)); } catch (error) { fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json'); return undefined; } if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { fail(res, 400, 'invalid-body'); return undefined; } return parsed; }