@orkestrel/server 0.0.28 → 0.0.29

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.
@@ -46,6 +46,40 @@ export declare interface BodyOptions {
46
46
  readonly decompression?: number;
47
47
  }
48
48
 
49
+ /**
50
+ * Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the
51
+ * `Response` constructor admits keeps that status, and every other value renders a 500 whose
52
+ * message stays hidden unless `expose` is `true`.
53
+ *
54
+ * @remarks
55
+ * The renderer is total: it returns a `Response` for every value and never throws.
56
+ * - An `HTTPError` whose status the `Response` constructor admits renders that status with its
57
+ * message as the body, and with no body for a null body status (204, 205, and 304).
58
+ * - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status
59
+ * no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a
60
+ * status that is not an integer). Its body is `Internal Server Error`, or the error's own message
61
+ * when `expose` is `true` and the value is an `Error`.
62
+ * - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status
63
+ * differs from its `status`. The server's boundary reports those values with their
64
+ * `RequestLine`, except a throw after the peer disconnected, which is no fault and reports
65
+ * nothing.
66
+ *
67
+ * @param error - The thrown value
68
+ * @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it
69
+ * carries `Internal Server Error`
70
+ * @returns The response to send
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * import { buildErrorResponse, HTTPError } from '@src/server'
75
+ *
76
+ * buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404
77
+ * buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500
78
+ * buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'
79
+ * ```
80
+ */
81
+ export declare function buildErrorResponse(error: unknown, expose: boolean): Response;
82
+
49
83
  /**
50
84
  * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
51
85
  *
@@ -74,7 +108,9 @@ export declare function clearCookie(headers: Headers, name: string, options?: Co
74
108
  * throwing a {@link ContentTooLargeError} (413) the instant the running total
75
109
  * exceeds `limit` — before the rest of the stream is buffered — rather than
76
110
  * collecting an unbounded body. A bodyless request (`request.body === null`)
77
- * resolves an empty array. A non-positive `limit` means unbounded.
111
+ * resolves an empty array. A non-positive `limit` means unbounded. When
112
+ * `request.signal` aborts before the call or while a read waits, the body is
113
+ * cancelled with the signal's reason and the promise rejects with that reason.
78
114
  *
79
115
  * @param request - The `Request` to drain
80
116
  * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
@@ -88,21 +124,46 @@ export declare function clearCookie(headers: Headers, name: string, options?: Co
88
124
  */
89
125
  export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
90
126
 
127
+ /**
128
+ * Compares two `1*DIGIT` strings by their decimal value, at any length.
129
+ *
130
+ * @remarks
131
+ * Drops leading zeros, then compares the digit counts and, at an equal count,
132
+ * the digits in order, so a bound longer than any safe integer compares
133
+ * exactly and never passes through `Number`. Both arguments must be
134
+ * `1*DIGIT`; the answer for any other text is unspecified.
135
+ *
136
+ * @param left - The first digit string
137
+ * @param right - The second digit string
138
+ * @returns `-1` if `left` is less, `1` if it is greater, `0` if the two are equal
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * compareDigits('9', '10') // -1
143
+ * compareDigits('007', '7') // 0
144
+ * ```
145
+ */
146
+ export declare function compareDigits(left: string, right: string): number;
147
+
91
148
  /**
92
149
  * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
93
- * handler into one request handler — the frozen middleware seam.
150
+ * handler into one request handler — the middleware seam.
94
151
  *
95
152
  * @remarks
96
153
  * `middleware[0]` runs outermost: it is invoked first, and its call to `next`
97
154
  * runs `middleware[1]`, and so on until the last middleware's `next` invokes
98
- * `terminal`. Each middleware's `next` may be called with a substituted
99
- * `Request` (the downstream chain then sees that request instead of the
100
- * original), called with no argument (the original request continues
101
- * downstream), or not called at all (a short-circuit — the middleware's own
102
- * returned `Response` is sent, and everything downstream never runs). A
103
- * second call to the same `next` within one middleware invocation rejects —
104
- * each link runs the chain at most once, so a middleware cannot fork the
105
- * request into two divergent downstream runs.
155
+ * `terminal`. Every layer and `terminal` receive the same `Request` and the same
156
+ * context object. A middleware's `next` is called with no argument, or not
157
+ * called at all (a short-circuit — the middleware's own returned `Response` is
158
+ * sent, and everything downstream never runs). A second call to the same
159
+ * `next` within one middleware invocation, or a call that passes an argument,
160
+ * rejects with a `ServerError` of code `'NEXT'` — each link runs the chain at
161
+ * most once, so a middleware cannot fork the request into two divergent
162
+ * downstream runs. Each `next` resolves the downstream response through
163
+ * {@link normalizeResponse}, so a layer can set headers on a redirect or a
164
+ * `fetch` result; each run keeps its own memo of checked responses, which ends
165
+ * with the run. `compose` copies `middleware` when called, so a layer added to
166
+ * the array later never runs in the returned handler.
106
167
  *
107
168
  * @typeParam TState - The consumer's opaque per-request state type
108
169
  * @param middleware - The ordered chain, outermost first
@@ -394,6 +455,26 @@ export declare function createNegotiator(): NegotiatorInterface;
394
455
  */
395
456
  export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
396
457
 
458
+ /**
459
+ * Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each
460
+ * created at this call.
461
+ *
462
+ * @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}
463
+ * @returns A {@link SignerInterface} whose first key signs and whose every key verifies
464
+ * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,
465
+ * when the list is empty, or when any entry is blank
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * import { createSigner, signToken, verifyToken } from '@orkestrel/server'
470
+ *
471
+ * const signer = createSigner(['current-secret', 'previous-secret'])
472
+ * const token = await signToken('session-7f3a', { signer, ttl: 60_000 })
473
+ * await verifyToken(token, signer) // 'session-7f3a'
474
+ * ```
475
+ */
476
+ export declare function createSigner(secret: TokenSecret): SignerInterface;
477
+
397
478
  /**
398
479
  * Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose
399
480
  * `response` is a fetch-standard streaming `Response` a route returns.
@@ -456,7 +537,7 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
456
537
  * @remarks
457
538
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
458
539
  * `TransformStream` that aborts the pipe the instant the running decompressed
459
- * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
540
+ * total exceeds `cap` — fail-before-materialize, because `DecompressionStream`
460
541
  * has no `maxOutputLength` knob. A cap breach surfaces
461
542
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
462
543
  * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
@@ -483,7 +564,7 @@ export declare const DEFAULT_BODY_LIMIT = 1048576;
483
564
  * it transparently decompresses a `Content-Encoding` request body.
484
565
  *
485
566
  * @remarks
486
- * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
567
+ * A small compressed body (under {@link DEFAULT_BODY_LIMIT} on the wire)
487
568
  * can inflate by many orders of magnitude — a classic decompression bomb.
488
569
  * Capping the decompressed byte count makes the pipe abort the moment the
489
570
  * output would exceed this, before the full bomb is materialized, so the
@@ -514,6 +595,19 @@ export declare const DEFAULT_DRAIN_MS = 10000;
514
595
  */
515
596
  export declare const DEFAULT_ENCODINGS: readonly Encoding[];
516
597
 
598
+ /**
599
+ * Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when
600
+ * `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the
601
+ * request timeout.
602
+ */
603
+ export declare const DEFAULT_HEADERS_TIMEOUT_MS = 60000;
604
+
605
+ /**
606
+ * Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when
607
+ * `timeouts.request` is omitted.
608
+ */
609
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 300000;
610
+
517
611
  /**
518
612
  * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
519
613
  * port where one is given and on an ephemeral port otherwise, reads the bound
@@ -576,7 +670,7 @@ export declare type Encoding = 'gzip' | 'deflate' | 'identity';
576
670
  * answers `406 Not Acceptable` when none of the offered types is acceptable.
577
671
  * The keys are the `available` set negotiation chooses from, so their order
578
672
  * is the server's tie-break preference (a client accepting the any-media-
579
- * range gets the first key).
673
+ * range gets the first key). A key matches its media type case-insensitively.
580
674
  */
581
675
  export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
582
676
 
@@ -603,10 +697,12 @@ export declare const HTTP_ERROR_BRAND: unique symbol;
603
697
  * @remarks
604
698
  * Carries the HTTP `status` to send and an optional `context` record (the
605
699
  * offending field / value). The server's built-in error boundary catches it
