@jini-ai/http-kit 0.7.2 → 0.7.3-next.1
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 +2 -10
- package/README.md +6 -6
- package/dist/adapter.d.ts +7 -50
- package/dist/adapter.js +12 -54
- package/dist/api-security-middleware.d.ts +0 -16
- package/dist/api-security-middleware.js +2 -18
- package/dist/index.d.ts +10 -15
- package/dist/index.js +7 -10
- package/dist/internal-error.d.ts +42 -0
- package/dist/internal-error.js +48 -0
- package/dist/local-daemon-request.d.ts +11 -4
- package/dist/local-daemon-request.js +1 -28
- package/dist/middleware.d.ts +1 -0
- package/dist/middleware.js +1 -0
- package/dist/node-bridge.d.ts +108 -0
- package/dist/node-bridge.js +356 -0
- package/dist/observability.d.ts +3 -14
- package/dist/origin.d.ts +13 -30
- package/dist/origin.js +13 -13
- package/dist/range.d.ts +53 -0
- package/dist/range.js +93 -0
- package/dist/rate-limit.d.ts +1 -13
- package/dist/rate-limit.js +5 -2
- package/dist/request.d.ts +2 -13
- package/dist/request.js +0 -13
- package/dist/response.d.ts +8 -7
- package/dist/response.js +0 -36
- package/dist/route-registration-guard.d.ts +14 -0
- package/dist/route-registration-guard.js +17 -0
- package/dist/run-credentials.d.ts +73 -0
- package/dist/run-credentials.js +71 -0
- package/dist/settings/contracts.d.ts +49 -0
- package/dist/settings/contracts.js +2 -0
- package/dist/settings/http-request.d.ts +36 -0
- package/dist/settings/http-request.js +50 -0
- package/dist/settings/http.d.ts +10 -0
- package/dist/settings/http.js +216 -0
- package/dist/settings/index.d.ts +4 -0
- package/dist/settings/index.js +3 -0
- package/dist/settings/shared.d.ts +16 -0
- package/dist/settings/shared.js +16 -0
- package/dist/settings/stream.d.ts +25 -0
- package/dist/settings/stream.js +180 -0
- package/dist/sse.d.ts +1 -15
- package/dist/sse.js +77 -72
- package/dist/trust-proxy.d.ts +36 -0
- package/dist/trust-proxy.js +45 -0
- package/dist/types.d.ts +4 -52
- package/dist/types.js +1 -4
- package/package.json +24 -14
- package/dist/active-context.d.ts +0 -99
- package/dist/active-context.js +0 -77
- package/dist/agents.d.ts +0 -64
- package/dist/agents.js +0 -23
- package/dist/attachments.d.ts +0 -534
- package/dist/attachments.js +0 -1032
- package/dist/cancel-owned-runs.d.ts +0 -44
- package/dist/cancel-owned-runs.js +0 -35
- package/dist/component-catalog.d.ts +0 -74
- package/dist/component-catalog.js +0 -74
- package/dist/connectors.d.ts +0 -165
- package/dist/connectors.js +0 -474
- package/dist/daemon-status.d.ts +0 -72
- package/dist/daemon-status.js +0 -60
- package/dist/db-ops.d.ts +0 -116
- package/dist/db-ops.js +0 -191
- package/dist/delegated-tools.d.ts +0 -146
- package/dist/delegated-tools.js +0 -286
- package/dist/frontend-control.d.ts +0 -131
- package/dist/frontend-control.js +0 -77
- package/dist/frontend-sessions.d.ts +0 -100
- package/dist/frontend-sessions.js +0 -180
- package/dist/health.d.ts +0 -91
- package/dist/health.js +0 -53
- package/dist/host-tools.d.ts +0 -174
- package/dist/host-tools.js +0 -338
- package/dist/media.d.ts +0 -131
- package/dist/media.js +0 -352
- package/dist/memory.d.ts +0 -230
- package/dist/memory.js +0 -331
- package/dist/model-proxy.d.ts +0 -45
- package/dist/model-proxy.js +0 -619
- package/dist/origin-validation.d.ts +0 -64
- package/dist/origin-validation.js +0 -226
- package/dist/raw-sse.d.ts +0 -49
- package/dist/raw-sse.js +0 -92
- package/dist/read-only-tools.d.ts +0 -67
- package/dist/read-only-tools.js +0 -59
- package/dist/remote-run-events.d.ts +0 -66
- package/dist/remote-run-events.js +0 -230
- package/dist/research.d.ts +0 -42
- package/dist/research.js +0 -316
- package/dist/route-manifest.d.ts +0 -31
- package/dist/route-manifest.js +0 -103
- package/dist/routines.d.ts +0 -114
- package/dist/routines.js +0 -320
- package/dist/runs.d.ts +0 -79
- package/dist/runs.js +0 -232
- package/dist/terminals.d.ts +0 -125
- package/dist/terminals.js +0 -349
- package/dist/tool-catalog.d.ts +0 -68
- package/dist/tool-catalog.js +0 -68
- package/dist/verified-origin/configured-origin.d.ts +0 -37
- package/dist/verified-origin/configured-origin.js +0 -99
- package/dist/verified-origin/index.d.ts +0 -7
- package/dist/verified-origin/index.js +0 -6
- package/dist/verified-origin/loopback-host.d.ts +0 -9
- package/dist/verified-origin/loopback-host.js +0 -17
- package/dist/verified-origin/origin.d.ts +0 -64
- package/dist/verified-origin/origin.js +0 -162
- package/dist/verified-origin/ports.d.ts +0 -38
- package/dist/verified-origin/ports.js +0 -2
- package/dist/verified-origin/repo.memory.d.ts +0 -32
- package/dist/verified-origin/repo.memory.js +0 -34
- package/dist/verified-origin/site-path.d.ts +0 -113
- package/dist/verified-origin/site-path.js +0 -188
- package/dist/verified-origin/types.d.ts +0 -33
- package/dist/verified-origin/types.js +0 -30
- package/dist/verified-origin.d.ts +0 -2
- package/dist/verified-origin.js +0 -2
- package/dist/workspace-root.d.ts +0 -69
- package/dist/workspace-root.js +0 -63
- package/dist/xai.d.ts +0 -86
- package/dist/xai.js +0 -668
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Serves a `Server` route table from Node's `http` request/response objects. This is the
|
|
3
|
+
* only code a host adapter needs: plain `node:http` calls `handle` with no `next`; an Express (4 or
|
|
4
|
+
* 5) host mounts `handle` as one middleware and passes `next`, so unmatched requests and handler
|
|
5
|
+
* errors fall through to the host's own routes and error handler. Express's `req`/`res` ARE Node's
|
|
6
|
+
* `IncomingMessage`/`ServerResponse`, which is why moving the host to Express 5 changes nothing here.
|
|
7
|
+
*/
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
import { Readable } from 'node:stream';
|
|
10
|
+
import { inspect } from 'node:util';
|
|
11
|
+
import { redactSecrets } from '@jini-ai/core';
|
|
12
|
+
import { createRouteTable } from '@jini-ai/core/contracts/server';
|
|
13
|
+
/**
|
|
14
|
+
* How many times longer a JSON text can get when it is parsed and printed again
|
|
15
|
+
* (`JSON.stringify(JSON.parse(text))`), which is what {@link consumedBody} does to a body an upstream
|
|
16
|
+
* parser already read. The only JSON production that grows is a number written in exponent form:
|
|
17
|
+
* `1e20` (4 bytes) prints as `100000000000000000000` (21 bytes), 21 / 4 = 5.25. Nothing does worse:
|
|
18
|
+
* from `1e21` up JavaScript prints the exponent form again, and a sign, a longer mantissa or a
|
|
19
|
+
* negative exponent adds input bytes faster than output bytes. Strings, escapes, whitespace and
|
|
20
|
+
* duplicate keys never grow.
|
|
21
|
+
*/
|
|
22
|
+
const JSON_RESERIALIZE_MAX_EXPANSION = 5.25;
|
|
23
|
+
/**
|
|
24
|
+
* Largest size a body of `parserLimitBytes` can have after the bridge re-serializes it. See JSON_RESERIALIZE_MAX_EXPANSION.
|
|
25
|
+
* A host with a JSON parser in front of the dispatcher passes this as the route-side body limit:
|
|
26
|
+
* the parser has already applied the real limit to the bytes on the wire, and the route limit
|
|
27
|
+
* only has to be large enough never to refuse a body the parser accepted.
|
|
28
|
+
*/
|
|
29
|
+
export function maxReserializedJsonBytes(required, _optional = {}) {
|
|
30
|
+
return Math.ceil(required.parserLimitBytes * JSON_RESERIALIZE_MAX_EXPANSION);
|
|
31
|
+
}
|
|
32
|
+
function consumedBody(parsedBody) {
|
|
33
|
+
if (parsedBody === undefined || parsedBody === null)
|
|
34
|
+
return null;
|
|
35
|
+
if (parsedBody instanceof Uint8Array)
|
|
36
|
+
return new Uint8Array(parsedBody);
|
|
37
|
+
if (typeof parsedBody === 'string')
|
|
38
|
+
return parsedBody;
|
|
39
|
+
return JSON.stringify(parsedBody);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The request path exactly as received, plus the URL for the web `Request`; `null` when no URL
|
|
43
|
+
* can be built (a Host header that is not a host, an absolute-form or `*` request target).
|
|
44
|
+
* Routes match on the raw path, never on a parsed URL's pathname: the URL parser resolves `..`
|
|
45
|
+
* and would read `//a/b` as host `a` + path `/b`, so it could pick a different route than the
|
|
46
|
+
* one the host framework's own gates looked at. The URL takes only the origin's scheme and host,
|
|
47
|
+
* so a Host header carrying a path cannot shift the path either.
|
|
48
|
+
*/
|
|
49
|
+
function requestTarget({ incoming, origin }) {
|
|
50
|
+
const target = incoming.url ?? '/';
|
|
51
|
+
if (!target.startsWith('/'))
|
|
52
|
+
return null;
|
|
53
|
+
const pathname = /^[^?#]*/.exec(target)?.[0] ?? target;
|
|
54
|
+
try {
|
|
55
|
+
const url = new URL(new URL(origin ?? `http://${incoming.headers.host ?? 'localhost'}`).origin);
|
|
56
|
+
url.pathname = pathname;
|
|
57
|
+
url.search = target.slice(pathname.length).split('#')[0] ?? '';
|
|
58
|
+
return { pathname, url };
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Makes the headers describe a body the bridge rebuilt from `parsedBody` instead of the one that
|
|
66
|
+
* was on the wire: `content-length` is the rebuilt byte length, `content-encoding` and
|
|
67
|
+
* `transfer-encoding` go. The upstream parser already decoded and de-chunked what it read (Express
|
|
68
|
+
* inflates gzip by default), and core's `readBodyBytes` refuses any `content-encoding` other than
|
|
69
|
+
* identity and compares `content-length` to its limit. Left as received, a gzip JSON call the
|
|
70
|
+
* host's parser accepted would be answered 415 behind the bridge.
|
|
71
|
+
*/
|
|
72
|
+
function describeRebuiltBody({ headers, body }) {
|
|
73
|
+
headers.set('content-length', String(typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength));
|
|
74
|
+
headers.delete('content-encoding');
|
|
75
|
+
headers.delete('transfer-encoding');
|
|
76
|
+
}
|
|
77
|
+
/** The body for the web `Request`: the untouched stream, or what an upstream parser left of it (with `headers` corrected to match). */
|
|
78
|
+
function requestBody({ incoming, headers, parsedBody }) {
|
|
79
|
+
if (!incoming.readableEnded)
|
|
80
|
+
return Readable.toWeb(incoming);
|
|
81
|
+
// An upstream parser has drained the socket; rebuild from what it produced, not from the empty stream.
|
|
82
|
+
const rebuilt = consumedBody(parsedBody);
|
|
83
|
+
if (rebuilt !== null)
|
|
84
|
+
describeRebuiltBody({ headers, body: rebuilt });
|
|
85
|
+
return rebuilt;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The headers of a Node request as web `Headers`: the one view of a header every route handler is given.
|
|
89
|
+
* A host that reads headers outside the bridge (its own route calling code that takes a web request)
|
|
90
|
+
* builds them with this, so a header reads the same either way. Node has already joined a repeated
|
|
91
|
+
* header (`cookie` with `; `, most others with `, `); one it keeps as a list (`set-cookie`) becomes one entry per value.
|
|
92
|
+
* @param required.incoming - The request as Node read it; its headers are copied at the moment of the call.
|
|
93
|
+
* @complexity O(headers) time and space; no I/O.
|
|
94
|
+
*/
|
|
95
|
+
export function nodeRequestHeaders({ incoming }, _optional = {}) {
|
|
96
|
+
const headers = new Headers();
|
|
97
|
+
for (const [name, value] of Object.entries(incoming.headers)) {
|
|
98
|
+
// Node gives a repeated header as an array; each value becomes its own entry.
|
|
99
|
+
for (const item of [value].flat())
|
|
100
|
+
if (item !== undefined)
|
|
101
|
+
headers.append(name, item);
|
|
102
|
+
}
|
|
103
|
+
return headers;
|
|
104
|
+
}
|
|
105
|
+
function toWebRequest({ incoming, url, signal, parsedBody }) {
|
|
106
|
+
const headers = nodeRequestHeaders({ incoming });
|
|
107
|
+
const method = incoming.method ?? 'GET';
|
|
108
|
+
if (method === 'GET' || method === 'HEAD')
|
|
109
|
+
return new Request(url, { method, headers, signal });
|
|
110
|
+
const body = requestBody({ incoming, headers, parsedBody });
|
|
111
|
+
// `duplex` is required by Node's fetch for a stream body but missing from the DOM RequestInit type.
|
|
112
|
+
const init = { method, headers, signal, body, duplex: 'half' };
|
|
113
|
+
return new Request(url, init);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Resolves once the socket takes more (`drain`) or the client is gone (`close`/`error`). All three
|
|
117
|
+
* listeners come off when it settles: one wait per full buffer, never a growing set of listeners
|
|
118
|
+
* or promise reactions over a long-lived SSE connection.
|
|
119
|
+
*/
|
|
120
|
+
function writableOrGone(out) {
|
|
121
|
+
// Already gone: its `close` has fired and will not fire again.
|
|
122
|
+
if (out.destroyed)
|
|
123
|
+
return Promise.resolve();
|
|
124
|
+
return new Promise((resolve) => {
|
|
125
|
+
const settle = () => {
|
|
126
|
+
out.off('drain', settle);
|
|
127
|
+
out.off('close', settle);
|
|
128
|
+
out.off('error', settle);
|
|
129
|
+
resolve();
|
|
130
|
+
};
|
|
131
|
+
out.on('drain', settle);
|
|
132
|
+
out.on('close', settle);
|
|
133
|
+
out.on('error', settle);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** Writes chunks until the stream ends (true) or the client leaves (false); waits whenever the socket buffer is full. */
|
|
137
|
+
async function copyChunks({ reader, out }) {
|
|
138
|
+
for (;;) {
|
|
139
|
+
// Checked before reading (a client gone before the first read never fires `close` again) and after (never write to a closed socket).
|
|
140
|
+
if (out.destroyed)
|
|
141
|
+
return false;
|
|
142
|
+
const chunk = await reader.read();
|
|
143
|
+
if (out.destroyed)
|
|
144
|
+
return false;
|
|
145
|
+
if (chunk.done)
|
|
146
|
+
return true;
|
|
147
|
+
if (!out.write(chunk.value))
|
|
148
|
+
await writableOrGone(out);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Copies `body` to `out` with backpressure: when the socket buffer is full, reading waits for
|
|
153
|
+
* `drain`, so a slow or stalled client holds the producer back instead of the stream filling
|
|
154
|
+
* Node's memory (the producers' own queue ceilings, e.g. SSE, only work if this waits). A client
|
|
155
|
+
* that leaves cancels the stream so its producer stops; cancelling also ends a read that is
|
|
156
|
+
* waiting on an idle producer. The reader is always released, so nothing keeps the stream locked.
|
|
157
|
+
* Returns false when the client left.
|
|
158
|
+
* @throws When the stream itself fails; the caller cuts the connection.
|
|
159
|
+
*/
|
|
160
|
+
async function pipeBody({ body, out }) {
|
|
161
|
+
const reader = body.getReader();
|
|
162
|
+
const onLeave = () => { reader.cancel().catch(() => undefined); };
|
|
163
|
+
out.once('close', onLeave);
|
|
164
|
+
let finished = false;
|
|
165
|
+
try {
|
|
166
|
+
finished = await copyChunks({ reader, out });
|
|
167
|
+
return finished;
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
out.off('close', onLeave);
|
|
171
|
+
if (!finished)
|
|
172
|
+
await reader.cancel().catch(() => undefined);
|
|
173
|
+
reader.releaseLock();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Writes a web `Response` to a Node `ServerResponse`: status, headers (each `Set-Cookie` on its own line), then the
|
|
178
|
+
* body with backpressure, headers flushed before the first chunk so a stream reaches the client before its first event.
|
|
179
|
+
* For a host that builds its own `Response` and answers through Node (Express) instead of registering a route, so it
|
|
180
|
+
* gets the same writer the dispatcher uses. `headOnly` writes the head and drops the body (a `HEAD` answer). A client
|
|
181
|
+
* that leaves cancels the body's producer; a body that fails mid-way rejects, and the caller cuts the connection.
|
|
182
|
+
* @throws When the body stream itself fails.
|
|
183
|
+
*/
|
|
184
|
+
export async function sendWebResponse({ response, res }, { headOnly = false } = {}) {
|
|
185
|
+
const out = res;
|
|
186
|
+
out.statusCode = response.status;
|
|
187
|
+
// Set-Cookie cannot be comma-joined (cookie dates contain commas), so each one gets its own line.
|
|
188
|
+
const cookies = response.headers.getSetCookie();
|
|
189
|
+
response.headers.forEach((value, name) => {
|
|
190
|
+
if (name !== 'set-cookie')
|
|
191
|
+
out.setHeader(name, value);
|
|
192
|
+
});
|
|
193
|
+
for (const cookie of cookies)
|
|
194
|
+
out.appendHeader('set-cookie', cookie);
|
|
195
|
+
if (!response.body || headOnly) {
|
|
196
|
+
await response.body?.cancel();
|
|
197
|
+
out.end();
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
// Headers first, so a streamed (SSE) response reaches the client before its first event.
|
|
201
|
+
out.flushHeaders();
|
|
202
|
+
if (await pipeBody({ body: response.body, out }))
|
|
203
|
+
out.end();
|
|
204
|
+
}
|
|
205
|
+
/** A finished plain-text answer; its length is stated, as Express stated it (a stream's is not, so only finished bodies get one). */
|
|
206
|
+
function plainText({ status, text }, { headers = {}, type = 'text/plain; charset=utf-8' } = {}) {
|
|
207
|
+
return new Response(text, { status, headers: { 'content-type': type, 'content-length': String(Buffer.byteLength(text)), ...headers } });
|
|
208
|
+
}
|
|
209
|
+
const MALFORMED_PATH_TEXT = 'The request address is not valid. A part of it is not valid percent-encoding.';
|
|
210
|
+
/** What Express answers an OPTIONS request with when a route owns the path: the allowed methods, as the `Allow` header and as the body. */
|
|
211
|
+
function optionsResponse({ allow }) {
|
|
212
|
+
const methods = allow.join(',');
|
|
213
|
+
return plainText({ status: 200, text: methods }, { headers: { allow: methods }, type: 'text/html; charset=utf-8' });
|
|
214
|
+
}
|
|
215
|
+
/** The dispatcher's own answer when no route takes the request (`match` null = no usable URL). */
|
|
216
|
+
function unroutedResponse(match) {
|
|
217
|
+
if (!match)
|
|
218
|
+
return plainText({ status: 400, text: 'The request address is not valid. Check the URL and the Host header.' });
|
|
219
|
+
if (match.kind === 'malformed-path')
|
|
220
|
+
return plainText({ status: 400, text: MALFORMED_PATH_TEXT });
|
|
221
|
+
if (match.kind === 'method-not-allowed')
|
|
222
|
+
return plainText({ status: 405, text: 'Method Not Allowed' }, { headers: { allow: match.allow.join(', ') } });
|
|
223
|
+
return plainText({ status: 404, text: 'Not Found' });
|
|
224
|
+
}
|
|
225
|
+
/** A short random reference that ties a caller's 500 to the server's log line; it reveals nothing about the failure. */
|
|
226
|
+
function newErrorReference() {
|
|
227
|
+
return randomBytes(6).toString('hex');
|
|
228
|
+
}
|
|
229
|
+
// Exceptions can echo credentials; inspect keeps stack and code, then the shared redactor runs (as adapter.ts does)
|
|
230
|
+
// with the host's own key shapes added, since only the host knows them.
|
|
231
|
+
function stderrSink(extraPatterns) {
|
|
232
|
+
return ({ error, reference }) => {
|
|
233
|
+
process.stderr.write(`[@jini-ai/http-kit] route handler failed (reference ${reference}): ${redactSecrets({ input: inspect(error) }, { redactPii: false, extraPatterns })}\n`);
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Wraps a sink so it can never throw into the dispatcher: a failing sink would otherwise turn a
|
|
238
|
+
* reported error into a rejected `handle()` (which the Express adapter discards) and skip cutting
|
|
239
|
+
* the connection. The fallback line names only the reference, never the error, so it cannot leak.
|
|
240
|
+
*/
|
|
241
|
+
function containedSink(sink) {
|
|
242
|
+
return (report) => {
|
|
243
|
+
try {
|
|
244
|
+
sink(report);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
try {
|
|
248
|
+
process.stderr.write(`[@jini-ai/http-kit] the error sink failed; error reference ${report.reference} was not logged\n`);
|
|
249
|
+
}
|
|
250
|
+
catch { /* nothing left to report to */ }
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
/** The 500 a caller sees: plain words plus a reference they can paste to whoever runs the site. */
|
|
255
|
+
function internalErrorResponse(reference) {
|
|
256
|
+
return plainText({ status: 500, text: `The server could not finish this request. Reference: ${reference}. Try again; if it keeps failing, send this reference to the site's owner.` });
|
|
257
|
+
}
|
|
258
|
+
/** Calls the matched route and writes its answer; a handler failure goes to `next(error)` or a plain 500. */
|
|
259
|
+
async function serveRoute({ incoming, out, method, options, onUnhandledError }, { url, match }) {
|
|
260
|
+
// A client that hangs up aborts `request.signal`, which is how a handler or stream notices.
|
|
261
|
+
// Observe response close: request close can fire when a POST body finishes while its response is still streaming. A normally finished response does not abort the signal.
|
|
262
|
+
const abort = new AbortController();
|
|
263
|
+
const onClose = () => { if (!out.writableFinished)
|
|
264
|
+
abort.abort(); };
|
|
265
|
+
out.on('close', onClose);
|
|
266
|
+
const address = incoming.socket?.remoteAddress;
|
|
267
|
+
let response;
|
|
268
|
+
try {
|
|
269
|
+
const request = toWebRequest({ incoming, url, signal: abort.signal, parsedBody: options.parsedBody });
|
|
270
|
+
response = await match.route.handler({ request, params: match.params, locals: { ...options.locals }, ...(address ? { client: { address } } : {}) });
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
out.off('close', onClose);
|
|
274
|
+
if (options.next) {
|
|
275
|
+
options.next(error);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const reference = newErrorReference();
|
|
279
|
+
onUnhandledError({ error, reference });
|
|
280
|
+
await sendWebResponse({ response: internalErrorResponse(reference), res: out })
|
|
281
|
+
.catch(() => { out.destroy(); });
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
await sendWebResponse({ response, res: out }, { headOnly: method === 'HEAD' });
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
// Headers are already on the wire, so no error page can follow: cut the connection so the
|
|
289
|
+
// client sees a failed response instead of a silently truncated one.
|
|
290
|
+
onUnhandledError({ error, reference: newErrorReference() });
|
|
291
|
+
out.destroy();
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
out.off('close', onClose);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/** Writes an answer the dispatcher itself chose; a failed write cuts the connection. */
|
|
298
|
+
function answerItself({ dispatch, response }) {
|
|
299
|
+
return sendWebResponse({ response, res: dispatch.out }, { headOnly: dispatch.method === 'HEAD' })
|
|
300
|
+
.catch(() => { dispatch.out.destroy(); });
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* The answers an `expressCompatible` dispatcher gives instead of falling through: OPTIONS on a path a route owns, and a 400 for a
|
|
304
|
+
* malformed `:name` segment. `undefined` means "not one of these", and the ordinary fall-through applies.
|
|
305
|
+
*/
|
|
306
|
+
function expressAnswer({ dispatch, match }) {
|
|
307
|
+
if (!dispatch.expressCompatible || !match)
|
|
308
|
+
return undefined;
|
|
309
|
+
if (match.kind === 'method-not-allowed' && dispatch.method === 'OPTIONS')
|
|
310
|
+
return answerItself({ dispatch, response: optionsResponse({ allow: match.allow }) });
|
|
311
|
+
if (match.kind !== 'malformed-path')
|
|
312
|
+
return undefined;
|
|
313
|
+
if (!dispatch.options.next)
|
|
314
|
+
return answerItself({ dispatch, response: unroutedResponse(match) });
|
|
315
|
+
dispatch.options.next(Object.assign(new Error(MALFORMED_PATH_TEXT), { status: 400, statusCode: 400, expose: true }));
|
|
316
|
+
return Promise.resolve();
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Creates a dispatcher with an empty route table.
|
|
320
|
+
* @param optional.onUnhandledError - Where a handler failure goes when no `next` was given, with the reference its 500 shows (default: redacted, to stderr).
|
|
321
|
+
* @param optional.redactionPatterns - Host key shapes the default stderr sink also masks.
|
|
322
|
+
* @param optional.expressCompatible - Keep Express's answers for path spellings, a bad percent-escape and OPTIONS (see {@link NodeDispatcherOptions}).
|
|
323
|
+
*/
|
|
324
|
+
export function createNodeDispatcher(_required = {}, { onUnhandledError, redactionPatterns = [], expressCompatible = false } = {}) {
|
|
325
|
+
const table = createRouteTable({}, { lenientPaths: expressCompatible });
|
|
326
|
+
const report = containedSink(onUnhandledError ?? stderrSink(redactionPatterns));
|
|
327
|
+
const dispatch = async (dispatchArgs) => {
|
|
328
|
+
const target = requestTarget({ incoming: dispatchArgs.incoming, origin: dispatchArgs.options.origin });
|
|
329
|
+
const match = target ? table.match({ method: dispatchArgs.method, pathname: target.pathname }) : null;
|
|
330
|
+
if (target && match?.kind === 'route')
|
|
331
|
+
return serveRoute(dispatchArgs, { url: target.url, match });
|
|
332
|
+
const answer = expressAnswer({ dispatch: dispatchArgs, match });
|
|
333
|
+
if (answer)
|
|
334
|
+
return answer;
|
|
335
|
+
// Not ours (or no usable URL): the host's own routes and validation decide, as before the dispatcher.
|
|
336
|
+
if (dispatchArgs.options.next)
|
|
337
|
+
return dispatchArgs.options.next();
|
|
338
|
+
return answerItself({ dispatch: dispatchArgs, response: unroutedResponse(match) });
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
server: { route: (route) => table.route(route) },
|
|
342
|
+
handle({ incoming, out }, options = {}) {
|
|
343
|
+
// The promise never rejects (the Express adapter discards it): anything left is reported and
|
|
344
|
+
// the connection cut. `report` is contained, and the cut runs even if it were not.
|
|
345
|
+
return dispatch({ incoming, out, method: incoming.method ?? 'GET', options, onUnhandledError: report, expressCompatible }).catch((error) => {
|
|
346
|
+
try {
|
|
347
|
+
report({ error, reference: newErrorReference() });
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
out.destroy();
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
//# sourceMappingURL=node-bridge.js.map
|
package/dist/observability.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Express, RequestHandler } from 'express';
|
|
2
|
+
import type { ObservabilityPort } from '@jini-ai/core/contracts/observability';
|
|
2
3
|
import { type Logger } from '@jini-ai/core/primitives';
|
|
3
4
|
/** Log request completions only when explicitly enabled, either all or above a threshold.
|
|
4
5
|
* Structured sinks retain correlation fields; the default console gets only the compact message.
|
|
@@ -17,31 +18,19 @@ export declare function logCompletedRequest(required: {
|
|
|
17
18
|
logRequests?: boolean;
|
|
18
19
|
slowRequestMs?: number;
|
|
19
20
|
}): void;
|
|
20
|
-
/** Structural port satisfied by diagnostics/observability, with host-owned logging and tracing. */
|
|
21
|
-
export interface HttpRequestObservabilityPort {
|
|
22
|
-
trackRequest(required: {
|
|
23
|
-
method: string;
|
|
24
|
-
path: string;
|
|
25
|
-
}): {
|
|
26
|
-
end(required: {
|
|
27
|
-
statusCode: number;
|
|
28
|
-
routePattern: string;
|
|
29
|
-
}): void;
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
21
|
/** Track requests before routing and read the mount-aware route pattern at response completion.
|
|
33
22
|
* Unmatched paths use a fixed label so attacker-selected paths do not become metric labels.
|
|
34
23
|
* Each response completes its tracker once; hook error policy belongs to the injected adapter.
|
|
35
24
|
* @complexity O(1) per request, excluding injected hooks and Express routing.
|
|
36
25
|
*/
|
|
37
26
|
export declare function createRequestTrackingMiddleware({ observability }: {
|
|
38
|
-
observability:
|
|
27
|
+
observability: Pick<ObservabilityPort, 'trackRequest'>;
|
|
39
28
|
}): RequestHandler;
|
|
40
29
|
/** Mount first, before serving gates and routes, so refusals and unmatched requests are measured.
|
|
41
30
|
* @complexity O(1) registration; effects are restricted to Express middleware registration.
|
|
42
31
|
*/
|
|
43
32
|
export declare function applyRequestTracking({ app, observability }: {
|
|
44
33
|
app: Express;
|
|
45
|
-
observability:
|
|
34
|
+
observability: Pick<ObservabilityPort, 'trackRequest'>;
|
|
46
35
|
}): void;
|
|
47
36
|
//# sourceMappingURL=observability.d.ts.map
|
package/dist/origin.d.ts
CHANGED
|
@@ -1,34 +1,17 @@
|
|
|
1
|
+
/** Express-side same-origin check for raw routes; the guard itself lives in core. */
|
|
2
|
+
import type { RequestWithOriginHeaders } from '@jini-ai/core';
|
|
3
|
+
import { type OriginContext } from '@jini-ai/core/contracts/server';
|
|
4
|
+
import { type ApiErrorResponseWriter } from './response.js';
|
|
1
5
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
6
|
+
* The same-origin check for a raw route (one not mounted through `mountJsonRoute`, e.g. an SSE
|
|
7
|
+
* stream): answers a cross-origin request with the guard's own error and status and returns
|
|
8
|
+
* `false`, so the caller only has to `return`. `mountJsonRoute` routes get this from `requireSameOrigin`.
|
|
9
|
+
* Framework-neutral: `req` needs only the origin headers, `res` only `status().json()`.
|
|
10
|
+
* @complexity O(1) plus the origin check.
|
|
4
11
|
*/
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
/** The subset of server startup state `guardSameOrigin` needs: the resolved local port, and the
|
|
9
|
-
* environment the origin policy is read from. */
|
|
10
|
-
export interface OriginContext extends OriginValidationEnvConfig {
|
|
11
|
-
resolvedPortRef: {
|
|
12
|
-
current: number;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Host-supplied environment; the host also names the bind-host, allowed-origin and web-port vars.
|
|
16
|
-
*
|
|
17
|
-
* Present because a host can inject its own environment (`@jini-ai/server`'s
|
|
18
|
-
* `createLocalNodeDaemon`/`composeJiniKernel` `env` option), and that injection already reaches
|
|
19
|
-
* the origin-guard *middleware* — which is handed an explicit `env`. Without the same seam here,
|
|
20
|
-
* the two halves of one decision read two different environments: the middleware admits an origin
|
|
21
|
-
* the host configured and the per-route guard then rejects it, or a bind host the host never set
|
|
22
|
-
* decides what counts as same-origin.
|
|
23
|
-
*/
|
|
24
|
-
env: NodeJS.ProcessEnv;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Wraps `isLocalSameOrigin` so the HTTP Adapter can fold the origin decision into the same
|
|
28
|
-
* error-handling pipeline as parse/handle failures.
|
|
29
|
-
*/
|
|
30
|
-
export declare function guardSameOrigin({ req, origin }: {
|
|
31
|
-
readonly req: Request;
|
|
12
|
+
export declare function passesSameOriginGuard({ req, res, origin }: {
|
|
13
|
+
readonly req: RequestWithOriginHeaders;
|
|
14
|
+
readonly res: ApiErrorResponseWriter;
|
|
32
15
|
readonly origin: OriginContext;
|
|
33
|
-
}, _optional?: Record<string, never>):
|
|
16
|
+
}, _optional?: Record<string, never>): boolean;
|
|
34
17
|
//# sourceMappingURL=origin.d.ts.map
|
package/dist/origin.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { err, ok } from './types.js';
|
|
1
|
+
import { guardSameOrigin, statusForError } from '@jini-ai/core/contracts/server';
|
|
2
|
+
import { sendApiError } from './response.js';
|
|
4
3
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* The same-origin check for a raw route (one not mounted through `mountJsonRoute`, e.g. an SSE
|
|
5
|
+
* stream): answers a cross-origin request with the guard's own error and status and returns
|
|
6
|
+
* `false`, so the caller only has to `return`. `mountJsonRoute` routes get this from `requireSameOrigin`.
|
|
7
|
+
* Framework-neutral: `req` needs only the origin headers, `res` only `status().json()`.
|
|
8
|
+
* @complexity O(1) plus the origin check.
|
|
7
9
|
*/
|
|
8
|
-
export function
|
|
9
|
-
const
|
|
10
|
-
if (
|
|
11
|
-
|
|
12
|
-
}))
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
return err({ error: createApiError({ code: 'FORBIDDEN', message: 'cross-origin request rejected' }) });
|
|
10
|
+
export function passesSameOriginGuard({ req, res, origin }, _optional = {}) {
|
|
11
|
+
const verdict = guardSameOrigin({ req, origin });
|
|
12
|
+
if (verdict.ok)
|
|
13
|
+
return true;
|
|
14
|
+
sendApiError({ res, status: statusForError({ error: verdict.error }), error: verdict.error });
|
|
15
|
+
return false;
|
|
16
16
|
}
|
|
17
17
|
//# sourceMappingURL=origin.js.map
|
package/dist/range.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file HTTP `Range` request parsing (RFC 7233 §2.1/§3.1) — a pure, dependency-free
|
|
3
|
+
* parser so host byte-serving routes can support
|
|
4
|
+
* `Range: bytes=...` without touching a request/response object, and so every edge
|
|
5
|
+
* case is directly unit-testable without booting an HTTP server.
|
|
6
|
+
*
|
|
7
|
+
* Deliberately narrow scope: single-range `bytes=` requests only.
|
|
8
|
+
* - No `Range` header, or a header this parser cannot make sense of (wrong unit,
|
|
9
|
+
* non-numeric bounds, an empty `bytes=-` spec, a `first > last` range, or more
|
|
10
|
+
* than one comma-separated range) is reported as `{ kind: "none" }`. RFC 7233
|
|
11
|
+
* §3.1 explicitly permits a server to ignore a Range header it does not want to
|
|
12
|
+
* honor — "A server MAY ignore the Range header field... [and] MAY ignore a
|
|
13
|
+
* Range header field that consists of more than one range" — so treating these
|
|
14
|
+
* as "serve the whole representation" is spec-legal, not a shortcut, and it is
|
|
15
|
+
* the safe choice for a header this parser cannot fully trust: no multipart/
|
|
16
|
+
* byteranges body needs to exist for that path to be correct.
|
|
17
|
+
* - A syntactically valid single range that is out of bounds for `totalLength`
|
|
18
|
+
* (e.g. `bytes=1000-` against a 10-byte resource) is reported as
|
|
19
|
+
* `{ kind: "unsatisfiable" }` — callers should respond `416` with
|
|
20
|
+
* `Content-Range: bytes * /{totalLength}` per RFC 7233 §4.4.
|
|
21
|
+
* - A satisfiable range clamps its end to `totalLength - 1` (RFC 7233 §2.1: "If
|
|
22
|
+
* the last-byte-pos value is absent, or if the value is greater than or equal
|
|
23
|
+
* to the current length of the representation data, the byte range is
|
|
24
|
+
* interpreted as the remainder of the representation").
|
|
25
|
+
*
|
|
26
|
+
* Every numeric bound is validated against `totalLength` (or rejected as
|
|
27
|
+
* non-finite) BEFORE a caller ever slices bytes with it — `{ kind: "range" }`'s
|
|
28
|
+
* `start`/`end` are always in `[0, totalLength - 1]` with `start <= end`, so a
|
|
29
|
+
* caller never over-reads or has to re-validate.
|
|
30
|
+
*/
|
|
31
|
+
export type ParsedRange = {
|
|
32
|
+
kind: "none";
|
|
33
|
+
} | {
|
|
34
|
+
kind: "unsatisfiable";
|
|
35
|
+
} | {
|
|
36
|
+
kind: "range";
|
|
37
|
+
start: number;
|
|
38
|
+
end: number;
|
|
39
|
+
};
|
|
40
|
+
export interface ParseRangeHeaderRequired {
|
|
41
|
+
/** The raw `Range` request header value, or `undefined`/`""` if absent. */
|
|
42
|
+
header: string | undefined;
|
|
43
|
+
/** The full resource length in bytes (`asset.byteLength`, not a client-supplied value). */
|
|
44
|
+
totalLength: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* @complexity O(1) — one regex match against a bounded-shape string and a handful of comparisons;
|
|
48
|
+
* no work proportional to `totalLength` or to the header's length beyond the regex engine's own
|
|
49
|
+
* linear scan of the (short, request-header-sized) input.
|
|
50
|
+
* @overallScore 100
|
|
51
|
+
*/
|
|
52
|
+
export declare function parseRangeHeader(required: ParseRangeHeaderRequired, _optional?: Record<string, never>): ParsedRange;
|
|
53
|
+
//# sourceMappingURL=range.d.ts.map
|
package/dist/range.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file HTTP `Range` request parsing (RFC 7233 §2.1/§3.1) — a pure, dependency-free
|
|
3
|
+
* parser so host byte-serving routes can support
|
|
4
|
+
* `Range: bytes=...` without touching a request/response object, and so every edge
|
|
5
|
+
* case is directly unit-testable without booting an HTTP server.
|
|
6
|
+
*
|
|
7
|
+
* Deliberately narrow scope: single-range `bytes=` requests only.
|
|
8
|
+
* - No `Range` header, or a header this parser cannot make sense of (wrong unit,
|
|
9
|
+
* non-numeric bounds, an empty `bytes=-` spec, a `first > last` range, or more
|
|
10
|
+
* than one comma-separated range) is reported as `{ kind: "none" }`. RFC 7233
|
|
11
|
+
* §3.1 explicitly permits a server to ignore a Range header it does not want to
|
|
12
|
+
* honor — "A server MAY ignore the Range header field... [and] MAY ignore a
|
|
13
|
+
* Range header field that consists of more than one range" — so treating these
|
|
14
|
+
* as "serve the whole representation" is spec-legal, not a shortcut, and it is
|
|
15
|
+
* the safe choice for a header this parser cannot fully trust: no multipart/
|
|
16
|
+
* byteranges body needs to exist for that path to be correct.
|
|
17
|
+
* - A syntactically valid single range that is out of bounds for `totalLength`
|
|
18
|
+
* (e.g. `bytes=1000-` against a 10-byte resource) is reported as
|
|
19
|
+
* `{ kind: "unsatisfiable" }` — callers should respond `416` with
|
|
20
|
+
* `Content-Range: bytes * /{totalLength}` per RFC 7233 §4.4.
|
|
21
|
+
* - A satisfiable range clamps its end to `totalLength - 1` (RFC 7233 §2.1: "If
|
|
22
|
+
* the last-byte-pos value is absent, or if the value is greater than or equal
|
|
23
|
+
* to the current length of the representation data, the byte range is
|
|
24
|
+
* interpreted as the remainder of the representation").
|
|
25
|
+
*
|
|
26
|
+
* Every numeric bound is validated against `totalLength` (or rejected as
|
|
27
|
+
* non-finite) BEFORE a caller ever slices bytes with it — `{ kind: "range" }`'s
|
|
28
|
+
* `start`/`end` are always in `[0, totalLength - 1]` with `start <= end`, so a
|
|
29
|
+
* caller never over-reads or has to re-validate.
|
|
30
|
+
*/
|
|
31
|
+
/** `bytes=<start>-<end>`, both optional (`-` is mandatory; digits are not) — matches "123-456",
|
|
32
|
+
* "123-", and "-456", but not "123" (no dash) or anything with a non-digit in either half. */
|
|
33
|
+
const SINGLE_RANGE_PATTERN = /^bytes=(\d*)-(\d*)$/;
|
|
34
|
+
/**
|
|
35
|
+
* Suffix range: `bytes=-500` -> the last 500 bytes.
|
|
36
|
+
*
|
|
37
|
+
* @complexity O(1)
|
|
38
|
+
*/
|
|
39
|
+
function resolveSuffixRange({ endText, totalLength }, _optional = {}) {
|
|
40
|
+
const suffixLength = Number(endText);
|
|
41
|
+
if (!Number.isFinite(suffixLength) || suffixLength <= 0)
|
|
42
|
+
return { kind: "unsatisfiable" };
|
|
43
|
+
const start = Math.max(0, totalLength - suffixLength);
|
|
44
|
+
return { kind: "range", start, end: totalLength - 1 };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Bounded (or open-ended) range: `bytes=100-`, `bytes=100-200`.
|
|
48
|
+
*
|
|
49
|
+
* @complexity O(1)
|
|
50
|
+
*/
|
|
51
|
+
function resolveBoundedRange({ startText, endText, totalLength }, _optional = {}) {
|
|
52
|
+
const start = Number(startText);
|
|
53
|
+
if (!Number.isFinite(start) || start >= totalLength)
|
|
54
|
+
return { kind: "unsatisfiable" };
|
|
55
|
+
const end = endText === "" ? totalLength - 1 : Math.min(Number(endText), totalLength - 1);
|
|
56
|
+
if (!Number.isFinite(end) || end < start)
|
|
57
|
+
return { kind: "unsatisfiable" };
|
|
58
|
+
return { kind: "range", start, end };
|
|
59
|
+
}
|
|
60
|
+
/** The two bound texts of a single `bytes=<start>-<end>` spec (each possibly empty), or undefined. */
|
|
61
|
+
function readRangeBounds({ header }, _optional = {}) {
|
|
62
|
+
const match = SINGLE_RANGE_PATTERN.exec(header.trim());
|
|
63
|
+
return match ? { startText: match[1] ?? "", endText: match[2] ?? "" } : undefined;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* @complexity O(1) — one regex match against a bounded-shape string and a handful of comparisons;
|
|
67
|
+
* no work proportional to `totalLength` or to the header's length beyond the regex engine's own
|
|
68
|
+
* linear scan of the (short, request-header-sized) input.
|
|
69
|
+
* @overallScore 100
|
|
70
|
+
*/
|
|
71
|
+
export function parseRangeHeader(required, _optional = {}) {
|
|
72
|
+
const { header, totalLength } = required;
|
|
73
|
+
if (!header)
|
|
74
|
+
return { kind: "none" };
|
|
75
|
+
// More than one range (comma-separated): RFC 7233 §3.1 explicitly allows a server to ignore this
|
|
76
|
+
// rather than build a multipart/byteranges response — see file header.
|
|
77
|
+
if (header.includes(","))
|
|
78
|
+
return { kind: "none" };
|
|
79
|
+
const bounds = readRangeBounds({ header });
|
|
80
|
+
if (!bounds)
|
|
81
|
+
return { kind: "none" };
|
|
82
|
+
const { startText, endText } = bounds;
|
|
83
|
+
if (startText === "" && endText === "")
|
|
84
|
+
return { kind: "none" }; // "bytes=-" — no bound at all.
|
|
85
|
+
// Nothing in an empty (or negative-length, which cannot occur for a real byte count but is
|
|
86
|
+
// guarded anyway) resource can ever satisfy a range.
|
|
87
|
+
if (totalLength <= 0)
|
|
88
|
+
return { kind: "unsatisfiable" };
|
|
89
|
+
return startText === ""
|
|
90
|
+
? resolveSuffixRange({ endText, totalLength })
|
|
91
|
+
: resolveBoundedRange({ startText, endText, totalLength });
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=range.js.map
|
package/dist/rate-limit.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Fixed-window counting over a host-owned clock and counter store. */
|
|
2
2
|
import type { Clock } from '@jini-ai/core/primitives';
|
|
3
|
+
import type { RateLimiter } from '@jini-ai/core/contracts/server';
|
|
3
4
|
export type { Clock } from '@jini-ai/core/primitives';
|
|
4
5
|
/** Host-selected window and request budget; no product profiles live here. */
|
|
5
6
|
export interface RateLimitProfile {
|
|
@@ -7,12 +8,6 @@ export interface RateLimitProfile {
|
|
|
7
8
|
readonly max: number;
|
|
8
9
|
readonly burst: number;
|
|
9
10
|
}
|
|
10
|
-
export type RateLimitResult = {
|
|
11
|
-
allowed: true;
|
|
12
|
-
} | {
|
|
13
|
-
allowed: false;
|
|
14
|
-
retryAfterSeconds: number;
|
|
15
|
-
};
|
|
16
11
|
export interface CounterWindow {
|
|
17
12
|
readonly windowStartMs: number;
|
|
18
13
|
readonly count: number;
|
|
@@ -36,13 +31,6 @@ export interface CounterStore {
|
|
|
36
31
|
entries(required: Record<string, never>): Promise<Iterable<readonly [string, CounterWindow]>>;
|
|
37
32
|
size(required: Record<string, never>): Promise<number>;
|
|
38
33
|
}
|
|
39
|
-
export interface RateLimiter {
|
|
40
|
-
/** Resolves the budget decision; rejects missing, non-string or empty keys with TypeError. */
|
|
41
|
-
check(required: {
|
|
42
|
-
key: string;
|
|
43
|
-
}): Promise<RateLimitResult>;
|
|
44
|
-
size(required: Record<string, never>): Promise<number>;
|
|
45
|
-
}
|
|
46
34
|
/**
|
|
47
35
|
* Creates an isolated in-memory CounterStore adapter.
|
|
48
36
|
* @param _required - No required configuration for this adapter.
|