@orkestrel/server 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,890 @@
1
+ import type { AcceptEntry, BodyOptions, CookieOptions, Encoding, MiddlewareContext, MiddlewareHandler, RangeSpec, SSEMessage, StreamInterface, StreamOptions, TokenOptions, TokenSecret } from './types.js';
2
+ /**
3
+ * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
4
+ * handler into one request handler — the frozen middleware seam (§5.1).
5
+ *
6
+ * @remarks
7
+ * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
8
+ * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
9
+ * `terminal`. Each middleware's `next` may be called with a substituted
10
+ * `Request` (the downstream chain then sees that request instead of the
11
+ * original), called with no argument (the original request continues
12
+ * downstream), or NOT called at all (a short-circuit — the middleware's own
13
+ * returned `Response` is sent, and everything downstream never runs). A
14
+ * SECOND call to the same `next` within one middleware invocation REJECTS —
15
+ * each link runs the chain at most once, so a middleware cannot fork the
16
+ * request into two divergent downstream runs.
17
+ *
18
+ * @typeParam TState - The consumer's opaque per-request state type
19
+ * @param middleware - The ordered chain, outermost first
20
+ * @param terminal - The innermost handler the chain ultimately reaches
21
+ * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
26
+ * const response = await next()
27
+ * response.headers.set('X-Powered-By', 'orkestrel')
28
+ * return response
29
+ * }
30
+ *
31
+ * const handle = compose([withHeader], async () => new Response('ok'))
32
+ * ```
33
+ */
34
+ export declare function compose<TState>(middleware: readonly MiddlewareHandler<TState>[], terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
35
+ /**
36
+ * Parse a raw `Cookie:` request header into a `name → value` lookup.
37
+ *
38
+ * @remarks
39
+ * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
40
+ * cookie-pair separator never precedes it), while every later segment has its
41
+ * inter-pair separator (ASCII space/tab) stripped before parsing — so a
42
+ * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
43
+ * {@link isCookieName} rather than silently reconciling into a
44
+ * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
45
+ * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
46
+ * malformed header yields an empty record, never throws (AGENTS §14).
47
+ *
48
+ * @param header - The raw `Cookie` header value (possibly `undefined`)
49
+ * @returns A record of every parsed cookie, `name → decoded value`
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
54
+ * ```
55
+ */
56
+ export declare function parseCookies(header: string | undefined): Record<string, string>;
57
+ /**
58
+ * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
59
+ * cookie-token chars with NO surrounding (or interior) whitespace.
60
+ *
61
+ * @remarks
62
+ * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
63
+ * which excludes every whitespace char (ASCII and Unicode) plus controls,
64
+ * separators, and `=`. The {@link parseCookies} hardening that stops a
65
+ * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
66
+ *
67
+ * @param value - The candidate cookie name
68
+ * @returns `true` when `value` is a valid, whitespace-free cookie token
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * isCookieName('__Host-session') // true
73
+ * isCookieName(' __Host-session') // false — whitespace-padded
74
+ * ```
75
+ */
76
+ export declare function isCookieName(value: string): boolean;
77
+ /**
78
+ * Decode a cookie value with `decodeURIComponent`, falling back to the raw
79
+ * text when the value is not valid percent-encoding.
80
+ *
81
+ * @param raw - The raw (trimmed) cookie value
82
+ * @returns The URL-decoded value, or the raw value when decoding would throw
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * decodeCookieValue('a%20b') // 'a b'
87
+ * decodeCookieValue('%') // '%' — malformed escape stays literal
88
+ * ```
89
+ */
90
+ export declare function decodeCookieValue(raw: string): string;
91
+ /**
92
+ * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
93
+ * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
94
+ * attributes with before emitting them.
95
+ *
96
+ * @remarks
97
+ * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
98
+ * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
99
+ * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
100
+ * directive. Total — never throws (a bad value returns `false`).
101
+ *
102
+ * @param value - The candidate attribute value (a `Domain` or `Path`)
103
+ * @returns `true` when `value` carries no separator / whitespace / control char
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * isCookieAttribute('/app') // true
108
+ * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
109
+ * ```
110
+ */
111
+ export declare function isCookieAttribute(value: string): boolean;
112
+ /**
113
+ * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
114
+ *
115
+ * @remarks
116
+ * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
117
+ * appends the present {@link CookieOptions} attributes in canonical order:
118
+ * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
119
+ * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
120
+ * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
121
+ * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
122
+ * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
123
+ * the `secure` option (the spec requires it); an un-resolved `undefined`
124
+ * `secure` here falls to OFF — request-aware callers resolve it first via
125
+ * {@link resolveSecure}.
126
+ *
127
+ * @param name - The cookie name
128
+ * @param value - The cookie value (URL-encoded into the output)
129
+ * @param options - The {@link CookieOptions} attributes; see its fields for defaults
130
+ * @returns The `Set-Cookie` header value
131
+ * @throws {HTTPError} When `domain` or `path` carries an injection char
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
136
+ * ```
137
+ */
138
+ export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
139
+ /**
140
+ * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
141
+ * `secure` setting and whether the request arrived over TLS.
142
+ *
143
+ * @remarks
144
+ * `true` / `false` are explicit overrides. `undefined` (the secure default —
145
+ * the option omitted) resolves to `encrypted` — `Secure` on a TLS
146
+ * connection, off over plaintext HTTP — so a production HTTPS deployment
147
+ * gets `Secure` automatically while local-dev HTTP still works.
148
+ *
149
+ * @param secure - The {@link CookieOptions} `secure` setting
150
+ * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
151
+ * @returns The concrete `Secure` flag to emit
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * resolveSecure(undefined, true) // true
156
+ * resolveSecure(undefined, false) // false
157
+ * resolveSecure(false, true) // false — explicit override wins
158
+ * ```
159
+ */
160
+ export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
161
+ /**
162
+ * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
163
+ * clobbering a prior one.
164
+ *
165
+ * @remarks
166
+ * `Headers.append` already accumulates repeated headers (unlike node's
167
+ * `setHeader`), so this is a thin, self-documenting wrapper naming the
168
+ * cookie-append intent — the primitive {@link writeSignedCookie} /
169
+ * {@link clearCookie} use.
170
+ *
171
+ * @param headers - The response `Headers` to write into
172
+ * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * const headers = new Headers()
177
+ * appendCookie(headers, serializeCookie('a', '1'))
178
+ * appendCookie(headers, serializeCookie('b', '2'))
179
+ * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
180
+ * ```
181
+ */
182
+ export declare function appendCookie(headers: Headers, cookie: string): void;
183
+ /**
184
+ * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
185
+ * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
186
+ *
187
+ * @remarks
188
+ * The cookie value is `await signToken(value, { secret })`
189
+ * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
190
+ * cookie — the same secret rotation and tamper rejection, no second HMAC
191
+ * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
192
+ * signing is asynchronous (§3 of the proposal).
193
+ *
194
+ * @param headers - The response `Headers` to write into
195
+ * @param name - The cookie name
196
+ * @param value - The opaque value to sign into the cookie
197
+ * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
198
+ * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * const headers = new Headers()
203
+ * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
204
+ * ```
205
+ */
206
+ export declare function writeSignedCookie(headers: Headers, name: string, value: string, secret: TokenSecret, options?: CookieOptions): Promise<void>;
207
+ /**
208
+ * Read + verify a SIGNED cookie off a request — TOTAL, returning the
209
+ * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
210
+ *
211
+ * @remarks
212
+ * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
213
+ * and verifies it with {@link verifyToken} against `secret` (a rotation list
214
+ * accepts a cookie signed by any of its secrets). ANY failure — an absent
215
+ * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
216
+ *
217
+ * @param request - The `Request` to read the `Cookie` header from
218
+ * @param name - The cookie name to read
219
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
220
+ * @returns The embedded value when the cookie is present + valid, else `undefined`
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * const value = await readSignedCookie(request, 'session', 'secret')
225
+ * ```
226
+ */
227
+ export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
228
+ /**
229
+ * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
230
+ *
231
+ * @remarks
232
+ * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
233
+ * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
234
+ * a cookie when those MATCH the one it set).
235
+ *
236
+ * @param headers - The response `Headers` to write into
237
+ * @param name - The cookie name to clear
238
+ * @param options - The {@link CookieOptions} that must match the original cookie
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * const headers = new Headers()
243
+ * clearCookie(headers, 'session')
244
+ * ```
245
+ */
246
+ export declare function clearCookie(headers: Headers, name: string, options?: CookieOptions): void;
247
+ /**
248
+ * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
249
+ * {@link verifyToken} use, and the signature encoding for the HMAC.
250
+ *
251
+ * @param bytes - The bytes to encode
252
+ * @returns The base64url string (no padding)
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
257
+ * ```
258
+ */
259
+ export declare function encodeBase64Url(bytes: Uint8Array): string;
260
+ /**
261
+ * Decode a base64url string back into its bytes — the inverse of
262
+ * {@link encodeBase64Url}.
263
+ *
264
+ * @remarks
265
+ * Restores the standard base64 alphabet + padding before decoding with
266
+ * `atob`. THROWS `DOMException` on a malformed input — callers on the
267
+ * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
268
+ *
269
+ * @param value - The base64url string to decode
270
+ * @returns The decoded bytes
271
+ * @throws {DOMException} When `value` is not valid base64url
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
276
+ * ```
277
+ */
278
+ export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
279
+ /**
280
+ * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
281
+ *
282
+ * @remarks
283
+ * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
284
+ * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
285
+ * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
286
+ * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
287
+ * {@link TokenSecret} (the current secret, or the head of a rotation list).
288
+ * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
289
+ * misconfigured secret with no usable entry THROWS an {@link HTTPError}
290
+ * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
291
+ * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
292
+ *
293
+ * @param value - The opaque value to embed (a session id, a deployment marker)
294
+ * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
295
+ * @returns The signed `<payload>.<signature>` token string
296
+ * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
301
+ * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
302
+ * ```
303
+ */
304
+ export declare function signToken(value: string, options: TokenOptions): Promise<string>;
305
+ /**
306
+ * Verify a stateless token and return its embedded value — TOTAL, never throws.
307
+ *
308
+ * @remarks
309
+ * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
310
+ * value containing dots survives), and checks the payload's HMAC-SHA256
311
+ * signature against EACH {@link TokenSecret} candidate via
312
+ * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
313
+ * retired, §3 of the proposal), accepting the token on the first match (the
314
+ * rotation path). It then decodes + narrows the payload (`isRecord` +
315
+ * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
316
+ * rejects an expired token. ANY failure — a malformed token, a bad signature,
317
+ * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
318
+ * yields `undefined` rather than throwing.
319
+ *
320
+ * @param token - The candidate token string (from a request header/cookie)
321
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
322
+ * @returns The embedded value when the token is valid + unexpired, else `undefined`
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * await verifyToken('bad.token', 'shh') // undefined — never throws
327
+ * ```
328
+ */
329
+ export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
330
+ /**
331
+ * Decode + narrow a signed token's base64url JSON payload, honoring its
332
+ * expiry — the shared decode step {@link verifyToken} applies after a
333
+ * signature match.
334
+ *
335
+ * @remarks
336
+ * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
337
+ * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
338
+ * TOTAL — any decode/shape/expiry failure yields `undefined`.
339
+ *
340
+ * @param encoded - The base64url-encoded payload segment (before the last `.`)
341
+ * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
342
+ */
343
+ export declare function decodeTokenPayload(encoded: string): string | undefined;
344
+ /**
345
+ * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
346
+ * backs both {@link signToken} and {@link verifyToken}.
347
+ *
348
+ * @remarks
349
+ * A single string becomes a one-element list; a rotation list is copied. Any
350
+ * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
351
+ * emptiness test; each kept secret is stored VERBATIM). The first kept
352
+ * element is the signing secret; all kept are accepted on verify.
353
+ *
354
+ * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
355
+ * @returns The kept (non-blank) secrets, in order — empty when none is usable
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
360
+ * ```
361
+ */
362
+ export declare function normalizeSecret(secret: TokenSecret): readonly string[];
363
+ /**
364
+ * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
365
+ * into its q-sorted entries.
366
+ *
367
+ * @remarks
368
+ * Splits on `,`; for each part takes the token before the first `;`
369
+ * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
370
+ * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
371
+ * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
372
+ * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
373
+ * the header's own order within a tie — a single pass with no backtracking,
374
+ * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
375
+ * empty/malformed header yields `[]`/best-effort entries, never throws.
376
+ *
377
+ * @param header - The raw weighted header value
378
+ * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
383
+ * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
384
+ * ```
385
+ */
386
+ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
387
+ /**
388
+ * The client's quality (q) for one content-coding from the parsed
389
+ * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
390
+ * server-preference selection.
391
+ *
392
+ * @remarks
393
+ * Prefers an EXACT named match (including an explicit `;q=0` rejection);
394
+ * failing that, a bare `*` wildcard's q applies. A coding that is neither
395
+ * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
396
+ * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
397
+ *
398
+ * @param entries - The parsed {@link AcceptEntry} list
399
+ * @param coding - The candidate coding to score
400
+ * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
405
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
406
+ * ```
407
+ */
408
+ export declare function codingQuality(entries: readonly AcceptEntry[], coding: string): number;
409
+ /**
410
+ * Select the best content-coding for an `Accept-Encoding` header from the
411
+ * codings the server offers.
412
+ *
413
+ * @remarks
414
+ * Parses the header ({@link parseAcceptHeader}) and scores each `available`
415
+ * coding in the SERVER's preference order ({@link codingQuality}), keeping
416
+ * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
417
+ * client-side tie). Returns `undefined` when the client accepts none of
418
+ * `available` (identity — no compression). TOTAL on hostile input.
419
+ *
420
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
421
+ * @param header - The raw `Accept-Encoding` header value
422
+ * @param available - The codings the server offers, in preference (tie-break) order
423
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
428
+ * ```
429
+ */
430
+ export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
431
+ /**
432
+ * Rank + quality of one `candidate` media type against the parsed `Accept`
433
+ * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
434
+ * uses to score each `available` candidate.
435
+ *
436
+ * @remarks
437
+ * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
438
+ * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
439
+ * `;q=0` entry explicitly rejects the candidate outright (returns
440
+ * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
441
+ * (less specific) coverage, so a later more-specific match can still allow
442
+ * it. Among multiple matching entries, the lowest `rank` wins, and among a
443
+ * rank tie the highest `q` wins.
444
+ *
445
+ * @param entries - The parsed {@link AcceptEntry} list
446
+ * @param candidate - The candidate media type to score (e.g. `'text/html'`)
447
+ * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
448
+ *
449
+ * @example
450
+ * ```ts
451
+ * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
452
+ * // { q: 1, rank: 0 }
453
+ * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
454
+ * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
455
+ * ```
456
+ */
457
+ export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string): {
458
+ readonly q: number;
459
+ readonly rank: number;
460
+ } | undefined;
461
+ /**
462
+ * The client's quality for one `candidate` language from the parsed
463
+ * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
464
+ *
465
+ * @remarks
466
+ * Prefers an exact match, then a primary-tag prefix match (`en` accepts
467
+ * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
468
+ * is an explicit rejection).
469
+ *
470
+ * @param entries - The parsed {@link AcceptEntry} list
471
+ * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
472
+ * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
473
+ *
474
+ * @example
475
+ * ```ts
476
+ * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
477
+ * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
478
+ * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
479
+ * ```
480
+ */
481
+ export declare function languageQuality(entries: readonly AcceptEntry[], candidate: string): number;
482
+ /**
483
+ * Whether a `Content-Type` is worth compressing.
484
+ *
485
+ * @remarks
486
+ * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
487
+ * type, a `+json`/`+xml` structured suffix, or one of the explicit
488
+ * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
489
+ * binary (`image/png`, `application/zip`) is NOT compressible. An
490
+ * absent/empty type is not compressible. TOTAL.
491
+ *
492
+ * @param type - The response `Content-Type` header value (with or without parameters)
493
+ * @returns `true` when the type is text-shaped and worth compressing
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * isCompressibleType('application/json; charset=utf-8') // true
498
+ * isCompressibleType('image/png') // false
499
+ * ```
500
+ */
501
+ export declare function isCompressibleType(type: string): boolean;
502
+ /**
503
+ * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
504
+ *
505
+ * @remarks
506
+ * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
507
+ * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
508
+ * default, encoding-AGNOSTIC, so the tag survives a downstream content
509
+ * re-encoding (gzip) and still matches on revalidation — or a STRONG one
510
+ * (`"<hash>"`, byte-identity) when `weak` is `false`.
511
+ *
512
+ * @param body - The full (uncompressed) response body to hash
513
+ * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
514
+ * @returns The `ETag` header value
515
+ *
516
+ * @example
517
+ * ```ts
518
+ * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
519
+ * ```
520
+ */
521
+ export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
522
+ /**
523
+ * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
524
+ * comparison body — the reduction {@link matchesETag} applies to both sides
525
+ * before the RFC 7232 §2.3.2 weak comparison.
526
+ *
527
+ * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
528
+ * @returns The tag with any leading `W/` removed (the quotes preserved)
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * unwrapETag('W/"abc"') // '"abc"'
533
+ * ```
534
+ */
535
+ export declare function unwrapETag(tag: string): string;
536
+ /**
537
+ * Whether a request's `If-None-Match` header matches a resource's current
538
+ * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
539
+ *
540
+ * @remarks
541
+ * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
542
+ * listed tag matches), or the `*` wildcard (matches ANY current
543
+ * representation — only a list of exactly `*` is the wildcard). Comparison is
544
+ * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
545
+ * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
546
+ * malformed/empty header matches nothing, never throws.
547
+ *
548
+ * @param header - The raw `If-None-Match` header value
549
+ * @param etag - The resource's current `ETag`
550
+ * @returns `true` when the conditional matches (the caller answers `304`)
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
555
+ * matchesETag('*', 'W/"anything"') // true — wildcard
556
+ * ```
557
+ */
558
+ export declare function matchesETag(header: string, etag: string): boolean;
559
+ /**
560
+ * Parse an HTTP `Range` request header against a known resource `size` —
561
+ * TOTAL, returning a {@link RangeSpec} or `undefined`.
562
+ *
563
+ * @remarks
564
+ * Handles the three single-range `bytes=` forms — closed (`start-end`), open
565
+ * (`start-`), and suffix (`-suffixLength`) — clamping the window to
566
+ * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
567
+ * `{ satisfiable: true, start, end }` for an overlapping range,
568
+ * `{ satisfiable: false }` for a range wholly past the resource, and
569
+ * `undefined` for the "serve the whole resource" case: an ABSENT header, a
570
+ * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
571
+ * supported), or any malformed/non-finite bound. NEVER throws on a hostile
572
+ * header.
573
+ *
574
+ * @param header - The raw `Range` header value
575
+ * @param size - The resource's total byte length
576
+ * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
577
+ *
578
+ * @example
579
+ * ```ts
580
+ * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
581
+ * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
582
+ * ```
583
+ */
584
+ export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
585
+ /**
586
+ * Resolve the `Access-Control-Allow-Origin` value for a request.
587
+ *
588
+ * @remarks
589
+ * `'*'` and a single origin string pass straight through. An allow-list
590
+ * echoes the request's `Origin` only when it is present in the list, else
591
+ * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
592
+ * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
593
+ * NEVER reflected even if `'null'` were listed, closing the hostile-context
594
+ * cross-origin-access hole.
595
+ *
596
+ * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
597
+ * @param requestOrigin - The request's `Origin` header value, if present
598
+ * @returns The allow-origin value to send, or `undefined` to set no header
599
+ *
600
+ * @example
601
+ * ```ts
602
+ * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
603
+ * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
604
+ * ```
605
+ */
606
+ export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
607
+ /**
608
+ * Merge a `Vary` value into an existing `Vary` header without duplication.
609
+ *
610
+ * @remarks
611
+ * Splits `existing` on `,`, trims each member, and appends `value` only when
612
+ * no existing member already matches it case-insensitively (`Vary` header
613
+ * names are case-insensitive). Preserves the existing members' order and
614
+ * appends the new one last.
615
+ *
616
+ * @param existing - The current `Vary` header value, if any
617
+ * @param value - The header name to ensure is listed
618
+ * @returns The merged `Vary` value
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * mergeVary(undefined, 'Origin') // 'Origin'
623
+ * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
624
+ * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
625
+ * ```
626
+ */
627
+ export declare function mergeVary(existing: string | undefined, value: string): string;
628
+ /**
629
+ * Resolve one opt-out, value-bearing security header.
630
+ *
631
+ * @remarks
632
+ * The shared "a `string` value, or `false` to omit, or a default when unset"
633
+ * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
634
+ * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
635
+ * override, `undefined` (unset) ⇒ `fallback` (the secure default).
636
+ *
637
+ * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
638
+ * @param fallback - The secure-default value used when `value` is unset
639
+ * @returns The header value to set, or `undefined` to omit the header
640
+ *
641
+ * @example
642
+ * ```ts
643
+ * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
644
+ * resolveSecurityHeader(false, 'DENY') // undefined — omitted
645
+ * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
646
+ * ```
647
+ */
648
+ export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
649
+ /**
650
+ * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
651
+ * header + `context.state`.
652
+ *
653
+ * @remarks
654
+ * A request id is echoed RAW into a response header and log lines, so an
655
+ * untrusted one is a header-injection + log-injection + DoS vector. This
656
+ * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
657
+ * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
658
+ * TOTAL — never throws.
659
+ *
660
+ * @param value - The candidate incoming request id
661
+ * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
662
+ *
663
+ * @example
664
+ * ```ts
665
+ * isValidRequestId('req_abc-123') // true
666
+ * isValidRequestId('bad\r\nheader') // false
667
+ * ```
668
+ */
669
+ export declare function isValidRequestId(value: string): boolean;
670
+ /**
671
+ * Compute the `/64` network of a full IPv6 address, or `undefined` when the
672
+ * input is not a plain IPv6 address to collapse.
673
+ *
674
+ * @remarks
675
+ * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
676
+ * is the identity) or any string that does not expand to exactly eight
677
+ * hextets. Expands a single `::` into the missing zero hextets, takes the
678
+ * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
679
+ * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
680
+ * first. Total — a malformed address returns `undefined`.
681
+ *
682
+ * @param address - The candidate IPv6 address
683
+ * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
684
+ *
685
+ * @example
686
+ * ```ts
687
+ * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
688
+ * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
689
+ * ```
690
+ */
691
+ export declare function ipv6Network(address: string): string | undefined;
692
+ /**
693
+ * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
694
+ * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
695
+ *
696
+ * @remarks
697
+ * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
698
+ * per-`/128` rate limit is trivially bypassed by rotating host bits — the
699
+ * real identity is the `/64` network. Delegates the IPv6 collapse to
700
+ * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
701
+ * a malformed string) is kept unchanged.
702
+ *
703
+ * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
704
+ * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
705
+ *
706
+ * @example
707
+ * ```ts
708
+ * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
709
+ * clientRateKey('192.0.2.1') // '192.0.2.1'
710
+ * ```
711
+ */
712
+ export declare function clientRateKey(address: string): string;
713
+ /**
714
+ * Serialize one {@link SSEMessage} to the SSE wire.
715
+ *
716
+ * @remarks
717
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
718
+ * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
719
+ * (so a consuming parser's multi-`data` concat reproduces the original
720
+ * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
721
+ * a `data:` line), then the terminating blank line.
722
+ *
723
+ * @param message - The event to serialize
724
+ * @returns The SSE wire text for the event (terminated by a blank line)
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
729
+ * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
730
+ * ```
731
+ */
732
+ export declare function serializeEvent(message: SSEMessage): string;
733
+ /**
734
+ * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
735
+ * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
736
+ *
737
+ * @remarks
738
+ * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
739
+ * merged under any `options.headers` (a seam-owned key is never overridden),
740
+ * at `options.status` (default `200`). The returned {@link StreamInterface}'s
741
+ * `write` serializes one message ({@link serializeEvent}) and enqueues it;
742
+ * `comment` writes a `: text` keep-alive line a conforming parser ignores;
743
+ * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
744
+ * by `end()`, or the consumer cancelled the stream), so a late write never
745
+ * throws.
746
+ *
747
+ * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
748
+ * @returns The {@link StreamInterface} handle
749
+ *
750
+ * @example
751
+ * ```ts
752
+ * const stream = openStream()
753
+ * stream.write({ event: 'token', data: 'hello' })
754
+ * stream.end()
755
+ * // return stream.response from the route handler
756
+ * ```
757
+ */
758
+ export declare function openStream(options?: StreamOptions): StreamInterface;
759
+ /**
760
+ * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
761
+ * or `prototype` — the three keys that, assigned onto a normal object, can
762
+ * reach and mutate `Object.prototype`.
763
+ *
764
+ * @param key - The candidate object key
765
+ * @returns `true` when `key` is one of the three prototype-pollution keys
766
+ *
767
+ * @example
768
+ * ```ts
769
+ * isDangerousKey('__proto__') // true
770
+ * isDangerousKey('name') // false
771
+ * ```
772
+ */
773
+ export declare function isDangerousKey(key: string): boolean;
774
+ /**
775
+ * Recursively STRIP the prototype-pollution keys from a parsed value IN
776
+ * PLACE.
777
+ *
778
+ * @remarks
779
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
780
+ * enumerable `__proto__` DATA property — but that own key becomes a
781
+ * pollution gadget the moment a downstream deep-merge copies it onto a live
782
+ * object. This walks the value and `delete`s any own {@link isDangerousKey}
783
+ * key at every depth, recursing into nested objects + array elements.
784
+ * Primitives/`null` pass through untouched. Total — never throws. Mutates the
785
+ * freshly-parsed value (which nothing else holds yet).
786
+ *
787
+ * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
788
+ * @returns The same `value`, with every dangerous key removed at every depth
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
793
+ * // { name: 'ok' } — the __proto__ key is gone
794
+ * ```
795
+ */
796
+ export declare function scrubPrototype(value: unknown): unknown;
797
+ /**
798
+ * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
799
+ *
800
+ * @remarks
801
+ * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
802
+ * throwing a {@link ContentTooLargeError} (413) the instant the running total
803
+ * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
804
+ * collecting an unbounded body. A bodyless request (`request.body === null`)
805
+ * resolves an empty array. A non-positive `limit` means unbounded.
806
+ *
807
+ * @param request - The `Request` to drain
808
+ * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
809
+ * @returns The full request body as one `Uint8Array`
810
+ * @throws {ContentTooLargeError} When the body exceeds `limit`
811
+ *
812
+ * @example
813
+ * ```ts
814
+ * const bytes = await collectRequestBody(request, 1_048_576)
815
+ * ```
816
+ */
817
+ export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
818
+ /**
819
+ * Narrow a raw `Content-Encoding` header value to a decompressible
820
+ * {@link Encoding} — the boundary guard {@link readBody} uses to decide
821
+ * whether a request body needs transparent decompression.
822
+ *
823
+ * @remarks
824
+ * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
825
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
826
+ * the proposal). An absent header, `identity`, an unknown value, or a
827
+ * comma-joined multi-coding all yield `undefined` (the body is read as-is).
828
+ * TOTAL — never asserts the loose `string | null` header.
829
+ *
830
+ * @param header - The raw `Content-Encoding` header value
831
+ * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
832
+ *
833
+ * @example
834
+ * ```ts
835
+ * requestEncoding('gzip') // 'gzip'
836
+ * requestEncoding('br') // undefined — unsupported by DecompressionStream
837
+ * ```
838
+ */
839
+ export declare function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined;
840
+ /**
841
+ * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
842
+ * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
843
+ * the zip-bomb defense.
844
+ *
845
+ * @remarks
846
+ * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
847
+ * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
848
+ * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
849
+ * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
850
+ * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
851
+ * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
852
+ * (never conflated with the cap). A non-positive `cap` means uncapped.
853
+ *
854
+ * @param bytes - The compressed bytes to decompress
855
+ * @param encoding - The {@link Encoding} the bytes are compressed with
856
+ * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
857
+ * @returns The decompressed bytes
858
+ * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
859
+ * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
860
+ */
861
+ export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
862
+ /**
863
+ * Collect + decode a `Request` body — the shared body-collection pipeline
864
+ * surfaced to middleware and handlers as the middleware context's cached
865
+ * `body()`.
866
+ *
867
+ * @remarks
868
+ * Collects the wire body capped at `options.limit` bytes ({@link
869
+ * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
870
+ * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
871
+ * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
872
+ * `options.decompression`, default {@link
873
+ * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
874
+ * content type: `application/json` is parsed via `@orkestrel/contract`'s
875
+ * `parseJSON` and scrubbed of prototype-pollution keys ({@link
876
+ * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
877
+ * decodes to `undefined`.
878
+ *
879
+ * @param request - The `Request` to read the body from
880
+ * @param options - The {@link BodyOptions} `limit` + `decompression` caps
881
+ * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
882
+ * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
883
+ * @throws {HTTPError} When the compressed body is corrupt (400)
884
+ *
885
+ * @example
886
+ * ```ts
887
+ * const body = await readBody(request, { limit: 1_048_576 })
888
+ * ```
889
+ */
890
+ export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;