606
- * and renders a response of `status` with the error's `message` as the body
607
- * — so an `HTTPError`'s message is always client-facing (it is the handler's
608
- * deliberate signal), unlike a generic throw whose message is hidden unless
609
- * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
700
+ * and renders a response of `status` with the error's `message` as the body,
701
+ * and no body for 204, 205, and 304 — so an `HTTPError`'s message is always
702
+ * client-facing (it is the handler's deliberate signal), unlike a generic
703
+ * throw whose message is hidden unless `expose` is set. A `status` the
704
+ * `Response` constructor refuses, an integer below 200 or above 599 or a
705
+ * status that is not an integer, renders `500` instead. Subclass it (as {@link ContentTooLargeError} does) for
610
706
  * specific statuses, or throw it directly. Narrow a caught value with
611
707
  * {@link isHTTPError}. The machine-readable discriminator is `status`; there is
612
708
  * no separate `code`.
@@ -878,7 +974,8 @@ export declare function matchesETag(header: string, etag: string): boolean;
878
974
  * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
879
975
  * (less specific) coverage, so a later more-specific match can still allow
880
976
  * it. Among multiple matching entries, the lowest `rank` wins, and among a
881
- * rank tie the highest `q` wins.
977
+ * rank tie the highest `q` wins. The candidate matches case-insensitively, as
978
+ * the entries do.
882
979
  *
883
980
  * @param entries - The parsed {@link AcceptEntry} list
884
981
  * @param candidate - The candidate media type to score (for example `'text/html'`)
@@ -946,16 +1043,24 @@ export declare function mergeVary(existing: string | undefined, value: string):
946
1043
  * - `state` — the shared bag threaded from the adapter's `state` factory,
947
1044
  * through every middleware, into `dispatcher.handle`'s `state` — the same
948
1045
  * object a route handler reads as `context.state`.
1046
+ * - `connection` — the {@link Connection} the server built for this request,
1047
+ * the same object the `state` factory received.
949
1048
  * - `body()` — lazily collect the request body (byte-limited, transparently
950
1049
  * decompressed, prototype-scrubbed for JSON), cached so repeated calls (a
951
1050
  * body-parsing middleware, then the handler) read the underlying stream
952
1051
  * exactly once.
1052
+ * - `abort(reason)` — abort this exchange: the request's own `signal` aborts
1053
+ * with `reason`. A second call changes nothing, and no other exchange is
1054
+ * aborted.
1055
+ *
1056
+ * One context describes the accepted exchange: `compose` hands every layer and
1057
+ * the terminal the same object, and nothing replaces it.
953
1058
  *
954
1059
  * @example
955
1060
  * ```ts
956
- * const middleware: MiddlewareHandler<{ readonly userId?: string }> = async (request, context, next) => {
1061
+ * const middleware: MiddlewareHandler<{ readonly userId?: string }> = async (_request, context, next) => {
957
1062
  * const body = await context.body()
958
- * return next(request)
1063
+ * return next()
959
1064
  * }
960
1065
  * ```
961
1066
  */
@@ -963,7 +1068,9 @@ export declare interface MiddlewareContext<TState> {
963
1068
  readonly url: URL;
964
1069
  readonly method: string;
965
1070
  readonly state: TState;
1071
+ readonly connection: Connection;
966
1072
  body(): Promise<unknown>;
1073
+ abort(reason?: unknown): void;
967
1074
  }
968
1075
 
969
1076
  /**
@@ -972,10 +1079,11 @@ export declare interface MiddlewareContext<TState> {
972
1079
  * @typeParam TState - The consumer's opaque per-request state type
973
1080
  *
974
1081
  * @remarks
975
- * Transform the request (call `next(newRequest)`), transform the response
976
- * (`await next()` then modify the result), short-circuit (return a `Response`
977
- * without calling `next`), or thread data through `context.state` — no mutable
978
- * framework object anywhere, only fetch-standard `Request`/`Response`.
1082
+ * Transform the response (`await next()` then modify the result),
1083
+ * short-circuit (return a `Response` without calling `next`), abort the
1084
+ * exchange (`context.abort(reason)`), or thread data through `context.state`
1085
+ * — only fetch-standard `Request`/`Response`, and the request every layer
1086
+ * receives is the one the server built.
979
1087
  *
980
1088
  * @example
981
1089
  * ```ts
@@ -997,7 +1105,7 @@ export declare type MiddlewareHandler<TState> = (request: Request, context: Midd
997
1105
  * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
998
1106
  * the two doors onto this axis cannot drift. Returns `undefined` when the
999
1107
  * client accepts none of `available` (identity — no compression). Total on
1000
- * hostile input.
1108
+ * malformed input.
1001
1109
  *
1002
1110
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
1003
1111
  * @param header - The raw `Accept-Encoding` header value
@@ -1020,9 +1128,10 @@ export declare function negotiateEncoding<T extends string>(header: string, avai
1020
1128
  * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1021
1129
  * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1022
1130
  * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
1023
- * rest of the substrate uses — one parser, never two. `format` reads the
1024
- * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1025
- * the winner — or answers `406 Not Acceptable`.
1131
+ * rest of the substrate uses — one parser, never two. A media type matches
1132
+ * case-insensitively. `format` reads the request `Accept`, negotiates a
1133
+ * {@link FormatHandlerMap}'s keys, and invokes the winner — or answers
1134
+ * `406 Not Acceptable` — and sets `Vary: Accept` on either answer.
1026
1135
  *
1027
1136
  * @example
1028
1137
  * ```ts
@@ -1041,7 +1150,8 @@ export declare class Negotiator implements NegotiatorInterface {
1041
1150
  *
1042
1151
  * @remarks
1043
1152
  * Errors thrown by the negotiated handler propagate unmodified — the
1044
- * server boundary classifies them, never this negotiator.
1153
+ * server boundary classifies them, never this negotiator. The answer is a
1154
+ * copy of the handler's response carrying `Vary: Accept`.
1045
1155
  */
1046
1156
  format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
1047
1157
  }
