omnicell-router 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/backend/dist/auth/api-keys.js +11 -0
  2. package/backend/dist/auth/key-models.d.ts +36 -0
  3. package/backend/dist/auth/key-models.js +99 -0
  4. package/backend/dist/cli/clients/activity.js +2 -0
  5. package/backend/dist/cli/clients/codex.d.ts +70 -0
  6. package/backend/dist/cli/clients/codex.js +470 -57
  7. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  8. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  9. package/backend/dist/cli/clients/opencode.js +3 -2
  10. package/backend/dist/cli/clients/reserved.js +2 -0
  11. package/backend/dist/cli/types.d.ts +9 -0
  12. package/backend/dist/config/comments-en.js +5 -1
  13. package/backend/dist/config/comments-zh.js +5 -1
  14. package/backend/dist/config/defaults.d.ts +98 -1
  15. package/backend/dist/config/defaults.js +98 -1
  16. package/backend/dist/config/index.d.ts +15 -1
  17. package/backend/dist/config/index.js +35 -1
  18. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  19. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  20. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  21. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  22. package/backend/dist/config/schema.d.ts +3 -3
  23. package/backend/dist/config/schema.js +8 -4
  24. package/backend/dist/config/types.d.ts +54 -3
  25. package/backend/dist/forward-proxy/egress.js +13 -0
  26. package/backend/dist/forward-proxy/h2-forward.js +6 -5
  27. package/backend/dist/forward-proxy/index.js +5 -0
  28. package/backend/dist/forward-proxy/server.d.ts +12 -0
  29. package/backend/dist/forward-proxy/server.js +113 -15
  30. package/backend/dist/index.js +6 -1
  31. package/backend/dist/ir/adapters/openai-chat.js +5 -3
  32. package/backend/dist/ir/adapters/openai-responses-output.js +2 -2
  33. package/backend/dist/ir/adapters/openai-responses.d.ts +33 -0
  34. package/backend/dist/ir/adapters/openai-responses.js +44 -2
  35. package/backend/dist/ir/capabilities.js +4 -0
  36. package/backend/dist/ir/validate.d.ts +24 -0
  37. package/backend/dist/ir/validate.js +113 -63
  38. package/backend/dist/opencode/catalog/auto-pull.js +8 -7
  39. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  40. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  41. package/backend/dist/opencode/catalog/overrides-store.d.ts +5 -3
  42. package/backend/dist/opencode/catalog/overrides-store.js +22 -19
  43. package/backend/dist/opencode/catalog/repository.js +3 -3
  44. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  45. package/backend/dist/opencode/catalog/sources/models-dev.js +29 -11
  46. package/backend/dist/opencode/catalog/types.d.ts +7 -9
  47. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  48. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  49. package/backend/dist/opencode/migrate/engine.js +71 -0
  50. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  51. package/backend/dist/opencode/migrate/migrator.js +6 -0
  52. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  53. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  54. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  55. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  56. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  57. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  58. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  59. package/backend/dist/opencode/provider-defs.js +45 -45
  60. package/backend/dist/opencode/user-config.d.ts +23 -26
  61. package/backend/dist/opencode/user-config.js +95 -77
  62. package/backend/dist/pipeline/orchestrator.js +17 -7
  63. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  64. package/backend/dist/plugins/host.d.ts +2 -2
  65. package/backend/dist/plugins/host.js +15 -12
  66. package/backend/dist/providers/boot-direct.js +32 -8
  67. package/backend/dist/providers/dial-wire.d.ts +17 -0
  68. package/backend/dist/providers/dial-wire.js +49 -0
  69. package/backend/dist/providers/protocols-field.d.ts +24 -0
  70. package/backend/dist/providers/protocols-field.js +66 -0
  71. package/backend/dist/providers/registry.d.ts +3 -1
  72. package/backend/dist/providers/registry.js +23 -7
  73. package/backend/dist/quota/cli-login.js +3 -1
  74. package/backend/dist/routes/console.js +115 -95
  75. package/backend/dist/server.js +91 -2
  76. package/backend/dist/surfaces/anthropic.js +4 -1
  77. package/backend/dist/surfaces/body-admission.d.ts +279 -0
  78. package/backend/dist/surfaces/body-admission.js +613 -0
  79. package/backend/dist/surfaces/transport-node-http.d.ts +44 -5
  80. package/backend/dist/surfaces/transport-node-http.js +86 -13
  81. package/backend/dist/utils/server-liveness.d.ts +27 -0
  82. package/backend/dist/utils/server-liveness.js +31 -0
  83. package/frontend/dist/assets/{index-55VVwfFQ.js → index-Dk76uc7e.js} +367 -366
  84. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-KI1OW5x6.css} +1 -1
  85. package/frontend/dist/index.html +2 -2
  86. package/package.json +1 -1
