@orkestrel/server 0.0.3 → 0.0.5

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,97 +1,1425 @@
1
1
  import { AddressInfo } from 'node:net';
2
- import { ConnectionInfo } from '../core/index.ts';
3
2
  import { DispatcherInterface } from '@orkestrel/router';
4
3
  import { Duplex } from 'node:stream';
5
4
  import { EmitterErrorHandler } from '@orkestrel/emitter';
6
5
  import { EmitterHooks } from '@orkestrel/emitter';
7
6
  import { EmitterInterface } from '@orkestrel/emitter';
8
7
  import { IncomingMessage } from 'node:http';
9
- import { MiddlewareHandler } from '../core/index.ts';
8
+
9
+ /**
10
+ * One parsed entry of a weighted `Accept` / `Accept-Encoding` / `Accept-Language`
11
+ * header — a value and its quality weight, the element type `parseAcceptHeader`
12
+ * returns (sorted by `q` descending).
13
+ *
14
+ * @remarks
15
+ * `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
16
+ * wildcard). `q` is the quality weight in `[0, 1]` (the `;q=` parameter,
17
+ * default `1` when absent); a `;q=0` entry explicitly REJECTS that token — a
18
+ * parser keeps it (so a caller can honor the rejection) rather than
19
+ * dropping it.
20
+ */
21
+ export declare interface AcceptEntry {
22
+ readonly value: string;
23
+ readonly q: number;
24
+ }
25
+
26
+ /**
27
+ * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
28
+ * clobbering a prior one.
29
+ *
30
+ * @remarks
31
+ * `Headers.append` already accumulates repeated headers (unlike node's
32
+ * `setHeader`), so this is a thin, self-documenting wrapper naming the
33
+ * cookie-append intent — the primitive {@link writeSignedCookie} /
34
+ * {@link clearCookie} use.
35
+ *
36
+ * @param headers - The response `Headers` to write into
37
+ * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const headers = new Headers()
42
+ * appendCookie(headers, serializeCookie('a', '1'))
43
+ * appendCookie(headers, serializeCookie('b', '2'))
44
+ * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
45
+ * ```
46
+ */
47
+ export declare function appendCookie(headers: Headers, cookie: string): void;
48
+
49
+ /**
50
+ * Options for `readBody` — how the shared body-collection pipeline caps and
51
+ * decompresses a request body.
52
+ *
53
+ * @param limit - The maximum request body size in bytes; a larger body
54
+ * throws a {@link import('./errors.js').ContentTooLargeError} (413).
55
+ * Defaults to {@link DEFAULT_BODY_LIMIT}.
56
+ * @param decompression - The maximum DECOMPRESSED body size in bytes (the
57
+ * zip-bomb cap) for a `Content-Encoding: gzip` / `deflate` request body. A
58
+ * highly-compressible payload small ON THE WIRE (under `limit`) can inflate
59
+ * enormously, so a byte-counting `TransformStream` aborts the pipe the
60
+ * instant decompressed output would exceed this. Defaults to {@link
61
+ * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT} (16 MiB) —
62
+ * INDEPENDENT of `limit`, not aligned with it; a non-positive value means
63
+ * UNCAPPED decompressed output — use only when `limit` already bounds the
64
+ * compressed input.
65
+ */
66
+ export declare interface BodyOptions {
67
+ readonly limit?: number;
68
+ readonly decompression?: number;
69
+ }
70
+
71
+ /**
72
+ * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
73
+ *
74
+ * @remarks
75
+ * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
76
+ * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
77
+ * a cookie when those MATCH the one it set).
78
+ *
79
+ * @param headers - The response `Headers` to write into
80
+ * @param name - The cookie name to clear
81
+ * @param options - The {@link CookieOptions} that must match the original cookie
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * const headers = new Headers()
86
+ * clearCookie(headers, 'session')
87
+ * ```
88
+ */
89
+ export declare function clearCookie(headers: Headers, name: string, options?: CookieOptions): void;
90
+
91
+ /**
92
+ * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
93
+ * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
94
+ *
95
+ * @remarks
96
+ * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
97
+ * per-`/128` rate limit is trivially bypassed by rotating host bits — the
98
+ * real identity is the `/64` network. Delegates the IPv6 collapse to
99
+ * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
100
+ * a malformed string) is kept unchanged.
101
+ *
102
+ * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
103
+ * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
108
+ * clientRateKey('192.0.2.1') // '192.0.2.1'
109
+ * ```
110
+ */
111
+ export declare function clientRateKey(address: string): string;
112
+
113
+ /**
114
+ * The client's quality (q) for one content-coding from the parsed
115
+ * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
116
+ * server-preference selection.
117
+ *
118
+ * @remarks
119
+ * Prefers an EXACT named match (including an explicit `;q=0` rejection);
120
+ * failing that, a bare `*` wildcard's q applies. A coding that is neither
121
+ * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
122
+ * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
123
+ *
124
+ * @param entries - The parsed {@link AcceptEntry} list
125
+ * @param coding - The candidate coding to score
126
+ * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
131
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
132
+ * ```
133
+ */
134
+ export declare function codingQuality(entries: readonly AcceptEntry[], coding: string): number;
135
+
136
+ /**
137
+ * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
138
+ *
139
+ * @remarks
140
+ * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
141
+ * throwing a {@link ContentTooLargeError} (413) the instant the running total
142
+ * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
143
+ * collecting an unbounded body. A bodyless request (`request.body === null`)
144
+ * resolves an empty array. A non-positive `limit` means unbounded.
145
+ *
146
+ * @param request - The `Request` to drain
147
+ * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
148
+ * @returns The full request body as one `Uint8Array`
149
+ * @throws {ContentTooLargeError} When the body exceeds `limit`
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * const bytes = await collectRequestBody(request, 1_048_576)
154
+ * ```
155
+ */
156
+ export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
157
+
158
+ /**
159
+ * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
160
+ * handler into one request handler — the frozen middleware seam (§5.1).
161
+ *
162
+ * @remarks
163
+ * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
164
+ * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
165
+ * `terminal`. Each middleware's `next` may be called with a substituted
166
+ * `Request` (the downstream chain then sees that request instead of the
167
+ * original), called with no argument (the original request continues
168
+ * downstream), or NOT called at all (a short-circuit — the middleware's own
169
+ * returned `Response` is sent, and everything downstream never runs). A
170
+ * SECOND call to the same `next` within one middleware invocation REJECTS —
171
+ * each link runs the chain at most once, so a middleware cannot fork the
172
+ * request into two divergent downstream runs.
173
+ *
174
+ * @typeParam TState - The consumer's opaque per-request state type
175
+ * @param middleware - The ordered chain, outermost first
176
+ * @param terminal - The innermost handler the chain ultimately reaches
177
+ * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
182
+ * const response = await next()
183
+ * response.headers.set('X-Powered-By', 'orkestrel')
184
+ * return response
185
+ * }
186
+ *
187
+ * const handle = compose([withHeader], async () => new Response('ok'))
188
+ * ```
189
+ */
190
+ export declare function compose<TState>(middleware: readonly MiddlewareHandler<TState>[], terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
191
+
192
+ /**
193
+ * The set of bare `Content-Type`s `isCompressibleType` treats as
194
+ * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
195
+ * `+xml`) rules that helper also applies.
196
+ *
197
+ * @remarks
198
+ * The text-shaped application types worth compressing (JSON / JavaScript /
199
+ * XML / SVG / WASM / a few document formats) — NOT already-compressed
200
+ * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
201
+ * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
202
+ * but never mutates the shared default.
203
+ */
204
+ export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
205
+
206
+ /**
207
+ * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
208
+ *
209
+ * @remarks
210
+ * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
211
+ * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
212
+ * default, encoding-AGNOSTIC, so the tag survives a downstream content
213
+ * re-encoding (gzip) and still matches on revalidation — or a STRONG one
214
+ * (`"<hash>"`, byte-identity) when `weak` is `false`.
215
+ *
216
+ * @param body - The full (uncompressed) response body to hash
217
+ * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
218
+ * @returns The `ETag` header value
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
223
+ * ```
224
+ */
225
+ export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
226
+
227
+ /**
228
+ * The per-request connection facts the server face injects — the ONLY data
229
+ * that genuinely exists solely on the socket, surfaced so middleware and a
230
+ * consumer's `state` factory stay core-pure.
231
+ *
232
+ * @remarks
233
+ * - `ip` — the socket peer address, for a spoof-proof rate-limit key. Never
234
+ * derived from `X-Forwarded-For` (a client-controlled header) — a
235
+ * deployment behind a trusted proxy derives its own client key explicitly.
236
+ * - `encrypted` — whether the connection is TLS, for an auto-`Secure` cookie
237
+ * decision ({@link CookieOptions.secure} left `undefined`).
238
+ */
239
+ export declare interface ConnectionInfo {
240
+ readonly ip?: string;
241
+ readonly encrypted: boolean;
242
+ }
10
243
 
11
244
  /**
12
245
  * Derives a consumer's per-request `TState` from the adapter-injected
13
246
  * {@link ConnectionInfo} — `ServerOptions.state`, invoked once per request
14
247
  * before the middleware onion runs.
15
248
  *
16
- * @typeParam TState - The consumer's opaque per-request state type
249
+ * @typeParam TState - The consumer's opaque per-request state type
250
+ */
251
+ export declare type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
252
+
253
+ /**
254
+ * The {@link HTTPError} thrown when a request body exceeds the body
255
+ * pipeline's size limit — a `413 Content Too Large`.
256
+ *
257
+ * @remarks
258
+ * Thrown by `readBody` (and the middleware context's cached `body()`) when
259
+ * the received bytes exceed the configured {@link
260
+ * import('./types.js').BodyOptions.limit}, carrying the `limit` in its
261
+ * `context`. The server's error boundary renders it as a 413.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * import { ContentTooLargeError, isHTTPError } from '@src/server'
266
+ *
267
+ * try {
268
+ * await readBody(request, { limit: 1024 })
269
+ * } catch (error) {
270
+ * if (isHTTPError(error)) console.log(error.status) // 413
271
+ * }
272
+ * ```
273
+ */
274
+ export declare class ContentTooLargeError extends HTTPError {
275
+ constructor(limit: number);
276
+ }
277
+
278
+ /**
279
+ * The `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie
280
+ * transport built over it).
281
+ *
282
+ * @param path - The `Path` directive; defaults to `'/'`.
283
+ * @param domain - The `Domain` directive; omitted ⇒ a host-only cookie.
284
+ * @param maxAge - The `Max-Age` directive in SECONDS (the wire unit, not a
285
+ * millisecond `ttl`); `0` expires the cookie immediately.
286
+ * @param httpOnly - The `HttpOnly` directive; defaults to `true`.
287
+ * @param secure - The `Secure` directive: `true` forces it, `false`
288
+ * suppresses it, and omitted/`undefined` (the default) derives it from the
289
+ * connection via {@link import('./helpers.js').resolveSecure} — `Secure` on
290
+ * a TLS connection, off over plaintext HTTP ({@link
291
+ * ConnectionInfo.encrypted}). A `sameSite: 'None'` cookie is ALWAYS
292
+ * `Secure` regardless (the spec requires it).
293
+ * @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
294
+ */
295
+ export declare interface CookieOptions {
296
+ readonly path?: string;
297
+ readonly domain?: string;
298
+ readonly maxAge?: number;
299
+ readonly httpOnly?: boolean;
300
+ readonly secure?: boolean;
301
+ readonly sameSite?: 'Strict' | 'Lax' | 'None';
302
+ }
303
+
304
+ /**
305
+ * Create a {@link NegotiatorInterface} — the reusable content-negotiation
306
+ * machine over the weighted `Accept` family.
307
+ *
308
+ * @remarks
309
+ * Prefer this over `new Negotiator()` at call sites that only need the
310
+ * interface.
311
+ *
312
+ * @returns A {@link NegotiatorInterface}
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * import { createNegotiator } from '@src/server'
317
+ *
318
+ * const negotiator = createNegotiator()
319
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
320
+ * // 'text/html'
321
+ * ```
322
+ */
323
+ export declare function createNegotiator(): NegotiatorInterface;
324
+
325
+ /**
326
+ * Create a {@link ServerInterface} — the node face's HTTP server facade over
327
+ * a consumed `@orkestrel/router` dispatcher.
328
+ *
329
+ * @typeParam TState - The consumer's opaque per-request state type
330
+ * @param options - {@link ServerOptions}
331
+ * @returns A {@link ServerInterface}, not yet started
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * import { createServer } from '@src/server'
336
+ * import { createDispatcher } from '@orkestrel/router'
337
+ *
338
+ * const dispatcher = createDispatcher<{ readonly ip?: string }>()
339
+ * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
340
+ *
341
+ * const server = createServer({
342
+ * dispatcher,
343
+ * state: (connection) => ({ ip: connection.ip }),
344
+ * })
345
+ * const port = await server.start()
346
+ * await server.stop()
347
+ * ```
348
+ */
349
+ export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
350
+
351
+ /**
352
+ * Decode a base64url string back into its bytes — the inverse of
353
+ * {@link encodeBase64Url}.
354
+ *
355
+ * @remarks
356
+ * Restores the standard base64 alphabet + padding before decoding with
357
+ * `atob`. THROWS `DOMException` on a malformed input — callers on the
358
+ * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
359
+ *
360
+ * @param value - The base64url string to decode
361
+ * @returns The decoded bytes
362
+ * @throws {DOMException} When `value` is not valid base64url
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
367
+ * ```
368
+ */
369
+ export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
370
+
371
+ /**
372
+ * Decode a cookie value with `decodeURIComponent`, falling back to the raw
373
+ * text when the value is not valid percent-encoding.
374
+ *
375
+ * @param raw - The raw (trimmed) cookie value
376
+ * @returns The URL-decoded value, or the raw value when decoding would throw
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * decodeCookieValue('a%20b') // 'a b'
381
+ * decodeCookieValue('%') // '%' — malformed escape stays literal
382
+ * ```
383
+ */
384
+ export declare function decodeCookieValue(raw: string): string;
385
+
386
+ /**
387
+ * Decode + narrow a signed token's base64url JSON payload, honoring its
388
+ * expiry — the shared decode step {@link verifyToken} applies after a
389
+ * signature match.
390
+ *
391
+ * @remarks
392
+ * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
393
+ * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
394
+ * TOTAL — any decode/shape/expiry failure yields `undefined`.
395
+ *
396
+ * @param encoded - The base64url-encoded payload segment (before the last `.`)
397
+ * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
398
+ */
399
+ export declare function decodeTokenPayload(encoded: string): string | undefined;
400
+
401
+ /**
402
+ * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
403
+ * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
404
+ * the zip-bomb defense.
405
+ *
406
+ * @remarks
407
+ * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
408
+ * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
409
+ * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
410
+ * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
411
+ * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
412
+ * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
413
+ * (never conflated with the cap). A non-positive `cap` means uncapped.
414
+ *
415
+ * @param bytes - The compressed bytes to decompress
416
+ * @param encoding - The {@link Encoding} the bytes are compressed with
417
+ * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
418
+ * @returns The decompressed bytes
419
+ * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
420
+ * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
421
+ */
422
+ export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
423
+
424
+ /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
425
+ export declare const DEFAULT_BODY_LIMIT = 1048576;
426
+
427
+ /**
428
+ * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
429
+ * the body pipeline's byte-counting `TransformStream` enforces when
430
+ * transparently decompressing a `Content-Encoding` request body.
431
+ *
432
+ * @remarks
433
+ * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
434
+ * can inflate by many orders of magnitude — a classic decompression bomb.
435
+ * Capping the decompressed byte count makes the pipe ABORT the moment the
436
+ * output would exceed this, BEFORE the full bomb is materialized, so the
437
+ * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
438
+ * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
439
+ * consumer raises it via {@link import('./types.js').BodyOptions}
440
+ * `decompression` for a workload that genuinely ships larger decompressed
441
+ * bodies.
442
+ */
443
+ export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
444
+
445
+ /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
446
+ export declare const DEFAULT_DRAIN_MS = 10000;
447
+
448
+ /**
449
+ * The default {@link Encoding} content-codings the substrate offers, in
450
+ * PREFERENCE order — `gzip` / `deflate`.
451
+ *
452
+ * @remarks
453
+ * `identity` (no compression) is always implicitly acceptable and is NOT
454
+ * listed here — it is the fall-through when a client accepts none of these.
455
+ * Brotli is omitted per the core's `CompressionStream`-only decision (see
456
+ * {@link Encoding}). Frozen so a consumer can read but never mutate the
457
+ * shared default.
458
+ */
459
+ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
460
+
461
+ /**
462
+ * Find a FREE TCP port — bind a throwaway `node:net` server, read the
463
+ * OS-assigned port, close it, and resolve that port.
464
+ *
465
+ * @remarks
466
+ * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
467
+ * and returns it. With a `preferred` port it tries THAT port first and
468
+ * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
469
+ * ephemeral free port rather than rejecting — a caller always gets a usable
470
+ * port. It binds then immediately closes a probe server, so the returned
471
+ * port is free at the instant of the probe (an inherent TOCTOU race — bind it
472
+ * promptly). Rejects only on an unexpected listen error other than a taken
473
+ * `preferred` port (e.g. a permission fault).
474
+ *
475
+ * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
476
+ * fall back to an ephemeral port
477
+ * @returns A free TCP port number
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * import { createServer, discoverPort } from '@src/server'
482
+ *
483
+ * const port = await discoverPort() // a guaranteed-free ephemeral port
484
+ * ```
485
+ */
486
+ export declare function discoverPort(preferred?: number): Promise<number>;
487
+
488
+ /**
489
+ * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
490
+ * {@link verifyToken} use, and the signature encoding for the HMAC.
491
+ *
492
+ * @param bytes - The bytes to encode
493
+ * @returns The base64url string (no padding)
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
498
+ * ```
499
+ */
500
+ export declare function encodeBase64Url(bytes: Uint8Array): string;
501
+
502
+ /**
503
+ * A content-coding the substrate compresses / decompresses with — the
504
+ * `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
505
+ *
506
+ * @remarks
507
+ * `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
508
+ * (web-standard, no external codec); `identity` is the no-op "uncompressed"
509
+ * coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
510
+ * is deliberately OMITTED here — Brotli parity is the future middleware
511
+ * package's node-entry decision (§3 of the proposal), not this core's. A
512
+ * constrained set of external-spec literals, so it stays a union, not a
513
+ * behavioral toggle (AGENTS §4.4).
514
+ */
515
+ export declare type Encoding = 'gzip' | 'deflate' | 'identity';
516
+
517
+ /**
518
+ * A map of media type → handler for {@link NegotiatorInterface.format} — the
519
+ * content-negotiation dispatch table.
520
+ *
521
+ * @typeParam TState - The consumer's opaque per-request state type
522
+ *
523
+ * @remarks
524
+ * Each key is a media type the route can PRODUCE (`application/json`,
525
+ * `text/html`, …) and each value the responder that returns that
526
+ * representation as a `Response`. `format` negotiates the client's preferred
527
+ * key from the request `Accept` header and invokes the matching handler, or
528
+ * answers `406 Not Acceptable` when none of the offered types is acceptable.
529
+ * The keys are the `available` set negotiation chooses from, so their order
530
+ * is the server's tie-break preference (a client accepting the any-media-
531
+ * range gets the first key).
532
+ */
533
+ export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
534
+
535
+ /**
536
+ * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
537
+ * an instance thrown by ANOTHER copy of this package (the dual-package
538
+ * hazard — a version-skewed or workspace-linked duplicate install), where
539
+ * `instanceof` alone fails because the two copies' `HTTPError` constructors
540
+ * are distinct objects.
541
+ *
542
+ * @remarks
543
+ * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every
544
+ * copy of this package that evaluates this key resolves the SAME symbol
545
+ * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
546
+ * unequal symbol per copy and defeat the whole point of a cross-copy brand.
547
+ */
548
+ export declare const HTTP_ERROR_BRAND: unique symbol;
549
+
550
+ /**
551
+ * An error a handler (or middleware) throws to produce an HTTP response of a
552
+ * specific status.
553
+ *
554
+ * @remarks
555
+ * Carries the HTTP `status` to send and an optional `context` record (the
556
+ * offending field / value). The server's built-in error boundary catches it
557
+ * and renders a response of `status` with the error's `message` as the body
558
+ * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
559
+ * deliberate signal), unlike a generic throw whose message is hidden unless
560
+ * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
561
+ * specific statuses, or throw it directly. Narrow a caught value with
562
+ * {@link isHTTPError}.
563
+ *
564
+ * @example
565
+ * ```ts
566
+ * import { HTTPError } from '@src/server'
567
+ *
568
+ * const handler = async (request: Request): Promise<Response> => {
569
+ * const user = await find(new URL(request.url).searchParams.get('id'))
570
+ * if (user === undefined) throw new HTTPError(404, 'user not found')
571
+ * return Response.json(user)
572
+ * }
573
+ * ```
574
+ */
575
+ export declare class HTTPError extends Error {
576
+ readonly status: number;
577
+ readonly context?: Readonly<Record<string, unknown>>;
578
+ readonly [HTTP_ERROR_BRAND] = true;
579
+ constructor(status: number, message: string, context?: Readonly<Record<string, unknown>>);
580
+ }
581
+
582
+ /**
583
+ * Compute the `/64` network of a full IPv6 address, or `undefined` when the
584
+ * input is not a plain IPv6 address to collapse.
585
+ *
586
+ * @remarks
587
+ * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
588
+ * is the identity) or any string that does not expand to exactly eight
589
+ * hextets. Expands a single `::` into the missing zero hextets, takes the
590
+ * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
591
+ * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
592
+ * first. Total — a malformed address returns `undefined`.
593
+ *
594
+ * @param address - The candidate IPv6 address
595
+ * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
596
+ *
597
+ * @example
598
+ * ```ts
599
+ * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
600
+ * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
601
+ * ```
602
+ */
603
+ export declare function ipv6Network(address: string): string | undefined;
604
+
605
+ /**
606
+ * Whether a `node:net` `server.address()` return is the structured
607
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
608
+ * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
609
+ * and the `Server`'s own port resolution read the bound port through.
610
+ *
611
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
612
+ * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * import { isAddressInfo } from '@src/server'
617
+ *
618
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
619
+ * isAddressInfo(null) // false
620
+ * ```
621
+ */
622
+ export declare function isAddressInfo(value: unknown): value is AddressInfo;
623
+
624
+ /**
625
+ * Whether a `Content-Type` is worth compressing.
626
+ *
627
+ * @remarks
628
+ * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
629
+ * type, a `+json`/`+xml` structured suffix, or one of the explicit
630
+ * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
631
+ * binary (`image/png`, `application/zip`) is NOT compressible. An
632
+ * absent/empty type is not compressible. TOTAL.
633
+ *
634
+ * @param type - The response `Content-Type` header value (with or without parameters)
635
+ * @returns `true` when the type is text-shaped and worth compressing
636
+ *
637
+ * @example
638
+ * ```ts
639
+ * isCompressibleType('application/json; charset=utf-8') // true
640
+ * isCompressibleType('image/png') // false
641
+ * ```
642
+ */
643
+ export declare function isCompressibleType(type: string): boolean;
644
+
645
+ /**
646
+ * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
647
+ * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
648
+ * attributes with before emitting them.
649
+ *
650
+ * @remarks
651
+ * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
652
+ * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
653
+ * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
654
+ * directive. Total — never throws (a bad value returns `false`).
655
+ *
656
+ * @param value - The candidate attribute value (a `Domain` or `Path`)
657
+ * @returns `true` when `value` carries no separator / whitespace / control char
658
+ *
659
+ * @example
660
+ * ```ts
661
+ * isCookieAttribute('/app') // true
662
+ * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
663
+ * ```
664
+ */
665
+ export declare function isCookieAttribute(value: string): boolean;
666
+
667
+ /**
668
+ * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
669
+ * cookie-token chars with NO surrounding (or interior) whitespace.
670
+ *
671
+ * @remarks
672
+ * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
673
+ * which excludes every whitespace char (ASCII and Unicode) plus controls,
674
+ * separators, and `=`. The {@link parseCookies} hardening that stops a
675
+ * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
676
+ *
677
+ * @param value - The candidate cookie name
678
+ * @returns `true` when `value` is a valid, whitespace-free cookie token
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * isCookieName('__Host-session') // true
683
+ * isCookieName(' __Host-session') // false — whitespace-padded
684
+ * ```
685
+ */
686
+ export declare function isCookieName(value: string): boolean;
687
+
688
+ /**
689
+ * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
690
+ * or `prototype` — the three keys that, assigned onto a normal object, can
691
+ * reach and mutate `Object.prototype`.
692
+ *
693
+ * @param key - The candidate object key
694
+ * @returns `true` when `key` is one of the three prototype-pollution keys
695
+ *
696
+ * @example
697
+ * ```ts
698
+ * isDangerousKey('__proto__') // true
699
+ * isDangerousKey('name') // false
700
+ * ```
701
+ */
702
+ export declare function isDangerousKey(key: string): boolean;
703
+
704
+ /**
705
+ * Narrow an unknown caught value to an {@link HTTPError} (including its
706
+ * subclasses, e.g. {@link ContentTooLargeError}).
707
+ *
708
+ * @param value - The value to test (typically a `catch` binding)
709
+ * @returns `true` when `value` is an {@link HTTPError}
710
+ *
711
+ * @remarks
712
+ * Tries `instanceof` first, then falls back to a total structural check for
713
+ * an instance built by a DIFFERENT copy of this package (the dual-package
714
+ * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
715
+ * constructor is a distinct object from this copy's: the value must carry
716
+ * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the
717
+ * same key) AND expose the exact fields the server's error boundary reads off
718
+ * a recognized `HTTPError` — a numeric `status` and a string `message`. A
719
+ * plain object that merely carries a `status` WITHOUT the brand is rejected.
720
+ *
721
+ * @example
722
+ * ```ts
723
+ * import { isHTTPError } from '@src/server'
724
+ *
725
+ * try {
726
+ * await handle(request)
727
+ * } catch (error) {
728
+ * if (isHTTPError(error)) console.log(error.status, error.message)
729
+ * }
730
+ * ```
731
+ */
732
+ export declare function isHTTPError(value: unknown): value is HTTPError;
733
+
734
+ /**
735
+ * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
736
+ * header + `context.state`.
737
+ *
738
+ * @remarks
739
+ * A request id is echoed RAW into a response header and log lines, so an
740
+ * untrusted one is a header-injection + log-injection + DoS vector. This
741
+ * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
742
+ * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
743
+ * TOTAL — never throws.
744
+ *
745
+ * @param value - The candidate incoming request id
746
+ * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
747
+ *
748
+ * @example
749
+ * ```ts
750
+ * isValidRequestId('req_abc-123') // true
751
+ * isValidRequestId('bad\r\nheader') // false
752
+ * ```
753
+ */
754
+ export declare function isValidRequestId(value: string): boolean;
755
+
756
+ /**
757
+ * The client's quality for one `candidate` language from the parsed
758
+ * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
759
+ *
760
+ * @remarks
761
+ * Prefers an exact match, then a primary-tag prefix match (`en` accepts
762
+ * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
763
+ * is an explicit rejection).
764
+ *
765
+ * @param entries - The parsed {@link AcceptEntry} list
766
+ * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
767
+ * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
768
+ *
769
+ * @example
770
+ * ```ts
771
+ * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
772
+ * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
773
+ * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
774
+ * ```
775
+ */
776
+ export declare function languageQuality(entries: readonly AcceptEntry[], candidate: string): number;
777
+
778
+ /**
779
+ * Whether a request's `If-None-Match` header matches a resource's current
780
+ * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
781
+ *
782
+ * @remarks
783
+ * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
784
+ * listed tag matches), or the `*` wildcard (matches ANY current
785
+ * representation — only a list of exactly `*` is the wildcard). Comparison is
786
+ * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
787
+ * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
788
+ * malformed/empty header matches nothing, never throws.
789
+ *
790
+ * @param header - The raw `If-None-Match` header value
791
+ * @param etag - The resource's current `ETag`
792
+ * @returns `true` when the conditional matches (the caller answers `304`)
793
+ *
794
+ * @example
795
+ * ```ts
796
+ * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
797
+ * matchesETag('*', 'W/"anything"') // true — wildcard
798
+ * ```
799
+ */
800
+ export declare function matchesETag(header: string, etag: string): boolean;
801
+
802
+ /**
803
+ * Rank + quality of one `candidate` media type against the parsed `Accept`
804
+ * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
805
+ * uses to score each `available` candidate.
806
+ *
807
+ * @remarks
808
+ * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
809
+ * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
810
+ * `;q=0` entry explicitly rejects the candidate outright (returns
811
+ * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
812
+ * (less specific) coverage, so a later more-specific match can still allow
813
+ * it. Among multiple matching entries, the lowest `rank` wins, and among a
814
+ * rank tie the highest `q` wins.
815
+ *
816
+ * @param entries - The parsed {@link AcceptEntry} list
817
+ * @param candidate - The candidate media type to score (e.g. `'text/html'`)
818
+ * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
819
+ *
820
+ * @example
821
+ * ```ts
822
+ * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
823
+ * // { q: 1, rank: 0 }
824
+ * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
825
+ * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
826
+ * ```
827
+ */
828
+ export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string): {
829
+ readonly q: number;
830
+ readonly rank: number;
831
+ } | undefined;
832
+
833
+ /**
834
+ * Merge a `Vary` value into an existing `Vary` header without duplication.
835
+ *
836
+ * @remarks
837
+ * Splits `existing` on `,`, trims each member, and appends `value` only when
838
+ * no existing member already matches it case-insensitively (`Vary` header
839
+ * names are case-insensitive). Preserves the existing members' order and
840
+ * appends the new one last.
841
+ *
842
+ * @param existing - The current `Vary` header value, if any
843
+ * @param value - The header name to ensure is listed
844
+ * @returns The merged `Vary` value
845
+ *
846
+ * @example
847
+ * ```ts
848
+ * mergeVary(undefined, 'Origin') // 'Origin'
849
+ * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
850
+ * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
851
+ * ```
852
+ */
853
+ export declare function mergeVary(existing: string | undefined, value: string): string;
854
+
855
+ /**
856
+ * The composition context — plain data, one per request, shared by every
857
+ * middleware AND (as `state`) by the route handlers behind the dispatcher.
858
+ *
859
+ * @typeParam TState - The consumer's opaque per-request state type
860
+ *
861
+ * @remarks
862
+ * - `url` — the parsed request {@link URL} (mirrors the router's own parse, so
863
+ * a middleware never re-parses it).
864
+ * - `method` — the raw request verb; the dispatcher (not this seam) narrows it
865
+ * to a known {@link import('@orkestrel/router').Method}.
866
+ * - `state` — THE shared bag threaded from the adapter's `state` factory,
867
+ * through every middleware, into `dispatcher.handle`'s `state` — the same
868
+ * object a route handler reads as `context.state`.
869
+ * - `body()` — lazily collect the request body (byte-limited, transparently
870
+ * decompressed, prototype-scrubbed for JSON), cached so repeated calls (a
871
+ * body-parsing middleware, then the handler) read the underlying stream
872
+ * exactly once.
873
+ *
874
+ * @example
875
+ * ```ts
876
+ * const middleware: MiddlewareHandler<{ readonly userId?: string }> = async (request, context, next) => {
877
+ * const body = await context.body()
878
+ * return next(request)
879
+ * }
880
+ * ```
881
+ */
882
+ export declare interface MiddlewareContext<TState> {
883
+ readonly url: URL;
884
+ readonly method: string;
885
+ readonly state: TState;
886
+ body(): Promise<unknown>;
887
+ }
888
+
889
+ /**
890
+ * One link in the middleware onion — runs around the rest of the chain.
891
+ *
892
+ * @typeParam TState - The consumer's opaque per-request state type
893
+ *
894
+ * @remarks
895
+ * Transform the request (call `next(newRequest)`), transform the response
896
+ * (`await next()` then modify the result), short-circuit (return a `Response`
897
+ * without calling `next`), or thread data via `context.state` — no mutable
898
+ * framework object anywhere, only fetch-standard `Request`/`Response`.
899
+ *
900
+ * @example
901
+ * ```ts
902
+ * const withRequestId: MiddlewareHandler<{ readonly requestId: string }> = async (request, context, next) => {
903
+ * const response = await next()
904
+ * response.headers.set('X-Request-ID', context.state.requestId)
905
+ * return response
906
+ * }
907
+ * ```
908
+ */
909
+ export declare type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
910
+
911
+ /**
912
+ * Select the best content-coding for an `Accept-Encoding` header from the
913
+ * codings the server offers.
914
+ *
915
+ * @remarks
916
+ * Parses the header ({@link parseAcceptHeader}) and scores each `available`
917
+ * coding in the SERVER's preference order ({@link codingQuality}), keeping
918
+ * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
919
+ * client-side tie). Returns `undefined` when the client accepts none of
920
+ * `available` (identity — no compression). TOTAL on hostile input.
921
+ *
922
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
923
+ * @param header - The raw `Accept-Encoding` header value
924
+ * @param available - The codings the server offers, in preference (tie-break) order
925
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
926
+ *
927
+ * @example
928
+ * ```ts
929
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
930
+ * ```
931
+ */
932
+ export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
933
+
934
+ /**
935
+ * The content-negotiation machine over the weighted `Accept` family — a
936
+ * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
937
+ * {@link NegotiatorInterface}.
938
+ *
939
+ * @remarks
940
+ * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
941
+ * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
942
+ * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
943
+ * rest of the substrate uses — one parser, never two. `format` reads the
944
+ * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
945
+ * the winner — or answers `406 Not Acceptable`.
946
+ *
947
+ * @example
948
+ * ```ts
949
+ * const negotiator = new Negotiator()
950
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
951
+ * // 'text/html'
952
+ * ```
17
953
  */
