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