@@ -0,0 +1,613 @@
1
+ /**
2
+ * Body admission — the ONE place that decides what the gateway accepts as a
3
+ * request body, and what it says when it refuses.
4
+ *
5
+ * WHY THIS MODULE EXISTS: before it, "what is the body limit" was written in
6
+ * four places (the Fastify route option, the node-http read loop, the h2 preface
7
+ * buffer, and a local `MiB` literal used to format the message) and "what does a
8
+ * rejection look like" in two (the surface envelope on the native leg, a bare
9
+ * string on the MITM leg). That is exactly how the original bug happened: the
10
+ * native leg silently inherited Fastify's 1 MiB framework default while the MITM
11
+ * leg admitted 32 MB, so the SAME request from the SAME client was 413 on one
12
+ * path and 200 on the other. Numbers, messages and envelopes now come from here.
13
+ *
14
+ * THE TIERS (values declared in config/defaults.ts, never re-declared here):
15
+ * - inference GATEWAY_MAX_BODY_BYTES — both inference legs;
16
+ * - admin ADMIN_MAX_BODY_BYTES — the Fastify instance default, so no
17
+ * console/API route can silently inherit 1 MiB;
18
+ * - upload IMPORT_BODY_LIMIT_BYTES / PLUGIN_PACKAGE_MAX_BYTES — declared
19
+ * per route, because those bodies are archives, not prompts.
20
+ *
21
+ * COMPRESSION: a client may send the body gzipped/deflate/br. Two things follow,
22
+ * both handled here so both legs behave identically:
23
+ * 1. the cap bounds the DECOMPRESSED body (Fastify measures the stream a
24
+ * `preParsing` hook returns; the MITM leg passes `maxOutputLength` to zlib),
25
+ * so a compressed bomb cannot inflate past the limit;
26
+ * 2. an encoding we cannot decode is an explicit 415, never a silent
27
+ * pass-through that surfaces as a misleading "Invalid JSON body" 400.
28
+ */
29
+ import { brotliDecompressSync, createBrotliDecompress, createGunzip, createInflate, gunzipSync, inflateRawSync, inflateSync, } from 'node:zlib';
30
+ import { ADMIN_MAX_BODY_BYTES, GATEWAY_MAX_BODY_BYTES, REQUEST_BODY_IDLE_TIMEOUT_MS } from '../config/defaults.js';
31
+ /** Bytes per MiB — declared once so no consumer writes `1024 * 1024` inline. */
32
+ export const BYTES_PER_MIB = 1024 * 1024;
33
+ /**
34
+ * A body that will not be admitted. It carries its own HTTP status and surface
35
+ * `code` so BOTH legs answer identically: the Fastify route `errorHandler` reads
36
+ * `statusCode`/`code` off the error, the node-http adapter passes the same pair
37
+ * to `sendPreDispatchError`. Neither leg keeps a private message template.
38
+ *
39
+ * `headers` carries the negotiation headers RFC 9110 tells a rejecting server it
40
+ * MAY/CAN send (see ACCEPT_ENCODING_ADVERTISEMENT / ACCEPT_MEDIA_ADVERTISEMENT):
41
+ * they ride on the error, not on the senders, so an admission refusal answers them
42
+ * on both legs and no other 4xx accidentally grows them.
43
+ */
44
+ export class BodyAdmissionError extends Error {
45
+ statusCode;
46
+ code;
47
+ headers;
48
+ constructor(statusCode, code, message, headers) {
49
+ super(message);
50
+ this.name = 'BodyAdmissionError';
51
+ this.statusCode = statusCode;
52
+ this.code = code;
53
+ this.headers = headers ?? admissionNegotiationHeaders(code);
54
+ }
55
+ }
56
+ /** 33554432 -> "32 MiB"; 512000 -> "500 KiB". Whole units only: a limit stated
57
+ * as "33554432 bytes" is never actionable for a human reading a 413. */
58
+ export function formatByteLimit(bytes) {
59
+ if (bytes >= BYTES_PER_MIB && bytes % BYTES_PER_MIB === 0)
60
+ return `${bytes / BYTES_PER_MIB} MiB`;
61
+ if (bytes >= 1024 && bytes % 1024 === 0)
62
+ return `${bytes / 1024} KiB`;
63
+ return `${bytes} bytes`;
64
+ }
65
+ /** The 413 sentence, shared by the native leg, the MITM leg and the h2 preface
66
+ * guard. Names the author (the gateway), the number, and the fix.
67
+ *
68
+ * No `Retry-After` is sent on purpose: RFC 9110 15.5.14 defines that header for
69
+ * when "the request condition is likely to be temporary" (rate limits, maintenance
70
+ * windows). An oversized body is not temporary — it stays oversized until the
71
+ * client changes the request — so a delay would only invite pointless retries of
72
+ * the same refusal. */
73
+ export function bodyTooLargeMessage(capBytes) {
74
+ return (`OmniCellRouter: request body exceeds the gateway limit of ${formatByteLimit(capBytes)}. ` +
75
+ 'Shorten the conversation history, or reference large media by URL/file id instead of inlining base64.');
76
+ }
77
+ /**
78
+ * The admission caps THIS process enforces. They start at the shipped constants and
79
+ * are replaced once at boot by `configureBodyLimits` from `client.bodyLimits`, so a
80
+ * build with no config (standalone CLI, a test that boots a bare server) behaves
81
+ * exactly as it did before the knobs existed.
82
+ *
83
+ * Boot-frozen on purpose, not by omission: Fastify reads a route's `bodyLimit` at
84
+ * REGISTRATION time, and a request already being parsed cannot be policed against a
85
+ * number that changed mid-flight. A new value therefore applies on the next
86
+ * controlled restart (ADR-0007), which is also the only moment the h2 preface and
87
+ * MITM drain guards are re-sized. Reading the caps through these two accessors —
88
+ * instead of importing the constants at each site — is what keeps the six admission
89
+ * legs on ONE number, which is the whole point of this module.
90
+ */
91
+ let effectiveGatewayCap = GATEWAY_MAX_BODY_BYTES;
92
+ let effectiveAdminCap = ADMIN_MAX_BODY_BYTES;
93
+ /** Install the configured caps (called once from `createServer`) and return what
94
+ * will actually be enforced, so the caller can log the effective number. Junk
95
+ * (non-finite, <= 0) falls back to the shipped constant: the cleaner in
96
+ * `resolveBodyLimits` already clamps a loaded file, so this is the guard for a
97
+ * hand-built config object, not a second policy. */
98
+ export function configureBodyLimits(limits) {
99
+ const sane = (value, fallback) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
100
+ effectiveGatewayCap = sane(limits?.maxBytes, GATEWAY_MAX_BODY_BYTES);
101
+ effectiveAdminCap = sane(limits?.adminMaxBytes, ADMIN_MAX_BODY_BYTES);
102
+ return { maxBytes: effectiveGatewayCap, adminMaxBytes: effectiveAdminCap };
103
+ }
104
+ /** The enforced cap of one plane. Read at call time, never captured at module load. */
105
+ export function bodyLimitFor(plane) {
106
+ return plane === 'admin' ? effectiveAdminCap : effectiveGatewayCap;
107
+ }
108
+ export function payloadTooLarge(capBytes = bodyLimitFor('gateway')) {
109
+ return new BodyAdmissionError(413, 'payload_too_large', bodyTooLargeMessage(capBytes));
110
+ }
111
+ /**
112
+ * A body that stopped arriving. 408 (RFC 9110 15.5.9), NOT another 413: nothing is
113
+ * oversized on this path, and the two verdicts ask the client for opposite fixes —
114
+ * shrink the payload versus send the same one again. `connection: close` rides with
115
+ * it because a stalled connection is exactly the thing we are reaping.
116
+ */
117
+ export function requestBodyTimeout(idleMs = REQUEST_BODY_IDLE_TIMEOUT_MS) {
118
+ return new BodyAdmissionError(408, 'request_body_timeout', `OmniCellRouter: the request body stalled — no bytes arrived for ${Math.round(idleMs / 1000)}s. Retry the request, or raise the client's write timeout.`, { connection: 'close' });
119
+ }
120
+ /** A body that arrived as text but is not JSON. Lives here so both legs use the
121
+ * same words as Fastify's own parser-failure path. */
122
+ export function invalidJsonBody() {
123
+ return new BodyAdmissionError(400, 'invalid_json_body', 'Invalid JSON body');
124
+ }
125
+ /**
126
+ * Content encodings this gateway decodes on the way IN. gzip/deflate/br are what
127
+ * agent SDKs actually send (the Anthropic SDK gzips system-prompt-heavy requests;
128
+ * opencode does it for large bodies). `zstd` is deliberately absent — Node ships
129
+ * no zstd binding — and an undecodable body must be refused by name rather than
130
+ * parsed as garbage.
131
+ */
132
+ const DECODABLE_ENCODINGS = new Set(['gzip', 'x-gzip', 'deflate', 'br']);
133
+ /**
134
+ * What we advertise as acceptable request codings, derived from the decode table
135
+ * so the advertisement and the decoder cannot drift. `x-gzip` is the same coding
136
+ * under a legacy name, so it is not advertised; `identity` needs no mention
137
+ * (RFC 9110 8.4.1: a coding token of `identity` is always acceptable).
138
+ *
139
+ * RFC 9110 15.5.16: a 415 response "CAN" list what the server accepts. The coding
140
+ * refusal is the 415 where that list is Content-Encoding, and 8.4.1 is explicit
141
+ * that the media-type 415 MUST NOT carry it — "an incorrectly generated
142
+ * Accept-Encoding header field would be interpreted by the client as an
143
+ * indication that the server supports the listed content codings" — which is why
144
+ * this header rides on the error object instead of on the shared send path.
145
+ */
146
+ export const ACCEPT_ENCODING_ADVERTISEMENT = [...DECODABLE_ENCODINGS]
147
+ .filter((coding) => coding !== 'x-gzip')
148
+ .join(', ');
149
+ /** The media-type 415 gets the other half of the same sentence: the media type
150
+ * whose body we will actually parse. `text/plain` is tolerated in the parser but
151
+ * not advertised, because it is a mis-declaration allowance, not a contract. */
152
+ export const ACCEPT_MEDIA_ADVERTISEMENT = 'application/json';
153
+ /** The codings a client may declare on the way in — the same table the decoders
154
+ * use, so the 415 message and the Accept-Encoding advertisement cannot drift. */
155
+ export const SUPPORTED_REQUEST_CODINGS = [...DECODABLE_ENCODINGS].filter((coding) => coding !== 'x-gzip');
156
+ /**
157
+ * The two headers a rejecting gateway is allowed to advertise, keyed by the code
158
+ * that fired. RFC 9110 15.5.16: a 415 "MUST NOT include a Content-Encoding"-family
159
+ * negotiation field for the rejected payload — it may include `Accept`; 12.5.3
160
+ * gives `Accept-Encoding` to the coding refusal. Attaching the wrong one is not
161
+ * cosmetic: `Accept-Encoding` on a 415 tells the client the media type was fine.
162
+ *
163
+ * Returns undefined for the codes that negotiate nothing (413, 400), so the send
164
+ * sites never have to know which code means what.
165
+ */
166
+ export function admissionNegotiationHeaders(code) {
167
+ if (code === 'unsupported_content_encoding')
168
+ return { 'accept-encoding': ACCEPT_ENCODING_ADVERTISEMENT };
169
+ if (code === 'unsupported_media_type')
170
+ return { accept: ACCEPT_MEDIA_ADVERTISEMENT };
171
+ return undefined;
172
+ }
173
+ /** True when the client declared `Expect: 100-continue` (token match, so an
174
+ * extension expectation alongside it does not confuse the guard). */
175
+ export function expects100Continue(headers) {
176
+ const raw = headers.expect;
177
+ const values = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw];
178
+ return values.some((v) => /(^|[,\s])100-continue([,\s]|$)/i.test(v));
179
+ }
180
+ /** The body size a client declared, or undefined when it declared none (chunked
181
+ * transfer, or a junk `Content-Length` — both are settled while reading). */
182
+ export function declaredBodyBytes(headers) {
183
+ const raw = headers['content-length'];
184
+ const first = Array.isArray(raw) ? raw[0] : raw;
185
+ if (typeof first !== 'string')
186
+ return undefined;
187
+ const n = Number(first.trim());
188
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
189
+ }
190
+ export function settleContinuationExpectation(req, res, resolveRoute) {
191
+ // A response already in flight (or a request that never set the expectation) is
192
+ // not ours to settle; write the continue only if the reply is still open.
193
+ if (!expects100Continue(req.headers) || res.writableEnded || res.headersSent) {
194
+ if (!res.writableEnded && !res.headersSent)
195
+ res.writeContinue();
196
+ return false;
197
+ }
198
+ const target = req.url || '';
199
+ const route = resolveRoute(target);
200
+ if (!route) {
201
+ res.writeContinue();
202
+ return false;
203
+ }
204
+ // Format first, then size: both are settled by the headers, and the order matches
205
+ // the post-body gate, so a client gets the same code whether or not it used the
206
+ // expectation.
207
+ const declared = declaredBodyBytes(req.headers);
208
+ const err = preflightBodyAdmission(req.headers, route.capBytes) ??
209
+ (declared !== undefined && declared > route.capBytes ? payloadTooLarge(route.capBytes) : undefined);
210
+ if (!err) {
211
+ res.writeContinue();
212
+ return false;
213
+ }
214
+ logBodyRejection({
215
+ leg: route.leg ?? 'native',
216
+ path: target,
217
+ err,
218
+ capBytes: route.capBytes,
219
+ receivedBytes: 0,
220
+ encoding: requestContentEncoding(req.headers),
221
+ }, route.log);
222
+ try {
223
+ const body = JSON.stringify(route.errorBody(err));
224
+ res.writeHead(err.statusCode, {
225
+ 'content-type': 'application/json; charset=utf-8',
226
+ 'content-length': String(Buffer.byteLength(body)),
227
+ connection: 'close',
228
+ ...(err.headers ?? {}),
229
+ });
230
+ res.end(body);
231
+ }
232
+ catch {
233
+ // Dead peer: the client saved the upload either way. Never let a continuation
234
+ // guard throw into the server's event loop (R-3: log, do not swallow silently).
235
+ logWriteFailure(err);
236
+ try {
237
+ res.destroy();
238
+ }
239
+ catch { }
240
+ }
241
+ try {
242
+ route.refuse?.();
243
+ }
244
+ catch { }
245
+ return true;
246
+ }
247
+ function logWriteFailure(err) {
248
+ console.error('[body-admission] continuation rejection write failed', err);
249
+ }
250
+ /** The encoding token of a request, normalised (`GZIP ` -> `gzip`). Missing,
251
+ * empty or `identity` all mean "no transformation" and return undefined. */
252
+ export function requestContentEncoding(headers) {
253
+ const raw = headers['content-encoding'];
254
+ const first = Array.isArray(raw) ? raw[0] : raw;
255
+ if (typeof first !== 'string')
256
+ return undefined;
257
+ const token = first.trim().toLowerCase();
258
+ return token.length > 0 && token !== 'identity' ? token : undefined;
259
+ }
260
+ function unsupportedEncoding(encoding) {
261
+ return new BodyAdmissionError(415, 'unsupported_content_encoding', `Unsupported Content-Encoding '${encoding}'. The gateway decodes: ${[...DECODABLE_ENCODINGS].join(', ')}.`, { 'accept-encoding': ACCEPT_ENCODING_ADVERTISEMENT });
262
+ }
263
+ /**
264
+ * Media types whose body this gateway reads as JSON. `application/json` (and any
265
+ * `+json` structured type) is the rule and `text/plain` is tolerated, because real
266
+ * agents do mis-declare and the body is unambiguous once you look at it.
267
+ *
268
+ * Anything else — form-urlencoded (what bare `curl -d` sends), multipart, XML, a
269
+ * binary type — and a MISSING header are refused with 415 on BOTH legs, before the
270
+ * body is buffered. Two reasons: an inference gateway has no business accepting a
271
+ * 30 MB upload it will never parse, and the native leg cannot be lenient here (that
272
+ * is Fastify's own content-type gate, which answers 415 for an undeclared type), so
273
+ * the stricter rule is the one that keeps the legs identical — the asymmetry is the
274
+ * bug family this whole pass is about. The refusal names the fix, so a hand-rolled
275
+ * request learns `Content-Type: application/json` instead of a mystery 400.
276
+ */
277
+ const JSON_MEDIA_TYPE = /^application\/([\w.+-]+\+)?json\b/i;
278
+ const TOLERATED_MEDIA_TYPE = /^text\/plain\b/i;
279
+ export function requestMediaType(headers) {
280
+ const raw = headers['content-type'];
281
+ const first = Array.isArray(raw) ? raw[0] : raw;
282
+ if (typeof first !== 'string')
283
+ return undefined;
284
+ const token = first.trim();
285
+ return token.length > 0 ? token : undefined;
286
+ }
287
+ function unsupportedMediaType(received) {
288
+ return new BodyAdmissionError(415, 'unsupported_media_type', received
289
+ ? `Unsupported Media Type '${received}'. The gateway reads a JSON request body (Content-Type: ${ACCEPT_MEDIA_ADVERTISEMENT}).`
290
+ : `Missing Content-Type. The gateway reads a JSON request body (Content-Type: ${ACCEPT_MEDIA_ADVERTISEMENT}).`, { accept: ACCEPT_MEDIA_ADVERTISEMENT });
291
+ }
292
+ /** True when this request's declared media type is one whose body we will parse.
293
+ * An absent header is NOT acceptable — it is the one case where leniency on one
294
+ * leg and a framework gate on the other would disagree silently. */
295
+ export function mediaTypeAcceptable(headers) {
296
+ const ct = requestMediaType(headers);
297
+ if (ct === undefined)
298
+ return false;
299
+ return JSON_MEDIA_TYPE.test(ct) || TOLERATED_MEDIA_TYPE.test(ct);
300
+ }
301
+ /**
302
+ * The MITM leg's media-type gate, thrown (not replied) so answering and logging
303
+ * stay on the single admission path in `model-gateway.ts`. Called BEFORE the body
304
+ * is read, which is the point: reject the type, not the size.
305
+ */
306
+ export function assertJsonMediaType(headers) {
307
+ if (!mediaTypeAcceptable(headers))
308
+ throw unsupportedMediaType(requestMediaType(headers));
309
+ }
310
+ /**
311
+ * Decide from the HEADERS alone whether this request could ever be admitted:
312
+ * framing first (an ambiguous `Content-Length` is not a message we may forward,
313
+ * RFC 9112 6.3), then media type (cheap, and independent of size), then the
314
+ * content coding, by asking the same decoder table `decompressBody` uses against
315
+ * an empty buffer -- an undecodable coding throws there and here, with the same
316
+ * 415, so the two checks cannot disagree about which codings exist. Also the
317
+ * header-only half of `settleContinuationExpectation`, which is why it returns
318
+ * the error instead of throwing it.
319
+ *
320
+ * Returns the rejection, or undefined when the request may proceed. The MITM legs
321
+ * call it BEFORE the body is drained, so a request we intend to refuse never pays
322
+ * for its own upload (the counterpart of the `Expect: 100-continue` guard, which
323
+ * cannot help a chunked body or a client that ignores the expectation).
324
+ */
325
+ export function preflightBodyAdmission(headers, capBytes = bodyLimitFor('gateway')) {
326
+ // FRAMING FIRST (RFC 9112 6.3): when `Content-Length` cannot be determined
327
+ // unambiguously the message must be rejected, never processed and never
328
+ // forwarded. Node's parser refuses a duplicated CL on its own, but BUN ACCEPTS
329
+ // two identical values and hands the application an ARRAY -- so without this
330
+ // check the gateway would relay the duplicate framing upstream and become the
331
+ // smuggle carrier. A non-numeric value is the same defect (no route to the
332
+ // framework's length error on either runtime).
333
+ const declaredLength = headers['content-length'];
334
+ if (declaredLength !== undefined && (Array.isArray(declaredLength) || !/^\d+$/.test(declaredLength))) {
335
+ return invalidContentLength();
336
+ }
337
+ try {
338
+ assertJsonMediaType(headers);
339
+ if (requestContentEncoding(headers))
340
+ decompressBody(Buffer.alloc(0), headers, capBytes);
341
+ return undefined;
342
+ }
343
+ catch (err) {
344
+ return isBodyAdmissionError(err) ? err : undefined;
345
+ }
346
+ }
347
+ /** A `Content-Length` the server could not frame: duplicated values, a non-numeric
348
+ * value, or bytes that do not match the declaration. 400 because the framing, not
349
+ * the payload, is broken (RFC 9110 8.6 makes a message with conflicting
350
+ * Content-Length values an error, not something to guess at). The declared numbers
351
+ * are deliberately NOT echoed: a mismatch gives the client nothing to fix beyond
352
+ * "reframe the request", and repeating a caller-chosen length into a response and a
353
+ * log line is free noise. */
354
+ export function invalidContentLength() {
355
+ return new BodyAdmissionError(400, 'invalid_content_length', 'The request declares an invalid or duplicated Content-Length. Send exactly one Content-Length, or use a chunked body.');
356
+ }
357
+ /**
358
+ * Normalize what Fastify handed the handler.
359
+ *
360
+ * A `text/plain` (or any tolerated-but-not-json) declaration makes Fastify's own
361
+ * parser deliver a raw STRING, and passing that to the pipeline produced the
362
+ * misleading `"messages" array is required` 400 for a perfectly valid body. Parse
363
+ * it here so the native leg agrees with the MITM leg, and reject a top-level
364
+ * non-object the same way the MITM leg does.
365
+ */
366
+ export function normalizeNativeBody(body) {
367
+ const parsed = typeof body === 'string' ? parseJsonBody(body) : body;
368
+ if (!parsed || typeof parsed !== 'object')
369
+ throw invalidJsonBody();
370
+ return parsed;
371
+ }
372
+ /**
373
+ * Streaming decoder for the native leg, returned from a Fastify `preParsing`
374
+ * hook. Returning a stream (instead of buffering) keeps the request on Fastify's
375
+ * normal parse path.
376
+ *
377
+ * The limit is deliberately NOT passed here: Fastify measures the stream this
378
+ * hook returns and enforces `bodyLimit` against its OUTPUT length, so an
379
+ * inflated bomb is refused at the same ceiling as a plain body.
380
+ *
381
+ * `receivedEncodedLength` is defined as a live getter over the COMPRESSED bytes:
382
+ * Fastify compares it against the `Content-Length` header and reads it after each
383
+ * chunk, so a static 0 makes the request fail as a length mismatch.
384
+ */
385
+ export function createBodyDecompressor(headers, payload) {
386
+ const encoding = requestContentEncoding(headers);
387
+ if (!encoding)
388
+ return payload;
389
+ if (!DECODABLE_ENCODINGS.has(encoding))
390
+ throw unsupportedEncoding(encoding);
391
+ const decoder = encoding === 'br'
392
+ ? createBrotliDecompress()
393
+ : encoding === 'gzip' || encoding === 'x-gzip'
394
+ ? createGunzip()
395
+ : createInflate();
396
+ let compressed = 0;
397
+ payload.on('data', (chunk) => {
398
+ compressed += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length;
399
+ });
400
+ Object.defineProperty(decoder, 'receivedEncodedLength', {
401
+ configurable: true,
402
+ get: () => compressed,
403
+ });
404
+ // `.pipe` alone would swallow a source error (a truncated or corrupt gzip
405
+ // stream) and leave Fastify waiting on a decoder that never ends, so the
406
+ // source error is forwarded as a destroy: the request then fails as a 400
407
+ // instead of hanging until socket timeout.
408
+ payload.pipe(decoder);
409
+ payload.on('error', (err) => {
410
+ if (!decoder.destroyed)
411
+ decoder.destroy(err);
412
+ });
413
+ return decoder;
414
+ }
415
+ /** Buffer decoder for the MITM leg, which already holds the whole body.
416
+ * `maxOutputLength` is the bomb guard: zlib aborts with ERR_BUFFER_TOO_LARGE
417
+ * rather than inflating past the cap, and that is reported as the SAME 413 the
418
+ * native leg produces. */
419
+ export function decompressBody(raw, headers, capBytes = bodyLimitFor('gateway')) {
420
+ const encoding = requestContentEncoding(headers);
421
+ if (!encoding)
422
+ return raw;
423
+ if (!DECODABLE_ENCODINGS.has(encoding))
424
+ throw unsupportedEncoding(encoding);
425
+ const opts = { maxOutputLength: capBytes };
426
+ try {
427
+ switch (encoding) {
428
+ case 'br':
429
+ return brotliDecompressSync(raw, opts);
430
+ case 'gzip':
431
+ case 'x-gzip':
432
+ return gunzipSync(raw, opts);
433
+ default:
434
+ // HTTP `deflate` is the zlib format (RFC 1950). Raw deflate (RFC 1951)
435
+ // has no valid zlib header but is sent in the wild, so sniff instead of
436
+ // rejecting: a 400 for a body we can actually read would be a lie.
437
+ return looksLikeZlibStream(raw) ? inflateSync(raw, opts) : inflateRawSync(raw, opts);
438
+ }
439
+ }
440
+ catch (err) {
441
+ const code = err.code;
442
+ if (code === 'ERR_BUFFER_TOO_LARGE')
443
+ throw payloadTooLarge(capBytes);
444
+ throw invalidJsonBody(); // undecodable bytes: the body itself is broken
445
+ }
446
+ }
447
+ /** zlib stream header check (RFC 1950): CM must be 8 and (CMF<<8|FLG) % 31 === 0. */
448
+ function looksLikeZlibStream(buf) {
449
+ return buf.length >= 2 && buf[0] === 0x78 && (((buf[0] << 8) | buf[1]) % 31 === 0);
450
+ }
451
+ /** Parse an admitted JSON body, rejecting with the shared 400 rather than a raw
452
+ * SyntaxError whose message leaks byte offsets to the client. */
453
+ export function parseJsonBody(body) {
454
+ const text = typeof body === 'string' ? body : body.toString('utf8');
455
+ try {
456
+ return JSON.parse(text);
457
+ }
458
+ catch {
459
+ throw invalidJsonBody();
460
+ }
461
+ }
462
+ /**
463
+ * One operator-facing line per admission rejection. Without it a 413/415 is
464
+ * invisible: capture records nothing on this path (ADR-0008 — 400/413 precede
465
+ * processing) and Fastify request logging is disabled, so an operator debugging
466
+ * "my agent fails on long sessions" has no server-side evidence at all.
467
+ * `log` is the request logger when available; the fallback keeps the line in the
468
+ * process log for the legs that have no pino child.
469
+ */
470
+ export function logBodyRejection(info, log) {
471
+ const record = {
472
+ type: 'body_rejected',
473
+ leg: info.leg,
474
+ path: info.path,
475
+ status: info.err.statusCode,
476
+ code: info.err.code,
477
+ capBytes: info.capBytes,
478
+ receivedBytes: info.receivedBytes,
479
+ contentEncoding: info.encoding ?? 'identity',
480
+ };
481
+ if (log)
482
+ log.warn(record, `body rejected (${info.err.code}) on ${info.leg} leg ${info.path}`);
483
+ else
484
+ console.warn(`[body-admission] body rejected (${info.err.code}) on ${info.leg} leg ${info.path}`, record);
485
+ }
486
+ /** Narrowing helper for the answering layers on both legs. */
487
+ export function isBodyAdmissionError(err) {
488
+ return err instanceof BodyAdmissionError;
489
+ }
490
+ /**
491
+ * Fastify codes for the failures the content parser raises BEFORE a handler runs.
492
+ * They must be answered here because at that point no transport and no capture
493
+ * event exists (ADR-0008: 400/413 precede process), so the only thing left to
494
+ * shape the response with is the surface's error envelope.
495
+ */
496
+ const FRAMEWORK_BODY_CODES = new Set(['FST_ERR_CTP_BODY_TOO_LARGE']);
497
+ const FRAMEWORK_JSON_CODES = new Set(['FST_ERR_CTP_INVALID_JSON_BODY', 'FST_ERR_CTP_EMPTY_JSON_BODY']);
498
+ // Two producers, one meaning: Fastify's content-type gate on the native leg, and
499
+ // Node's own media-type abort on the raw/MITM leg (node/lib/_http_server.js).
500
+ const FRAMEWORK_MEDIA_CODES = new Set(['FST_ERR_CTP_INVALID_MEDIA_TYPE', 'ERR_HTTP_INVALID_MEDIA_TYPE']);
501
+ // Framing errors on the raw legs: the LLM client cannot act on "your lengths
502
+ // disagree", but it can reframe -- and silence (Node aborts with no response) is
503
+ // worse than a 400 that says so.
504
+ const FRAMEWORK_LENGTH_CODES = new Set([
505
+ 'ERR_REQUEST_CONTENT_LENGTH_COUNT',
506
+ 'ERR_REQUEST_CONTENT_LENGTH_INVALID',
507
+ 'ERR_REQUEST_CONTENT_LENGTH_INVALID_CHAR',
508
+ 'ERR_REQUEST_CONTENT_LENGTH_MISMATCH',
509
+ ]);
510
+ /**
511
+ * Route options that give the NATIVE leg the same admission policy the MITM leg
512
+ * applies by hand: decode `Content-Encoding` on the way in, cap the DECOMPRESSED
513
+ * body at the configured inference cap (`bodyLimitFor('gateway')`), and answer every
514
+ * rejection in the surface's own envelope with a machine-readable `code`.
515
+ *
516
+ * `preParsing` is registered per route rather than app-wide on purpose — an
517
+ * app-wide hook would also decompress admin/upload bodies it knows nothing about.
518
+ */
519
+ export function surfaceBodyAdmissionOptions(surface) {
520
+ const capBytes = bodyLimitFor('gateway');
521
+ return {
522
+ bodyLimit: capBytes,
523
+ preParsing(request, _reply, payload, done) {
524
+ try {
525
+ done(null, createBodyDecompressor(request.headers, payload));
526
+ }
527
+ catch (err) {
528
+ // A 415 for an encoding we cannot decode. Passing it to `done` (rather
529
+ // than replying from the hook) keeps ONE answering path for every
530
+ // rejection and leaves Fastify to drain/close the socket.
531
+ done(err);
532
+ }
533
+ },
534
+ errorHandler(err, request, reply) {
535
+ // One translation call covers the framework's own refusals, including
536
+ // FST_ERR_CTP_INVALID_MEDIA_TYPE: Fastify answers that with its own
537
+ // string-`error` envelope, which Anthropic-style clients cannot parse, so it
538
+ // is re-answered here naming the type that was actually received.
539
+ const admission = isBodyAdmissionError(err)
540
+ ? err
541
+ : frameworkBodyError(err, capBytes, requestMediaType(request.headers));
542
+ if (!admission)
543
+ throw err; // not ours: delegate to the parent handler
544
+ logBodyRejection({
545
+ leg: 'native',
546
+ path: request.url,
547
+ err: admission,
548
+ capBytes,
549
+ encoding: requestContentEncoding(request.headers),
550
+ }, request.log);
551
+ return reply
552
+ .status(admission.statusCode)
553
+ .headers(admissionHeaders(admission))
554
+ .send(surface.errorBody(admission.statusCode, admission.message, admission.code));
555
+ },
556
+ };
557
+ }
558
+ /**
559
+ * App-level `errorHandler` for the ADMIN plane (everything that is not a
560
+ * protocol surface). The console reads failures as `{ success: false, message }`;
561
+ * Fastify's default shape is `{ statusCode, code, error, message }` whose
562
+ * `error` is a reason phrase, which the UI renders as the bare
563
+ * `Error: 413 "Payload Too Large"` this whole module exists to kill.
564
+ *
565
+ * Non-admission errors are RE-THROWN, which hands them to Fastify's default
566
+ * handler (fastify/docs/Reference/Errors.md) — this handler must not become a
567
+ * second, worse error serializer for validation and 5xx paths it knows nothing
568
+ * about, and it never echoes a stack or an upstream body.
569
+ */
570
+ export function adminBodyErrorHandler(err, request, reply) {
571
+ const capBytes = bodyLimitFor('admin');
572
+ const admission = isBodyAdmissionError(err)
573
+ ? err
574
+ : frameworkBodyError(err, capBytes, requestMediaType(request.headers));
575
+ if (!admission)
576
+ throw err;
577
+ logBodyRejection({
578
+ leg: 'native',
579
+ path: request.url,
580
+ err: admission,
581
+ capBytes,
582
+ encoding: requestContentEncoding(request.headers),
583
+ }, request.log);
584
+ return reply
585
+ .status(admission.statusCode)
586
+ .headers(admissionHeaders(admission))
587
+ .send({ success: false, message: admission.message });
588
+ }
589
+ function admissionHeaders(err) {
590
+ return (err.headers ?? {});
591
+ }
592
+ /** Translate a framework content-parser failure into this module's error type, so
593
+ * one message builder and one `code` cover both producers. Returns undefined for
594
+ * errors that belong to somebody else. */
595
+ function frameworkBodyError(err, capBytes, receivedMediaType) {
596
+ if (FRAMEWORK_BODY_CODES.has(err.code ?? ''))
597
+ return payloadTooLarge(capBytes);
598
+ if (FRAMEWORK_JSON_CODES.has(err.code ?? ''))
599
+ return invalidJsonBody();
600
+ // A refused media type from the framework does not name what was SENT (our own
601
+ // gate does, via unsupportedMediaType(received)), so this variant says what the
602
+ // server accepts instead; the `Accept` header carries the same answer.
603
+ if (FRAMEWORK_MEDIA_CODES.has(err.code ?? ''))
604
+ return unsupportedMediaType(receivedMediaType);
605
+ if (FRAMEWORK_LENGTH_CODES.has(err.code ?? ''))
606
+ return invalidContentLength();
607
+ // A body that ENDS SHORT of its declared length is deliberately NOT mapped: Node
608
+ // (and Bun) abort the request and no response is written at all -- there is
609
+ // nothing here to shape (verified on both runtimes). The reachable truncation case
610
+ // is the reverse, a declared length SHORTER than the bytes sent: the parser sees a
611
+ // truncated JSON document and answers `invalid_json_body` above.
612
+ return undefined;
613
+ }
@@ -1,18 +1,57 @@
1
1
  import type http from 'node:http';
