| 1 | import { createHash } from 'node:crypto'; |
| 2 | export class RequestBodyError extends Error { |
| 3 | status; |
| 4 | constructor(message, status) { |
| 5 | super(message); |
| 6 | this.status = status; |
| 7 | } |
| 8 | } |
| 9 | /** Bound memory while draining oversized requests so the route can return 413. */ |
| 10 | export async function readJsonRequest(req, maxBytes = 1_000_000) { |
| 11 | const raw = await new Promise((resolve, reject) => { |
| 12 | let size = 0; |
| 13 | let settled = false; |
| 14 | const chunks = []; |
| 15 | const finish = (error) => { |
| 16 | if (settled) |
| 17 | return; |
| 18 | settled = true; |
| 19 | req.off('data', onData); |
| 20 | req.off('end', onEnd); |
| 21 | req.off('aborted', onAborted); |
| 22 | req.off('error', onError); |
| 23 | if (error) { |
| 24 | chunks.length = 0; |
| 25 | // IncomingMessage may still receive data; discard it without buffering. |
| 26 | req.once('error', () => { }); |
| 27 | req.resume(); |
| 28 | reject(error); |
| 29 | } |
| 30 | else { |
| 31 | resolve(Buffer.concat(chunks).toString('utf8')); |
| 32 | } |
| 33 | }; |
| 34 | const onData = (chunk) => { |
| 35 | const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 36 | size += part.length; |
| 37 | if (size > maxBytes) |
| 38 | finish(new RequestBodyError('request body is too large', 413)); |
| 39 | else |
| 40 | chunks.push(part); |
| 41 | }; |
| 42 | const onEnd = () => finish(); |
| 43 | const onAborted = () => finish(new RequestBodyError('request body was aborted', 400)); |
| 44 | const onError = () => finish(new RequestBodyError('invalid request body', 400)); |
| 45 | req.on('data', onData); |
| 46 | req.once('end', onEnd); |
| 47 | req.once('aborted', onAborted); |
| 48 | req.once('error', onError); |
| 49 | }); |
| 50 | let value; |
| 51 | try { |
| 52 | value = raw.trim() === '' ? {} : JSON.parse(raw); |
| 53 | } |
| 54 | catch { |
| 55 | throw new RequestBodyError('invalid JSON', 400); |
| 56 | } |
| 57 | if (typeof value !== 'object' || value === null || Array.isArray(value)) { |
| 58 | throw new RequestBodyError('body must be an object', 400); |
| 59 | } |
| 60 | return value; |
| 61 | } |
| 62 | function matchesEntityTagList(header, tag) { |
| 63 | if (header === undefined) |
| 64 | return false; |
| 65 | if (header.trim() === '*') |
| 66 | return true; |
| 67 | // A comma can be part of the quoted opaque tag. Consume whole list entries |
| 68 | // and compare their quoted values, accepting either weak or strong spelling. |
| 69 | const entry = /[ \t]*(?:(?:W\/)?("[\x21\x23-\x7e\x80-\xff]*"))?[ \t]*(?:,|$)/y; |
| 70 | let matched = false; |
| 71 | while (entry.lastIndex < header.length) { |
| 72 | const parsed = entry.exec(header); |
| 73 | if (parsed === null) |
| 74 | return false; |
| 75 | matched ||= parsed[1] === tag; |
| 76 | } |
| 77 | return matched; |
| 78 | } |
| 79 | /** Revalidate a current JSON representation across both identity and gzip delivery. */ |
| 80 | export function writeJsonWithEtag(req, res, body) { |
| 81 | const tag = `"${createHash('sha256').update(body).digest('base64url')}"`; |
| 82 | const headers = { 'cache-control': 'no-store', etag: `W/${tag}` }; |
| 83 | if ((req.method === 'GET' || req.method === 'HEAD') |
| 84 | && matchesEntityTagList(req.headers['if-none-match'], tag)) { |
| 85 | res.writeHead(304, headers); |
| 86 | res.end(); |
| 87 | return; |
| 88 | } |
| 89 | res.writeHead(200, { ...headers, 'content-type': 'application/json; charset=utf-8' }); |
| 90 | res.end(body); |
| 91 | } |
| 92 | /** Raw WebServer routes do not inherit Connection's authentication fence. */ |
| 93 | export function authenticatedWebRoutes(server, connection) { |
| 94 | return { |
| 95 | register(route) { |
| 96 | return server.register({ |
| 97 | ...route, |
| 98 | async handler(req, res) { |
| 99 | const gate = connection(); |
| 100 | // Missing/disposing Connection is an assembly failure, never an |
| 101 | // invitation to expose workspace state or accept plan mutations. |
| 102 | const rejection = gate === undefined ? 503 : gate.requestRejection(req); |
| 103 | if (rejection !== undefined) { |
| 104 | res.writeHead(rejection, { |
| 105 | 'content-type': 'application/json; charset=utf-8', |
| 106 | 'cache-control': 'no-store', |
| 107 | }); |
| 108 | res.end(JSON.stringify({ error: rejection === 503 ? 'authentication unavailable' |
| 109 | : rejection === 401 ? 'unauthorized' : 'forbidden' })); |
| 110 | return; |
| 111 | } |
| 112 | await route.handler(req, res); |
| 113 | }, |
| 114 | }); |
| 115 | }, |
| 116 | }; |
| 117 | } |
| 118 |