18
- export declare type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
954
+ export declare class Negotiator implements NegotiatorInterface {
955
+ negotiate(header: string, available: readonly string[]): string | undefined;
956
+ encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
957
+ language(header: string, available: readonly string[]): string | undefined;
958
+ /**
959
+ * @remarks
960
+ * Errors thrown by the negotiated handler propagate UNMODIFIED — the
961
+ * server boundary classifies them, never this negotiator.
962
+ */
963
+ format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
964
+ }
19
965
 
20
966
  /**
21
- * Create a {@link ServerInterface} — the node face's HTTP server facade over
22
- * a consumed `@orkestrel/router` dispatcher.
967
+ * Content negotiation over the weighted `Accept` family — a reusable,
968
+ * cross-middleware machine (not itself a middleware).
23
969
  *
24
- * @typeParam TState - The consumer's opaque per-request state type
25
- * @param options - {@link ServerOptions}
26
- * @returns A {@link ServerInterface}, not yet started
970
+ * @remarks
971
+ * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
972
+ * (q-values honored, `*` wildcards honored, a `;q=0` rejection respected) and
973
+ * picks the client's most-preferred value the server also offers. `negotiate`
974
+ * is the generic primitive (media types); `encoding` / `language` are its
975
+ * sibling axes. `format` is the dispatcher — it reads the request `Accept`,
976
+ * negotiates against a {@link FormatHandlerMap}'s keys, and invokes the
977
+ * winning handler, resolving `406 Not Acceptable` when none is acceptable.
27
978
  *
28
979
  * @example
29
980
  * ```ts
30
- * import { createServer } from '@src/server'
31
- * import { createDispatcher } from '@orkestrel/router'
981
+ * const response = await negotiator.format(request, context, {
982
+ * 'application/json': (request, context) => Response.json({ ok: true }),
983
+ * 'text/html': (request, context) => new Response('<p>ok</p>', { headers: { 'Content-Type': 'text/html' } }),
984
+ * })
985
+ * ```
986
+ */
987
+ export declare interface NegotiatorInterface {
988
+ /**
989
+ * Pick the best `available` value for a weighted `Accept`-style `header` —
990
+ * the generic media-type primitive (`encoding` / `language` build on it).
991
+ *
992
+ * @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
993
+ * @param available - The values the server can produce, in preference (tie-break) order
994
+ * @returns The best acceptable value, or `undefined` when none is
995
+ */
996
+ negotiate(header: string, available: readonly string[]): string | undefined;
997
+ /**
998
+ * Pick the best `available` content-coding for an `Accept-Encoding` header
999
+ * — `negotiate` scoped to codings (a bare `*` wildcard ⇒ the first `available`).
1000
+ *
1001
+ * @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
1002
+ * @param available - The codings the server offers, in preference order
1003
+ * @returns The best acceptable coding, or `undefined` when none is
1004
+ */
1005
+ encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
1006
+ /**
1007
+ * Pick the best `available` language for an `Accept-Language` header —
1008
+ * `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
1009
+ * bare `*` wildcard.
1010
+ *
1011
+ * @param header - The raw `Accept-Language` header value (e.g. `en-US, en;q=0.8, fr;q=0.5`)
1012
+ * @param available - The languages the server offers, in preference order
1013
+ * @returns The best acceptable language, or `undefined` when none is
1014
+ */
1015
+ language(header: string, available: readonly string[]): string | undefined;
1016
+ /**
1017
+ * Dispatch to the handler whose media type the client most prefers — read
1018
+ * the request `Accept`, negotiate against `handlers`' keys, and invoke the
1019
+ * winner; `406` when none is acceptable.
1020
+ *
1021
+ * @typeParam TState - The consumer's opaque per-request state type
1022
+ * @param request - The in-flight `Request`
1023
+ * @param context - The request's {@link MiddlewareContext}
1024
+ * @param handlers - The media type → responder {@link FormatHandlerMap} the route offers
1025
+ * @returns The winning handler's `Response`, or a `406 Not Acceptable` `Response`
1026
+ */
1027
+ format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
1028
+ }
1029
+
1030
+ /**
1031
+ * The downstream continuation a {@link MiddlewareHandler} invokes to run the
1032
+ * rest of the onion.
32
1033
  *
33
- * const dispatcher = createDispatcher<{ readonly ip?: string }>()
34
- * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
1034
+ * @remarks
1035
+ * Call it (optionally with a substituted `Request`) to run the downstream
1036
+ * chain and receive its `Response`; omit the call entirely to short-circuit
1037
+ * with a `Response` built by this middleware instead. A SECOND call rejects
1038
+ * (the double-`next` guard) — each middleware runs the chain at most once.
35
1039
  *
36
- * const server = createServer({
37
- * dispatcher,
38
- * state: (connection) => ({ ip: connection.ip }),
39
- * })
40
- * const port = await server.start()
41
- * await server.stop()
1040
+ * @param request - An optional replacement `Request` to hand downstream
1041
+ * (omitted ⇒ the original request continues)
1042
+ * @returns The downstream chain's resolved `Response`
1043
+ */
1044
+ export declare type NextFunction = (request?: Request) => Promise<Response>;
1045
+
1046
+ /**
1047
+ * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
1048
+ * backs both {@link signToken} and {@link verifyToken}.
1049
+ *
1050
+ * @remarks
1051
+ * A single string becomes a one-element list; a rotation list is copied. Any
1052
+ * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
1053
+ * emptiness test; each kept secret is stored VERBATIM). The first kept
1054
+ * element is the signing secret; all kept are accepted on verify.
1055
+ *
1056
+ * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
1057
+ * @returns The kept (non-blank) secrets, in order — empty when none is usable
1058
+ *
1059
+ * @example
1060
+ * ```ts
1061
+ * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
42
1062
  * ```
43
1063
  */
