99 lines
3.5 KiB
TypeScript
99 lines
3.5 KiB
TypeScript
/**
|
|
* HTTP plumbing shared by every route module — body reading, origin checks and
|
|
* the JSON response helpers. No bundle state lives here.
|
|
*/
|
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
|
|
/** 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: ((event: string, detail: Record<string, unknown>) => void) | undefined
|
|
|
|
export function setRouteErrorHook(hook: ((event: string, detail: Record<string, unknown>) => void) | undefined): void {
|
|
routeErrorHook = hook
|
|
}
|
|
|
|
/** Collect a request body as UTF-8 text. */
|
|
export async function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise<string> {
|
|
const chunks: Buffer[] = []
|
|
let bytes = 0
|
|
for await (const chunk of req) {
|
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array)
|
|
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: IncomingMessage): boolean {
|
|
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: ServerResponse, status: number, body: unknown): void {
|
|
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: ServerResponse, status: number, message: string, asHtml = false): void {
|
|
try {
|
|
routeErrorHook?.('route.error', { status, error: message, html: asHtml })
|
|
} catch {
|
|
/* diagnostics must never change the response */
|
|
}
|
|
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: IncomingMessage, res: ServerResponse): Promise<Record<string, unknown> | undefined> {
|
|
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: unknown
|
|
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 as Record<string, unknown>
|
|
}
|