2
2
  import type { ProtocolSurface, TransportContext } from './types.js';
3
3
  /**
4
- * Read the request body with a hard 32 MB cap (migrated verbatim from the
5
- * pre-refactor interceptor). Oversized bodies reject with 'Request body
6
- * too large' → the caller maps that to 413 via surface.errorBody.
4
+ * Raw node:http transport (the MITM forward-proxy leg) — the second
5
+ * implementation of the frozen TransportContext terminal-send discipline
6
+ * (contract §1.5). The interceptor reads the body, hands this transport to
7
+ * dispatchSurface, and the SAME chat pipelines then run byte-comparable on
8
+ * both legs.
9
+ *
10
+ * POLICY EXEMPTION (deliberate): intercepted traffic carries NO gateway key —
11
+ * the upstream Authorization header belongs to the real upstream API, so
12
+ * per-key model-access policies cannot apply here. This surface is a trusted
13
+ * local-machine convenience (the user explicitly points their tools at the
14
+ * proxy); anyone who can reach the proxy could equally call the native
15
+ * endpoints if they held a key, and inference cost-control for untrusted
16
+ * remote callers is the proxy operator's job (bind it to loopback). Do NOT
17
+ * "fix" this by inventing key headers the caller cannot send.
18
+ * (Authoritative text — interceptor.ts keeps only a pointer here.)
7
19
  */