44
- export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
1064
+ export declare function normalizeSecret(secret: TokenSecret): readonly string[];
45
1065
 
46
1066
  /**
47
- * Find a FREE TCP port — bind a throwaway `node:net` server, read the
48
- * OS-assigned port, close it, and resolve that port.
1067
+ * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1068
+ * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
49
1069
  *
50
1070
  * @remarks
51
- * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
52
- * and returns it. With a `preferred` port it tries THAT port first and
53
- * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
54
- * ephemeral free port rather than rejecting — a caller always gets a usable
55
- * port. It binds then immediately closes a probe server, so the returned
56
- * port is free at the instant of the probe (an inherent TOCTOU race — bind it
57
- * promptly). Rejects only on an unexpected listen error other than a taken
58
- * `preferred` port (e.g. a permission fault).
1071
+ * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1072
+ * merged under any `options.headers` (a seam-owned key is never overridden),
1073
+ * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1074
+ * `write` serializes one message ({@link serializeEvent}) and enqueues it;
1075
+ * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1076
+ * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1077
+ * by `end()`, or the consumer cancelled the stream), so a late write never
1078
+ * throws.
59
1079
  *
60
- * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
61
- * fall back to an ephemeral port
62
- * @returns A free TCP port number
1080
+ * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1081
+ * @returns The {@link StreamInterface} handle
63
1082
  *
64
1083
  * @example
65
1084
  * ```ts
66
- * import { createServer, discoverPort } from '@src/server'
1085
+ * const stream = openStream()
1086
+ * stream.write({ event: 'token', data: 'hello' })
1087
+ * stream.end()
1088
+ * // return stream.response from the route handler
1089
+ * ```
1090
+ */
1091
+ export declare function openStream(options?: StreamOptions): StreamInterface;
1092
+
1093
+ /**
1094
+ * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
1095
+ * into its q-sorted entries.
67
1096
  *
68
- * const port = await discoverPort() // a guaranteed-free ephemeral port
1097
+ * @remarks
1098
+ * Splits on `,`; for each part takes the token before the first `;`
1099
+ * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
1100
+ * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
1101
+ * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
1102
+ * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
1103
+ * the header's own order within a tie — a single pass with no backtracking,
1104
+ * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
1105
+ * empty/malformed header yields `[]`/best-effort entries, never throws.
1106
+ *
1107
+ * @param header - The raw weighted header value
1108
+ * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
1109
+ *
1110
+ * @example
1111
+ * ```ts
1112
+ * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
1113
+ * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
69
1114
  * ```
70
1115
  */
