@jini-ai/http-kit 0.7.3-next.1 → 0.7.3-next.3
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.
- package/CHANGELOG.md +8 -0
- package/README.md +49 -0
- package/dist/adapter-request.d.ts +101 -0
- package/dist/adapter-request.js +100 -0
- package/dist/adapter.d.ts +31 -7
- package/dist/adapter.js +291 -43
- package/dist/deferred-body.d.ts +14 -0
- package/dist/deferred-body.js +85 -0
- package/dist/dev-proxy.d.ts +76 -0
- package/dist/dev-proxy.js +244 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/node-bridge.d.ts +11 -1
- package/dist/node-bridge.js +59 -11
- package/dist/rate-limit.d.ts +2 -14
- package/dist/raw-route.d.ts +35 -0
- package/dist/raw-route.js +279 -0
- package/dist/reporter-internal-error.d.ts +19 -0
- package/dist/reporter-internal-error.js +34 -0
- package/dist/request-id.d.ts +9 -0
- package/dist/request-id.js +21 -0
- package/dist/request.d.ts +8 -3
- package/dist/request.js +17 -2
- package/dist/types.d.ts +129 -6
- package/package.json +19 -7
package/dist/adapter.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { assertRequestFactsPort, requestScopedDeps, routeRequestInput, routeBodyRefusal, writeBodyRefusal, applyAdmittedResponseHeaders, applyResponseHeaders } from './adapter-request.js';
|
|
2
|
+
import { ClientFacingError, guardSameOrigin, httpFallbackCopy, internalErrorMessage, isRouteReply, statusForError } from '@jini-ai/core/contracts/server';
|
|
3
|
+
import { runOperation, UNAVAILABLE_ERROR_ID } from '@jini-ai/core/errors/reporter';
|
|
2
4
|
import { reportRouteInternalError } from './internal-error.js';
|
|
3
|
-
import { rawInput } from './request.js';
|
|
4
5
|
import { sendApiError, sendJson } from './response.js';
|
|
5
6
|
import { passesSameOriginGuard } from './origin.js';
|
|
6
7
|
/**
|
|
@@ -8,7 +9,7 @@ import { passesSameOriginGuard } from './origin.js';
|
|
|
8
9
|
* parameters at the definition site so callers do not have to repeat them. Optional settings take
|
|
9
10
|
* precedence. The returned spec is consumed by `mountJsonRoute` (live)
|
|
10
11
|
* and by tests (direct invocation of `route.parse` / `route.handle`).
|
|
11
|
-
* @param optionalArgs - Origin/success policy and optional injected host ports.
|
|
12
|
+
* @param optionalArgs - Origin/success policy, body ceiling and optional injected host ports.
|
|
12
13
|
* @returns A fresh route spec; never mutates either argument.
|
|
13
14
|
* @complexity O(1) time/space for the fixed spec fields.
|
|
14
15
|
*/
|
|
@@ -24,8 +25,18 @@ export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
|
|
|
24
25
|
* @returns Void; registers one handler, without starting a listener.
|
|
25
26
|
* @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
|
|
26
27
|
*/
|
|
27
|
-
export function mountJsonRoute(
|
|
28
|
-
app
|
|
28
|
+
export function mountJsonRoute(required, optional = {}) {
|
|
29
|
+
const { app, spec, adapter } = required;
|
|
30
|
+
const mountedDeps = required.deps;
|
|
31
|
+
const resolveDeps = required.depsForRequest ?? ((facts) => requestScopedDeps({ ...facts, deps: mountedDeps }, optional));
|
|
32
|
+
assertRequestFactsPort({ spec });
|
|
33
|
+
// Read once at mount: the per-request callback stays within the complexity budget.
|
|
34
|
+
const onReturnedError = spec.ports?.onReturnedError;
|
|
35
|
+
// The mode is chosen here, once per mount (never per request), so two requests of one host can
|
|
36
|
+
// never take different incident paths: reporter mode when the host passed `errors`, else legacy.
|
|
37
|
+
const errors = adapter?.errors;
|
|
38
|
+
// `optional.bodyParsers` run between the path and this handler, for this one route only.
|
|
39
|
+
app[spec.method](spec.path, ...(optional.bodyParsers ?? []), async (req, res) => {
|
|
29
40
|
// The client-disconnect signal a `handle` can opt into via optional arguments. Observed on `res`,
|
|
30
41
|
// not `req` — `sse.ts` already established why for this exact "detect a disconnect before
|
|
31
42
|
// ever writing a response" shape (its own doc: safe to register "before `open` is ever
|
|
@@ -35,7 +46,8 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
35
46
|
// response is sent, with no disconnect having happened at all. `res`'s `'close'` isn't
|
|
36
47
|
// entangled with the request body's lifecycle, only with the response's own connection, so it
|
|
37
48
|
// doesn't share that false positive. Registered before anything awaits and unconditionally
|
|
38
|
-
// detached in `finally` below, so it never outlives one request.
|
|
49
|
+
// detached in `finally` below, so it never outlives one request. In reporter mode the same
|
|
50
|
+
// signal is what turns an abort-like throw into a cancelled operation with no write and no report.
|
|
39
51
|
const abortController = new AbortController();
|
|
40
52
|
const onResponseClose = () => abortController.abort();
|
|
41
53
|
// Optional-called rather than assumed present: a real Express `Response` always has `.on`, but
|
|
@@ -43,60 +55,296 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
|
|
|
43
55
|
// that doesn't implement `EventEmitter` at all. Those callers simply never observe an abort,
|
|
44
56
|
// which is the correct behavior for a double that never fires `close` anyway.
|
|
45
57
|
res.on?.('close', onResponseClose);
|
|
58
|
+
const call = { req, res, spec, resolveDeps, mountOptions: optional, adapter, onReturnedError, signal: abortController.signal };
|
|
46
59
|
try {
|
|
47
|
-
|
|
48
|
-
if (spec.ports?.workspace)
|
|
49
|
-
await spec.ports.workspace({ raw, deps });
|
|
50
|
-
if (!allowRouteOrigin({ req, res, spec, adapter }))
|
|
51
|
-
return;
|
|
52
|
-
let context;
|
|
53
|
-
if (spec.ports?.authenticate)
|
|
54
|
-
context = await spec.ports.authenticate({ raw, res, deps });
|
|
55
|
-
const parsed = spec.parse(raw);
|
|
56
|
-
if (!parsed.ok) {
|
|
57
|
-
sendApiError({ res, status: statusForError({ error: parsed.error }), error: parsed.error });
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
// The route chooses where authorization occurs: reads may authorize before validation,
|
|
61
|
-
// while writes must reject an inconsistent tenant target before asking for a permission.
|
|
62
|
-
const authorize = async ({ permission, entityType }) => {
|
|
63
|
-
if (!spec.ports?.authorize)
|
|
64
|
-
throw new Error('JSON route authorizer is required');
|
|
65
|
-
await spec.ports.authorize({ context, deps, permission, entityType });
|
|
66
|
-
};
|
|
67
|
-
const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: abortController.signal });
|
|
68
|
-
sendRouteResult({ res, result, spec, signal: abortController.signal });
|
|
69
|
-
}
|
|
70
|
-
catch (e) {
|
|
71
|
-
sendRouteException({ res, spec, adapter, error: e });
|
|
60
|
+
await (errors ? reporterServe(call, { errors }) : legacyServe(call));
|
|
72
61
|
}
|
|
73
62
|
finally {
|
|
74
63
|
res.off?.('close', onResponseClose);
|
|
75
64
|
}
|
|
76
65
|
});
|
|
77
66
|
}
|
|
78
|
-
|
|
67
|
+
const COMPLETED = { outcome: 'completed', failed: false };
|
|
68
|
+
const REFUSED = { outcome: 'refused', failed: false };
|
|
69
|
+
const FAILED = { outcome: 'failed', failed: true };
|
|
70
|
+
/** The non-standard "client closed request" sentinel, used only as the ended operation's status label. */
|
|
71
|
+
const CLIENT_CLOSED_STATUS = 499;
|
|
72
|
+
const noWrite = () => { };
|
|
73
|
+
/** Stamps the status the write will send on the verdict, so the operation ends with `http.status_code`. */
|
|
74
|
+
function answer({ verdict, status, write }) {
|
|
75
|
+
return { write, verdict: { ...verdict, attributes: { ...verdict.attributes, 'http.status_code': status } } };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A returned `INTERNAL_ERROR` was produced inside the route by its reporter-backed
|
|
79
|
+
* `reportInternalError`, which already wrote the one record and tracker report: the producer owns
|
|
80
|
+
* that report, so this only classifies it `failed` and never records it again.
|
|
81
|
+
*/
|
|
82
|
+
function verdictFor({ apiError }) {
|
|
83
|
+
return apiError.code === 'INTERNAL_ERROR' ? FAILED : REFUSED;
|
|
84
|
+
}
|
|
85
|
+
/** Legacy mode (no `errors`): today's flow, every write at once, the SEC-005 sink on a throw. */
|
|
86
|
+
async function legacyServe(call) {
|
|
87
|
+
const { res, spec, adapter } = call;
|
|
88
|
+
try {
|
|
89
|
+
(await serveExpressRoute(call)).write();
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
sendRouteException({ res, spec, adapter, error: e });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Reporter mode: the request is one `http.route` operation. `runOperation` settles the work and
|
|
97
|
+
* ends the operation exactly once, and only then does the adapter write: the operation's owner is
|
|
98
|
+
* `runOperation`, the answer's owner is this function. A thrown failure is described by the
|
|
99
|
+
* reporter (one ID, one host record, one tracker report); `onInternalError` is never called here.
|
|
100
|
+
*/
|
|
101
|
+
async function reporterServe(call, { errors }) {
|
|
102
|
+
const method = call.spec.method.toUpperCase();
|
|
103
|
+
const run = await runOperation({
|
|
104
|
+
deps: errors, operation: 'http.route', scope: 'http', step: `Handle ${method} ${call.spec.path}`, fallback: httpFallbackCopy({ method }),
|
|
105
|
+
// The registered pattern (`/runs/:id`), never `req.originalUrl`: a URL carries ids, query strings
|
|
106
|
+
// and tokens, which would leak into telemetry and give every request its own unbounded group.
|
|
107
|
+
attributes: { 'http.method': method, 'http.route': call.spec.path },
|
|
108
|
+
work: () => tracedServe(call, { errors }),
|
|
109
|
+
classify: tagged => tagged.verdict,
|
|
110
|
+
settle: error => disconnectVerdict({ signal: call.signal, error }),
|
|
111
|
+
}, { audience: 'anonymous' });
|
|
112
|
+
if (run.ok && run.value.forwarded)
|
|
113
|
+
throw run.value.forwarded.error;
|
|
114
|
+
// A client that already went away gets nothing: a cancelled run, and equally a real failure
|
|
115
|
+
// recorded after the disconnect, have nobody to answer.
|
|
116
|
+
if ('cancelled' in run || call.signal.aborted)
|
|
117
|
+
return;
|
|
118
|
+
const write = run.ok ? run.value.write : () => writeFailure({ res: call.res, failure: run.failure });
|
|
119
|
+
deliver({ call, write }, { errors });
|
|
120
|
+
}
|
|
121
|
+
async function tracedServe(call, { errors }) {
|
|
122
|
+
try {
|
|
123
|
+
return await serveExpressRoute(call);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const onError = call.spec.ports?.onError;
|
|
127
|
+
// No host policy: the throw reaches `runOperation`, whose reporter classifies it (a
|
|
128
|
+
// ClientFacingError or catalog refusal, else one incident).
|
|
129
|
+
if (!onError)
|
|
130
|
+
throw error;
|
|
131
|
+
return hostPolicyAnswer({ call, error, onError }, { errors });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* An explicit host error port answers BEFORE the reporter classifies anything, exactly as in legacy
|
|
136
|
+
* mode (it also wins over ClientFacingError). The Express port writes to `res` itself, so it is the
|
|
137
|
+
* one exception to end-before-write: it runs inside the operation, is called once, and the verdict
|
|
138
|
+
* comes from the status it actually set. If the policy throws, that failure is recorded as its own
|
|
139
|
+
* incident and the ORIGINAL error is rethrown, so the reply (if headers are still unsent) carries
|
|
140
|
+
* the original's ID rather than the policy's.
|
|
141
|
+
*/
|
|
142
|
+
function hostPolicyAnswer({ call, error, onError }, { errors }) {
|
|
143
|
+
// The route's static headers are already on `res`: `serveExpressRoute` set them before any gate ran.
|
|
144
|
+
const { res } = call;
|
|
145
|
+
try {
|
|
146
|
+
onError({ res, error });
|
|
147
|
+
}
|
|
148
|
+
catch (policyError) {
|
|
149
|
+
if (call.mountOptions.preserveHostErrorRouting)
|
|
150
|
+
return { verdict: FAILED, write: noWrite, forwarded: { error: policyError } };
|
|
151
|
+
recordQuietly({ reporter: errors.reporter, error: policyError, step: 'Answer with host error policy' });
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
return answer({ verdict: res.statusCode >= 500 ? FAILED : REFUSED, status: res.statusCode, write: noWrite });
|
|
155
|
+
}
|
|
156
|
+
/** The reporter promises never to throw; this guard keeps a broken one from replacing the failure being answered. */
|
|
157
|
+
function recordQuietly({ reporter, error, step }) {
|
|
158
|
+
try {
|
|
159
|
+
return reporter.record({ error, step, operation: 'http.route' });
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return {};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Cancellation only when the client is gone AND the throw is the abort itself: an abort-like throw
|
|
167
|
+
* after the response closed is the handler stopping because nobody is listening. Any other throw
|
|
168
|
+
* after a disconnect is still a real failure and is recorded (and, with nobody listening, not written).
|
|
169
|
+
*/
|
|
170
|
+
function disconnectVerdict({ signal, error }) {
|
|
171
|
+
if (!signal.aborted)
|
|
172
|
+
return undefined;
|
|
173
|
+
const abortLike = error === signal.reason || (typeof error === 'object' && error !== null && error.name === 'AbortError');
|
|
174
|
+
return abortLike ? { outcome: 'cancelled', failed: false, attributes: { 'http.status_code': CLIENT_CLOSED_STATUS } } : undefined;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Runs the adapter-owned write after the operation ended. A write that throws (a body that will not
|
|
178
|
+
* serialize, a socket that refuses) is transport-owned: it is recorded once, never a new route
|
|
179
|
+
* operation and never a reason to run the handler again; the caller still gets an answer when
|
|
180
|
+
* nothing was sent yet, else the half-written response is destroyed.
|
|
181
|
+
*/
|
|
182
|
+
function deliver({ call, write }, { errors }) {
|
|
183
|
+
const { res, spec } = call;
|
|
184
|
+
try {
|
|
185
|
+
// The route's static (and admitted) headers are already on `res`: `serveExpressRoute` set them
|
|
186
|
+
// before its gates, in merge order, so an admitted header still wins over a static one of the same name.
|
|
187
|
+
write();
|
|
188
|
+
}
|
|
189
|
+
catch (writeError) {
|
|
190
|
+
if (!res.headersSent && call.mountOptions.preserveHostErrorRouting && spec.ports?.onError) {
|
|
191
|
+
spec.ports.onError({ res, error: writeError });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const { errorId } = recordQuietly({ reporter: errors.reporter, error: writeError, step: `Write ${spec.method.toUpperCase()} ${spec.path} response` });
|
|
195
|
+
const id = errorId ?? UNAVAILABLE_ERROR_ID;
|
|
196
|
+
const fallback = httpFallbackCopy({ method: spec.method });
|
|
197
|
+
const error = { code: 'INTERNAL_ERROR', message: `${fallback.message} ${fallback.action} (error ${id})`, requestId: id };
|
|
198
|
+
if (res.headersSent)
|
|
199
|
+
res.destroy?.();
|
|
200
|
+
else
|
|
201
|
+
sendApiError({ res, status: 500, error });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The reporter's answer: a refusal's own status and safe words (no ID), or an incident's 500 with
|
|
206
|
+
* the original incident ID as `requestId`. Once headers are out (a host policy wrote, then threw)
|
|
207
|
+
* nothing is answered a second time; an unfinished response is destroyed instead.
|
|
208
|
+
*/
|
|
209
|
+
function writeFailure({ res, failure }) {
|
|
210
|
+
if (res.headersSent) {
|
|
211
|
+
if (!res.writableEnded)
|
|
212
|
+
res.destroy?.();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
sendApiError({ res, status: failure.status, error: failure.error });
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Parse, authorize, handle and answer, after the pre-parse gates admitted the request (those gates now
|
|
219
|
+
* run here too), deciding the answer without writing it (`write` does). Split out of the per-request
|
|
220
|
+
* callback only to keep it within the complexity budget, and so reporter mode can end the operation
|
|
221
|
+
* before that write.
|
|
222
|
+
* Gate order: static headers → request-scoped deps → raw input → body cap → workspace → admitted
|
|
223
|
+
* headers → origin → authenticate → parse → handle. Setting a header is not a write on the wire, so
|
|
224
|
+
* reporter mode still ends the operation before anything is sent.
|
|
225
|
+
* Not awaited-before-handle: `parse` and `authorize` are synchronous, so `handle` still starts in
|
|
226
|
+
* the same tick as before the split (adapter-pins.test.ts pins that a disconnect right after dispatch
|
|
227
|
+
* reaches `handle`'s signal).
|
|
228
|
+
*/
|
|
229
|
+
async function serveExpressRoute(call) {
|
|
230
|
+
const { req, res, spec, adapter, onReturnedError, signal } = call;
|
|
231
|
+
applyResponseHeaders({ res, headers: spec.responseHeaders });
|
|
232
|
+
// Once per request, before every gate: the ports and `handle` see this request's bound deps.
|
|
233
|
+
const deps = call.resolveDeps({ req, res });
|
|
234
|
+
const raw = routeRequestInput({ req, spec, deps });
|
|
235
|
+
const tooLarge = routeBodyRefusal({ req, spec });
|
|
236
|
+
if (tooLarge)
|
|
237
|
+
return answer({ verdict: REFUSED, status: statusForError({ error: tooLarge.error }), write: () => writeBodyRefusal({ res, spec, refusal: tooLarge }) });
|
|
238
|
+
if (spec.ports?.workspace)
|
|
239
|
+
await spec.ports.workspace({ raw, deps });
|
|
240
|
+
applyAdmittedResponseHeaders({ res, raw, spec });
|
|
241
|
+
const crossOrigin = routeOriginRefusal({ req, spec, adapter });
|
|
242
|
+
if (crossOrigin)
|
|
243
|
+
return refusalAnswer({ res, error: crossOrigin });
|
|
244
|
+
let context;
|
|
245
|
+
if (spec.ports?.authenticate)
|
|
246
|
+
context = await spec.ports.authenticate({ raw, res, deps });
|
|
247
|
+
const parsed = spec.parse(raw);
|
|
248
|
+
if (!parsed.ok)
|
|
249
|
+
return returnedFailureAnswer({ res, onReturnedError, error: parsed.error, phase: 'parse' });
|
|
250
|
+
const authorize = routeAuthorize({ ports: spec.ports, deps, context });
|
|
251
|
+
const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal });
|
|
252
|
+
return routeResultAnswer({ res, result, spec: { successStatus: spec.successStatus, onReturnedError }, signal });
|
|
253
|
+
}
|
|
254
|
+
/** The origin gate's refusal: its own status and core's words, written by the adapter (the body cap has `writeBodyRefusal`). */
|
|
255
|
+
function refusalAnswer({ res, error }) {
|
|
256
|
+
const status = statusForError({ error });
|
|
257
|
+
return answer({ verdict: REFUSED, status, write: () => sendApiError({ res, status, error }) });
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* The `authorize` a handler calls. The route chooses where authorization occurs: reads may
|
|
261
|
+
* authorize before validation, while writes must reject an inconsistent tenant target before
|
|
262
|
+
* asking for a permission. A by-id route's scope (`entityId`) reaches the host port; an id-free
|
|
263
|
+
* call reaches it with the required arguments alone, exactly as before scopes existed. Likewise an
|
|
264
|
+
* `entityType` reaches it only when the handler named one (list-style permissions name none).
|
|
265
|
+
* @complexity O(1) plus the injected host authorizer.
|
|
266
|
+
*/
|
|
267
|
+
export function routeAuthorize({ ports, deps, context }, _optional = {}) {
|
|
268
|
+
return async ({ permission, entityType }, scope) => {
|
|
269
|
+
if (!ports?.authorize)
|
|
270
|
+
throw new Error('JSON route authorizer is required');
|
|
271
|
+
const required = { context, deps, permission, ...(entityType === undefined ? {} : { entityType }) };
|
|
272
|
+
await (scope ? ports.authorize(required, scope) : ports.authorize(required));
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
export function allowRouteOrigin({ req, res, spec, adapter }, _optional = {}) {
|
|
79
276
|
if (!spec.requireSameOrigin)
|
|
80
277
|
return true;
|
|
81
278
|
if (!adapter)
|
|
82
279
|
throw new Error('same-origin adapter context is required');
|
|
83
280
|
return passesSameOriginGuard({ req, res, origin: adapter });
|
|
84
281
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
282
|
+
/** The same-origin decision without the write (`passesSameOriginGuard` writes the 403 itself), so
|
|
283
|
+
* the adapter owns that write and can make it after the operation ended. `undefined` admits. */
|
|
284
|
+
function routeOriginRefusal({ req, spec, adapter }) {
|
|
285
|
+
if (!spec.requireSameOrigin)
|
|
286
|
+
return undefined;
|
|
287
|
+
if (!adapter)
|
|
288
|
+
throw new Error('same-origin adapter context is required');
|
|
289
|
+
const verdict = guardSameOrigin({ req, origin: adapter });
|
|
290
|
+
return verdict.ok ? undefined : verdict.error;
|
|
291
|
+
}
|
|
292
|
+
function routeResultAnswer({ res, result, spec, signal }, _optional = {}) {
|
|
293
|
+
// `signal` can only have been aborted by `onResponseClose` firing while the `await spec.handle`
|
|
294
|
+
// in `serveExpressRoute` was pending — nothing here runs concurrently with it — so this
|
|
295
|
+
// unambiguously means the client was already gone before any response was sent. Writing one now
|
|
296
|
+
// would be wasted work at best and, worse, would route a benign disconnect into the SEC-005
|
|
297
|
+
// catch as a false internal error if the socket rejects the write.
|
|
91
298
|
if (signal.aborted)
|
|
299
|
+
return answer({ verdict: { outcome: 'cancelled', failed: false }, status: CLIENT_CLOSED_STATUS, write: noWrite });
|
|
300
|
+
if (!result.ok)
|
|
301
|
+
return returnedFailureAnswer({ res, onReturnedError: spec.onReturnedError, error: result.error, phase: 'handle' });
|
|
302
|
+
const value = result.value;
|
|
303
|
+
const candidate = { value };
|
|
304
|
+
if (isRouteReply(candidate)) {
|
|
305
|
+
const { value: reply } = candidate;
|
|
306
|
+
return answer({ verdict: COMPLETED, status: reply.status, write: () => sendRouteReply({ res, reply }) });
|
|
307
|
+
}
|
|
308
|
+
const status = spec.successStatus ?? 200;
|
|
309
|
+
// A no-content status forbids a body: end the response instead of serializing `result.value`
|
|
310
|
+
// through `res.json`, matching hand-mounted handlers that answered `res.status(204).end()`.
|
|
311
|
+
if (NO_CONTENT_STATUSES.has(status))
|
|
312
|
+
return answer({ verdict: COMPLETED, status, write: () => { res.status(status).end(); } });
|
|
313
|
+
return answer({ verdict: COMPLETED, status, write: () => sendJson({ res, status, body: value }) });
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* A returned parse/handle failure. It is classified here, from the core status, BEFORE the host's
|
|
317
|
+
* `onReturnedError` shapes the wire: that port only chooses the bytes, never the verdict, so a
|
|
318
|
+
* host that re-maps the status cannot turn a producer-reported `INTERNAL_ERROR` into a refusal.
|
|
319
|
+
*/
|
|
320
|
+
function returnedFailureAnswer({ res, onReturnedError, error, phase }) {
|
|
321
|
+
return answer({ verdict: verdictFor({ apiError: error }), status: statusForError({ error }), write: () => sendReturnedFailure({ res, onReturnedError, error, phase }) });
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* A handler's explicit `routeReply`: its headers, its status, and its JSON body — or, with no body, a
|
|
325
|
+
* bare `send()` (no content type, never JSON `null`), which a 204/304 must be.
|
|
326
|
+
*/
|
|
327
|
+
function sendRouteReply({ res, reply }, _optional = {}) {
|
|
328
|
+
applyResponseHeaders({ res, headers: reply.headers });
|
|
329
|
+
if (reply.body === undefined) {
|
|
330
|
+
res.status(reply.status).send();
|
|
92
331
|
return;
|
|
93
|
-
|
|
94
|
-
|
|
332
|
+
}
|
|
333
|
+
sendJson({ res, status: reply.status, body: reply.body });
|
|
334
|
+
}
|
|
335
|
+
/** Success statuses that must carry no response body (RFC 9110 §15.3.5, §15.3.6, §15.4.5). */
|
|
336
|
+
const NO_CONTENT_STATUSES = new Set([204, 205, 304]);
|
|
337
|
+
function sendReturnedFailure({ res, onReturnedError, error, phase }, _optional = {}) {
|
|
338
|
+
const status = statusForError({ error });
|
|
339
|
+
// Returned and thrown failures share one wire shape only when the host asks for it; the core
|
|
340
|
+
// envelope stays the default so hosts that never opted in keep their pinned bodies.
|
|
341
|
+
if (onReturnedError) {
|
|
342
|
+
onReturnedError({ res, error, status, phase });
|
|
95
343
|
return;
|
|
96
344
|
}
|
|
97
|
-
|
|
345
|
+
sendApiError({ res, status, error });
|
|
98
346
|
}
|
|
99
|
-
function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
|
|
347
|
+
export function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
|
|
100
348
|
// An explicit host error port owns exception classification and serialization, including
|
|
101
349
|
// its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
|
|
102
350
|
if (spec.ports?.onError) {
|
|
@@ -121,7 +369,7 @@ function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
|
|
|
121
369
|
const apiError = reportRouteInternalError({
|
|
122
370
|
report: { method: spec.method, path: spec.path, error: e },
|
|
123
371
|
logSource: `${spec.method.toUpperCase()} ${spec.path}`,
|
|
124
|
-
message:
|
|
372
|
+
message: internalErrorMessage({ method: spec.method }),
|
|
125
373
|
}, { onInternalError: adapter?.onInternalError });
|
|
126
374
|
sendApiError({ res, status: 500, error: apiError });
|
|
127
375
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Request, Response } from 'express';
|
|
2
|
+
import type { RouteBodyReader } from '@jini-ai/core/contracts/server';
|
|
3
|
+
/**
|
|
4
|
+
* The `readBody` a raw route's handler receives. Nothing is read until it is called; the request stream
|
|
5
|
+
* is consumed once, so a later call (concurrent or after) with options identical to the first answers the
|
|
6
|
+
* first call's outcome, and one asking for anything else — another parser, media type or limit — is
|
|
7
|
+
* refused as `incompatible-read` instead of being handed bytes read under different rules.
|
|
8
|
+
* @complexity O(1) to build; each request at most one parse.
|
|
9
|
+
*/
|
|
10
|
+
export declare function deferredBodyReader({ req, res }: {
|
|
11
|
+
readonly req: Request;
|
|
12
|
+
readonly res: Response;
|
|
13
|
+
}, _optional?: Record<string, never>): RouteBodyReader;
|
|
14
|
+
//# sourceMappingURL=deferred-body.d.ts.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The Express side of a raw route's deferred body (`raw.readBody`, `@jini-ai/core/contracts/server`
|
|
3
|
+
* `RouteBodyReader`): the host's own `express.raw` / `express.urlencoded` parser, run only when the
|
|
4
|
+
* handler asks — after the route's gates — so no unauthorized request gets its body read. The parser is
|
|
5
|
+
* Express's, so its limit, 413 and encoding refusal are exactly what a parser registered ahead of the
|
|
6
|
+
* route answered; only the moment of reading moves.
|
|
7
|
+
*/
|
|
8
|
+
import express from 'express';
|
|
9
|
+
const URLENCODED = 'application/x-www-form-urlencoded';
|
|
10
|
+
/** body-parser's error `type` -> the neutral refusal; any other failure is `unreadable`. */
|
|
11
|
+
const REFUSAL_BY_PARSER_TYPE = {
|
|
12
|
+
'encoding.unsupported': 'unsupported-encoding',
|
|
13
|
+
'entity.parse.failed': 'malformed',
|
|
14
|
+
'request.aborted': 'aborted',
|
|
15
|
+
'request.size.invalid': 'size-mismatch',
|
|
16
|
+
};
|
|
17
|
+
/** The neutral refusal for a parser error; `too-large` carries the parser's own byte limit. @complexity O(1). */
|
|
18
|
+
function refusalFor({ error, limit }) {
|
|
19
|
+
const { type, limit: parserLimit } = (error ?? {});
|
|
20
|
+
if (type === 'entity.too.large')
|
|
21
|
+
return { reason: 'too-large', limit: typeof parserLimit === 'number' ? parserLimit : limit };
|
|
22
|
+
return { reason: (typeof type === 'string' ? REFUSAL_BY_PARSER_TYPE[type] : undefined) ?? 'unreadable' };
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The parser for one read. Never inflates: a compressed body is refused (`unsupported-encoding`), the
|
|
26
|
+
* owner's 2026-11-14 rule for every body this package reads. A form is flat (`extended: false`).
|
|
27
|
+
* @complexity O(1).
|
|
28
|
+
*/
|
|
29
|
+
function parserFor(options) {
|
|
30
|
+
if (options.type === 'raw')
|
|
31
|
+
return express.raw({ type: options.mediaType, limit: options.limit, inflate: false });
|
|
32
|
+
return express.urlencoded({ type: URLENCODED, extended: false, limit: options.limit, inflate: false });
|
|
33
|
+
}
|
|
34
|
+
/** Whether the parsed `req.body` is the kind the read asked for. @complexity O(1). */
|
|
35
|
+
function isReadValue({ options, body }) {
|
|
36
|
+
if (options.type === 'raw')
|
|
37
|
+
return Buffer.isBuffer(body);
|
|
38
|
+
return typeof body === 'object' && body !== null && !Buffer.isBuffer(body);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* One read: the media-type check (`req.is`, the same test the parser applies, which also answers no body
|
|
42
|
+
* as a mismatch), then the parser. A body a parser registered ahead of the route already read is left as
|
|
43
|
+
* that parser left it — the read only reports it.
|
|
44
|
+
* @complexity O(n) in the body bytes, bounded by `limit`.
|
|
45
|
+
*/
|
|
46
|
+
async function readOnce({ req, res, options }) {
|
|
47
|
+
if (!req.is(options.type === 'raw' ? options.mediaType : URLENCODED))
|
|
48
|
+
return { ok: false, refusal: { reason: 'media-type' } };
|
|
49
|
+
const parse = parserFor(options);
|
|
50
|
+
const error = await new Promise((resolve) => parse(req, res, (failure) => resolve(failure)));
|
|
51
|
+
if (error)
|
|
52
|
+
return { ok: false, refusal: refusalFor({ error, limit: options.limit }) };
|
|
53
|
+
const body = req.body;
|
|
54
|
+
if (!isReadValue({ options, body }))
|
|
55
|
+
return { ok: false, refusal: { reason: 'media-type' } };
|
|
56
|
+
return { ok: true, value: body };
|
|
57
|
+
}
|
|
58
|
+
/** Whether a later read asked for exactly what the first did (same parser, media type, limit). @complexity O(1). */
|
|
59
|
+
function sameOptions({ first, later }) {
|
|
60
|
+
const a = first;
|
|
61
|
+
const b = later;
|
|
62
|
+
return new Set([...Object.keys(a), ...Object.keys(b)]).size === Object.keys(a).length && Object.keys(a).every((key) => a[key] === b[key]);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The `readBody` a raw route's handler receives. Nothing is read until it is called; the request stream
|
|
66
|
+
* is consumed once, so a later call (concurrent or after) with options identical to the first answers the
|
|
67
|
+
* first call's outcome, and one asking for anything else — another parser, media type or limit — is
|
|
68
|
+
* refused as `incompatible-read` instead of being handed bytes read under different rules.
|
|
69
|
+
* @complexity O(1) to build; each request at most one parse.
|
|
70
|
+
*/
|
|
71
|
+
export function deferredBodyReader({ req, res }, _optional = {}) {
|
|
72
|
+
let first;
|
|
73
|
+
const read = (options) => {
|
|
74
|
+
// Snapshot first: a caller that mutates and re-sends the same object must be compared against what the first read ran under.
|
|
75
|
+
if (first === undefined) {
|
|
76
|
+
const snapshot = { ...options };
|
|
77
|
+
first = { options: snapshot, outcome: readOnce({ req, res, options: snapshot }) };
|
|
78
|
+
}
|
|
79
|
+
else if (!sameOptions({ first: first.options, later: options }))
|
|
80
|
+
return Promise.resolve({ ok: false, refusal: { reason: 'incompatible-read' } });
|
|
81
|
+
return first.outcome;
|
|
82
|
+
};
|
|
83
|
+
return read;
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=deferred-body.js.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { Socket } from "node:net";
|
|
3
|
+
/**
|
|
4
|
+
* Rewrites a bare `/admin` request to `/admin/` before it reaches Vite. Vite's `base: "/admin/"`
|
|
5
|
+
* only falls through to `index.html` on an exact base match, trailing slash included — a bare
|
|
6
|
+
* `/admin` 404s at Vite itself. Mirrors the identical fix the redirect branch this module replaces
|
|
7
|
+
* used to apply (`req.path === "/admin" ? "/admin/" : req.originalUrl`), rewritten to work directly
|
|
8
|
+
* off a raw URL string so the same helper serves both the request proxy (which has `req.originalUrl`)
|
|
9
|
+
* and the upgrade proxy (which only has the raw `req.url`).
|
|
10
|
+
*
|
|
11
|
+
* @param url - the incoming request's full path + query string.
|
|
12
|
+
* @param basePath - the mount path the dev server serves under, without a trailing slash (e.g. `/admin`).
|
|
13
|
+
* @complexity O(n) in `url`'s length (one indexOf, one slice).
|
|
14
|
+
*/
|
|
15
|
+
export declare function resolveDevProxyPath({ url, basePath }: {
|
|
16
|
+
url: string;
|
|
17
|
+
basePath: string;
|
|
18
|
+
}, _optional?: {}): string;
|
|
19
|
+
/**
|
|
20
|
+
* Drops hop-by-hop headers (see {@link HOP_BY_HOP_RESPONSE_HEADERS}) from an upstream response
|
|
21
|
+
* before it is relayed to the actual client. Node's `IncomingMessage.headers` keys are already
|
|
22
|
+
* lower-cased, so a plain `Set` lookup is enough — no case-folding needed here.
|
|
23
|
+
*
|
|
24
|
+
* @complexity O(n) in the number of response headers.
|
|
25
|
+
*/
|
|
26
|
+
export declare function stripHopByHopHeaders({ headers }: {
|
|
27
|
+
headers: IncomingMessage["headers"];
|
|
28
|
+
}, _optional?: {}): IncomingMessage["headers"];
|
|
29
|
+
/**
|
|
30
|
+
* The host's reply when the upstream cannot be reached before any response head went out. The host
|
|
31
|
+
* owns the status, content type and copy; this module only reports what failed. `Res` is the host's
|
|
32
|
+
* own response type (an Express `Response` stays an Express `Response` inside the writer).
|
|
33
|
+
* @returns Void; the writer must end `res`.
|
|
34
|
+
*/
|
|
35
|
+
export type DevProxyFailureWriter<Res extends ServerResponse = ServerResponse> = (args: {
|
|
36
|
+
res: Res;
|
|
37
|
+
error: Error;
|
|
38
|
+
target: URL;
|
|
39
|
+
}) => void;
|
|
40
|
+
/**
|
|
41
|
+
* Builds the Node request listener that proxies ordinary (non-WebSocket) `/admin/*` requests to Vite.
|
|
42
|
+
* It speaks `IncomingMessage`/`ServerResponse` only, so any host (an Express `app.all`, a bare
|
|
43
|
+
* `http.createServer`) can mount it.
|
|
44
|
+
*
|
|
45
|
+
* Streams both directions rather than buffering: `req` is piped straight into the upstream request,
|
|
46
|
+
* and the upstream response is piped straight into `res`, so this scales to Vite's large module
|
|
47
|
+
* bundles and source maps without holding them in memory.
|
|
48
|
+
*
|
|
49
|
+
* @param required.writeFailure - REQUIRED: the host's reply for an unreachable upstream (called only
|
|
50
|
+
* while `res.headersSent` is false; after the head went out the response is destroyed instead).
|
|
51
|
+
* @complexity O(1) setup per request; the actual byte volume is bounded by whatever Vite serves.
|
|
52
|
+
*/
|
|
53
|
+
export declare function createDevProxyRequestHandler<Res extends ServerResponse = ServerResponse>({ devProxyUrl, basePath, writeFailure }: {
|
|
54
|
+
devProxyUrl: string;
|
|
55
|
+
basePath: string;
|
|
56
|
+
writeFailure: DevProxyFailureWriter<Res>;
|
|
57
|
+
}, _optional?: {}): (req: IncomingMessage, res: Res) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Builds the `upgrade` listener that makes Vite's HMR WebSocket work through the dev proxy — see
|
|
60
|
+
* this file's module doc for why an ordinary request proxy cannot provide this on its own.
|
|
61
|
+
*
|
|
62
|
+
* The host attaches the returned listener to the actual `http.Server`/`https.Server` instance (not
|
|
63
|
+
* the Express `app`): `upgrade` is a socket-level server event Express's own request routing never
|
|
64
|
+
* sees. Whether to attach it at all (dev-proxy URL configured, not a packaged build) is the host's
|
|
65
|
+
* decision — this module reads no environment.
|
|
66
|
+
*
|
|
67
|
+
* Only claims upgrade requests whose path starts with `basePath`; anything else is left alone (no
|
|
68
|
+
* `socket.destroy()`) so a future unrelated `upgrade` listener on the same server is not pre-empted.
|
|
69
|
+
*
|
|
70
|
+
* @complexity O(1) setup; the listener is O(1) per upgrade request.
|
|
71
|
+
*/
|
|
72
|
+
export declare function createDevProxyUpgradeListener({ devProxyUrl, basePath }: {
|
|
73
|
+
devProxyUrl: string;
|
|
74
|
+
basePath: string;
|
|
75
|
+
}, _optional?: {}): (req: IncomingMessage, socket: Socket, head: Buffer) => void;
|
|
76
|
+
//# sourceMappingURL=dev-proxy.d.ts.map
|