8
- export declare function readRequestBody(req: http.IncomingMessage): Promise<Buffer>;
20
+ /**
21
+ * Read the request body with the gateway's hard cap (`bodyLimitFor('gateway')` —
22
+ * the SAME number the native Fastify routes pass as bodyLimit, so one admission
23
+ * ceiling covers both legs; `client.bodyLimits.maxBytes` moves it for both at the
24
+ * next boot). Oversized bodies reject with a BodyAdmissionError
25
+ * that already carries the 413 status, the `payload_too_large` code and the
26
+ * client-facing sentence; the caller only has to answer with it.
27
+ *
28
+ * The cap is measured on the WIRE here (this leg buffers before decoding), and
29
+ * `model-gateway.ts` re-checks after `decompressBody`, so a compressed body
30
+ * cannot slip past the ceiling that the native leg applies to its inflated
31
+ * stream.
32
+ *
33
+ * A STALLED body is refused too, with 408 (see `requestBodyTimeout`). The
34
+ * server-level `requestTimeout` cannot express it: that clock covers the whole
35
+ * request, so one byte per minute never trips it — and on Bun no such clock is
36
+ * armed at all. This timer is re-armed on every chunk, so liveness is measured on
37
+ * the axis that actually fails in practice: progress, not elapsed time.
38
+ *
39
+ * `idleMs` is a seam (a test cannot wait a minute, and a later config knob needs
40
+ * one call site); production callers pass nothing and get the single-source default.
41
+ */
42
+ export declare function readRequestBody(req: http.IncomingMessage, idleMs?: number): Promise<Buffer>;
9
43
  /**
10
44
  * Pre-dispatch error (413 oversized body / 400 invalid JSON): sent through
11
45
  * the surface's own error envelope BEFORE any orchestrator call, so no
12
46
  * capture events exist on this path on either leg (contract §4: 400/403
13
47
  * precede process). Adapters never throw — write failures are logged loud.
14
48
  */
15
- export declare function sendPreDispatchError(res: http.ServerResponse, surface: ProtocolSurface, status: number, message: string): void;
49
+ export declare function sendPreDispatchError(res: http.ServerResponse, surface: ProtocolSurface, status: number, message: string, code?: string,
50
+ /** The rejection's negotiation headers (`Accept-Encoding` for a refused coding,
51
+ * `Accept` for a refused media type). Carried through so the MITM leg advertises
52
+ * exactly what the native leg does — a client that only reads the headers learns
53
+ * the fix on neither leg if they are dropped here. */
54
+ headers?: Record<string, string>): void;
16
55
  /**
17
56
  * Build the MITM-leg transport. `captureEnabled` is the SURFACE capture
18
57
  * policy threaded in by the caller: `true` wires the