@orkestrel/server 0.0.2 → 0.0.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.
@@ -1,1665 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _orkestrel_contract = require("@orkestrel/contract");
3
- //#region src/core/constants.ts
4
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
5
- var DEFAULT_DRAIN_MS = 1e4;
6
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
7
- var DEFAULT_BODY_LIMIT = 1048576;
8
- /**
9
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
10
- * the body pipeline's byte-counting `TransformStream` enforces when
11
- * transparently decompressing a `Content-Encoding` request body.
12
- *
13
- * @remarks
14
- * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
15
- * can inflate by many orders of magnitude — a classic decompression bomb.
16
- * Capping the decompressed byte count makes the pipe ABORT the moment the
17
- * output would exceed this, BEFORE the full bomb is materialized, so the
18
- * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
19
- * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
20
- * consumer raises it via {@link import('./types.js').BodyOptions}
21
- * `decompression` for a workload that genuinely ships larger decompressed
22
- * bodies.
23
- */
24
- var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
25
- /**
26
- * The SSE response headers the `openStream` seam always sets.
27
- *
28
- * @remarks
29
- * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
30
- * keeps a proxy from caching the stream; `keep-alive` holds the connection
31
- * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
32
- * events flush promptly rather than batching. Frozen so a consumer can read
33
- * but never mutate the shared default; `openStream` merges any
34
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
35
- */
36
- var SSE_HEADERS = Object.freeze({
37
- "Content-Type": "text/event-stream; charset=utf-8",
38
- "Cache-Control": "no-cache",
39
- Connection: "keep-alive",
40
- "X-Accel-Buffering": "no"
41
- });
42
- /**
43
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
44
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
45
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
46
- * instead) rather than ever riding into a response header or `context.state`
47
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
48
- * shared default.
49
- */
50
- var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
51
- /**
52
- * The set of bare `Content-Type`s `isCompressibleType` treats as
53
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
54
- * `+xml`) rules that helper also applies.
55
- *
56
- * @remarks
57
- * The text-shaped application types worth compressing (JSON / JavaScript /
58
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
59
- * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
60
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
61
- * but never mutates the shared default.
62
- */
63
- var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
64
- "application/json",
65
- "application/javascript",
66
- "application/xml",
67
- "application/xhtml+xml",
68
- "application/rss+xml",
69
- "application/atom+xml",
70
- "application/ld+json",
71
- "application/manifest+json",
72
- "application/vnd.api+json",
73
- "application/wasm",
74
- "image/svg+xml",
75
- "application/pdf"
76
- ]);
77
- /**
78
- * The default {@link Encoding} content-codings the substrate offers, in
79
- * PREFERENCE order — `gzip` / `deflate`.
80
- *
81
- * @remarks
82
- * `identity` (no compression) is always implicitly acceptable and is NOT
83
- * listed here — it is the fall-through when a client accepts none of these.
84
- * Brotli is omitted per the core's `CompressionStream`-only decision (see
85
- * {@link Encoding}). Frozen so a consumer can read but never mutate the
86
- * shared default.
87
- */
88
- var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
89
- //#endregion
90
- //#region src/core/errors.ts
91
- /**
92
- * An error a handler (or middleware) throws to produce an HTTP response of a
93
- * specific status.
94
- *
95
- * @remarks
96
- * Carries the HTTP `status` to send and an optional `context` record (the
97
- * offending field / value). The server's built-in error boundary catches it
98
- * and renders a response of `status` with the error's `message` as the body
99
- * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
100
- * deliberate signal), unlike a generic throw whose message is hidden unless
101
- * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
102
- * specific statuses, or throw it directly. Narrow a caught value with
103
- * {@link isHTTPError}.
104
- *
105
- * @example
106
- * ```ts
107
- * import { HTTPError } from '@src/core'
108
- *
109
- * const handler = async (request: Request): Promise<Response> => {
110
- * const user = await find(new URL(request.url).searchParams.get('id'))
111
- * if (user === undefined) throw new HTTPError(404, 'user not found')
112
- * return Response.json(user)
113
- * }
114
- * ```
115
- */
116
- var HTTPError = class extends Error {
117
- status;
118
- context;
119
- constructor(status, message, context) {
120
- super(message);
121
- this.name = "HTTPError";
122
- this.status = status;
123
- this.context = context;
124
- }
125
- };
126
- /**
127
- * The {@link HTTPError} thrown when a request body exceeds the body
128
- * pipeline's size limit — a `413 Content Too Large`.
129
- *
130
- * @remarks
131
- * Thrown by `readBody` (and the middleware context's cached `body()`) when
132
- * the received bytes exceed the configured {@link
133
- * import('./types.js').BodyOptions.limit}, carrying the `limit` in its
134
- * `context`. The server's error boundary renders it as a 413.
135
- *
136
- * @example
137
- * ```ts
138
- * import { ContentTooLargeError, isHTTPError } from '@src/core'
139
- *
140
- * try {
141
- * await readBody(request, { limit: 1024 })
142
- * } catch (error) {
143
- * if (isHTTPError(error)) console.log(error.status) // 413
144
- * }
145
- * ```
146
- */
147
- var ContentTooLargeError = class extends HTTPError {
148
- constructor(limit) {
149
- super(413, `request body exceeds the ${limit}-byte limit`, { limit });
150
- this.name = "ContentTooLargeError";
151
- }
152
- };
153
- /**
154
- * Narrow an unknown caught value to an {@link HTTPError} (including its
155
- * subclasses, e.g. {@link ContentTooLargeError}).
156
- *
157
- * @param value - The value to test (typically a `catch` binding)
158
- * @returns `true` when `value` is an {@link HTTPError}
159
- *
160
- * @example
161
- * ```ts
162
- * import { isHTTPError } from '@src/core'
163
- *
164
- * try {
165
- * await handle(request)
166
- * } catch (error) {
167
- * if (isHTTPError(error)) console.log(error.status, error.message)
168
- * }
169
- * ```
170
- */
171
- function isHTTPError(value) {
172
- return value instanceof HTTPError;
173
- }
174
- //#endregion
175
- //#region src/core/helpers.ts
176
- /**
177
- * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
178
- * handler into one request handler — the frozen middleware seam (§5.1).
179
- *
180
- * @remarks
181
- * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
182
- * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
183
- * `terminal`. Each middleware's `next` may be called with a substituted
184
- * `Request` (the downstream chain then sees that request instead of the
185
- * original), called with no argument (the original request continues
186
- * downstream), or NOT called at all (a short-circuit — the middleware's own
187
- * returned `Response` is sent, and everything downstream never runs). A
188
- * SECOND call to the same `next` within one middleware invocation REJECTS —
189
- * each link runs the chain at most once, so a middleware cannot fork the
190
- * request into two divergent downstream runs.
191
- *
192
- * @typeParam TState - The consumer's opaque per-request state type
193
- * @param middleware - The ordered chain, outermost first
194
- * @param terminal - The innermost handler the chain ultimately reaches
195
- * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
196
- *
197
- * @example
198
- * ```ts
199
- * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
200
- * const response = await next()
201
- * response.headers.set('X-Powered-By', 'orkestrel')
202
- * return response
203
- * }
204
- *
205
- * const handle = compose([withHeader], async () => new Response('ok'))
206
- * ```
207
- */
208
- function compose(middleware, terminal) {
209
- return async (request, context) => {
210
- const dispatch = (index, currentRequest) => {
211
- const layer = middleware[index];
212
- if (layer === void 0) return terminal(currentRequest, context);
213
- let called = false;
214
- const next = (nextRequest) => {
215
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
216
- called = true;
217
- return dispatch(index + 1, nextRequest ?? currentRequest);
218
- };
219
- return Promise.resolve(layer(currentRequest, context, next));
220
- };
221
- return dispatch(0, request);
222
- };
223
- }
224
- /**
225
- * Parse a raw `Cookie:` request header into a `name → value` lookup.
226
- *
227
- * @remarks
228
- * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
229
- * cookie-pair separator never precedes it), while every later segment has its
230
- * inter-pair separator (ASCII space/tab) stripped before parsing — so a
231
- * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
232
- * {@link isCookieName} rather than silently reconciling into a
233
- * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
234
- * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
235
- * malformed header yields an empty record, never throws (AGENTS §14).
236
- *
237
- * @param header - The raw `Cookie` header value (possibly `undefined`)
238
- * @returns A record of every parsed cookie, `name → decoded value`
239
- *
240
- * @example
241
- * ```ts
242
- * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
243
- * ```
244
- */
245
- function parseCookies(header) {
246
- const out = {};
247
- if (header === void 0) return out;
248
- const segments = header.split(";");
249
- for (let index = 0; index < segments.length; index += 1) {
250
- const raw = segments[index] ?? "";
251
- const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
252
- const eq = segment.indexOf("=");
253
- if (eq < 0) continue;
254
- const name = segment.slice(0, eq);
255
- if (!isCookieName(name)) continue;
256
- out[name] = decodeCookieValue(segment.slice(eq + 1).trim());
257
- }
258
- return out;
259
- }
260
- /**
261
- * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
262
- * cookie-token chars with NO surrounding (or interior) whitespace.
263
- *
264
- * @remarks
265
- * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
266
- * which excludes every whitespace char (ASCII and Unicode) plus controls,
267
- * separators, and `=`. The {@link parseCookies} hardening that stops a
268
- * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
269
- *
270
- * @param value - The candidate cookie name
271
- * @returns `true` when `value` is a valid, whitespace-free cookie token
272
- *
273
- * @example
274
- * ```ts
275
- * isCookieName('__Host-session') // true
276
- * isCookieName(' __Host-session') // false — whitespace-padded
277
- * ```
278
- */
279
- function isCookieName(value) {
280
- return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
281
- }
282
- /**
283
- * Decode a cookie value with `decodeURIComponent`, falling back to the raw
284
- * text when the value is not valid percent-encoding.
285
- *
286
- * @param raw - The raw (trimmed) cookie value
287
- * @returns The URL-decoded value, or the raw value when decoding would throw
288
- *
289
- * @example
290
- * ```ts
291
- * decodeCookieValue('a%20b') // 'a b'
292
- * decodeCookieValue('%') // '%' — malformed escape stays literal
293
- * ```
294
- */
295
- function decodeCookieValue(raw) {
296
- try {
297
- return decodeURIComponent(raw);
298
- } catch {
299
- return raw;
300
- }
301
- }
302
- /**
303
- * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
304
- * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
305
- * attributes with before emitting them.
306
- *
307
- * @remarks
308
- * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
309
- * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
310
- * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
311
- * directive. Total — never throws (a bad value returns `false`).
312
- *
313
- * @param value - The candidate attribute value (a `Domain` or `Path`)
314
- * @returns `true` when `value` carries no separator / whitespace / control char
315
- *
316
- * @example
317
- * ```ts
318
- * isCookieAttribute('/app') // true
319
- * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
320
- * ```
321
- */
322
- function isCookieAttribute(value) {
323
- for (const char of value) {
324
- if (char === ";" || char === "," || /\s/.test(char)) return false;
325
- const code = char.codePointAt(0);
326
- if (code !== void 0 && (code < 32 || code === 127)) return false;
327
- }
328
- return true;
329
- }
330
- /**
331
- * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
332
- *
333
- * @remarks
334
- * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
335
- * appends the present {@link CookieOptions} attributes in canonical order:
336
- * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
337
- * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
338
- * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
339
- * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
340
- * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
341
- * the `secure` option (the spec requires it); an un-resolved `undefined`
342
- * `secure` here falls to OFF — request-aware callers resolve it first via
343
- * {@link resolveSecure}.
344
- *
345
- * @param name - The cookie name
346
- * @param value - The cookie value (URL-encoded into the output)
347
- * @param options - The {@link CookieOptions} attributes; see its fields for defaults
348
- * @returns The `Set-Cookie` header value
349
- * @throws {HTTPError} When `domain` or `path` carries an injection char
350
- *
351
- * @example
352
- * ```ts
353
- * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
354
- * ```
355
- */
356
- function serializeCookie(name, value, options) {
357
- const sameSite = options?.sameSite ?? "Lax";
358
- const domain = options?.domain;
359
- if (domain !== void 0 && !isCookieAttribute(domain)) throw new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`);
360
- const path = options?.path ?? "/";
361
- if (!isCookieAttribute(path)) throw new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`);
362
- const secure = sameSite === "None" || options?.secure === true;
363
- const parts = [`${name}=${encodeURIComponent(value)}`];
364
- if (domain !== void 0) parts.push(`Domain=${domain}`);
365
- parts.push(`Path=${path}`);
366
- if (options?.maxAge !== void 0) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);
367
- if (options?.httpOnly !== false) parts.push("HttpOnly");
368
- if (secure) parts.push("Secure");
369
- parts.push(`SameSite=${sameSite}`);
370
- return parts.join("; ");
371
- }
372
- /**
373
- * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
374
- * `secure` setting and whether the request arrived over TLS.
375
- *
376
- * @remarks
377
- * `true` / `false` are explicit overrides. `undefined` (the secure default —
378
- * the option omitted) resolves to `encrypted` — `Secure` on a TLS
379
- * connection, off over plaintext HTTP — so a production HTTPS deployment
380
- * gets `Secure` automatically while local-dev HTTP still works.
381
- *
382
- * @param secure - The {@link CookieOptions} `secure` setting
383
- * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
384
- * @returns The concrete `Secure` flag to emit
385
- *
386
- * @example
387
- * ```ts
388
- * resolveSecure(undefined, true) // true
389
- * resolveSecure(undefined, false) // false
390
- * resolveSecure(false, true) // false — explicit override wins
391
- * ```
392
- */
393
- function resolveSecure(secure, encrypted) {
394
- if (secure === true || secure === false) return secure;
395
- return encrypted;
396
- }
397
- /**
398
- * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
399
- * clobbering a prior one.
400
- *
401
- * @remarks
402
- * `Headers.append` already accumulates repeated headers (unlike node's
403
- * `setHeader`), so this is a thin, self-documenting wrapper naming the
404
- * cookie-append intent — the primitive {@link writeSignedCookie} /
405
- * {@link clearCookie} use.
406
- *
407
- * @param headers - The response `Headers` to write into
408
- * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
409
- *
410
- * @example
411
- * ```ts
412
- * const headers = new Headers()
413
- * appendCookie(headers, serializeCookie('a', '1'))
414
- * appendCookie(headers, serializeCookie('b', '2'))
415
- * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
416
- * ```
417
- */
418
- function appendCookie(headers, cookie) {
419
- headers.append("set-cookie", cookie);
420
- }
421
- /**
422
- * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
423
- * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
424
- *
425
- * @remarks
426
- * The cookie value is `await signToken(value, { secret })`
427
- * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
428
- * cookie — the same secret rotation and tamper rejection, no second HMAC
429
- * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
430
- * signing is asynchronous (§3 of the proposal).
431
- *
432
- * @param headers - The response `Headers` to write into
433
- * @param name - The cookie name
434
- * @param value - The opaque value to sign into the cookie
435
- * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
436
- * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
437
- *
438
- * @example
439
- * ```ts
440
- * const headers = new Headers()
441
- * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
442
- * ```
443
- */
444
- async function writeSignedCookie(headers, name, value, secret, options) {
445
- appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
446
- }
447
- /**
448
- * Read + verify a SIGNED cookie off a request — TOTAL, returning the
449
- * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
450
- *
451
- * @remarks
452
- * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
453
- * and verifies it with {@link verifyToken} against `secret` (a rotation list
454
- * accepts a cookie signed by any of its secrets). ANY failure — an absent
455
- * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
456
- *
457
- * @param request - The `Request` to read the `Cookie` header from
458
- * @param name - The cookie name to read
459
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
460
- * @returns The embedded value when the cookie is present + valid, else `undefined`
461
- *
462
- * @example
463
- * ```ts
464
- * const value = await readSignedCookie(request, 'session', 'secret')
465
- * ```
466
- */
467
- async function readSignedCookie(request, name, secret) {
468
- const cookie = parseCookies(request.headers.get("cookie") ?? void 0)[name];
469
- return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
470
- }
471
- /**
472
- * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
473
- *
474
- * @remarks
475
- * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
476
- * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
477
- * a cookie when those MATCH the one it set).
478
- *
479
- * @param headers - The response `Headers` to write into
480
- * @param name - The cookie name to clear
481
- * @param options - The {@link CookieOptions} that must match the original cookie
482
- *
483
- * @example
484
- * ```ts
485
- * const headers = new Headers()
486
- * clearCookie(headers, 'session')
487
- * ```
488
- */
489
- function clearCookie(headers, name, options) {
490
- appendCookie(headers, serializeCookie(name, "", {
491
- ...options,
492
- maxAge: 0
493
- }));
494
- }
495
- /**
496
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
497
- * {@link verifyToken} use, and the signature encoding for the HMAC.
498
- *
499
- * @param bytes - The bytes to encode
500
- * @returns The base64url string (no padding)
501
- *
502
- * @example
503
- * ```ts
504
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
505
- * ```
506
- */
507
- function encodeBase64Url(bytes) {
508
- let binary = "";
509
- for (const byte of bytes) binary += String.fromCharCode(byte);
510
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
511
- }
512
- /**
513
- * Decode a base64url string back into its bytes — the inverse of
514
- * {@link encodeBase64Url}.
515
- *
516
- * @remarks
517
- * Restores the standard base64 alphabet + padding before decoding with
518
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
519
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
520
- *
521
- * @param value - The base64url string to decode
522
- * @returns The decoded bytes
523
- * @throws {DOMException} When `value` is not valid base64url
524
- *
525
- * @example
526
- * ```ts
527
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
528
- * ```
529
- */
530
- function decodeBase64Url(value) {
531
- const restored = value.replace(/-/g, "+").replace(/_/g, "/");
532
- const padding = restored.length % 4 === 0 ? "" : "=".repeat(4 - restored.length % 4);
533
- const binary = atob(restored + padding);
534
- const bytes = new Uint8Array(binary.length);
535
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
536
- return bytes;
537
- }
538
- /**
539
- * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
540
- *
541
- * @remarks
542
- * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
543
- * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
544
- * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
545
- * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
546
- * {@link TokenSecret} (the current secret, or the head of a rotation list).
547
- * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
548
- * misconfigured secret with no usable entry THROWS an {@link HTTPError}
549
- * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
550
- * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
551
- *
552
- * @param value - The opaque value to embed (a session id, a deployment marker)
553
- * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
554
- * @returns The signed `<payload>.<signature>` token string
555
- * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
556
- *
557
- * @example
558
- * ```ts
559
- * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
560
- * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
561
- * ```
562
- */
563
- async function signToken(value, options) {
564
- const secret = normalizeSecret(options.secret)[0];
565
- if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
566
- const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
567
- const encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({
568
- value,
569
- exp
570
- })));
571
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
572
- name: "HMAC",
573
- hash: "SHA-256"
574
- }, false, ["sign"]);
575
- const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
576
- return `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`;
577
- }
578
- /**
579
- * Verify a stateless token and return its embedded value — TOTAL, never throws.
580
- *
581
- * @remarks
582
- * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
583
- * value containing dots survives), and checks the payload's HMAC-SHA256
584
- * signature against EACH {@link TokenSecret} candidate via
585
- * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
586
- * retired, §3 of the proposal), accepting the token on the first match (the
587
- * rotation path). It then decodes + narrows the payload (`isRecord` +
588
- * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
589
- * rejects an expired token. ANY failure — a malformed token, a bad signature,
590
- * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
591
- * yields `undefined` rather than throwing.
592
- *
593
- * @param token - The candidate token string (from a request header/cookie)
594
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
595
- * @returns The embedded value when the token is valid + unexpired, else `undefined`
596
- *
597
- * @example
598
- * ```ts
599
- * await verifyToken('bad.token', 'shh') // undefined — never throws
600
- * ```
601
- */
602
- async function verifyToken(token, secret) {
603
- const secrets = normalizeSecret(secret);
604
- if (secrets.length === 0) return void 0;
605
- const dot = token.lastIndexOf(".");
606
- if (dot < 0) return void 0;
607
- const encoded = token.slice(0, dot);
608
- const signatureText = token.slice(dot + 1);
609
- try {
610
- const signature = decodeBase64Url(signatureText);
611
- const data = new TextEncoder().encode(encoded);
612
- for (const candidate of secrets) {
613
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
614
- name: "HMAC",
615
- hash: "SHA-256"
616
- }, false, ["verify"]);
617
- if (await crypto.subtle.verify("HMAC", key, signature, data)) return decodeTokenPayload(encoded);
618
- }
619
- return;
620
- } catch {
621
- return;
622
- }
623
- }
624
- /**
625
- * Decode + narrow a signed token's base64url JSON payload, honoring its
626
- * expiry — the shared decode step {@link verifyToken} applies after a
627
- * signature match.
628
- *
629
- * @remarks
630
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
631
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
632
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
633
- *
634
- * @param encoded - The base64url-encoded payload segment (before the last `.`)
635
- * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
636
- */
637
- function decodeTokenPayload(encoded) {
638
- try {
639
- const text = new TextDecoder().decode(decodeBase64Url(encoded));
640
- const payload = JSON.parse(text);
641
- if (!(0, _orkestrel_contract.isRecord)(payload)) return void 0;
642
- if (typeof payload.value !== "string") return void 0;
643
- if (payload.exp !== void 0 && typeof payload.exp !== "number") return void 0;
644
- if (payload.exp !== void 0 && Date.now() >= payload.exp) return void 0;
645
- return payload.value;
646
- } catch {
647
- return;
648
- }
649
- }
650
- /**
651
- * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
652
- * backs both {@link signToken} and {@link verifyToken}.
653
- *
654
- * @remarks
655
- * A single string becomes a one-element list; a rotation list is copied. Any
656
- * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
657
- * emptiness test; each kept secret is stored VERBATIM). The first kept
658
- * element is the signing secret; all kept are accepted on verify.
659
- *
660
- * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
661
- * @returns The kept (non-blank) secrets, in order — empty when none is usable
662
- *
663
- * @example
664
- * ```ts
665
- * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
666
- * ```
667
- */
668
- function normalizeSecret(secret) {
669
- return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
670
- }
671
- /**
672
- * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
673
- * into its q-sorted entries.
674
- *
675
- * @remarks
676
- * Splits on `,`; for each part takes the token before the first `;`
677
- * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
678
- * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
679
- * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
680
- * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
681
- * the header's own order within a tie — a single pass with no backtracking,
682
- * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
683
- * empty/malformed header yields `[]`/best-effort entries, never throws.
684
- *
685
- * @param header - The raw weighted header value
686
- * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
687
- *
688
- * @example
689
- * ```ts
690
- * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
691
- * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
692
- * ```
693
- */
694
- function parseAcceptHeader(header) {
695
- const entries = [];
696
- for (const part of header.split(",")) {
697
- const trimmed = part.trim();
698
- if (trimmed.length === 0) continue;
699
- const semicolon = trimmed.indexOf(";");
700
- const value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase();
701
- if (value.length === 0) continue;
702
- let q = 1;
703
- if (semicolon !== -1) {
704
- const match = /;\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon));
705
- if (match !== null) {
706
- const parsed = Number(match[1]);
707
- if (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed));
708
- }
709
- }
710
- entries.push({
711
- value,
712
- q
713
- });
714
- }
715
- return entries.map((entry, index) => ({
716
- entry,
717
- index
718
- })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
719
- }
720
- /**
721
- * The client's quality (q) for one content-coding from the parsed
722
- * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
723
- * server-preference selection.
724
- *
725
- * @remarks
726
- * Prefers an EXACT named match (including an explicit `;q=0` rejection);
727
- * failing that, a bare `*` wildcard's q applies. A coding that is neither
728
- * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
729
- * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
730
- *
731
- * @param entries - The parsed {@link AcceptEntry} list
732
- * @param coding - The candidate coding to score
733
- * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
734
- *
735
- * @example
736
- * ```ts
737
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
738
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
739
- * ```
740
- */
741
- function codingQuality(entries, coding) {
742
- const named = entries.find((entry) => entry.value === coding);
743
- if (named !== void 0) return named.q;
744
- return entries.find((entry) => entry.value === "*")?.q ?? 0;
745
- }
746
- /**
747
- * Select the best content-coding for an `Accept-Encoding` header from the
748
- * codings the server offers.
749
- *
750
- * @remarks
751
- * Parses the header ({@link parseAcceptHeader}) and scores each `available`
752
- * coding in the SERVER's preference order ({@link codingQuality}), keeping
753
- * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
754
- * client-side tie). Returns `undefined` when the client accepts none of
755
- * `available` (identity — no compression). TOTAL on hostile input.
756
- *
757
- * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
758
- * @param header - The raw `Accept-Encoding` header value
759
- * @param available - The codings the server offers, in preference (tie-break) order
760
- * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
761
- *
762
- * @example
763
- * ```ts
764
- * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
765
- * ```
766
- */
767
- function negotiateEncoding(header, available) {
768
- if (available.length === 0) return void 0;
769
- const entries = parseAcceptHeader(header);
770
- let best;
771
- let bestQuality = 0;
772
- for (const coding of available) {
773
- const quality = codingQuality(entries, coding);
774
- if (quality > bestQuality) {
775
- best = coding;
776
- bestQuality = quality;
777
- }
778
- }
779
- return best;
780
- }
781
- /**
782
- * Rank + quality of one `candidate` media type against the parsed `Accept`
783
- * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
784
- * uses to score each `available` candidate.
785
- *
786
- * @remarks
787
- * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
788
- * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
789
- * `;q=0` entry explicitly rejects the candidate outright (returns
790
- * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
791
- * (less specific) coverage, so a later more-specific match can still allow
792
- * it. Among multiple matching entries, the lowest `rank` wins, and among a
793
- * rank tie the highest `q` wins.
794
- *
795
- * @param entries - The parsed {@link AcceptEntry} list
796
- * @param candidate - The candidate media type to score (e.g. `'text/html'`)
797
- * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
798
- *
799
- * @example
800
- * ```ts
801
- * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
802
- * // { q: 1, rank: 0 }
803
- * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
804
- * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
805
- * ```
806
- */
807
- function matchMediaType(entries, candidate) {
808
- const slash = candidate.indexOf("/");
809
- const type = slash === -1 ? candidate : candidate.slice(0, slash);
810
- let best;
811
- for (const entry of entries) {
812
- let rank;
813
- if (entry.value === candidate) rank = 0;
814
- else if (entry.value === `${type}/*`) rank = 1;
815
- else if (entry.value === "*/*") rank = 2;
816
- if (rank === void 0) continue;
817
- if (entry.q === 0) {
818
- if (rank === 0) return void 0;
819
- continue;
820
- }
821
- if (best === void 0 || rank < best.rank || rank === best.rank && entry.q > best.q) best = {
822
- q: entry.q,
823
- rank
824
- };
825
- }
826
- return best;
827
- }
828
- /**
829
- * The client's quality for one `candidate` language from the parsed
830
- * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
831
- *
832
- * @remarks
833
- * Prefers an exact match, then a primary-tag prefix match (`en` accepts
834
- * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
835
- * is an explicit rejection).
836
- *
837
- * @param entries - The parsed {@link AcceptEntry} list
838
- * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
839
- * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
840
- *
841
- * @example
842
- * ```ts
843
- * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
844
- * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
845
- * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
846
- * ```
847
- */
848
- function languageQuality(entries, candidate) {
849
- const lower = candidate.toLowerCase();
850
- const primary = lower.split("-")[0];
851
- let named;
852
- let prefixed;
853
- let wildcard;
854
- for (const entry of entries) {
855
- const entryPrimary = entry.value.split("-")[0];
856
- if (entry.value === lower) named = entry.q;
857
- else if (entryPrimary === primary) {
858
- if (prefixed === void 0) prefixed = entry.q;
859
- } else if (entry.value === "*") wildcard = entry.q;
860
- }
861
- if (named !== void 0) return named;
862
- if (prefixed !== void 0) return prefixed;
863
- return wildcard ?? 0;
864
- }
865
- /**
866
- * Whether a `Content-Type` is worth compressing.
867
- *
868
- * @remarks
869
- * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
870
- * type, a `+json`/`+xml` structured suffix, or one of the explicit
871
- * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
872
- * binary (`image/png`, `application/zip`) is NOT compressible. An
873
- * absent/empty type is not compressible. TOTAL.
874
- *
875
- * @param type - The response `Content-Type` header value (with or without parameters)
876
- * @returns `true` when the type is text-shaped and worth compressing
877
- *
878
- * @example
879
- * ```ts
880
- * isCompressibleType('application/json; charset=utf-8') // true
881
- * isCompressibleType('image/png') // false
882
- * ```
883
- */
884
- function isCompressibleType(type) {
885
- const semicolon = type.indexOf(";");
886
- const bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase();
887
- if (bare.length === 0) return false;
888
- if (bare.startsWith("text/")) return true;
889
- if (bare.endsWith("+json") || bare.endsWith("+xml")) return true;
890
- return COMPRESSIBLE_TYPES.has(bare);
891
- }
892
- /**
893
- * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
894
- *
895
- * @remarks
896
- * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
897
- * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
898
- * default, encoding-AGNOSTIC, so the tag survives a downstream content
899
- * re-encoding (gzip) and still matches on revalidation — or a STRONG one
900
- * (`"<hash>"`, byte-identity) when `weak` is `false`.
901
- *
902
- * @param body - The full (uncompressed) response body to hash
903
- * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
904
- * @returns The `ETag` header value
905
- *
906
- * @example
907
- * ```ts
908
- * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
909
- * ```
910
- */
911
- async function computeBodyETag(body, weak = true) {
912
- const digest = await crypto.subtle.digest("SHA-256", body);
913
- const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
914
- return weak ? `W/"${hex}"` : `"${hex}"`;
915
- }
916
- /**
917
- * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
918
- * comparison body — the reduction {@link matchesETag} applies to both sides
919
- * before the RFC 7232 §2.3.2 weak comparison.
920
- *
921
- * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
922
- * @returns The tag with any leading `W/` removed (the quotes preserved)
923
- *
924
- * @example
925
- * ```ts
926
- * unwrapETag('W/"abc"') // '"abc"'
927
- * ```
928
- */
929
- function unwrapETag(tag) {
930
- const trimmed = tag.trim();
931
- return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
932
- }
933
- /**
934
- * Whether a request's `If-None-Match` header matches a resource's current
935
- * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
936
- *
937
- * @remarks
938
- * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
939
- * listed tag matches), or the `*` wildcard (matches ANY current
940
- * representation — only a list of exactly `*` is the wildcard). Comparison is
941
- * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
942
- * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
943
- * malformed/empty header matches nothing, never throws.
944
- *
945
- * @param header - The raw `If-None-Match` header value
946
- * @param etag - The resource's current `ETag`
947
- * @returns `true` when the conditional matches (the caller answers `304`)
948
- *
949
- * @example
950
- * ```ts
951
- * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
952
- * matchesETag('*', 'W/"anything"') // true — wildcard
953
- * ```
954
- */
955
- function matchesETag(header, etag) {
956
- const trimmed = header.trim();
957
- if (trimmed === "*") return true;
958
- const target = unwrapETag(etag);
959
- for (const member of trimmed.split(",")) {
960
- const candidate = member.trim();
961
- if (candidate.length === 0) continue;
962
- if (unwrapETag(candidate) === target) return true;
963
- }
964
- return false;
965
- }
966
- /**
967
- * Parse an HTTP `Range` request header against a known resource `size` —
968
- * TOTAL, returning a {@link RangeSpec} or `undefined`.
969
- *
970
- * @remarks
971
- * Handles the three single-range `bytes=` forms — closed (`start-end`), open
972
- * (`start-`), and suffix (`-suffixLength`) — clamping the window to
973
- * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
974
- * `{ satisfiable: true, start, end }` for an overlapping range,
975
- * `{ satisfiable: false }` for a range wholly past the resource, and
976
- * `undefined` for the "serve the whole resource" case: an ABSENT header, a
977
- * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
978
- * supported), or any malformed/non-finite bound. NEVER throws on a hostile
979
- * header.
980
- *
981
- * @param header - The raw `Range` header value
982
- * @param size - The resource's total byte length
983
- * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
984
- *
985
- * @example
986
- * ```ts
987
- * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
988
- * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
989
- * ```
990
- */
991
- function parseRange(header, size) {
992
- if (header === void 0) return void 0;
993
- const match = /^bytes=(.*)$/.exec(header.trim());
994
- if (match === null) return void 0;
995
- const spec = match[1].trim();
996
- if (spec.includes(",")) return void 0;
997
- const dash = spec.indexOf("-");
998
- if (dash < 0) return void 0;
999
- const startText = spec.slice(0, dash).trim();
1000
- const endText = spec.slice(dash + 1).trim();
1001
- if (startText === "") {
1002
- const suffix = Number(endText);
1003
- if (endText === "" || !Number.isInteger(suffix) || suffix <= 0) return void 0;
1004
- if (size === 0) return { satisfiable: false };
1005
- return {
1006
- satisfiable: true,
1007
- start: Math.max(0, size - suffix),
1008
- end: size - 1
1009
- };
1010
- }
1011
- const start = Number(startText);
1012
- if (!Number.isInteger(start) || start < 0) return void 0;
1013
- if (start >= size) return { satisfiable: false };
1014
- if (endText === "") return {
1015
- satisfiable: true,
1016
- start,
1017
- end: size - 1
1018
- };
1019
- const end = Number(endText);
1020
- if (!Number.isInteger(end) || end < start) return void 0;
1021
- return {
1022
- satisfiable: true,
1023
- start,
1024
- end: Math.min(end, size - 1)
1025
- };
1026
- }
1027
- /**
1028
- * Resolve the `Access-Control-Allow-Origin` value for a request.
1029
- *
1030
- * @remarks
1031
- * `'*'` and a single origin string pass straight through. An allow-list
1032
- * echoes the request's `Origin` only when it is present in the list, else
1033
- * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1034
- * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1035
- * NEVER reflected even if `'null'` were listed, closing the hostile-context
1036
- * cross-origin-access hole.
1037
- *
1038
- * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
1039
- * @param requestOrigin - The request's `Origin` header value, if present
1040
- * @returns The allow-origin value to send, or `undefined` to set no header
1041
- *
1042
- * @example
1043
- * ```ts
1044
- * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
1045
- * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
1046
- * ```
1047
- */
1048
- function resolveOrigin(origin, requestOrigin) {
1049
- if ((0, _orkestrel_contract.isString)(origin)) return origin;
1050
- if (!(0, _orkestrel_contract.isString)(requestOrigin)) return void 0;
1051
- if (requestOrigin === "null") return void 0;
1052
- return origin.includes(requestOrigin) ? requestOrigin : void 0;
1053
- }
1054
- /**
1055
- * Merge a `Vary` value into an existing `Vary` header without duplication.
1056
- *
1057
- * @remarks
1058
- * Splits `existing` on `,`, trims each member, and appends `value` only when
1059
- * no existing member already matches it case-insensitively (`Vary` header
1060
- * names are case-insensitive). Preserves the existing members' order and
1061
- * appends the new one last.
1062
- *
1063
- * @param existing - The current `Vary` header value, if any
1064
- * @param value - The header name to ensure is listed
1065
- * @returns The merged `Vary` value
1066
- *
1067
- * @example
1068
- * ```ts
1069
- * mergeVary(undefined, 'Origin') // 'Origin'
1070
- * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
1071
- * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
1072
- * ```
1073
- */
1074
- function mergeVary(existing, value) {
1075
- const members = existing === void 0 ? [] : existing.split(",").map((member) => member.trim()).filter((member) => member.length > 0);
1076
- return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1077
- }
1078
- /**
1079
- * Resolve one opt-out, value-bearing security header.
1080
- *
1081
- * @remarks
1082
- * The shared "a `string` value, or `false` to omit, or a default when unset"
1083
- * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1084
- * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1085
- * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1086
- *
1087
- * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
1088
- * @param fallback - The secure-default value used when `value` is unset
1089
- * @returns The header value to set, or `undefined` to omit the header
1090
- *
1091
- * @example
1092
- * ```ts
1093
- * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
1094
- * resolveSecurityHeader(false, 'DENY') // undefined — omitted
1095
- * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
1096
- * ```
1097
- */
1098
- function resolveSecurityHeader(value, fallback) {
1099
- if (value === false) return void 0;
1100
- return value ?? fallback;
1101
- }
1102
- /**
1103
- * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1104
- * header + `context.state`.
1105
- *
1106
- * @remarks
1107
- * A request id is echoed RAW into a response header and log lines, so an
1108
- * untrusted one is a header-injection + log-injection + DoS vector. This
1109
- * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
1110
- * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
1111
- * TOTAL — never throws.
1112
- *
1113
- * @param value - The candidate incoming request id
1114
- * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1115
- *
1116
- * @example
1117
- * ```ts
1118
- * isValidRequestId('req_abc-123') // true
1119
- * isValidRequestId('bad\r\nheader') // false
1120
- * ```
1121
- */
1122
- function isValidRequestId(value) {
1123
- return REQUEST_ID_PATTERN.test(value);
1124
- }
1125
- /**
1126
- * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1127
- * input is not a plain IPv6 address to collapse.
1128
- *
1129
- * @remarks
1130
- * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
1131
- * is the identity) or any string that does not expand to exactly eight
1132
- * hextets. Expands a single `::` into the missing zero hextets, takes the
1133
- * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
1134
- * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
1135
- * first. Total — a malformed address returns `undefined`.
1136
- *
1137
- * @param address - The candidate IPv6 address
1138
- * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
1139
- *
1140
- * @example
1141
- * ```ts
1142
- * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1143
- * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1144
- * ```
1145
- */
1146
- function ipv6Network(address) {
1147
- if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1148
- const percent = address.indexOf("%");
1149
- const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
1150
- if (halves.length > 2) return void 0;
1151
- const head = halves[0] === "" ? [] : halves[0].split(":");
1152
- const tail = halves.length === 2 ? halves[1] === "" ? [] : halves[1].split(":") : [];
1153
- let groups;
1154
- if (halves.length === 2) {
1155
- const missing = 8 - head.length - tail.length;
1156
- if (missing < 0) return void 0;
1157
- groups = [
1158
- ...head,
1159
- ...Array.from({ length: missing }, () => "0"),
1160
- ...tail
1161
- ];
1162
- } else groups = head;
1163
- if (groups.length !== 8) return void 0;
1164
- const prefix = [];
1165
- for (const group of groups.slice(0, 4)) {
1166
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return void 0;
1167
- prefix.push(Number.parseInt(group, 16).toString(16));
1168
- }
1169
- return `${prefix.join(":")}::/64`;
1170
- }
1171
- /**
1172
- * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1173
- * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1174
- *
1175
- * @remarks
1176
- * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1177
- * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1178
- * real identity is the `/64` network. Delegates the IPv6 collapse to
1179
- * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1180
- * a malformed string) is kept unchanged.
1181
- *
1182
- * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1183
- * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1184
- *
1185
- * @example
1186
- * ```ts
1187
- * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1188
- * clientRateKey('192.0.2.1') // '192.0.2.1'
1189
- * ```
1190
- */
1191
- function clientRateKey(address) {
1192
- return ipv6Network(address) ?? address;
1193
- }
1194
- /**
1195
- * Serialize one {@link SSEMessage} to the SSE wire.
1196
- *
1197
- * @remarks
1198
- * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1199
- * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1200
- * (so a consuming parser's multi-`data` concat reproduces the original
1201
- * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1202
- * a `data:` line), then the terminating blank line.
1203
- *
1204
- * @param message - The event to serialize
1205
- * @returns The SSE wire text for the event (terminated by a blank line)
1206
- *
1207
- * @example
1208
- * ```ts
1209
- * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
1210
- * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
1211
- * ```
1212
- */
1213
- function serializeEvent(message) {
1214
- const lines = [];
1215
- if (message.event !== void 0) lines.push(`event: ${message.event}`);
1216
- if (message.id !== void 0) lines.push(`id: ${message.id}`);
1217
- if (message.retry !== void 0) lines.push(`retry: ${message.retry}`);
1218
- for (const segment of message.data.split(/\r\n|\r|\n/)) lines.push(`data: ${segment}`);
1219
- return `${lines.join("\n")}\n\n`;
1220
- }
1221
- /**
1222
- * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1223
- * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1224
- *
1225
- * @remarks
1226
- * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1227
- * merged under any `options.headers` (a seam-owned key is never overridden),
1228
- * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1229
- * `write` serializes one message ({@link serializeEvent}) and enqueues it;
1230
- * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1231
- * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1232
- * by `end()`, or the consumer cancelled the stream), so a late write never
1233
- * throws.
1234
- *
1235
- * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1236
- * @returns The {@link StreamInterface} handle
1237
- *
1238
- * @example
1239
- * ```ts
1240
- * const stream = openStream()
1241
- * stream.write({ event: 'token', data: 'hello' })
1242
- * stream.end()
1243
- * // return stream.response from the route handler
1244
- * ```
1245
- */
1246
- function openStream(options) {
1247
- const encoder = new TextEncoder();
1248
- let closed = false;
1249
- let controller;
1250
- const body = new ReadableStream({
1251
- start(streamController) {
1252
- controller = streamController;
1253
- },
1254
- cancel() {
1255
- closed = true;
1256
- }
1257
- });
1258
- const headers = new Headers({
1259
- ...SSE_HEADERS,
1260
- ...options?.headers
1261
- });
1262
- const response = new Response(body, {
1263
- status: options?.status ?? 200,
1264
- headers
1265
- });
1266
- const enqueue = (text) => {
1267
- if (closed || controller === void 0) return;
1268
- controller.enqueue(encoder.encode(text));
1269
- };
1270
- return {
1271
- response,
1272
- get closed() {
1273
- return closed;
1274
- },
1275
- write(message) {
1276
- enqueue(serializeEvent(message));
1277
- },
1278
- comment(text) {
1279
- enqueue(`: ${text}\n\n`);
1280
- },
1281
- end() {
1282
- if (closed) return;
1283
- closed = true;
1284
- controller?.close();
1285
- }
1286
- };
1287
- }
1288
- /**
1289
- * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1290
- * or `prototype` — the three keys that, assigned onto a normal object, can
1291
- * reach and mutate `Object.prototype`.
1292
- *
1293
- * @param key - The candidate object key
1294
- * @returns `true` when `key` is one of the three prototype-pollution keys
1295
- *
1296
- * @example
1297
- * ```ts
1298
- * isDangerousKey('__proto__') // true
1299
- * isDangerousKey('name') // false
1300
- * ```
1301
- */
1302
- function isDangerousKey(key) {
1303
- return key === "__proto__" || key === "constructor" || key === "prototype";
1304
- }
1305
- /**
1306
- * Recursively STRIP the prototype-pollution keys from a parsed value IN
1307
- * PLACE.
1308
- *
1309
- * @remarks
1310
- * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1311
- * enumerable `__proto__` DATA property — but that own key becomes a
1312
- * pollution gadget the moment a downstream deep-merge copies it onto a live
1313
- * object. This walks the value and `delete`s any own {@link isDangerousKey}
1314
- * key at every depth, recursing into nested objects + array elements.
1315
- * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1316
- * freshly-parsed value (which nothing else holds yet).
1317
- *
1318
- * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1319
- * @returns The same `value`, with every dangerous key removed at every depth
1320
- *
1321
- * @example
1322
- * ```ts
1323
- * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
1324
- * // { name: 'ok' } — the __proto__ key is gone
1325
- * ```
1326
- */
1327
- function scrubPrototype(value) {
1328
- if (Array.isArray(value)) {
1329
- for (const item of value) scrubPrototype(item);
1330
- return value;
1331
- }
1332
- if ((0, _orkestrel_contract.isRecord)(value)) {
1333
- for (const key of Object.keys(value)) {
1334
- if (isDangerousKey(key)) {
1335
- Reflect.deleteProperty(value, key);
1336
- continue;
1337
- }
1338
- scrubPrototype(value[key]);
1339
- }
1340
- return value;
1341
- }
1342
- return value;
1343
- }
1344
- /**
1345
- * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1346
- *
1347
- * @remarks
1348
- * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
1349
- * throwing a {@link ContentTooLargeError} (413) the instant the running total
1350
- * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
1351
- * collecting an unbounded body. A bodyless request (`request.body === null`)
1352
- * resolves an empty array. A non-positive `limit` means unbounded.
1353
- *
1354
- * @param request - The `Request` to drain
1355
- * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
1356
- * @returns The full request body as one `Uint8Array`
1357
- * @throws {ContentTooLargeError} When the body exceeds `limit`
1358
- *
1359
- * @example
1360
- * ```ts
1361
- * const bytes = await collectRequestBody(request, 1_048_576)
1362
- * ```
1363
- */
1364
- async function collectRequestBody(request, limit) {
1365
- if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1366
- const reader = request.body.getReader();
1367
- const chunks = [];
1368
- let total = 0;
1369
- for (;;) {
1370
- const { done, value } = await reader.read();
1371
- if (done) break;
1372
- total += value.byteLength;
1373
- if (limit > 0 && total > limit) {
1374
- await reader.cancel();
1375
- throw new ContentTooLargeError(limit);
1376
- }
1377
- chunks.push(value);
1378
- }
1379
- const merged = new Uint8Array(total);
1380
- let offset = 0;
1381
- for (const chunk of chunks) {
1382
- merged.set(chunk, offset);
1383
- offset += chunk.byteLength;
1384
- }
1385
- return merged;
1386
- }
1387
- /**
1388
- * Narrow a raw `Content-Encoding` header value to a decompressible
1389
- * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1390
- * whether a request body needs transparent decompression.
1391
- *
1392
- * @remarks
1393
- * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1394
- * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1395
- * the proposal). An absent header, `identity`, an unknown value, or a
1396
- * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1397
- * TOTAL — never asserts the loose `string | null` header.
1398
- *
1399
- * @param header - The raw `Content-Encoding` header value
1400
- * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1401
- *
1402
- * @example
1403
- * ```ts
1404
- * requestEncoding('gzip') // 'gzip'
1405
- * requestEncoding('br') // undefined — unsupported by DecompressionStream
1406
- * ```
1407
- */
1408
- function requestEncoding(header) {
1409
- if (!(0, _orkestrel_contract.isString)(header)) return void 0;
1410
- const value = header.trim().toLowerCase();
1411
- return value === "gzip" || value === "deflate" ? value : void 0;
1412
- }
1413
- /**
1414
- * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1415
- * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1416
- * the zip-bomb defense.
1417
- *
1418
- * @remarks
1419
- * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1420
- * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1421
- * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1422
- * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1423
- * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1424
- * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1425
- * (never conflated with the cap). A non-positive `cap` means uncapped.
1426
- *
1427
- * @param bytes - The compressed bytes to decompress
1428
- * @param encoding - The {@link Encoding} the bytes are compressed with
1429
- * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
1430
- * @returns The decompressed bytes
1431
- * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
1432
- * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
1433
- */
1434
- async function decompressRequestBody(bytes, encoding, cap) {
1435
- let total = 0;
1436
- const capStream = new TransformStream({ transform(chunk, controller) {
1437
- total += chunk.byteLength;
1438
- if (cap > 0 && total > cap) {
1439
- controller.error(new ContentTooLargeError(cap));
1440
- return;
1441
- }
1442
- controller.enqueue(chunk);
1443
- } });
1444
- const reader = new ReadableStream({ start(controller) {
1445
- controller.enqueue(bytes);
1446
- controller.close();
1447
- } }).pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream).getReader();
1448
- const chunks = [];
1449
- let size = 0;
1450
- try {
1451
- for (;;) {
1452
- const { done, value } = await reader.read();
1453
- if (done) break;
1454
- chunks.push(value);
1455
- size += value.byteLength;
1456
- }
1457
- } catch (error) {
1458
- if (error instanceof ContentTooLargeError) throw error;
1459
- throw new HTTPError(400, "malformed compressed request body");
1460
- }
1461
- const merged = new Uint8Array(size);
1462
- let offset = 0;
1463
- for (const chunk of chunks) {
1464
- merged.set(chunk, offset);
1465
- offset += chunk.byteLength;
1466
- }
1467
- return merged;
1468
- }
1469
- /**
1470
- * Collect + decode a `Request` body — the shared body-collection pipeline
1471
- * surfaced to middleware and handlers as the middleware context's cached
1472
- * `body()`.
1473
- *
1474
- * @remarks
1475
- * Collects the wire body capped at `options.limit` bytes ({@link
1476
- * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
1477
- * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
1478
- * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1479
- * `options.decompression`, default {@link
1480
- * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1481
- * content type: `application/json` is parsed via `@orkestrel/contract`'s
1482
- * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1483
- * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1484
- * decodes to `undefined`.
1485
- *
1486
- * @param request - The `Request` to read the body from
1487
- * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1488
- * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1489
- * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1490
- * @throws {HTTPError} When the compressed body is corrupt (400)
1491
- *
1492
- * @example
1493
- * ```ts
1494
- * const body = await readBody(request, { limit: 1_048_576 })
1495
- * ```
1496
- */
1497
- async function readBody(request, options) {
1498
- const limit = options?.limit ?? 1048576;
1499
- const decompression = options?.decompression ?? 16777216;
1500
- const wire = await collectRequestBody(request, limit);
1501
- const encoding = requestEncoding(request.headers.get("content-encoding"));
1502
- const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1503
- if (bytes.length === 0) return void 0;
1504
- const contentType = request.headers.get("content-type");
1505
- const semicolon = contentType === null ? -1 : contentType.indexOf(";");
1506
- const bareType = contentType === null ? "" : (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase();
1507
- const text = new TextDecoder().decode(bytes);
1508
- if (bareType === "application/json") return scrubPrototype((0, _orkestrel_contract.parseJSON)(text));
1509
- return text;
1510
- }
1511
- //#endregion
1512
- //#region src/core/Negotiator.ts
1513
- /**
1514
- * The content-negotiation machine over the weighted `Accept` family — a
1515
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1516
- * {@link NegotiatorInterface}.
1517
- *
1518
- * @remarks
1519
- * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1520
- * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1521
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
1522
- * rest of the substrate uses — one parser, never two. `format` reads the
1523
- * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1524
- * the winner — or answers `406 Not Acceptable`.
1525
- *
1526
- * @example
1527
- * ```ts
1528
- * const negotiator = new Negotiator()
1529
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1530
- * // 'text/html'
1531
- * ```
1532
- */
1533
- var Negotiator = class {
1534
- negotiate(header, available) {
1535
- if (available.length === 0) return void 0;
1536
- const entries = parseAcceptHeader(header);
1537
- if (entries.length === 0) return available[0];
1538
- let best;
1539
- let bestQuality = 0;
1540
- let bestRank = Number.POSITIVE_INFINITY;
1541
- for (const candidate of available) {
1542
- const match = matchMediaType(entries, candidate);
1543
- if (match === void 0) continue;
1544
- const { q, rank } = match;
1545
- if (q > bestQuality || q === bestQuality && rank < bestRank) {
1546
- best = candidate;
1547
- bestQuality = q;
1548
- bestRank = rank;
1549
- }
1550
- }
1551
- return best;
1552
- }
1553
- encoding(header, available) {
1554
- return negotiateEncoding(header, available);
1555
- }
1556
- language(header, available) {
1557
- if (available.length === 0) return void 0;
1558
- const entries = parseAcceptHeader(header);
1559
- if (entries.length === 0) return available[0];
1560
- let best;
1561
- let bestQuality = 0;
1562
- for (const candidate of available) {
1563
- const quality = languageQuality(entries, candidate);
1564
- if (quality > bestQuality) {
1565
- best = candidate;
1566
- bestQuality = quality;
1567
- }
1568
- }
1569
- return best;
1570
- }
1571
- /**
1572
- * @remarks
1573
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1574
- * server boundary classifies them, never this negotiator.
1575
- */
1576
- async format(request, context, handlers) {
1577
- const keys = Object.keys(handlers);
1578
- const header = request.headers.get("accept");
1579
- const type = header === null ? keys[0] : this.negotiate(header, keys);
1580
- if (type === void 0) return new Response("Not Acceptable", { status: 406 });
1581
- const handler = handlers[type];
1582
- if (handler === void 0) return new Response("Not Acceptable", { status: 406 });
1583
- return handler(request, context);
1584
- }
1585
- };
1586
- //#endregion
1587
- //#region src/core/factories.ts
1588
- /**
1589
- * Create a {@link NegotiatorInterface} — the reusable content-negotiation
1590
- * machine over the weighted `Accept` family.
1591
- *
1592
- * @remarks
1593
- * Prefer this over `new Negotiator()` at call sites that only need the
1594
- * interface.
1595
- *
1596
- * @returns A {@link NegotiatorInterface}
1597
- *
1598
- * @example
1599
- * ```ts
1600
- * import { createNegotiator } from '@src/core'
1601
- *
1602
- * const negotiator = createNegotiator()
1603
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1604
- * // 'text/html'
1605
- * ```
1606
- */
1607
- function createNegotiator() {
1608
- return new Negotiator();
1609
- }
1610
- //#endregion
1611
- exports.COMPRESSIBLE_TYPES = COMPRESSIBLE_TYPES;
1612
- exports.ContentTooLargeError = ContentTooLargeError;
1613
- exports.DEFAULT_BODY_LIMIT = DEFAULT_BODY_LIMIT;
1614
- exports.DEFAULT_DECOMPRESSED_LIMIT = DEFAULT_DECOMPRESSED_LIMIT;
1615
- exports.DEFAULT_DRAIN_MS = DEFAULT_DRAIN_MS;
1616
- exports.DEFAULT_ENCODINGS = DEFAULT_ENCODINGS;
1617
- exports.HTTPError = HTTPError;
1618
- exports.Negotiator = Negotiator;
1619
- exports.REQUEST_ID_PATTERN = REQUEST_ID_PATTERN;
1620
- exports.SSE_HEADERS = SSE_HEADERS;
1621
- exports.appendCookie = appendCookie;
1622
- exports.clearCookie = clearCookie;
1623
- exports.clientRateKey = clientRateKey;
1624
- exports.codingQuality = codingQuality;
1625
- exports.collectRequestBody = collectRequestBody;
1626
- exports.compose = compose;
1627
- exports.computeBodyETag = computeBodyETag;
1628
- exports.createNegotiator = createNegotiator;
1629
- exports.decodeBase64Url = decodeBase64Url;
1630
- exports.decodeCookieValue = decodeCookieValue;
1631
- exports.decodeTokenPayload = decodeTokenPayload;
1632
- exports.decompressRequestBody = decompressRequestBody;
1633
- exports.encodeBase64Url = encodeBase64Url;
1634
- exports.ipv6Network = ipv6Network;
1635
- exports.isCompressibleType = isCompressibleType;
1636
- exports.isCookieAttribute = isCookieAttribute;
1637
- exports.isCookieName = isCookieName;
1638
- exports.isDangerousKey = isDangerousKey;
1639
- exports.isHTTPError = isHTTPError;
1640
- exports.isValidRequestId = isValidRequestId;
1641
- exports.languageQuality = languageQuality;
1642
- exports.matchMediaType = matchMediaType;
1643
- exports.matchesETag = matchesETag;
1644
- exports.mergeVary = mergeVary;
1645
- exports.negotiateEncoding = negotiateEncoding;
1646
- exports.normalizeSecret = normalizeSecret;
1647
- exports.openStream = openStream;
1648
- exports.parseAcceptHeader = parseAcceptHeader;
1649
- exports.parseCookies = parseCookies;
1650
- exports.parseRange = parseRange;
1651
- exports.readBody = readBody;
1652
- exports.readSignedCookie = readSignedCookie;
1653
- exports.requestEncoding = requestEncoding;
1654
- exports.resolveOrigin = resolveOrigin;
1655
- exports.resolveSecure = resolveSecure;
1656
- exports.resolveSecurityHeader = resolveSecurityHeader;
1657
- exports.scrubPrototype = scrubPrototype;
1658
- exports.serializeCookie = serializeCookie;
1659
- exports.serializeEvent = serializeEvent;
1660
- exports.signToken = signToken;
1661
- exports.unwrapETag = unwrapETag;
1662
- exports.verifyToken = verifyToken;
1663
- exports.writeSignedCookie = writeSignedCookie;
1664
-
1665
- //# sourceMappingURL=index.cjs.map