71
- export declare function discoverPort(preferred?: number): Promise<number>;
1116
+ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
72
1117
 
73
1118
  /**
74
- * Whether a `node:net` `server.address()` return is the structured
75
- * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
76
- * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
77
- * and the `Server`'s own port resolution read the bound port through.
1119
+ * Parse a raw `Cookie:` request header into a `name → value` lookup.
78
1120
  *
79
- * @param value - The `server.address()` return (`AddressInfo | string | null`)
80
- * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
1121
+ * @remarks
1122
+ * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
1123
+ * cookie-pair separator never precedes it), while every later segment has its
1124
+ * inter-pair separator (ASCII space/tab) stripped before parsing — so a
1125
+ * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
1126
+ * {@link isCookieName} rather than silently reconciling into a
1127
+ * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
1128
+ * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
1129
+ * malformed header yields an empty record, never throws (AGENTS §14).
1130
+ *
1131
+ * @param header - The raw `Cookie` header value (possibly `undefined`)
1132
+ * @returns A record of every parsed cookie, `name → decoded value`
81
1133
  *
82
1134
  * @example
83
1135
  * ```ts
84
- * import { isAddressInfo } from '@src/server'
1136
+ * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
1137
+ * ```
1138
+ */
1139
+ export declare function parseCookies(header: string | undefined): Record<string, string>;
1140
+
1141
+ /**
1142
+ * Parse an HTTP `Range` request header against a known resource `size` —
1143
+ * TOTAL, returning a {@link RangeSpec} or `undefined`.
85
1144
  *
86
- * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
87
- * isAddressInfo(null) // false
1145
+ * @remarks
1146
+ * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1147
+ * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1148
+ * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1149
+ * `{ satisfiable: true, start, end }` for an overlapping range,
1150
+ * `{ satisfiable: false }` for a range wholly past the resource, and
1151
+ * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1152
+ * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1153
+ * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1154
+ * header.
1155
+ *
1156
+ * @param header - The raw `Range` header value
1157
+ * @param size - The resource's total byte length
1158
+ * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1163
+ * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
88
1164
  * ```
89
1165
  */