@@ -1110,6 +1220,13 @@ export declare interface NegotiatorInterface {
1110
1220
  * reads the request `Accept`, negotiates against `handlers`' keys, and
1111
1221
  * invokes the winner; `406` when none is acceptable.
1112
1222
  *
1223
+ * @remarks
1224
+ * Every response it returns, the `406` included, carries `Vary: Accept`
1225
+ * merged into any `Vary` the handler set, because `Accept` selected it. The
1226
+ * handler's response is returned as a copy with those headers, so a
1227
+ * response whose headers are immutable, such as `Response.redirect`, also
1228
+ * carries the field.
1229
+ *
1113
1230
  * @typeParam TState - The consumer's opaque per-request state type
1114
1231
  * @param request - The in-flight `Request`
1115
1232
  * @param context - The request's {@link MiddlewareContext}
@@ -1124,36 +1241,67 @@ export declare interface NegotiatorInterface {
1124
1241
  * rest of the onion — guarded so a second call within one invocation rejects.
1125
1242
  *
1126
1243
  * @remarks
1127
- * Call it (optionally with a substituted `Request`) to run the downstream
1128
- * chain and receive its `Response`; omit the call entirely to short-circuit
1129
- * with a `Response` built by this middleware instead. A second call rejects
1130
- * (the double-`next` guard) — each middleware runs the chain at most once.
1244
+ * Call it with no argument to run the downstream chain on the same `Request`
1245
+ * and context and receive its `Response`; omit the call entirely to
1246
+ * short-circuit with a `Response` built by this middleware instead. A second
1247
+ * call, or a call that passes an argument, rejects with a `ServerError` of
1248
+ * code `'NEXT'`, and a refused call still spends the one call: each middleware
1249
+ * runs the chain at most once, and every layer sees the one `Request` the server
1250
+ * built. A response whose headers are
1251
+ * immutable, such as a `Response.redirect` result, resolves as a copy whose
1252
+ * headers the layer can set.
1131
1253
  *
1132
- * @param request - An optional replacement `Request` to hand downstream
1133
- * (omitted ⇒ the original request continues)
1134
1254
  * @returns The downstream chain's resolved `Response`
1135
1255
  */
1136
- export declare type NextFunction = (request?: Request) => Promise<Response>;
1256
+ export declare type NextFunction = () => Promise<Response>;
1137
1257
 
1138
1258
  /**
1139
- * Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
1140
- * behind both {@link signToken} and {@link verifyToken}.
1259
+ * Returns a response whose headers a middleware can set: a copy of `response` when its headers are
1260
+ * immutable and its status lies from 200 through 599, and `response` itself otherwise.
1141
1261
  *
1142
1262
  * @remarks
1143
- * A single string becomes a one-element list; a rotation list is copied. Any
1144
- * blank/whitespace-only entry is dropped (`.trim()` is used only for that
1145
- * emptiness test; each kept secret is stored verbatim). The first kept
1146
- * element is the signing secret; all kept are accepted on verify.
1263
+ * A `Response.redirect` result and a `fetch` result carry immutable headers, so `headers.set`
1264
+ * throws on them. The copy keeps the body, the status, the status text, and every header; it
1265
+ * drops the fields a constructed `Response` cannot carry, such as `url` and `redirected`. A
1266
+ * response whose status lies outside 200 through 599, such as `Response.error()`, passes through
1267
+ * unchanged. `known` maps each response already checked to its answer, and the copy to itself, so
1268
+ * a response that crosses several layers of one composed run is checked once.
1269
+ *
1270
+ * @param response - The response a downstream handler resolved
1271
+ * @param known - The memo of one composed run; Default: a fresh `Map`
1272
+ * @returns `response` itself, or its mutable copy
1273
+ *
1274
+ * @example
1275
+ * ```ts
1276
+ * const response = normalizeResponse(Response.redirect('http://localhost/next', 302))
1277
+ * response.headers.set('X-Request-ID', 'abc') // no throw
1278
+ * ```
1279
+ */
1280
+ export declare function normalizeResponse(response: Response, known?: Map<Response, Response>): Response;
1281
+
1282
+ /**
1283
+ * Normalizes a {@link TokenSecret} to its `[current, ...older]` list — the list a
1284
+ * signer creates its keys from — refusing a malformed secret.
1285
+ *
1286
+ * @remarks
1287
+ * A single string becomes a one-element list; a rotation list is copied once
1288
+ * and its copy validated, each secret kept verbatim. A blank entry is refused,
1289
+ * never dropped, because dropping a blank current secret would make an older
1290
+ * key sign. The refusal names the blank or non-string positions in `context`
1291
+ * and carries no secret text.
1147
1292
  *
1148
1293
  * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
1149
- * @returns The kept (non-blank) secrets, in order — empty when none is usable
1294
+ * @returns The secrets, current first
1295
+ * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of
1296
+ * strings, when the list is empty, or when any entry is blank
1150
1297
  *
1151
1298
  * @example
1152
1299
  * ```ts
1153
- * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
1300
+ * normalizeSecret(['new', 'old']) // ['new', 'old']
1301
+ * normalizeSecret(['new', ' ']) // throws ServerError 'SECRET', context { entries: [1], count: 2 }
1154
1302
  * ```
1155
1303
  */
1156
- export declare function normalizeSecret(secret: TokenSecret): readonly string[];
1304
+ export declare function normalizeSecret(secret: TokenSecret): readonly [string, ...string[]];
1157
1305
 
1158
1306
  /**
1159
1307
  * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
@@ -1193,8 +1341,12 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
1193
1341
  * name, is skipped; a later duplicate name wins. Total — an absent/empty/
1194
1342
  * malformed header yields an empty record, never throws.
1195
1343
  *
1344
+ * The record has a null prototype, so a name that `Object.prototype` carries
1345
+ * (`constructor`, `toString`, `__proto__`) reads as an ordinary cookie when
1346
+ * present and as `undefined` when absent.
1347
+ *
1196
1348
  * @param header - The raw `Cookie` header value (possibly `undefined`)
1197
- * @returns A record of every parsed cookie, `name → decoded value`
1349
+ * @returns A null-prototype record of every parsed cookie, `name → decoded value`
1198
1350
  *
1199
1351
  * @example
1200
1352
  * ```ts
@@ -1231,15 +1383,28 @@ export declare function parseEncoding(header: string | null): Exclude<Encoding,
1231
1383
  * total, returning a {@link RangeSpec} or `undefined`.
1232
1384
  *
1233
1385
  * @remarks
1234
- * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1235
- * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1236
- * `[0, size - 1]` (the HTTP inclusive-end convention). Returns
1237
- * `{ satisfiable: true, start, end }` for an overlapping range,
1238
- * `{ satisfiable: false }` for a range wholly past the resource, and
1239
- * `undefined` for the "serve the whole resource" case: an absent header, a
1240
- * non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
1241
- * supported), or any malformed/non-finite bound. Never throws on a hostile
1242
- * header.
1386
+ * Reads the field value by RFC 9110 § 14.1:
1387
+ * `range-unit "=" OWS range-set`, where the unit matches `bytes`
1388
+ * case-insensitively and `range-set` is `1#range-spec` under the § 5.6.1 list
1389
+ * rule, so empty list elements are skipped. OWS is a space or a tab, and it
1390
+ * stands only around the field value, after `=`, and around a `,`; a range
1391
+ * holds none. A range is an `int-range` (`first-pos "-" [ last-pos ]`) or a
1392
+ * `suffix-range` (`"-" suffix-length`), each bound `1*DIGIT` ({@link
1393
+ * import('./constants.js').RANGE_BOUND_PATTERN}). A bound of any length is
1394
+ * compared with {@link compareDigits}, so none is misread through `Number`.
1395
+ * OWS is stripped with {@link stripOWS}, so the read is linear in the header's
1396
+ * length.
1397
+ *
1398
+ * Returns `{ satisfiable: true, start, end }` with the window clamped to
1399
+ * `[0, size - 1]` (the HTTP inclusive-end convention), and
1400
+ * `{ satisfiable: false }` when the range does not overlap the resource: a
1401
+ * `first-pos` at or past `size`, or a zero `suffix-length`.
1402
+ * Returns `undefined`, the § 14.2 "ignore the field and serve the whole
1403
+ * resource" answer, for an absent header, another unit, text outside the
1404
+ * grammar, a `last-pos` below its `first-pos`, more than one range (not
1405
+ * supported), a non-zero `suffix-length` on an empty resource (satisfiable by
1406
+ * § 14.1.2, but it selects no window to serve), and a `size` that is not a
1407
+ * non-negative safe integer. Never throws on a malformed header.
1243
1408
  *
1244
1409
  * @param header - The raw `Range` header value
1245
1410
  * @param size - The resource's total byte length
@@ -1248,7 +1413,10 @@ export declare function parseEncoding(header: string | null): Exclude<Encoding,
1248
1413
  * @example
1249
1414
  * ```ts
1250
1415
  * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1416
+ * parseRange('Bytes=-100,', 1000) // { satisfiable: true, start: 900, end: 999 }
1251
1417
  * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
1418
+ * parseRange('bytes=0x10-', 1000) // undefined — not a decimal bound
1419
+ * parseRange('bytes=5 - 9', 1000) // undefined — no OWS inside a range
1252
1420
  * ```
1253
1421
  */
1254
1422
  export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
@@ -1273,6 +1441,17 @@ export declare function parseRange(header: string | undefined, size: number): Ra
1273
1441
  */
1274
1442
  export declare function probePort(port: number): Promise<number>;
1275
1443
 
1444
+ /**
1445
+ * Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`.
1446
+ *
1447
+ * @remarks
1448
+ * Mirrors the `first-pos`, `last-pos`, and `suffix-length` rules of RFC 9110
1449
+ * § 14.1.1. A numeral `Number` reads but the grammar refuses — a hexadecimal,
1450
+ * octal, or binary prefix, an exponent, a sign, or a decimal point — fails the
1451
+ * match, as does a digit outside ASCII, which `Number` reads as `NaN`.
1452
+ */
1453
+ export declare const RANGE_BOUND_PATTERN: Readonly<RegExp>;
1454
+
1276
1455
  /**
1277
1456
  * Represents the parsed outcome of an HTTP `Range` request header.
1278
1457
  *
@@ -1313,8 +1492,11 @@ export declare type RangeSpec = {
1313
1492
  * `options.decompression`, default {@link
1314
1493
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1315
1494
  * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1316
- * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1317
- * scrubPrototype}); any other type decodes as UTF-8 text.
1495
+ * `parseJSON`, `application/x-www-form-urlencoded` is read through
1496
+ * `URLSearchParams` into a record whose repeated field keeps its last value,
1497
+ * and both are scrubbed of prototype-pollution keys ({@link scrubPrototype});
1498
+ * any other type decodes as UTF-8 text. The media type matches
1499
+ * case-insensitively and ignores its parameters.
1318
1500
  *
1319
1501
  * A malformed JSON body is total: it decodes rather than throwing, so a handler
1320
1502
  * that must reject one checks for `undefined` itself, and nothing in the returned
@@ -1322,8 +1504,9 @@ export declare type RangeSpec = {
1322
1504
  *
1323
1505
  * @param request - The `Request` to read the body from
1324
1506
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1325
- * @returns The parsed JSON value, the raw text, or `undefined` — for an empty
1326
- * body, and for an `application/json` body whose text is not valid JSON
1507
+ * @returns The parsed JSON value, the decoded form record, the raw text, or
1508
+ * `undefined` — for an empty body, and for an `application/json` body whose
1509
+ * text is not valid JSON
1327
1510
  * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1328
1511
  * @throws {HTTPError} When the compressed body is corrupt (400)
1329
1512
  *
@@ -1335,33 +1518,35 @@ export declare type RangeSpec = {
1335
1518
  export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
1336
1519
 
1337
1520
  /**
1338
- * Reads and verifies a signed cookie off a request — total, returning the
1339
- * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
1521
+ * Reads and verifies a signed cookie off a request, returning the embedded value
1522
+ * or `undefined` (the inverse of {@link writeSignedCookie}).
1340
1523
  *
1341
1524
  * @remarks
1342
1525
  * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
1343
- * and verifies it with {@link verifyToken} against `secret` (a rotation list
1344
- * accepts a cookie signed by any of its secrets). Any failure — an absent
1345
- * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
1526
+ * and verifies it with {@link verifyToken} against `signer` (a signer over a
1527
+ * rotation list accepts a cookie signed by any of its keys). An absent cookie,
1528
+ * a tampered value, and a wrong key each yield `undefined`, a name such as
1529
+ * `constructor` included. It rejects only when `signer.verify` rejects, which
1530
+ * the signer `createSigner` returns never does.
1346
1531
  *
1347
1532
  * @param request - The `Request` to read the `Cookie` header from
1348
1533
  * @param name - The cookie name to read
1349
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
1534
+ * @param signer - The {@link SignerInterface} to verify against
1350
1535
  * @returns The embedded value when the cookie is present + valid, else `undefined`
1351
1536
  *
1352
1537
  * @example
1353
1538
  * ```ts
1354
- * const value = await readSignedCookie(request, 'session', 'secret')
1539
+ * const value = await readSignedCookie(request, 'session', createSigner('secret'))
1355
1540
  * ```
1356
1541
  */
1357
- export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
1542
+ export declare function readSignedCookie(request: Request, name: string, signer: SignerInterface): Promise<string | undefined>;
1358
1543
 
1359
1544
  /**
1360
1545
  * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
1361
1546
  * to match, `^[A-Za-z0-9_-]{1,200}$`.
1362
1547
  *
1363
1548
  * @remarks
1364
- * An incoming id carrying CRLF, a log-injection payload, a control character,
1549
+ * An incoming id carrying CRLF, log-injection input, a control character,
1365
1550
  * or more characters than the pattern admits fails the match and is rejected —
1366
1551
  * a fresh id is minted instead — so it never rides into a response header or
1367
1552
  * `context.state`. Frozen so a consumer can read but never mutate the shared
@@ -1397,7 +1582,7 @@ export declare interface RequestLine {
1397
1582
  * keeps the earlier-offered coding on a client-side tie, which is what makes
1398
1583
  * `available` the server's preference order. An empty `available` list, and a
1399
1584
  * list the client rejects outright, both yield `undefined` (identity — no
1400
- * compression). Total on hostile input.
1585
+ * compression). Total on malformed input.
1401
1586
  *
1402
1587
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
1403
1588
  * @param entries - The parsed {@link AcceptEntry} list
@@ -1420,7 +1605,7 @@ export declare function resolveCoding<T extends string>(entries: readonly Accept
1420
1605
  * echoes the request's `Origin` only when it is present in the list, else
1421
1606
  * `undefined` (no header set). Security: the literal `'null'` origin — sent
1422
1607
  * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1423
- * never reflected even if `'null'` were listed, closing the hostile-context
1608
+ * never reflected even if `'null'` were listed, closing the opaque-origin
1424
1609
  * cross-origin-access hole.
1425
1610
  *
1426
1611
  * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
@@ -1500,17 +1685,21 @@ export declare interface ResponseRecord {
1500
1685
  }
1501
1686
 
1502
1687
  /**
1503
- * Strips the prototype-pollution keys from a parsed value in place, recursively.
1688
+ * Strips the prototype-pollution keys from a parsed value in place, at every depth.
1504
1689
  *
1505
1690
  * @remarks
1506
1691
  * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
1507
1692
  * enumerable `__proto__` data property — but that own key becomes a
1508
1693
  * pollution gadget the moment a downstream deep-merge copies it onto a live
1509
1694
  * object. This walks the value and `delete`s any own {@link isDangerousKey}
1510
- * key at every depth, recursing into nested objects + array elements.
1695
+ * key at every depth, into nested records and array elements.
1511
1696
  * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1512
1697
  * freshly-parsed value (which nothing else holds yet).
1513
1698
  *
1699
+ * The walk keeps a worklist rather than the call stack, so a value nested as
1700
+ * deep as the body limit admits costs no stack depth, and it reads a node
1701
+ * reached twice once, so a self-referencing value terminates.
1702
+ *
1514
1703
  * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1515
1704
  * @returns The same `value`, with every dangerous key removed at every depth
1516
1705
  *
@@ -1522,6 +1711,21 @@ export declare interface ResponseRecord {
1522
1711
  */
1523
1712
  export declare function scrubPrototype(value: unknown): unknown;
1524
1713
 
1714
+ /**
1715
+ * Serializes a comment to the SSE wire, one `: ` line per line of `text`.
1716
+ *
1717
+ * @remarks
1718
+ * Splits `text` on `\r\n`, `\r`, and `\n`, so no line of the comment can
1719
+ * reach a parser as a field and no comment can dispatch an event.
1720
+ *
1721
+ * @example
1722
+ * ```ts
1723
+ * serializeComment('keep-alive') // ': keep-alive\n\n'
1724
+ * serializeComment('a\nb') // ': a\n: b\n\n'
1725
+ * ```
1726
+ */
1727
+ export declare function serializeComment(text: string): string;
1728
+
1525
1729
  /**
1526
1730
  * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
1527
1731
  *
@@ -1555,12 +1759,19 @@ export declare function serializeCookie(name: string, value: string, options?: C
1555
1759
  * @remarks
1556
1760
  * Emits an `event:`/`id:`/`retry:` line for each present field, then one
1557
1761
  * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1558
- * (so a consuming parser's multi-`data` concat reproduces the original
1559
- * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1560
- * a `data:` line), then the terminating blank line.
1762
+ * (so a consuming parser's multi-`data` concat reproduces `data` with each
1763
+ * line break read as `\n`, and no raw `\r` or `\n` can ever ride onto the wire
1764
+ * inside a `data:` line), then the terminating blank line.
1765
+ *
1766
+ * It refuses a field the wire cannot carry rather than emit a second field or
1767
+ * a second event: an `event` with a line break, an `id` with a line break or
1768
+ * a NUL (which a conforming parser drops), and a `retry` that is not a
1769
+ * non-negative safe integer.
1561
1770
  *
1562
1771
  * @param message - The event to serialize
1563
1772
  * @returns The SSE wire text for the event (terminated by a blank line)
1773
+ * @throws {ServerError} Thrown when a field is refused, with code `'EVENT'`
1774
+ * and `context.field` naming the field
1564
1775
  *
1565
1776
  * @example
1566
1777
  * ```ts
@@ -1586,9 +1797,9 @@ export declare function serializeEvent(message: SSEMessage): string;
1586
1797
  * bind is pending, and transitions `idle → starting → listening`. A
1587
1798
  * cancelled or expired bind closes its partial server and resets to `idle` for
1588
1799
  * another start. `stop()` transitions
1589
- * to `stopping`: fires a fresh-per-run stop signal so in-flight handlers
1800
+ * to `stopping`: aborts the signal of every in-flight request so handlers
1590
1801
  * observe cancellation (a request that arrives during the drain is served
1591
- * with that signal already aborted), drains in-flight requests and
1802
+ * with its signal already aborted), drains in-flight requests and
1592
1803
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1593
1804
  * busy-loop), then closes → `stopped`. After a clean drain the close
1594
1805
  * destroys every connection that carries no open request exchange, and a
@@ -1600,27 +1811,35 @@ export declare function serializeEvent(message: SSEMessage): string;
1600
1811
  * counted before the close. After an expired drain the close destroys every
1601
1812
  * socket. A `stop()` call made while a stop runs returns that stop's
1602
1813
  * promise. `destroy()` is the idempotent final teardown.
1603
- * - **Per request.** In-flight is tracked (finished on response `finish` or
1604
- * `close`); a `Request` is built through the router's `buildRequest`, its
1605
- * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
1606
- * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1607
- * `buildRequest`'s own abort, armed by request-side and response-side
1608
- * teardown, composes with the server's stop signal through `AbortSignal.any`,
1609
- * so a handler awaiting `request.signal` observes either); `context.state` is built through
1610
- * {@link ServerOptions.state} from the connection facts; the composed
1611
- * middleware onion runs, terminating in `dispatcher.handle`; the result is
1612
- * written back through `sendResponse`.
1814
+ * - **Per request.** The exchange's own `AbortController` joins the
1815
+ * in-flight registry until the response's `close`; the one
1816
+ * `Request` of the exchange is built through the router's `buildRequest`
1817
+ * with that controller's signal, so `request.signal` aborts on a peer
1818
+ * disconnect, on `context.abort(reason)`, or on `stop()`, and no request
1819
+ * signal links to a signal that outlives the exchange; `context.state` is
1820
+ * built through {@link ServerOptions.state} from the connection facts, which
1821
+ * `context.connection` carries as the same object; the composed middleware
1822
+ * onion runs, terminating in `dispatcher.handle`; the result is written
1823
+ * back through `sendResponse`.
1613
1824
  * - **The built-in boundary** wraps the whole per-request chain, including
1614
1825
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1615
1826
  * throw (for example, a malformed `Host` header) to a silent `400` with no
1616
- * `error` emit; everything after (`Request` reconstruction, connection
1827
+ * `error` emit; everything after (connection
1617
1828
  * facts, `state`, the composed onion, and `dispatcher.handle`) runs
1618
- * behind the outer boundary — a thrown `HTTPError` renders as its status +
1619
- * message; any other throw renders `500` (message hidden unless
1620
- * `expose`), `report` is invoked (its own throw swallowed), and `error` is
1621
- * emitted. A server-owned last resort wraps the final `sendResponse`
1622
- * write itself: if even that fails, the connection is destroyed rather
1623
- * than left to escape as an unhandled error.
1829
+ * behind the outer boundary, which renders a throw through
1830
+ * `buildErrorResponse`: an `HTTPError` whose status `Response` admits
1831
+ * keeps that status, with no body for 204, 205, and 304, and every other
1832
+ * throw renders `500` (message hidden unless `expose`). Each fault, every
1833
+ * throw except an `HTTPError` whose status the response carries and a
1834
+ * throw after a peer disconnect the server read first (the peer's FIN or a
1835
+ * reset), reaches `error` and `report` with its
1836
+ * `RequestLine`; a fault on the inner phase's `400` path carries none,
1837
+ * because no `Request` exists there. A `report` that throws or rejects is
1838
+ * contained, except a rejected native promise whose species constructor
1839
+ * cannot build a promise, which reaches `unhandledRejection` (see
1840
+ * `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,
1841
+ * and a terminal catch over the whole exchange, the `400` path included,
1842
+ * holds a throw from any step.
1624
1843
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1625
1844
  * throwing handler is treated as declined and surfaced on `error`, an
1626
1845
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
@@ -1669,15 +1888,21 @@ export declare class ServerBinding {
1669
1888
 
1670
1889
  /**
1671
1890
  * Represents the error this package raises when a caller programmed a call the
1672
- * entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
1891
+ * entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code.
1673
1892
  *
1674
1893
  * @remarks
1675
1894
  * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
1676
1895
  * record naming the offending facts. This is a programmer error, so it carries
1677
1896
  * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
1678
- * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
1897
+ * invoked the lifecycle method, a `'NEXT'` refusal of a second `next` call or
1898
+ * of a `next` call with an argument escapes its
1679
1899
  * middleware into the request boundary, which reaches it as a generic 500 with
1680
- * the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
1900
+ * the message hidden unless `expose` is set, and an `'EVENT'` refusal is raised
1901
+ * to the caller that serialized an SSE message, its `context.field` naming the
1902
+ * refused field, and a `'SECRET'` refusal is raised to the caller that built a
1903
+ * signer from a malformed secret, its `context` naming the refused positions,
1904
+ * or the received type for a value that is not a string or a readable list, and holding
1905
+ * no secret text. Throw an {@link HTTPError} for a
1681
1906
  * client-facing fault instead. Narrow a caught value with
1682
1907
  * {@link isServerError}.
1683
1908
  *
@@ -1699,9 +1924,9 @@ export declare class ServerError extends Error {
1699
1924
 
1700
1925
  /**
1701
1926
  * Represents the machine-readable category a
1702
- * {@link import('./errors.js').ServerError} carries — `'STATUS'` for a lifecycle
1703
- * call the current status forbids, `'NEXT'` for a middleware that called its `next`
1704
- * a second time.
1927
+ * {@link import('./errors.js').ServerError} carries — `'STATUS'` for a forbidden
1928
+ * lifecycle call, `'NEXT'` for a second `next` call or one with an argument, `'EVENT'` for an SSE field
1929
+ * the wire cannot carry, `'SECRET'` for a malformed signer secret.
1705
1930
  *
1706
1931
  * @remarks
1707
1932
  * A `ServerError` reports a call the caller programmed and the substrate
@@ -1713,8 +1938,12 @@ export declare class ServerError extends Error {
1713
1938
  export declare type ServerErrorCode =
1714
1939
  /** Identifies a lifecycle call the current {@link ServerStatus} forbids. */
1715
1940
  'STATUS'
1716
- /** Identifies a middleware that called its `next` a second time within one invocation. */
1717
- | 'NEXT';
1941
+ /** Identifies a middleware that called its `next` a second time, or with an argument. */
1942
+ | 'NEXT'
1943
+ /** Identifies an SSE message field the event-stream wire cannot carry. */
1944
+ | 'EVENT'
1945
+ /** Identifies a signer secret that is not a string or a list of strings, is empty, or holds a blank entry. */
1946
+ | 'SECRET';
1718
1947
 
1719
1948
  /**
1720
1949
  * Represents the `Server`'s observable lifecycle events.
@@ -1726,12 +1955,18 @@ export declare type ServerErrorCode =
1726
1955
  * runs, carrying the raw method + the parsed pathname.
1727
1956
  * - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
1728
1957
  * `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
1729
- * - `error` — a server-level fault: an escaping throw past the built-in
1730
- * boundary, an upgrade handler's throw, or a listen failure. Carries the
1731
- * originating request's method + parsed `url` when the fault happened on
1732
- * the per-request path; `undefined` for an upgrade-handler throw (no fetch
1733
- * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
1734
- * failure.
1958
+ * - `error` — a fault, fired once per fault. On the per-request path that is
1959
+ * a throw the built-in boundary reports (every throw except an `HTTPError`
1960
+ * whose status the response carries, a returned status no `Response`
1961
+ * carries included), a response write that fails unless the peer
1962
+ * disconnected first, or a throw the terminal
1963
+ * catch holds; each carries the request's {@link RequestLine}, the same
1964
+ * pair `report` receives. A throw after a peer disconnect the server read
1965
+ * before the throw, the peer's FIN or a reset, is no fault and fires nothing;
1966
+ * a `stop()` cut, `destroy()`, and Node's 408 close are no peer disconnect. The request is `undefined` for an upgrade-handler throw
1967
+ * (no fetch `Request` exists on that path — only a raw `IncomingMessage`),
1968
+ * a listen failure, and a fault on the `400` path of a request no
1969
+ * `Request` could be built for, a failed write of that `400` included.
1735
1970
  * - `stop` — `stop()` began (status moved to `'stopping'`). An upgrade
1736
1971
  * handler that owns a long-lived socket closes it from here, so the drain
1737
1972
  * settles instead of running out the deadline.
@@ -1739,13 +1974,19 @@ export declare type ServerErrorCode =
1739
1974
  * carries the still-pending request count and the still-attached upgraded
1740
1975
  * socket count. Both `0` is a clean drain; either non-zero means the close
1741
1976
  * that follows was forced and cut that work.
1742
- * - `response` — fired after the response has been sent, for every request
1743
- * that reaches the middleware pipeline (the success path and the
1744
- * outer-boundary error path); carries the method, parsed pathname, final
1745
- * status, and elapsed time in milliseconds. A request rejected at the
1746
- * `buildRequest` inner boundary (a plain `400`, for example a malformed
1747
- * `Host` header) emits no `response` — no parsed `Request` exists yet to derive
1748
- * its facts from.
1977
+ * - `response` — fired once for each response that finished, after the
1978
+ * server wrote its last byte, on the success path and the outer-boundary
1979
+ * error path alike. It carries the method, the parsed pathname, `status`,
1980
+ * the status the server wrote (the handler's, or the rendered status of a
1981
+ * throw), and `ms`, the time from the exchange's acceptance, before
1982
+ * `request` fires, to that last byte, in whole milliseconds. A response
1983
+ * whose peer disconnected first, a body-less answer included, and a write
1984
+ * that failed fire no `response`; `response` fires after Node hands the
1985
+ * last byte to the operating system, so a peer that resets before it reads
1986
+ * the answer leaves the record,
1987
+ * and neither does a request rejected at the `buildRequest` inner boundary
1988
+ * (a plain `400`, for example a malformed `Host` header), because no parsed
1989
+ * `Request` exists yet to derive its facts from.
1749
1990
  */
1750
1991
  export declare type ServerEventMap = {
1751
1992
  readonly start: readonly [port: number];
@@ -1771,17 +2012,18 @@ export declare type ServerEventMap = {
1771
2012
  * from the bound address), exposes that {@link AddressInfo} through `address`,
1772
2013
  * observes caller cancellation plus `timeouts.start` while binding, and resolves
1773
2014
  * the actually-bound port. A cancelled or expired bind closes its partial server
1774
- * and resets to `idle`. `stop()` fires the stop signal so in-flight handlers
1775
- * can observe it, drains in-flight requests and claimed upgraded sockets up to
2015
+ * and resets to `idle`. `stop()` aborts the signal of every in-flight request so
2016
+ * handlers can observe it, drains in-flight requests and claimed upgraded sockets up to
1776
2017
  * the configured deadline, then closes the listener and ends each connection
1777
2018
  * when no request exchange is open on it; when that same deadline expires it
1778
- * destroys every socket still open. `destroy()` is the final idempotent teardown. Per request: a `Request` is
1779
- * built through the router's `buildRequest` (its signal linked to the server's
1780
- * stop signal), the composed middleware onion runs terminating in
2019
+ * destroys every socket still open. `destroy()` is the final idempotent teardown. Per request: one `Request` is
2020
+ * built through the router's `buildRequest` with the exchange's own abort signal,
2021
+ * the composed middleware onion runs terminating in
1781
2022
  * `dispatcher.handle`, and the result is written back through
1782
2023
  * `sendResponse` — every escaping throw is caught by the
1783
- * built-in boundary (`HTTPError` → its status; anything else → a
1784
- * hidden-unless-`expose` `500`) so a handler error can never crash the process.
2024
+ * built-in boundary (an `HTTPError` whose status `Response` admits → its
2025
+ * status; anything else → a hidden-unless-`expose` `500`) so a handler error
2026
+ * can never crash the process.
1785
2027
  */
1786
2028
  export declare interface ServerInterface<TState> {
1787
2029
  /** Holds the instance's correlation id, minted once per `Server` and stable for its lifetime. */
@@ -1837,7 +2079,7 @@ export declare interface ServerInterface<TState> {
1837
2079
  */
1838
2080
  start(signal?: AbortSignal): Promise<number>;
1839
2081
  /**
1840
- * Stops gracefully within the `drain` deadline: fires the stop signal, drains in-flight
2082
+ * Stops gracefully within the `drain` deadline: aborts every in-flight request's signal, drains in-flight
1841
2083
  * requests and claimed upgraded sockets, then closes the listener; after a clean drain it
1842
2084
  * ends each connection when no request exchange is open on it, and when the deadline
1843
2085
  * expires it destroys every socket still open.
@@ -1851,19 +2093,19 @@ export declare interface ServerInterface<TState> {
1851
2093
  * request or an upgrade that a connection sends after the listener closes
1852
2094
  * is refused: the server destroys that connection before the request is
1853
2095
  * counted or a handler sees it. An exchange opens when a request reaches
1854
- * the handler and stays open until its request message has ended or closed
1855
- * and its response has finished or closed. The `error` listeners that this
1856
- * tracking attaches to the message and the response stay attached, so a
1857
- * later error on either raises no uncaught exception. After a clean drain
2096
+ * the handler and stays open until its request message and its response
2097
+ * have closed. The `close` listeners that this tracking attaches leave when
2098
+ * they fire, so none outlives the exchange. After a clean drain
1858
2099
  * the close destroys every connection with no open exchange: an idle
1859
2100
  * keep-alive one, one that never sent a request, and one partway through
1860
2101
  * any header block, because a request whose headers never completed is not
1861
2102
  * counted work. A connection that still carries an open exchange, including
1862
2103
  * one whose handler answered while its body still uploads, ends when its
1863
2104
  * last exchange completes, and the `stop()` call resolves after that
1864
- * connection closes. Each body byte restarts Node's keep-alive socket
1865
- * timer, so no Node timeout bounds an upload that keeps sending. The
1866
- * deadline that bounds the drain therefore stays armed through this wait:
2105
+ * connection closes. Node's `request` timeout bounds an upload that keeps
2106
+ * sending after its response, unless `timeouts.request` is `0`, when no
2107
+ * Node timeout bounds it. The deadline that bounds the drain therefore
2108
+ * stays armed through this wait:
1867
2109
  * when it expires before the server's `close` event, the server destroys
1868
2110
  * every socket still open, as an expired drain does, so no connection
1869
2111
  * holds the `stop()` call past the `drain` deadline. A request Node
@@ -1878,7 +2120,7 @@ export declare interface ServerInterface<TState> {
1878
2120
  * also reset the connection and lose the answered response the peer has
1879
2121
  * not yet read. No event reports that cut or that loss. A `stop()` call
1880
2122
  * made while a stop runs returns that stop's promise, including a call
1881
- * made from a `stop` event listener or from a listener on the stop signal.
2123
+ * made from a `stop` event listener or from a listener on an aborted request signal.
1882
2124
  *
1883
2125
  * @returns Resolves after the listener is closed and the status is
1884
2126
  * `'stopped'`; a call from `'idle'`, `'starting'`, or `'stopped'` while
@@ -1930,22 +2172,53 @@ export declare interface ServerInterface<TState> {
1930
2172
  * @param expose - Whether a non-`HTTPError` throw's message is sent in the
1931
2173
  * 500 response body (an `HTTPError`'s own message is always client-facing).
1932
2174
  * Defaults to `false`.
1933
- * @param report - A fire-and-forget sink the built-in boundary hands every
1934
- * caught error to (logging / metrics), along with the originating
1935
- * request's method + parsed `url` when one is available (absent on an
1936
- * upgrade-path fault); its own throw is swallowed so reporting can never
1937
- * crash the response.
1938
- * @param timeouts - Lifecycle and `node:http` tuning knobs: `start` (maximum
1939
- * time to bind the listener; `0` permits no startup window), `request` (max
1940
- * time to fully receive + respond, `requestTimeout`), `headers` (max time
1941
- * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1942
- * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1943
- * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1944
- * otherwise. A present `start` must be an integer from 0 through
1945
- * 2_147_483_647, and every other present value a non-negative finite
1946
- * number; construction throws a `TypeError` otherwise. A startup expiry
1947
- * rejects with a `DOMException` named `TimeoutError`; caller
1948
- * cancellation rejects with the caller signal's `reason`.
2175
+ * @param report - A fire-and-forget sink the built-in boundary hands each
2176
+ * fault to (logging / metrics), with the same `(error, RequestLine)` the
2177
+ * `error` event carries: every throw except an `HTTPError` whose status the
2178
+ * response carries, a returned status no `Response` carries, a response
2179
+ * write that fails unless the peer disconnected first, and a throw the terminal catch holds. A throw after a
2180
+ * peer disconnect the server read first is no fault. A sink that throws, or returns a promise
2181
+ * that rejects, is contained, so the response still goes out, except a
2182
+ * rejected native promise whose species constructor cannot build a promise:
2183
+ * its `constructor` lookup throws or yields a value that is neither
2184
+ * `undefined` nor an object, its `Symbol.species` lookup throws or yields a
2185
+ * value that is neither `undefined`, `null`, nor a constructor, or that
2186
+ * constructor throws or never passes its executor callable resolve and
2187
+ * reject functions. Such a promise refuses every reaction, so its rejection
2188
+ * reaches `unhandledRejection`, which ends the process under Node's default
2189
+ * unhandled-rejection mode; the response still goes out. The request is absent
2190
+ * only for a fault on the `400` path of a request no `Request` could be
2191
+ * built for, a failed write of that `400` included.
2192
+ * @param timeouts - Timeouts in milliseconds: `start` (the maximum time to
2193
+ * bind the listener; `0` permits no startup window), and three that
2194
+ * `start()` passes to `node:http`'s `createServer` as options: `headers`
2195
+ * (`headersTimeout`, the time to receive the request headers), `request`
2196
+ * (`requestTimeout`, the time to receive the whole request; no server
2197
+ * timeout bounds the response), and `keepalive` (`keepAliveTimeout`, the
2198
+ * idle time a kept-alive connection waits for its next request; Node adds
2199
+ * its `keepAliveTimeoutBuffer`, 1_000 ms by default, so a `keepalive` of
2200
+ * 400 closes an idle connection after about 1_400 ms). `0` disables each
2201
+ * of those three. An omitted one keeps Node's default: `request` is
2202
+ * `DEFAULT_REQUEST_TIMEOUT_MS`, `headers` the lesser of
2203
+ * `DEFAULT_HEADERS_TIMEOUT_MS` and `request`, and `keepalive` Node's
2204
+ * `keepAliveTimeout` default. When `headers` or `request` passes while a
2205
+ * response is being sent, Node closes the connection, which cuts that
2206
+ * response short; otherwise, including after a response has finished
2207
+ * while its upload continues, Node answers `408` and closes the
2208
+ * connection. The server sets Node's
2209
+ * `connectionsCheckingInterval` to `Math.ceil(m / 2)` milliseconds, where
2210
+ * `m` is the smaller positive of `headers` and `request` as Node applies
2211
+ * them, so each expires at most one such interval after it passes; with
2212
+ * neither positive, Node keeps its own interval. `start`, `headers`, and
2213
+ * `request` must be integers from 0 through 2_147_483_647, and
2214
+ * `keepalive` an integer from 0 through 2_147_482_647, so that Node's
2215
+ * timer of `keepalive` plus its buffer stays within that limit; `headers`
2216
+ * must not exceed `request` while `request` is positive, Node's own
2217
+ * relation. Construction throws a `TypeError` otherwise. A response deadline belongs to a middleware, such as
2218
+ * `@orkestrel/middleware`'s `createDeadline`, which aborts the exchange
2219
+ * through `context.abort`. A startup expiry rejects with a `DOMException`
2220
+ * named `TimeoutError`; caller cancellation rejects with the caller
2221
+ * signal's `reason`.
1949
2222
  * @param sockets - `node:http` socket caps: `connections` maps to
1950
2223
  * `maxConnections` (`0` rejects every incoming connection), `headers` maps
1951
2224
  * to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
@@ -1987,12 +2260,84 @@ export declare interface ServerOptions<TState> {
1987
2260
  * @remarks
1988
2261
  * `idle` (never started, or a fresh instance) → `starting` (binding the
1989
2262
  * listener) → `listening` (accepting requests) → `stopping` (draining
1990
- * in-flight requests) → `stopped` (closed; `start()` may run again, minting a
1991
- * fresh stop signal). `destroy()` is a terminal teardown reachable from any
2263
+ * in-flight requests) → `stopped` (closed; `start()` may run again).
2264
+ * `destroy()` is a terminal teardown reachable from any
1992
2265
  * state, idempotent once `stopped`.
1993
2266
  */
1994
2267
  export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
1995
2268
 
2269
+ /**
2270
+ * Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at
2271
+ * construction and reuses it on every call. Implements exactly {@link SignerInterface}.
2272
+ *
2273
+ * @remarks
2274
+ * The constructor normalizes the secret through {@link normalizeSecret}, so it
2275
+ * throws a {@link ServerError} of code `'SECRET'` for a secret that is not a
2276
+ * string or a list of strings, an empty list, or a list holding a blank entry.
2277
+ * `verify` compares signature bytes only through `timingSafeEqual`, after a
2278
+ * length check.
2279
+ *
2280
+ * @example
2281
+ * ```ts
2282
+ * import { Signer } from '@orkestrel/server'
2283
+ *
2284
+ * const signer = new Signer(['current-secret', 'previous-secret'])
2285
+ * await signer.verify('payload', await signer.sign('payload')) // true
2286
+ * ```
2287
+ */
2288
+ export declare class Signer implements SignerInterface {
2289
+ #private;
2290
+ constructor(secret: TokenSecret);
2291
+ sign(message: string): Promise<string>;
2292
+ verify(message: string, signature: string): Promise<boolean>;
2293
+ }
2294
+
2295
+ /**
2296
+ * Represents an HMAC-SHA256 signer over the keys of one {@link TokenSecret}, held in
2297
+ * `[current, ...older]` order.
2298
+ *
2299
+ * @remarks
2300
+ * A changed secret list is another signer: build another one and hand it to
2301
+ * every consumer, because no method rotates the keys in place.
2302
+ *
2303
+ * @example
2304
+ * ```ts
2305
+ * import { createSigner } from '@orkestrel/server'
2306
+ *
2307
+ * const signer = createSigner(['current-secret', 'previous-secret'])
2308
+ * const signature = await signer.sign('payload')
2309
+ * await signer.verify('payload', signature) // true
2310
+ * ```
2311
+ */
2312
+ export declare interface SignerInterface {
2313
+ /**
2314
+ * Signs `message` with the first (current) key — the base64url HMAC-SHA256 of
2315
+ * its UTF-8 bytes.
2316
+ *
2317
+ * @param message - The text to sign; a lone surrogate encodes as U+FFFD
2318
+ * @returns The canonical base64url signature
2319
+ */
2320
+ sign(message: string): Promise<string>;
2321
+ /**
2322
+ * Checks whether `signature` is the canonical base64url HMAC-SHA256 of
2323
+ * `message` under any held key, walking the keys in order and returning at
2324
+ * the first match.
2325
+ *
2326
+ * @param message - The signed text
2327
+ * @param signature - The candidate signature
2328
+ * @returns True if a held key signed `message` as `signature`; false otherwise
2329
+ *
2330
+ * @remarks
2331
+ * Answers `false` before reading a key when `signature` is not canonical
2332
+ * base64url or does not decode to the 32 bytes of an HMAC-SHA256. A valid
2333
+ * signature returns at its key's position, so its timing reveals that
2334
+ * position; an invalid one reads every key. The `Signer` class never rejects
2335
+ * for a pair of strings; a consumer implementation whose `verify` rejects
2336
+ * makes `verifyToken` and `readSignedCookie` reject with its error.
2337
+ */
2338
+ verify(message: string, signature: string): Promise<boolean>;
2339
+ }
2340
+
1996
2341
  /**
1997
2342
  * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
1998
2343
  *
@@ -2000,22 +2345,18 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
2000
2345
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
2001
2346
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
2002
2347
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
2003
- * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
2004
- * {@link TokenSecret} (the current secret, or the head of a rotation list).
2005
- * Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
2006
- * misconfigured secret with no usable entry throws an {@link HTTPError}
2007
- * (`500`) — fail-closed, a programmer error. Verify with
2008
- * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
2348
+ * the signature), signed by `options.signer`, whose first key signs. Verify
2349
+ * with {@link verifyToken}. Omitting `ttl` mints a token that never expires.
2009
2350
  *
2010
2351
  * @param value - The opaque value to embed (a session id, a deployment marker)
2011
- * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
2352
+ * @param options - The `signer` and optional `ttl` (ms); see {@link TokenOptions}
2012
2353
  * @returns The signed `<payload>.<signature>` token string
2013
- * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
2014
2354
  *
2015
2355
  * @example
2016
2356
  * ```ts
2017
- * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
2018
- * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
2357
+ * const signer = createSigner('shh')
2358
+ * const token = await signToken('client', { signer, ttl: 60_000 })
2359
+ * await verifyToken(token, signer) // 'client' (within 60s), else undefined
2019
2360
  * ```
2020
2361
  */
2021
2362
  export declare function signToken(value: string, options: TokenOptions): Promise<string>;
@@ -2034,13 +2375,20 @@ export declare function signToken(value: string, options: TokenOptions): Promise
2034
2375
  */
2035
2376
  export declare const SSE_HEADERS: Readonly<Record<string, string>>;
2036
2377
 
2378
+ /**
2379
+ * Defines the line terminators of the SSE wire, `\r\n`, `\r`, and `\n`, which
2380
+ * `serializeEvent` and `serializeComment` split text on.
2381
+ */
2382
+ export declare const SSE_LINE_PATTERN: Readonly<RegExp>;
2383
+
2037
2384
  /**
2038
2385
  * Represents one Server-Sent Event to serialize to the wire.
2039
2386
  *
2040
2387
  * @remarks
2041
2388
  * - `data` — the event payload (required). Serialized as one or more `data:`
2042
- * lines: the value is split on `\n` into a `data:` line per segment, so it
2043
- * round-trips through a consumer's multi-`data` concat.
2389
+ * lines: the value is split on `\r\n`, `\r`, and `\n` into a `data:` line
2390
+ * per segment, so it round-trips through a consumer's multi-`data` concat
2391
+ * with each line break read as `\n`.
2044
2392
  * - `event` — the optional event type, emitted as an `event:` line; omitted
2045
2393
  * ⇒ the consumer's default (`message`).
2046
2394
  * - `id` — the optional last-event-id, emitted as an `id:` line.
@@ -2049,10 +2397,11 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
2049
2397
  */
2050
2398
  export declare interface SSEMessage {
2051
2399
  readonly data: string;
2052
- /** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
2400
+ /** Requires one line; `serializeEvent` refuses a line break. */
2053
2401
  readonly event?: string;
2054
- /** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
2402
+ /** Requires one line with no NUL; `serializeEvent` refuses a line break or a NUL. */
2055
2403
  readonly id?: string;
2404
+ /** Requires a non-negative safe integer; `serializeEvent` refuses any other number. */
2056
2405
  readonly retry?: number;
2057
2406
  }
2058
2407
 
@@ -2069,9 +2418,11 @@ export declare interface SSEMessage {
2069
2418
  * message to the wire, enqueues it, and reports whether that process-local
2070
2419
  * queue still has capacity; a producer that receives `false` parks on
2071
2420
  * `drain()` before writing again. `comment` writes a `: text` keep-alive line
2072
- * (ignored by a conforming SSE parser — no spurious event); `end` closes the
2073
- * stream. Every method is a safe no-op once `closed` is `true`, so a late
2074
- * `write` never throws.
2421
+ * per line of its text (ignored by a conforming SSE parser — no spurious
2422
+ * event); `end` closes the stream. The stream opens with one comment line, so
2423
+ * the response pump has a first chunk and the headers leave before any event.
2424
+ * Every method is a safe no-op while `closed` is `true`, so a late `write`
2425
+ * never throws.
2075
2426
  *
2076
2427
  * The readiness signal is deliberately local: it reflects the
2077
2428
  * `ReadableStream` controller's queue, not proof that a remote peer consumed
@@ -2081,8 +2432,9 @@ export declare interface SSEMessage {
2081
2432
  * that ignores the boolean keeps the prior unconditional-enqueue behavior.
2082
2433
  * The stream's default strategy measures queued chunks, not their byte length,
2083
2434
  * so a producer seeking a byte bound must also bound each individual message.
2084
- * Return `response` before awaiting a `false` write: the consumer cannot pull
2085
- * until it receives the response.
2435
+ * Return `response` before awaiting a `false` write or `drain()`: the consumer
2436
+ * cannot pull until it receives the response, and the opening comment fills
2437
+ * the queue, so a `drain()` before any write also waits on that pull.
2086
2438
  */
2087
2439
  export declare interface SSEStreamInterface {
2088
2440
  /** Holds the streaming `Response` to return from the route handler. */
@@ -2091,21 +2443,23 @@ export declare interface SSEStreamInterface {
2091
2443
  readonly closed: boolean;
2092
2444
  /**
2093
2445
  * Serializes and enqueues one {@link SSEMessage} to the wire, reporting whether the
2094
- * process-local queue still has capacity afterward — `false` also once the stream
2095
- * is closed.
2446
+ * process-local queue still has capacity afterward — `false` also after the stream
2447
+ * closes.
2096
2448
  *
2097
2449
  * @param message - The event to send (its `data` split on `\n` into `data:` lines)
2098
2450
  * @returns True if the process-local stream queue has capacity after
2099
2451
  * accepting the event; false otherwise — the queue is full or the stream
2100
2452
  * is closed. A `false` event was still accepted unless `closed` was already
2101
2453
  * `true`; await {@link drain} before producing another event.
2454
+ * @throws {ServerError} Thrown when the stream is open and `serializeEvent`
2455
+ * refuses a field of `message`, with code `'EVENT'`; nothing is enqueued
2102
2456
  */
2103
2457
  write(message: SSEMessage): boolean;
2104
2458
  /**
2105
2459
  * Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores,
2106
- * and a no-op once the stream is closed.
2460
+ * and a no-op after the stream closes.
2107
2461
  *
2108
- * @param text - The comment text (sent after the `: ` prefix)
2462
+ * @param text - The comment text (sent after the `: ` prefix, one comment line per line)
2109
2463
  */
2110
2464
  comment(text: string): void;
2111
2465
  /**
@@ -2120,7 +2474,7 @@ export declare interface SSEStreamInterface {
2120
2474
  */
2121
2475
  drain(): Promise<void>;
2122
2476
  /**
2123
- * Ends the stream, completing the response — a no-op once already `closed`, and it
2477
+ * Ends the stream, completing the response — a no-op after the stream closes, and it
2124
2478
  * settles any parked producer.
2125
2479
  */
2126
2480
  end(): void;
@@ -2140,13 +2494,18 @@ export declare interface SSEStreamInterface {
2140
2494
  * wakeup, so the whole handle is one entity rather than a closure over four
2141
2495
  * bindings.
2142
2496
  *
2497
+ * The stream opens with one comment line ({@link serializeComment}), so the
2498
+ * response pump has a first chunk and the headers leave before any event.
2143
2499
  * `write` serializes one message ({@link serializeEvent}), enqueues it, and
2144
- * returns whether the controller still has positive desired size. A producer
2500
+ * returns whether the controller still has positive desired size; on an open
2501
+ * stream it throws the `ServerError` `serializeEvent` raises for a refused
2502
+ * field and enqueues nothing. A producer
2145
2503
  * receiving `false` awaits `drain()`; that promise resolves on the next
2146
2504
  * consumer pull restoring capacity, or on stream closure. `comment` writes a
2147
- * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
2148
- * stream. Every method is a safe no-op once `closed` (ended by `end()`, or
2149
- * the consumer cancelled the stream), so a late write never throws.
2505
+ * `: text` keep-alive line per line of its text, which a conforming SSE parser
2506
+ * ignores; `end` closes the stream. Every method is a safe no-op while `closed`
2507
+ * (ended by `end()`, or the consumer cancelled the stream), so a late write
2508
+ * never throws.
2150
2509
  *
2151
2510
  * The readiness signal reflects only the process-local `ReadableStream`
2152
2511
  * queue — it is not proof that a remote peer consumed bytes. When the response
@@ -2155,8 +2514,9 @@ export declare interface SSEStreamInterface {
2155
2514
  * its buffering. Ignoring the return value preserves an unconditional-enqueue
2156
2515
  * producer. The default stream strategy counts chunks rather than their byte
2157
2516
  * length, so a byte-bounded producer must also cap each message. Return
2158
- * `response` before awaiting a `false` write, because the consumer cannot pull
2159
- * until it receives the response.
2517
+ * `response` before awaiting a `false` write or `drain()`, because the consumer
2518
+ * cannot pull until it receives the response, and the opening comment fills
2519
+ * the queue, so a `drain()` before any write also waits on that pull.
2160
2520
  *
2161
2521
  * @example
2162
2522
  * ```ts
@@ -2197,19 +2557,56 @@ export declare interface StreamOptions {
2197
2557
  readonly headers?: Readonly<Record<string, string>>;
2198
2558
  }
2199
2559
 
2560
+ /**
2561
+ * Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other
2562
+ * character — from both ends of a text, in time linear in its length.
2563
+ *
2564
+ * @remarks
2565
+ * Reads the leading run with one anchored match and the trailing run with one
2566
+ * scan from the end, so a long run of spaces followed by another character
2567
+ * costs one pass, where a search for a trailing run restarts at every space.
2568
+ * A Unicode space such as U+00A0 stays, unlike `trim`.
2569
+ *
2570
+ * @param text - The text to strip
2571
+ * @returns `text` without its leading and trailing spaces and tabs
2572
+ *
2573
+ * @example
2574
+ * ```ts
2575
+ * stripOWS(' \tbytes=0-1 ') // 'bytes=0-1'
2576
+ * ```
2577
+ */
2578
+ export declare function stripOWS(text: string): string;
2579
+
2580
+ /**
2581
+ * Checks whether a `Headers` object accepts changes, leaving its entries as they were.
2582
+ *
2583
+ * @remarks
2584
+ * Fetch refuses `delete` on immutable headers before it looks the name up, so deleting a name
2585
+ * the headers lack answers the question and changes nothing. When the probe name is present, the
2586
+ * check sets it to its own combined value instead.
2587
+ *
2588
+ * @param headers - The headers to check
2589
+ * @returns True if `headers` accepts changes; false otherwise
2590
+ *
2591
+ * @example
2592
+ * ```ts
2593
+ * supportsMutation(new Headers()) // true
2594
+ * supportsMutation(Response.redirect('http://localhost/', 302).headers) // false
2595
+ * ```
2596
+ */
2597
+ export declare function supportsMutation(headers: Headers): boolean;
2598
+
2200
2599
  /**
2201
2600
  * Options for `signToken` — how a stateless, HMAC-signed token is minted.
2202
2601
  *
2203
- * @param secret - The {@link TokenSecret} to sign with; `signToken` always
2204
- * uses the first secret (a single string, or the current head of a
2205
- * rotation list). An empty rotation list is a misconfiguration and throws.
2602
+ * @param signer - The {@link SignerInterface} whose `sign` signs the payload.
2206
2603
  * @param ttl - An optional lifetime in milliseconds. When set, the expiry
2207
2604
  * timestamp is bound into the signed payload (HMAC-covered, tamper-proof);
2208
- * `verifyToken` rejects the token once that instant has passed. Omitted ⇒
2605
+ * `verifyToken` refuses the token after that instant passes. Omitted ⇒
2209
2606
  * the token never expires.
2210
2607
  */
2211
2608
  export declare interface TokenOptions {
2212
- readonly secret: TokenSecret;
2609
+ readonly signer: SignerInterface;
2213
2610
  readonly ttl?: number;
2214
2611
  }
2215
2612
 
@@ -2219,10 +2616,11 @@ export declare interface TokenOptions {
2219
2616
  *
2220
2617
  * @remarks
2221
2618
  * A single `string` is the lone secret. A `readonly string[]` is a rotation
2222
- * list in `[current, ...older]` order: `signToken` always signs with the
2223
- * first (current) secret, while `verifyToken` accepts a token signed by any
2224
- * secret in the list — so a key rotates by prepending the fresh one and keeping
2225
- * the old until every outstanding token has expired, with zero downtime.
2619
+ * list in `[current, ...older]` order: the signer `createSigner` builds from it
2620
+ * signs with the first (current) key and verifies a token signed by any key in
2621
+ * the list — so a key rotates by building a signer with the fresh secret
2622
+ * prepended and keeping the old until every outstanding token has expired.
2623
+ * Every entry is non-blank; `createSigner` refuses a blank one.
2226
2624
  */
2227
2625
  export declare type TokenSecret = string | readonly string[];
2228
2626
 
@@ -2273,44 +2671,44 @@ export declare function unwrapETag(tag: string): string;
2273
2671
  export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
2274
2672
 
2275
2673
  /**
2276
- * Verifies a stateless token and returns its embedded value — total, never throws.
2674
+ * Verifies a stateless token and returns its embedded value, or `undefined` for a
2675
+ * malformed, tampered, or expired token.
2277
2676
  *
2278
2677
  * @remarks
2279
2678
  * The inverse of {@link signToken}: splits the token on its last `.` (so a
2280
- * value containing dots survives), decodes the signature with
2281
- * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
2282
- * base64url is refused there, before any key import — and checks the payload's
2283
- * HMAC-SHA256 signature against each {@link TokenSecret} candidate through
2284
- * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
2285
- * retired), accepting the token on the first match (the
2286
- * rotation path). It then decodes + narrows the payload (`isRecord` +
2287
- * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
2288
- * token. Any failure — a malformed token, a bad signature,
2289
- * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
2290
- * yields `undefined` rather than throwing.
2679
+ * value containing dots survives), checks the signature with `signer.verify`
2680
+ * (a signer over a rotation list accepts any of its keys), then decodes and
2681
+ * narrows the payload with {@link decodeTokenPayload}, which refuses an
2682
+ * elapsed expiry. It rejects only when `signer.verify` rejects, which the
2683
+ * signer `createSigner` returns never does, so a consumer signer's outage
2684
+ * surfaces as an error rather than as an invalid token.
2291
2685
  *
2292
2686
  * @param token - The candidate token string (from a request header/cookie)
2293
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
2687
+ * @param signer - The {@link SignerInterface} to verify against
2294
2688
  * @returns The embedded value when the token is valid + unexpired, else `undefined`
2295
2689
  *
2296
2690
  * @example
2297
2691
  * ```ts
2298
- * await verifyToken('bad.token', 'shh') // undefined — never throws
2692
+ * await verifyToken('bad.token', createSigner('shh')) // undefined
2299
2693
  * ```
2300
2694
  */
2301
- export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
2695
+ export declare function verifyToken(token: string, signer: SignerInterface): Promise<string | undefined>;
2302
2696
 
2303
2697
  /**
2304
2698
  * Wraps one middleware layer around its downstream handler, enforcing the one-call
2305
2699
  * `next` invariant.
2306
2700
  *
2307
2701
  * @remarks
2308
- * The returned handler enforces the one-call `next` invariant while preserving
2309
- * request substitution and the middleware's synchronous or asynchronous result.
2702
+ * The returned handler enforces the one-call, no-argument `next` invariant: every
2703
+ * call, refused or not, spends the layer's one call, so a call after a refused
2704
+ * `next(request)` rejects too. It hands `next` the same request and context, and
2705
+ * keeps the middleware's synchronous or asynchronous result.
2310
2706
  *
2311
2707
  * @typeParam TState - The consumer's opaque per-request state type
2312
2708
  * @param layer - The middleware layer to invoke
2313
2709
  * @param next - The downstream handler wrapped by `layer`
2710
+ * @param known - The {@link normalizeResponse} memo of one composed run, shared by its
2711
+ * layers; Default: a fresh `Map` per call of the returned handler
2314
2712
  * @returns A handler with `layer` composed around `next`
2315
2713
  *
2316
2714
  * @example
@@ -2321,31 +2719,31 @@ export declare function verifyToken(token: string, secret: TokenSecret): Promise
2321
2719
  * )
2322
2720
  * ```
2323
2721
  */
2324
- export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
2722
+ export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>, known?: Map<Response, Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
2325
2723
 
2326
2724
  /**
2327
2725
  * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
2328
2726
  * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
2329
2727
  *
2330
2728
  * @remarks
2331
- * The cookie value is `await signToken(value, { secret })`
2729
+ * The cookie value is `await signToken(value, { signer })`
2332
2730
  * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
2333
- * cookie — the same secret rotation and tamper rejection, no second HMAC
2731
+ * cookie — the same key rotation and tamper rejection, no second HMAC
2334
2732
  * scheme. Appends (never clobbers) through `Headers.append`, which accumulates
2335
- * repeated headers. Async — WebCrypto signing is asynchronous.
2733
+ * repeated headers.
2336
2734
  *
2337
2735
  * @param headers - The response `Headers` to write into
2338
2736
  * @param name - The cookie name
2339
2737
  * @param value - The opaque value to sign into the cookie
2340
- * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
2738
+ * @param signer - The {@link SignerInterface} that signs (its first key signs)
2341
2739
  * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
2342
2740
  *
2343
2741
  * @example
2344
2742
  * ```ts
2345
2743
  * const headers = new Headers()
2346
- * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
2744
+ * await writeSignedCookie(headers, 'session', 'user-1', createSigner('secret'))
2347
2745
  * ```
2348
2746
  */
2349
- export declare function writeSignedCookie(headers: Headers, name: string, value: string, secret: TokenSecret, options?: CookieOptions): Promise<void>;
2747
+ export declare function writeSignedCookie(headers: Headers, name: string, value: string, signer: SignerInterface, options?: CookieOptions): Promise<void>;
2350
2748
 
2351
2749
  export { }