dsh-brain/lib/http.js

79 lines
2.8 KiB
JavaScript

/** Largest request body we accept (a settings patch is tiny). */
export const MAX_BODY_BYTES = 64 * 1024;
/** 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) {
const text = asHtml
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
: 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;
}