90
- export declare function isAddressInfo(value: unknown): value is AddressInfo;
1166
+ export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
1167
+
1168
+ /**
1169
+ * The parsed outcome of an HTTP `Range` request header.
1170
+ *
1171
+ * @remarks
1172
+ * A `Range: bytes=start-end` against a known resource `size` resolves to ONE
1173
+ * of two shapes, discriminated by `satisfiable` (the axis is whether the
1174
+ * requested span overlaps the resource):
1175
+ *
1176
+ * - **`satisfiable: true`** — a concrete, clamped byte window `[start, end]`
1177
+ * (INCLUSIVE, the HTTP wire convention), normalized from the header's
1178
+ * open / suffix / closed forms against `size`.
1179
+ * - **`satisfiable: false`** — the range lies wholly outside the resource.
1180
+ *
1181
+ * `parseRange` returns `undefined` for an ABSENT / unparseable / multi-range
1182
+ * / non-`bytes` header — the "no range, serve the whole resource" case — so
1183
+ * the three outcomes (full / partial / unsatisfiable) are distinguished
1184
+ * without a separate flag. It is TOTAL — a hostile header never throws.
1185
+ */
1186
+ export declare type RangeSpec = {
1187
+ readonly satisfiable: true;
1188
+ readonly start: number;
1189
+ readonly end: number;
1190
+ } | {
1191
+ readonly satisfiable: false;
1192
+ };
1193
+
1194
+ /**
1195
+ * Collect + decode a `Request` body — the shared body-collection pipeline
1196
+ * surfaced to middleware and handlers as the middleware context's cached
1197
+ * `body()`.
1198
+ *
1199
+ * @remarks
1200
+ * Collects the wire body capped at `options.limit` bytes ({@link
1201
+ * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
1202
+ * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
1203
+ * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1204
+ * `options.decompression`, default {@link
1205
+ * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1206
+ * content type: `application/json` is parsed via `@orkestrel/contract`'s
1207
+ * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1208
+ * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1209
+ * decodes to `undefined`.
1210
+ *
1211
+ * @param request - The `Request` to read the body from
1212
+ * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1213
+ * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1214
+ * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1215
+ * @throws {HTTPError} When the compressed body is corrupt (400)
1216
+ *
1217
+ * @example
1218
+ * ```ts
1219
+ * const body = await readBody(request, { limit: 1_048_576 })
1220
+ * ```
1221
+ */
1222
+ export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
1223
+
1224
+ /**
1225
+ * Read + verify a SIGNED cookie off a request — TOTAL, returning the
1226
+ * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
1227
+ *
1228
+ * @remarks
1229
+ * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
1230
+ * and verifies it with {@link verifyToken} against `secret` (a rotation list
1231
+ * accepts a cookie signed by any of its secrets). ANY failure — an absent
1232
+ * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
1233
+ *
1234
+ * @param request - The `Request` to read the `Cookie` header from
1235
+ * @param name - The cookie name to read
1236
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
1237
+ * @returns The embedded value when the cookie is present + valid, else `undefined`
1238
+ *
1239
+ * @example
1240
+ * ```ts
1241
+ * const value = await readSignedCookie(request, 'session', 'secret')
1242
+ * ```
1243
+ */
1244
+ export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
1245
+
1246
+ /**
1247
+ * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
1248
+ * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
1249
+ * / control-char-bearing incoming id is REJECTED (a fresh id is minted
1250
+ * instead) rather than ever riding into a response header or `context.state`
1251
+ * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
1252
+ * shared default.
1253
+ */
1254
+ export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
1255
+
1256
+ /**
1257
+ * Narrow a raw `Content-Encoding` header value to a decompressible
1258
+ * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1259
+ * whether a request body needs transparent decompression.
1260
+ *
1261
+ * @remarks
1262
+ * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1263
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1264
+ * the proposal). An absent header, `identity`, an unknown value, or a
1265
+ * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1266
+ * TOTAL — never asserts the loose `string | null` header.
1267
+ *
1268
+ * @param header - The raw `Content-Encoding` header value
1269
+ * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1270
+ *
1271
+ * @example
1272
+ * ```ts
1273
+ * requestEncoding('gzip') // 'gzip'
1274
+ * requestEncoding('br') // undefined — unsupported by DecompressionStream
1275
+ * ```
1276
+ */
1277
+ export declare function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined;
1278
+
1279
+ /**
1280
+ * Resolve the `Access-Control-Allow-Origin` value for a request.
1281
+ *
1282
+ * @remarks
1283
+ * `'*'` and a single origin string pass straight through. An allow-list
1284
+ * echoes the request's `Origin` only when it is present in the list, else
1285
+ * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1286
+ * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1287
+ * NEVER reflected even if `'null'` were listed, closing the hostile-context
1288
+ * cross-origin-access hole.
1289
+ *
1290
+ * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
1291
+ * @param requestOrigin - The request's `Origin` header value, if present
1292
+ * @returns The allow-origin value to send, or `undefined` to set no header
1293
+ *
1294
+ * @example
1295
+ * ```ts
1296
+ * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
1297
+ * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
1298
+ * ```
1299
+ */
1300
+ export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
1301
+
1302
+ /**
1303
+ * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
1304
+ * `secure` setting and whether the request arrived over TLS.
1305
+ *
1306
+ * @remarks
1307
+ * `true` / `false` are explicit overrides. `undefined` (the secure default —
1308
+ * the option omitted) resolves to `encrypted` — `Secure` on a TLS
1309
+ * connection, off over plaintext HTTP — so a production HTTPS deployment
1310
+ * gets `Secure` automatically while local-dev HTTP still works.
1311
+ *
1312
+ * @param secure - The {@link CookieOptions} `secure` setting
1313
+ * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
1314
+ * @returns The concrete `Secure` flag to emit
1315
+ *
1316
+ * @example
1317
+ * ```ts
1318
+ * resolveSecure(undefined, true) // true
1319
+ * resolveSecure(undefined, false) // false
1320
+ * resolveSecure(false, true) // false — explicit override wins
1321
+ * ```
1322
+ */
1323
+ export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
1324
+
1325
+ /**
1326
+ * Resolve one opt-out, value-bearing security header.
1327
+ *
1328
+ * @remarks
1329
+ * The shared "a `string` value, or `false` to omit, or a default when unset"
1330
+ * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1331
+ * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1332
+ * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1333
+ *
1334
+ * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
1335
+ * @param fallback - The secure-default value used when `value` is unset
1336
+ * @returns The header value to set, or `undefined` to omit the header
1337
+ *
1338
+ * @example
1339
+ * ```ts
1340
+ * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
1341
+ * resolveSecurityHeader(false, 'DENY') // undefined — omitted
1342
+ * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
1343
+ * ```
1344
+ */
1345
+ export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
1346
+
1347
+ /**
1348
+ * Recursively STRIP the prototype-pollution keys from a parsed value IN
1349
+ * PLACE.
1350
+ *
1351
+ * @remarks
1352
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1353
+ * enumerable `__proto__` DATA property — but that own key becomes a
1354
+ * pollution gadget the moment a downstream deep-merge copies it onto a live
1355
+ * object. This walks the value and `delete`s any own {@link isDangerousKey}
1356
+ * key at every depth, recursing into nested objects + array elements.
1357
+ * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1358
+ * freshly-parsed value (which nothing else holds yet).
1359
+ *
1360
+ * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1361
+ * @returns The same `value`, with every dangerous key removed at every depth
1362
+ *
1363
+ * @example
1364
+ * ```ts
1365
+ * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
1366
+ * // { name: 'ok' } — the __proto__ key is gone
1367
+ * ```
1368
+ */
1369
+ export declare function scrubPrototype(value: unknown): unknown;
1370
+
1371
+ /**
1372
+ * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
1373
+ *
1374
+ * @remarks
1375
+ * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
1376
+ * appends the present {@link CookieOptions} attributes in canonical order:
1377
+ * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
1378
+ * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
1379
+ * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
1380
+ * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
1381
+ * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
1382
+ * the `secure` option (the spec requires it); an un-resolved `undefined`
1383
+ * `secure` here falls to OFF — request-aware callers resolve it first via
1384
+ * {@link resolveSecure}.
1385
+ *
1386
+ * @param name - The cookie name
1387
+ * @param value - The cookie value (URL-encoded into the output)
1388
+ * @param options - The {@link CookieOptions} attributes; see its fields for defaults
1389
+ * @returns The `Set-Cookie` header value
1390
+ * @throws {HTTPError} When `domain` or `path` carries an injection char
1391
+ *
1392
+ * @example
1393
+ * ```ts
1394
+ * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
1395
+ * ```
1396
+ */
1397
+ export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
91
1398
 
92
1399
  /**
93
- * The HTTP server facade — an observable `node:http` lifecycle composing the
94
- * `@src/core` middleware onion around a consumed `@orkestrel/router`
1400
+ * Serialize one {@link SSEMessage} to the SSE wire.
1401
+ *
1402
+ * @remarks
1403
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1404
+ * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1405
+ * (so a consuming parser's multi-`data` concat reproduces the original
1406
+ * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1407
+ * a `data:` line), then the terminating blank line.
1408
+ *
1409
+ * @param message - The event to serialize
1410
+ * @returns The SSE wire text for the event (terminated by a blank line)
1411
+ *
1412
+ * @example
1413
+ * ```ts
1414
+ * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
1415
+ * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
1416
+ * ```
1417
+ */
1418
+ export declare function serializeEvent(message: SSEMessage): string;
1419
+
1420
+ /**
1421
+ * The HTTP server facade — an observable `node:http` lifecycle composing this
1422
+ * module's own middleware onion around a consumed `@orkestrel/router`
95
1423
  * dispatcher.
96
1424
  *
97
1425
  * @typeParam TState - The consumer's opaque per-request state type
@@ -198,7 +1526,7 @@ export declare type ServerEventMap = {
198
1526
 
199
1527
  /**
200
1528
  * The HTTP server facade — an observable `node:http` lifecycle that composes
201
- * a middleware onion (the `@src/core` seam) around a consumed
1529
+ * a middleware onion (this module's own middleware seam) around a consumed
202
1530
  * `@orkestrel/router` {@link DispatcherInterface}.
203
1531
  *
204
1532
  * @typeParam TState - The consumer's opaque per-request state type
@@ -310,6 +1638,162 @@ export declare interface ServerOptions<TState> {
310
1638
  */
311
1639
  export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
312
1640
 
1641
+ /**
1642
+ * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
1643
+ *
1644
+ * @remarks
1645
+ * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
1646
+ * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
1647
+ * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
1648
+ * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
1649
+ * {@link TokenSecret} (the current secret, or the head of a rotation list).
1650
+ * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
1651
+ * misconfigured secret with no usable entry THROWS an {@link HTTPError}
1652
+ * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
1653
+ * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
1654
+ *
1655
+ * @param value - The opaque value to embed (a session id, a deployment marker)
1656
+ * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
1657
+ * @returns The signed `<payload>.<signature>` token string
1658
+ * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
1659
+ *
1660
+ * @example
1661
+ * ```ts
1662
+ * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
1663
+ * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
1664
+ * ```
1665
+ */
1666
+ export declare function signToken(value: string, options: TokenOptions): Promise<string>;
1667
+
1668
+ /**
1669
+ * The SSE response headers the `openStream` seam always sets.
1670
+ *
1671
+ * @remarks
1672
+ * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
1673
+ * keeps a proxy from caching the stream; `keep-alive` holds the connection
1674
+ * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
1675
+ * events flush promptly rather than batching. Frozen so a consumer can read
1676
+ * but never mutate the shared default; `openStream` merges any
1677
+ * {@link import('./types.js').StreamOptions.headers} UNDER these.
1678
+ */
1679
+ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
1680
+
1681
+ /**
1682
+ * One Server-Sent Event to serialize to the wire.
1683
+ *
1684
+ * @remarks
1685
+ * - `data` — the event payload (required). Serialized as one or more `data:`
1686
+ * lines: the value is split on `\n` into a `data:` line PER segment, so it
1687
+ * round-trips through a consumer's multi-`data` concat.
1688
+ * - `event` — the optional event TYPE, emitted as an `event:` line; omitted
1689
+ * ⇒ the consumer's default (`message`).
1690
+ * - `id` — the optional last-event-id, emitted as an `id:` line.
1691
+ * - `retry` — the optional reconnection time in milliseconds, emitted as a
1692
+ * `retry:` line.
1693
+ */
1694
+ export declare interface SSEMessage {
1695
+ readonly data: string;
1696
+ /** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1697
+ readonly event?: string;
1698
+ /** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1699
+ readonly id?: string;
1700
+ readonly retry?: number;
1701
+ }
1702
+
1703
+ /**
1704
+ * A handle to write Server-Sent Events to an open, fetch-standard streaming
1705
+ * `Response` — the generic streaming surface `openStream` returns over a
1706
+ * `ReadableStream`.
1707
+ *
1708
+ * @remarks
1709
+ * Agent-agnostic by design: it speaks only the SSE wire vocabulary ({@link
1710
+ * SSEMessage}), so any streaming consumer maps its own events onto `write`.
1711
+ * `response` is the `Response` to return from the route handler (its body is
1712
+ * the `ReadableStream` this handle writes into). Each `write` serializes the
1713
+ * message to the wire and enqueues it; `comment` writes a `: text` keep-alive
1714
+ * line (ignored by a conforming SSE parser — no spurious event); `end` closes
1715
+ * the stream. Every method is a SAFE NO-OP once `closed` is `true`, so a late
1716
+ * `write` never throws.
1717
+ */
1718
+ export declare interface StreamInterface {
1719
+ /** The streaming `Response` to return from the route handler. */
1720
+ readonly response: Response;
1721
+ /** Whether the underlying stream is done (ended, or the consumer disconnected). */
1722
+ readonly closed: boolean;
1723
+ /**
1724
+ * Serialize + enqueue one {@link SSEMessage} to the wire (a no-op once `closed`).
1725
+ *
1726
+ * @param message - The event to send (its `data` split on `\n` into `data:` lines)
1727
+ */
1728
+ write(message: SSEMessage): void;
1729
+ /**
1730
+ * Write a `: text` SSE comment line — a keep-alive a conforming parser ignores.
1731
+ *
1732
+ * @param text - The comment text (sent after the `: ` prefix)
1733
+ */
1734
+ comment(text: string): void;
1735
+ /** End the stream, completing the response (a no-op once already `closed`). */
1736
+ end(): void;
1737
+ }
1738
+
1739
+ /**
1740
+ * Options for the `openStream` seam.
1741
+ *
1742
+ * @param status - The HTTP status the streaming response is opened with;
1743
+ * defaults to `200`.
1744
+ * @param headers - Extra response headers merged with the SSE headers the
1745
+ * seam always sets ({@link SSE_HEADERS}) — a key the seam owns is never
1746
+ * overridden.
1747
+ */
1748
+ export declare interface StreamOptions {
1749
+ readonly status?: number;
1750
+ readonly headers?: Readonly<Record<string, string>>;
1751
+ }
1752
+
1753
+ /**
1754
+ * Options for `signToken` — how a stateless, HMAC-signed token is minted.
1755
+ *
1756
+ * @param secret - The {@link TokenSecret} to sign with; `signToken` always
1757
+ * uses the FIRST secret (a single string, or the current head of a
1758
+ * rotation list). An empty rotation list is a misconfiguration and throws.
1759
+ * @param ttl - An optional lifetime in milliseconds. When set, the expiry
1760
+ * timestamp is bound INTO the signed payload (HMAC-covered, tamper-proof);
1761
+ * `verifyToken` rejects the token once that instant has passed. Omitted ⇒
1762
+ * the token never expires.
1763
+ */
1764
+ export declare interface TokenOptions {
1765
+ readonly secret: TokenSecret;
1766
+ readonly ttl?: number;
1767
+ }
1768
+
1769
+ /**
1770
+ * A secret (or rotation list) for signing + verifying a stateless, HMAC-signed
1771
+ * token.
1772
+ *
1773
+ * @remarks
1774
+ * A single `string` is the lone secret. A `readonly string[]` is a rotation
1775
+ * list in `[current, ...older]` order: `signToken` always signs with the
1776
+ * FIRST (current) secret, while `verifyToken` accepts a token signed by ANY
1777
+ * secret in the list — so a key rotates by prepending the new one and keeping
1778
+ * the old until every outstanding token has expired, with zero downtime.
1779
+ */
1780
+ export declare type TokenSecret = string | readonly string[];
1781
+
1782
+ /**
1783
+ * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1784
+ * comparison body — the reduction {@link matchesETag} applies to both sides
1785
+ * before the RFC 7232 §2.3.2 weak comparison.
1786
+ *
1787
+ * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
1788
+ * @returns The tag with any leading `W/` removed (the quotes preserved)
1789
+ *
1790
+ * @example
1791
+ * ```ts
1792
+ * unwrapETag('W/"abc"') // '"abc"'
1793
+ * ```
1794
+ */
1795
+ export declare function unwrapETag(tag: string): string;
1796
+
313
1797
  /**
314
1798
  * A raw `node:http` protocol-upgrade claimant — registered via
315
1799
  * {@link ServerInterface.upgrade}.
@@ -331,4 +1815,55 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
331
1815
  */
332
1816
  export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
333
1817
 
1818
+ /**
1819
+ * Verify a stateless token and return its embedded value — TOTAL, never throws.
1820
+ *
1821
+ * @remarks
1822
+ * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
1823
+ * value containing dots survives), and checks the payload's HMAC-SHA256
1824
+ * signature against EACH {@link TokenSecret} candidate via
1825
+ * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
1826
+ * retired, §3 of the proposal), accepting the token on the first match (the
1827
+ * rotation path). It then decodes + narrows the payload (`isRecord` +
1828
+ * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
1829
+ * rejects an expired token. ANY failure — a malformed token, a bad signature,
1830
+ * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
1831
+ * yields `undefined` rather than throwing.
1832
+ *
1833
+ * @param token - The candidate token string (from a request header/cookie)
1834
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
1835
+ * @returns The embedded value when the token is valid + unexpired, else `undefined`
1836
+ *
1837
+ * @example
1838
+ * ```ts
1839
+ * await verifyToken('bad.token', 'shh') // undefined — never throws
1840
+ * ```
1841
+ */
1842
+ export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
1843
+
1844
+ /**
1845
+ * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
1846
+ * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
1847
+ *
1848
+ * @remarks
1849
+ * The cookie value is `await signToken(value, { secret })`
1850
+ * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
1851
+ * cookie — the same secret rotation and tamper rejection, no second HMAC
1852
+ * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
1853
+ * signing is asynchronous (§3 of the proposal).
1854
+ *
1855
+ * @param headers - The response `Headers` to write into
1856
+ * @param name - The cookie name
1857
+ * @param value - The opaque value to sign into the cookie
1858
+ * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
1859
+ * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
1860
+ *
1861
+ * @example
1862
+ * ```ts
1863
+ * const headers = new Headers()
1864
+ * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
1865
+ * ```
1866
+ */
1867
+ export declare function writeSignedCookie(headers: Headers, name: string, value: string, secret: TokenSecret, options?: CookieOptions): Promise<void>;
1868
+
334
1869
  export { }