@orkestrel/server 0.0.27 → 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.
@@ -4,11 +4,11 @@ let node_events = require("node:events");
4
4
  let node_net = require("node:net");
5
5
  let _orkestrel_codec = require("@orkestrel/codec");
6
6
  let node_http = require("node:http");
7
- let node_stream_promises = require("node:stream/promises");
8
7
  let _orkestrel_abort = require("@orkestrel/abort");
9
8
  let _orkestrel_timeout = require("@orkestrel/timeout");
10
9
  let _orkestrel_router_server = require("@orkestrel/router/server");
11
10
  let _orkestrel_emitter = require("@orkestrel/emitter");
11
+ let node_crypto = require("node:crypto");
12
12
  // src/server/constants.ts
13
13
  /**
14
14
  * Names the default graceful-stop deadline `stop()` gives in-flight requests and
@@ -16,6 +16,17 @@ let _orkestrel_emitter = require("@orkestrel/emitter");
16
16
  */
17
17
  var DEFAULT_DRAIN_MS = 1e4;
18
18
  /**
19
+ * Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when
20
+ * `timeouts.request` is omitted.
21
+ */
22
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
23
+ /**
24
+ * Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when
25
+ * `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the
26
+ * request timeout.
27
+ */
28
+ var DEFAULT_HEADERS_TIMEOUT_MS = 6e4;
29
+ /**
19
30
  * Names the `Symbol.for`-interned brand `HTTPError` carries,
20
31
  * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
21
32
  * package copies. A consumer never sets it by hand.
@@ -41,7 +52,7 @@ var DEFAULT_BODY_LIMIT = 1048576;
41
52
  * it transparently decompresses a `Content-Encoding` request body.
42
53
  *
43
54
  * @remarks
44
- * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
55
+ * A small compressed body (under {@link DEFAULT_BODY_LIMIT} on the wire)
45
56
  * can inflate by many orders of magnitude — a classic decompression bomb.
46
57
  * Capping the decompressed byte count makes the pipe abort the moment the
47
58
  * output would exceed this, before the full bomb is materialized, so the
@@ -75,7 +86,7 @@ var SSE_HEADERS = Object.freeze({
75
86
  * to match, `^[A-Za-z0-9_-]{1,200}$`.
76
87
  *
77
88
  * @remarks
78
- * An incoming id carrying CRLF, a log-injection payload, a control character,
89
+ * An incoming id carrying CRLF, log-injection input, a control character,
79
90
  * or more characters than the pattern admits fails the match and is rejected —
80
91
  * a fresh id is minted instead — so it never rides into a response header or
81
92
  * `context.state`. Frozen so a consumer can read but never mutate the shared
@@ -83,6 +94,21 @@ var SSE_HEADERS = Object.freeze({
83
94
  */
84
95
  var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
85
96
  /**
97
+ * Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`.
98
+ *
99
+ * @remarks
100
+ * Mirrors the `first-pos`, `last-pos`, and `suffix-length` rules of RFC 9110
101
+ * § 14.1.1. A numeral `Number` reads but the grammar refuses — a hexadecimal,
102
+ * octal, or binary prefix, an exponent, a sign, or a decimal point — fails the
103
+ * match, as does a digit outside ASCII, which `Number` reads as `NaN`.
104
+ */
105
+ var RANGE_BOUND_PATTERN = Object.freeze(/^[0-9]+$/);
106
+ /**
107
+ * Defines the line terminators of the SSE wire, `\r\n`, `\r`, and `\n`, which
108
+ * `serializeEvent` and `serializeComment` split text on.
109
+ */
110
+ var SSE_LINE_PATTERN = Object.freeze(/\r\n|\r|\n/);
111
+ /**
86
112
  * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
87
113
  * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
88
114
  * helper also applies.
@@ -133,10 +159,12 @@ var CONTENT_TOO_LARGE_ERROR_BRAND = Symbol.for("@orkestrel/server.ContentTooLarg
133
159
  * @remarks
134
160
  * Carries the HTTP `status` to send and an optional `context` record (the
135
161
  * offending field / value). The server's built-in error boundary catches it
136
- * and renders a response of `status` with the error's `message` as the body
137
- * — so an `HTTPError`'s message is always client-facing (it is the handler's
138
- * deliberate signal), unlike a generic throw whose message is hidden unless
139
- * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
162
+ * and renders a response of `status` with the error's `message` as the body,
163
+ * and no body for 204, 205, and 304 — so an `HTTPError`'s message is always
164
+ * client-facing (it is the handler's deliberate signal), unlike a generic
165
+ * throw whose message is hidden unless `expose` is set. A `status` the
166
+ * `Response` constructor refuses, an integer below 200 or above 599 or a
167
+ * status that is not an integer, renders `500` instead. Subclass it (as {@link ContentTooLargeError} does) for
140
168
  * specific statuses, or throw it directly. Narrow a caught value with
141
169
  * {@link isHTTPError}. The machine-readable discriminator is `status`; there is
142
170
  * no separate `code`.
@@ -238,15 +266,21 @@ function isContentTooLargeError(value) {
238
266
  }
239
267
  /**
240
268
  * Represents the error this package raises when a caller programmed a call the
241
- * entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
269
+ * entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code.
242
270
  *
243
271
  * @remarks
244
272
  * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
245
273
  * record naming the offending facts. This is a programmer error, so it carries
246
274
  * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
247
- * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
275
+ * invoked the lifecycle method, a `'NEXT'` refusal of a second `next` call or
276
+ * of a `next` call with an argument escapes its
248
277
  * middleware into the request boundary, which reaches it as a generic 500 with
249
- * the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
278
+ * the message hidden unless `expose` is set, and an `'EVENT'` refusal is raised
279
+ * to the caller that serialized an SSE message, its `context.field` naming the
280
+ * refused field, and a `'SECRET'` refusal is raised to the caller that built a
281
+ * signer from a malformed secret, its `context` naming the refused positions,
282
+ * or the received type for a value that is not a string or a readable list, and holding
283
+ * no secret text. Throw an {@link HTTPError} for a
250
284
  * client-facing fault instead. Narrow a caught value with
251
285
  * {@link isServerError}.
252
286
  *
@@ -305,7 +339,7 @@ function isServerError(value) {
305
339
  if (_orkestrel_contract.INTRINSICS.describe(value, SERVER_ERROR_BRAND)?.value !== value) return false;
306
340
  const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
307
341
  const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
308
- return (code === "STATUS" || code === "NEXT") && (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(value, "message")) && (context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context));
342
+ return (code === "STATUS" || code === "NEXT" || code === "EVENT" || code === "SECRET") && (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(value, "message")) && (context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context));
309
343
  });
310
344
  }
311
345
  // src/server/validators.ts
@@ -336,19 +370,23 @@ function isAddressInfo(value) {
336
370
  // src/server/helpers.ts
337
371
  /**
338
372
  * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
339
- * handler into one request handler — the frozen middleware seam.
373
+ * handler into one request handler — the middleware seam.
340
374
  *
341
375
  * @remarks
342
376
  * `middleware[0]` runs outermost: it is invoked first, and its call to `next`
343
377
  * runs `middleware[1]`, and so on until the last middleware's `next` invokes
344
- * `terminal`. Each middleware's `next` may be called with a substituted
345
- * `Request` (the downstream chain then sees that request instead of the
346
- * original), called with no argument (the original request continues
347
- * downstream), or not called at all (a short-circuit — the middleware's own
348
- * returned `Response` is sent, and everything downstream never runs). A
349
- * second call to the same `next` within one middleware invocation rejects —
350
- * each link runs the chain at most once, so a middleware cannot fork the
351
- * request into two divergent downstream runs.
378
+ * `terminal`. Every layer and `terminal` receive the same `Request` and the same
379
+ * context object. A middleware's `next` is called with no argument, or not
380
+ * called at all (a short-circuit — the middleware's own returned `Response` is
381
+ * sent, and everything downstream never runs). A second call to the same
382
+ * `next` within one middleware invocation, or a call that passes an argument,
383
+ * rejects with a `ServerError` of code `'NEXT'` — each link runs the chain at
384
+ * most once, so a middleware cannot fork the request into two divergent
385
+ * downstream runs. Each `next` resolves the downstream response through
386
+ * {@link normalizeResponse}, so a layer can set headers on a redirect or a
387
+ * `fetch` result; each run keeps its own memo of checked responses, which ends
388
+ * with the run. `compose` copies `middleware` when called, so a layer added to
389
+ * the array later never runs in the returned handler.
352
390
  *
353
391
  * @typeParam TState - The consumer's opaque per-request state type
354
392
  * @param middleware - The ordered chain, outermost first
@@ -367,19 +405,27 @@ function isAddressInfo(value) {
367
405
  * ```
368
406
  */
369
407
  function compose(middleware, terminal) {
370
- return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
408
+ const layers = [...middleware];
409
+ return (request, context) => {
410
+ const known = /* @__PURE__ */ new Map();
411
+ return layers.reduceRight((next, layer) => wrapMiddleware(layer, next, known), terminal)(request, context);
412
+ };
371
413
  }
372
414
  /**
373
415
  * Wraps one middleware layer around its downstream handler, enforcing the one-call
374
416
  * `next` invariant.
375
417
  *
376
418
  * @remarks
377
- * The returned handler enforces the one-call `next` invariant while preserving
378
- * request substitution and the middleware's synchronous or asynchronous result.
419
+ * The returned handler enforces the one-call, no-argument `next` invariant: every
420
+ * call, refused or not, spends the layer's one call, so a call after a refused
421
+ * `next(request)` rejects too. It hands `next` the same request and context, and
422
+ * keeps the middleware's synchronous or asynchronous result.
379
423
  *
380
424
  * @typeParam TState - The consumer's opaque per-request state type
381
425
  * @param layer - The middleware layer to invoke
382
426
  * @param next - The downstream handler wrapped by `layer`
427
+ * @param known - The {@link normalizeResponse} memo of one composed run, shared by its
428
+ * layers; Default: a fresh `Map` per call of the returned handler
383
429
  * @returns A handler with `layer` composed around `next`
384
430
  *
385
431
  * @example
@@ -390,18 +436,79 @@ function compose(middleware, terminal) {
390
436
  * )
391
437
  * ```
392
438
  */
393
- function wrapMiddleware(layer, next) {
439
+ function wrapMiddleware(layer, next, known) {
394
440
  return async (request, context) => {
441
+ const memo = known ?? /* @__PURE__ */ new Map();
395
442
  const calls = [next].values();
396
- return Promise.resolve(layer(request, context, (nextRequest) => {
443
+ return Promise.resolve(layer(request, context, (...args) => {
397
444
  const invocation = calls.next();
398
445
  if (invocation.done) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
399
- const downstream = invocation.value;
400
- return downstream(nextRequest ?? request, context);
446
+ if (args.length > 0) return Promise.reject(new ServerError("NEXT", "next() takes no argument; every layer reads one request"));
447
+ return invocation.value(request, context).then((response) => normalizeResponse(response, memo));
401
448
  }));
402
449
  };
403
450
  }
404
451
  /**
452
+ * Returns a response whose headers a middleware can set: a copy of `response` when its headers are
453
+ * immutable and its status lies from 200 through 599, and `response` itself otherwise.
454
+ *
455
+ * @remarks
456
+ * A `Response.redirect` result and a `fetch` result carry immutable headers, so `headers.set`
457
+ * throws on them. The copy keeps the body, the status, the status text, and every header; it
458
+ * drops the fields a constructed `Response` cannot carry, such as `url` and `redirected`. A
459
+ * response whose status lies outside 200 through 599, such as `Response.error()`, passes through
460
+ * unchanged. `known` maps each response already checked to its answer, and the copy to itself, so
461
+ * a response that crosses several layers of one composed run is checked once.
462
+ *
463
+ * @param response - The response a downstream handler resolved
464
+ * @param known - The memo of one composed run; Default: a fresh `Map`
465
+ * @returns `response` itself, or its mutable copy
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * const response = normalizeResponse(Response.redirect('http://localhost/next', 302))
470
+ * response.headers.set('X-Request-ID', 'abc') // no throw
471
+ * ```
472
+ */
473
+ function normalizeResponse(response, known = /* @__PURE__ */ new Map()) {
474
+ const remembered = known.get(response);
475
+ if (remembered !== void 0) return remembered;
476
+ const normal = response.status < 200 || response.status > 599 || supportsMutation(response.headers) ? response : new Response(response.body, {
477
+ status: response.status,
478
+ statusText: response.statusText,
479
+ headers: new Headers(response.headers)
480
+ });
481
+ known.set(response, normal);
482
+ if (normal !== response) known.set(normal, normal);
483
+ return normal;
484
+ }
485
+ /**
486
+ * Checks whether a `Headers` object accepts changes, leaving its entries as they were.
487
+ *
488
+ * @remarks
489
+ * Fetch refuses `delete` on immutable headers before it looks the name up, so deleting a name
490
+ * the headers lack answers the question and changes nothing. When the probe name is present, the
491
+ * check sets it to its own combined value instead.
492
+ *
493
+ * @param headers - The headers to check
494
+ * @returns True if `headers` accepts changes; false otherwise
495
+ *
496
+ * @example
497
+ * ```ts
498
+ * supportsMutation(new Headers()) // true
499
+ * supportsMutation(Response.redirect('http://localhost/', 302).headers) // false
500
+ * ```
501
+ */
502
+ function supportsMutation(headers) {
503
+ const name = "x-orkestrel-probe";
504
+ const value = headers.get(name);
505
+ return (0, _orkestrel_contract.holds)(() => {
506
+ if (value === null) headers.delete(name);
507
+ else headers.set(name, value);
508
+ return true;
509
+ });
510
+ }
511
+ /**
405
512
  * Parses a raw `Cookie:` request header into a `name → value` lookup.
406
513
  *
407
514
  * @remarks
@@ -414,8 +521,12 @@ function wrapMiddleware(layer, next) {
414
521
  * name, is skipped; a later duplicate name wins. Total — an absent/empty/
415
522
  * malformed header yields an empty record, never throws.
416
523
  *
524
+ * The record has a null prototype, so a name that `Object.prototype` carries
525
+ * (`constructor`, `toString`, `__proto__`) reads as an ordinary cookie when
526
+ * present and as `undefined` when absent.
527
+ *
417
528
  * @param header - The raw `Cookie` header value (possibly `undefined`)
418
- * @returns A record of every parsed cookie, `name → decoded value`
529
+ * @returns A null-prototype record of every parsed cookie, `name → decoded value`
419
530
  *
420
531
  * @example
421
532
  * ```ts
@@ -423,18 +534,16 @@ function wrapMiddleware(layer, next) {
423
534
  * ```
424
535
  */
425
536
  function parseCookies(header) {
426
- const out = {};
427
- if (header === void 0) return out;
428
- const segments = header.split(";");
429
- for (const [index, raw] of segments.entries()) {
537
+ const pairs = (header ?? "").split(";").flatMap((raw, index) => {
430
538
  const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
431
539
  const eq = segment.indexOf("=");
432
- if (eq < 0) continue;
540
+ if (eq < 0) return [];
433
541
  const name = segment.slice(0, eq);
434
- if (!isCookieName(name)) continue;
435
- out[name] = decodeCookieValue(segment.slice(eq + 1).trim());
436
- }
437
- return out;
542
+ return isCookieName(name) ? [[name, decodeCookieValue(segment.slice(eq + 1).trim())]] : [];
543
+ });
544
+ const cookies = Object.fromEntries(pairs);
545
+ Object.setPrototypeOf(cookies, null);
546
+ return cookies;
438
547
  }
439
548
  /**
440
549
  * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
@@ -580,50 +689,52 @@ function resolveSecure(secure, encrypted) {
580
689
  * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
581
690
  *
582
691
  * @remarks
583
- * The cookie value is `await signToken(value, { secret })`
692
+ * The cookie value is `await signToken(value, { signer })`
584
693
  * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
585
- * cookie — the same secret rotation and tamper rejection, no second HMAC
694
+ * cookie — the same key rotation and tamper rejection, no second HMAC
586
695
  * scheme. Appends (never clobbers) through `Headers.append`, which accumulates
587
- * repeated headers. Async — WebCrypto signing is asynchronous.
696
+ * repeated headers.
588
697
  *
589
698
  * @param headers - The response `Headers` to write into
590
699
  * @param name - The cookie name
591
700
  * @param value - The opaque value to sign into the cookie
592
- * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
701
+ * @param signer - The {@link SignerInterface} that signs (its first key signs)
593
702
  * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
594
703
  *
595
704
  * @example
596
705
  * ```ts
597
706
  * const headers = new Headers()
598
- * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
707
+ * await writeSignedCookie(headers, 'session', 'user-1', createSigner('secret'))
599
708
  * ```
600
709
  */
601
- async function writeSignedCookie(headers, name, value, secret, options) {
602
- headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
710
+ async function writeSignedCookie(headers, name, value, signer, options) {
711
+ headers.append("set-cookie", serializeCookie(name, await signToken(value, { signer }), options));
603
712
  }
604
713
  /**
605
- * Reads and verifies a signed cookie off a request — total, returning the
606
- * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
714
+ * Reads and verifies a signed cookie off a request, returning the embedded value
715
+ * or `undefined` (the inverse of {@link writeSignedCookie}).
607
716
  *
608
717
  * @remarks
609
718
  * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
610
- * and verifies it with {@link verifyToken} against `secret` (a rotation list
611
- * accepts a cookie signed by any of its secrets). Any failure — an absent
612
- * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
719
+ * and verifies it with {@link verifyToken} against `signer` (a signer over a
720
+ * rotation list accepts a cookie signed by any of its keys). An absent cookie,
721
+ * a tampered value, and a wrong key each yield `undefined`, a name such as
722
+ * `constructor` included. It rejects only when `signer.verify` rejects, which
723
+ * the signer `createSigner` returns never does.
613
724
  *
614
725
  * @param request - The `Request` to read the `Cookie` header from
615
726
  * @param name - The cookie name to read
616
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
727
+ * @param signer - The {@link SignerInterface} to verify against
617
728
  * @returns The embedded value when the cookie is present + valid, else `undefined`
618
729
  *
619
730
  * @example
620
731
  * ```ts
621
- * const value = await readSignedCookie(request, 'session', 'secret')
732
+ * const value = await readSignedCookie(request, 'session', createSigner('secret'))
622
733
  * ```
623
734
  */
624
- async function readSignedCookie(request, name, secret) {
735
+ async function readSignedCookie(request, name, signer) {
625
736
  const cookie = parseCookies(request.headers.get("cookie") ?? void 0)[name];
626
- return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
737
+ return cookie === void 0 ? void 0 : verifyToken(cookie, signer);
627
738
  }
628
739
  /**
629
740
  * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
@@ -656,86 +767,55 @@ function clearCookie(headers, name, options) {
656
767
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
657
768
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
658
769
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
659
- * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
660
- * {@link TokenSecret} (the current secret, or the head of a rotation list).
661
- * Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
662
- * misconfigured secret with no usable entry throws an {@link HTTPError}
663
- * (`500`) — fail-closed, a programmer error. Verify with
664
- * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
770
+ * the signature), signed by `options.signer`, whose first key signs. Verify
771
+ * with {@link verifyToken}. Omitting `ttl` mints a token that never expires.
665
772
  *
666
773
  * @param value - The opaque value to embed (a session id, a deployment marker)
667
- * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
774
+ * @param options - The `signer` and optional `ttl` (ms); see {@link TokenOptions}
668
775
  * @returns The signed `<payload>.<signature>` token string
669
- * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
670
776
  *
671
777
  * @example
672
778
  * ```ts
673
- * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
674
- * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
779
+ * const signer = createSigner('shh')
780
+ * const token = await signToken('client', { signer, ttl: 60_000 })
781
+ * await verifyToken(token, signer) // 'client' (within 60s), else undefined
675
782
  * ```
676
783
  */
677
784
  async function signToken(value, options) {
678
- const secret = normalizeSecret(options.secret)[0];
679
- if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
680
785
  const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
681
786
  const encoded = (0, _orkestrel_codec.encodeBase64URL)(new TextEncoder().encode(JSON.stringify({
682
787
  value,
683
788
  exp
684
789
  })));
685
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
686
- name: "HMAC",
687
- hash: "SHA-256"
688
- }, false, ["sign"]);
689
- const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
690
- return `${encoded}.${(0, _orkestrel_codec.encodeBase64URL)(new Uint8Array(signature))}`;
790
+ return `${encoded}.${await options.signer.sign(encoded)}`;
691
791
  }
692
792
  /**
693
- * Verifies a stateless token and returns its embedded value — total, never throws.
793
+ * Verifies a stateless token and returns its embedded value, or `undefined` for a
794
+ * malformed, tampered, or expired token.
694
795
  *
695
796
  * @remarks
696
797
  * The inverse of {@link signToken}: splits the token on its last `.` (so a
697
- * value containing dots survives), decodes the signature with
698
- * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
699
- * base64url is refused there, before any key import — and checks the payload's
700
- * HMAC-SHA256 signature against each {@link TokenSecret} candidate through
701
- * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
702
- * retired), accepting the token on the first match (the
703
- * rotation path). It then decodes + narrows the payload (`isRecord` +
704
- * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
705
- * token. Any failure — a malformed token, a bad signature,
706
- * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
707
- * yields `undefined` rather than throwing.
798
+ * value containing dots survives), checks the signature with `signer.verify`
799
+ * (a signer over a rotation list accepts any of its keys), then decodes and
800
+ * narrows the payload with {@link decodeTokenPayload}, which refuses an
801
+ * elapsed expiry. It rejects only when `signer.verify` rejects, which the
802
+ * signer `createSigner` returns never does, so a consumer signer's outage
803
+ * surfaces as an error rather than as an invalid token.
708
804
  *
709
805
  * @param token - The candidate token string (from a request header/cookie)
710
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
806
+ * @param signer - The {@link SignerInterface} to verify against
711
807
  * @returns The embedded value when the token is valid + unexpired, else `undefined`
712
808
  *
713
809
  * @example
714
810
  * ```ts
715
- * await verifyToken('bad.token', 'shh') // undefined — never throws
811
+ * await verifyToken('bad.token', createSigner('shh')) // undefined
716
812
  * ```
717
813
  */
718
- async function verifyToken(token, secret) {
719
- const secrets = normalizeSecret(secret);
720
- if (secrets.length === 0) return void 0;
814
+ async function verifyToken(token, signer) {
721
815
  const dot = token.lastIndexOf(".");
722
816
  if (dot < 0) return void 0;
723
817
  const encoded = token.slice(0, dot);
724
- const signature = (0, _orkestrel_codec.decodeBase64URL)(token.slice(dot + 1));
725
- if (signature === void 0) return void 0;
726
- const data = new TextEncoder().encode(encoded);
727
- try {
728
- for (const candidate of secrets) {
729
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
730
- name: "HMAC",
731
- hash: "SHA-256"
732
- }, false, ["verify"]);
733
- if (await crypto.subtle.verify("HMAC", key, signature, data)) return decodeTokenPayload(encoded);
734
- }
735
- return;
736
- } catch {
737
- return;
738
- }
818
+ return await signer.verify(encoded, token.slice(dot + 1)) ? decodeTokenPayload(encoded) : void 0;
739
819
  }
740
820
  /**
741
821
  * Decodes and narrows a signed token's base64url JSON payload, honoring its
@@ -763,25 +843,38 @@ function decodeTokenPayload(encoded) {
763
843
  return payload.value;
764
844
  }
765
845
  /**
766
- * Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
767
- * behind both {@link signToken} and {@link verifyToken}.
846
+ * Normalizes a {@link TokenSecret} to its `[current, ...older]` list — the list a
847
+ * signer creates its keys from — refusing a malformed secret.
768
848
  *
769
849
  * @remarks
770
- * A single string becomes a one-element list; a rotation list is copied. Any
771
- * blank/whitespace-only entry is dropped (`.trim()` is used only for that
772
- * emptiness test; each kept secret is stored verbatim). The first kept
773
- * element is the signing secret; all kept are accepted on verify.
850
+ * A single string becomes a one-element list; a rotation list is copied once
851
+ * and its copy validated, each secret kept verbatim. A blank entry is refused,
852
+ * never dropped, because dropping a blank current secret would make an older
853
+ * key sign. The refusal names the blank or non-string positions in `context`
854
+ * and carries no secret text.
774
855
  *
775
856
  * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
776
- * @returns The kept (non-blank) secrets, in order — empty when none is usable
857
+ * @returns The secrets, current first
858
+ * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of
859
+ * strings, when the list is empty, or when any entry is blank
777
860
  *
778
861
  * @example
779
862
  * ```ts
780
- * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
863
+ * normalizeSecret(['new', 'old']) // ['new', 'old']
864
+ * normalizeSecret(['new', ' ']) // throws ServerError 'SECRET', context { entries: [1], count: 2 }
781
865
  * ```
782
866
  */
783
867
  function normalizeSecret(secret) {
784
- return ((0, _orkestrel_contract.isString)(secret) ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
868
+ const copied = (0, _orkestrel_contract.attempt)(() => (0, _orkestrel_contract.isString)(secret) ? [secret] : (0, _orkestrel_contract.isArray)(secret) ? Array.from(secret) : void 0);
869
+ const entries = copied.success ? copied.value : void 0;
870
+ if (entries === void 0) throw new ServerError("SECRET", "the signing secret is not a string or a list of strings: pass a non-blank string or a non-empty list of non-blank strings", { received: typeof secret });
871
+ const blank = entries.flatMap((entry, index) => (0, _orkestrel_contract.isString)(entry) && entry.trim().length > 0 ? [] : [index]);
872
+ const [current, ...older] = entries;
873
+ if (!(0, _orkestrel_contract.isString)(current) || blank.length > 0 || !older.every(_orkestrel_contract.isString)) throw new ServerError("SECRET", entries.length === 0 ? "the signing secret is an empty list: pass a non-blank string or a non-empty list of non-blank strings" : `the signing secret has blank or non-string entries at ${blank.join(", ")}: pass a non-blank string or a non-empty list of non-blank strings`, {
874
+ entries: blank,
875
+ count: entries.length
876
+ });
877
+ return [current, ...older];
785
878
  }
786
879
  /**
787
880
  * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
@@ -866,7 +959,7 @@ function computeCodingQuality(entries, coding) {
866
959
  * keeps the earlier-offered coding on a client-side tie, which is what makes
867
960
  * `available` the server's preference order. An empty `available` list, and a
868
961
  * list the client rejects outright, both yield `undefined` (identity — no
869
- * compression). Total on hostile input.
962
+ * compression). Total on malformed input.
870
963
  *
871
964
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
872
965
  * @param entries - The parsed {@link AcceptEntry} list
@@ -897,7 +990,7 @@ function resolveCoding(entries, available) {
897
990
  * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
898
991
  * the two doors onto this axis cannot drift. Returns `undefined` when the
899
992
  * client accepts none of `available` (identity — no compression). Total on
900
- * hostile input.
993
+ * malformed input.
901
994
  *
902
995
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
903
996
  * @param header - The raw `Accept-Encoding` header value
@@ -925,7 +1018,8 @@ function negotiateEncoding(header, available) {
925
1018
  * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
926
1019
  * (less specific) coverage, so a later more-specific match can still allow
927
1020
  * it. Among multiple matching entries, the lowest `rank` wins, and among a
928
- * rank tie the highest `q` wins.
1021
+ * rank tie the highest `q` wins. The candidate matches case-insensitively, as
1022
+ * the entries do.
929
1023
  *
930
1024
  * @param entries - The parsed {@link AcceptEntry} list
931
1025
  * @param candidate - The candidate media type to score (for example `'text/html'`)
@@ -955,10 +1049,11 @@ function matchMediaType(entries, candidate) {
955
1049
  * ```
956
1050
  */
957
1051
  function* iterateMediaMatches(entries, candidate) {
958
- const slash = candidate.indexOf("/");
959
- const type = slash === -1 ? candidate : candidate.slice(0, slash);
1052
+ const media = candidate.toLowerCase();
1053
+ const slash = media.indexOf("/");
1054
+ const type = slash === -1 ? media : media.slice(0, slash);
960
1055
  for (const entry of entries) {
961
- const rank = entry.value === candidate ? 0 : entry.value === `${type}/*` ? 1 : entry.value === "*/*" ? 2 : void 0;
1056
+ const rank = entry.value === media ? 0 : entry.value === `${type}/*` ? 1 : entry.value === "*/*" ? 2 : void 0;
962
1057
  if (rank === void 0) continue;
963
1058
  if (entry.q === 0) {
964
1059
  if (rank === 0) {
@@ -1137,15 +1232,28 @@ function matchesETag(header, etag) {
1137
1232
  * total, returning a {@link RangeSpec} or `undefined`.
1138
1233
  *
1139
1234
  * @remarks
1140
- * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1141
- * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1142
- * `[0, size - 1]` (the HTTP inclusive-end convention). Returns
1143
- * `{ satisfiable: true, start, end }` for an overlapping range,
1144
- * `{ satisfiable: false }` for a range wholly past the resource, and
1145
- * `undefined` for the "serve the whole resource" case: an absent header, a
1146
- * non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
1147
- * supported), or any malformed/non-finite bound. Never throws on a hostile
1148
- * header.
1235
+ * Reads the field value by RFC 9110 § 14.1:
1236
+ * `range-unit "=" OWS range-set`, where the unit matches `bytes`
1237
+ * case-insensitively and `range-set` is `1#range-spec` under the § 5.6.1 list
1238
+ * rule, so empty list elements are skipped. OWS is a space or a tab, and it
1239
+ * stands only around the field value, after `=`, and around a `,`; a range
1240
+ * holds none. A range is an `int-range` (`first-pos "-" [ last-pos ]`) or a
1241
+ * `suffix-range` (`"-" suffix-length`), each bound `1*DIGIT` ({@link
1242
+ * import('./constants.js').RANGE_BOUND_PATTERN}). A bound of any length is
1243
+ * compared with {@link compareDigits}, so none is misread through `Number`.
1244
+ * OWS is stripped with {@link stripOWS}, so the read is linear in the header's
1245
+ * length.
1246
+ *
1247
+ * Returns `{ satisfiable: true, start, end }` with the window clamped to
1248
+ * `[0, size - 1]` (the HTTP inclusive-end convention), and
1249
+ * `{ satisfiable: false }` when the range does not overlap the resource: a
1250
+ * `first-pos` at or past `size`, or a zero `suffix-length`.
1251
+ * Returns `undefined`, the § 14.2 "ignore the field and serve the whole
1252
+ * resource" answer, for an absent header, another unit, text outside the
1253
+ * grammar, a `last-pos` below its `first-pos`, more than one range (not
1254
+ * supported), a non-zero `suffix-length` on an empty resource (satisfiable by
1255
+ * § 14.1.2, but it selects no window to serve), and a `size` that is not a
1256
+ * non-negative safe integer. Never throws on a malformed header.
1149
1257
  *
1150
1258
  * @param header - The raw `Range` header value
1151
1259
  * @param size - The resource's total byte length
@@ -1154,48 +1262,95 @@ function matchesETag(header, etag) {
1154
1262
  * @example
1155
1263
  * ```ts
1156
1264
  * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1265
+ * parseRange('Bytes=-100,', 1000) // { satisfiable: true, start: 900, end: 999 }
1157
1266
  * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
1267
+ * parseRange('bytes=0x10-', 1000) // undefined — not a decimal bound
1268
+ * parseRange('bytes=5 - 9', 1000) // undefined — no OWS inside a range
1158
1269
  * ```
1159
1270
  */
1160
1271
  function parseRange(header, size) {
1161
- if (header === void 0) return void 0;
1162
- const match = /^bytes=(.*)$/.exec(header.trim());
1163
- if (match === null) return void 0;
1164
- const capture = match[1];
1165
- if (capture === void 0) return void 0;
1166
- const spec = capture.trim();
1167
- if (spec.includes(",")) return void 0;
1272
+ if (header === void 0 || !Number.isSafeInteger(size) || size < 0) return void 0;
1273
+ const field = stripOWS(header);
1274
+ const equals = field.indexOf("=");
1275
+ if (equals < 0 || field.slice(0, equals).toLowerCase() !== "bytes") return void 0;
1276
+ const specs = field.slice(equals + 1).split(",").map((item) => stripOWS(item)).filter((spec) => spec !== "");
1277
+ const spec = specs[0];
1278
+ if (spec === void 0 || specs.length > 1) return void 0;
1168
1279
  const dash = spec.indexOf("-");
1169
1280
  if (dash < 0) return void 0;
1170
- const startText = spec.slice(0, dash).trim();
1171
- const endText = spec.slice(dash + 1).trim();
1172
- if (startText === "") {
1173
- const suffix = Number(endText);
1174
- if (endText === "" || !(0, _orkestrel_contract.isInteger)(suffix) || suffix <= 0) return void 0;
1175
- if (size === 0) return { satisfiable: false };
1281
+ const first = spec.slice(0, dash);
1282
+ const last = spec.slice(dash + 1);
1283
+ const extent = String(size);
1284
+ if (first === "") {
1285
+ if (!RANGE_BOUND_PATTERN.test(last)) return void 0;
1286
+ if (compareDigits(last, "0") === 0) return { satisfiable: false };
1287
+ if (size === 0) return void 0;
1176
1288
  return {
1177
1289
  satisfiable: true,
1178
- start: Math.max(0, size - suffix),
1290
+ start: compareDigits(last, extent) < 0 ? size - Number(last) : 0,
1179
1291
  end: size - 1
1180
1292
  };
1181
1293
  }
1182
- const start = Number(startText);
1183
- if (!(0, _orkestrel_contract.isInteger)(start) || start < 0) return void 0;
1184
- if (start >= size) return { satisfiable: false };
1185
- if (endText === "") return {
1186
- satisfiable: true,
1187
- start,
1188
- end: size - 1
1189
- };
1190
- const end = Number(endText);
1191
- if (!(0, _orkestrel_contract.isInteger)(end) || end < start) return void 0;
1294
+ if (!RANGE_BOUND_PATTERN.test(first)) return void 0;
1295
+ if (last !== "" && !RANGE_BOUND_PATTERN.test(last)) return void 0;
1296
+ if (last !== "" && compareDigits(last, first) < 0) return void 0;
1297
+ if (compareDigits(first, extent) >= 0) return { satisfiable: false };
1298
+ const end = last === "" || compareDigits(last, extent) >= 0 ? size - 1 : Number(last);
1192
1299
  return {
1193
1300
  satisfiable: true,
1194
- start,
1195
- end: Math.min(end, size - 1)
1301
+ start: Number(first),
1302
+ end
1196
1303
  };
1197
1304
  }
1198
1305
  /**
1306
+ * Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other
1307
+ * character — from both ends of a text, in time linear in its length.
1308
+ *
1309
+ * @remarks
1310
+ * Reads the leading run with one anchored match and the trailing run with one
1311
+ * scan from the end, so a long run of spaces followed by another character
1312
+ * costs one pass, where a search for a trailing run restarts at every space.
1313
+ * A Unicode space such as U+00A0 stays, unlike `trim`.
1314
+ *
1315
+ * @param text - The text to strip
1316
+ * @returns `text` without its leading and trailing spaces and tabs
1317
+ *
1318
+ * @example
1319
+ * ```ts
1320
+ * stripOWS(' \tbytes=0-1 ') // 'bytes=0-1'
1321
+ * ```
1322
+ */
1323
+ function stripOWS(text) {
1324
+ const start = /^[ \t]*/.exec(text)?.[0].length ?? 0;
1325
+ const end = text.split("").findLastIndex((char) => char !== " " && char !== " ") + 1;
1326
+ return end <= start ? "" : text.slice(start, end);
1327
+ }
1328
+ /**
1329
+ * Compares two `1*DIGIT` strings by their decimal value, at any length.
1330
+ *
1331
+ * @remarks
1332
+ * Drops leading zeros, then compares the digit counts and, at an equal count,
1333
+ * the digits in order, so a bound longer than any safe integer compares
1334
+ * exactly and never passes through `Number`. Both arguments must be
1335
+ * `1*DIGIT`; the answer for any other text is unspecified.
1336
+ *
1337
+ * @param left - The first digit string
1338
+ * @param right - The second digit string
1339
+ * @returns `-1` if `left` is less, `1` if it is greater, `0` if the two are equal
1340
+ *
1341
+ * @example
1342
+ * ```ts
1343
+ * compareDigits('9', '10') // -1
1344
+ * compareDigits('007', '7') // 0
1345
+ * ```
1346
+ */
1347
+ function compareDigits(left, right) {
1348
+ const a = left.replace(/^0+/, "");
1349
+ const b = right.replace(/^0+/, "");
1350
+ if (a.length !== b.length) return a.length < b.length ? -1 : 1;
1351
+ return a < b ? -1 : a > b ? 1 : 0;
1352
+ }
1353
+ /**
1199
1354
  * Resolves the `Access-Control-Allow-Origin` value for a request.
1200
1355
  *
1201
1356
  * @remarks
@@ -1203,7 +1358,7 @@ function parseRange(header, size) {
1203
1358
  * echoes the request's `Origin` only when it is present in the list, else
1204
1359
  * `undefined` (no header set). Security: the literal `'null'` origin — sent
1205
1360
  * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1206
- * never reflected even if `'null'` were listed, closing the hostile-context
1361
+ * never reflected even if `'null'` were listed, closing the opaque-origin
1207
1362
  * cross-origin-access hole.
1208
1363
  *
1209
1364
  * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
@@ -1369,12 +1524,19 @@ function computeClientKey(address) {
1369
1524
  * @remarks
1370
1525
  * Emits an `event:`/`id:`/`retry:` line for each present field, then one
1371
1526
  * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1372
- * (so a consuming parser's multi-`data` concat reproduces the original
1373
- * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1374
- * a `data:` line), then the terminating blank line.
1527
+ * (so a consuming parser's multi-`data` concat reproduces `data` with each
1528
+ * line break read as `\n`, and no raw `\r` or `\n` can ever ride onto the wire
1529
+ * inside a `data:` line), then the terminating blank line.
1530
+ *
1531
+ * It refuses a field the wire cannot carry rather than emit a second field or
1532
+ * a second event: an `event` with a line break, an `id` with a line break or
1533
+ * a NUL (which a conforming parser drops), and a `retry` that is not a
1534
+ * non-negative safe integer.
1375
1535
  *
1376
1536
  * @param message - The event to serialize
1377
1537
  * @returns The SSE wire text for the event (terminated by a blank line)
1538
+ * @throws {ServerError} Thrown when a field is refused, with code `'EVENT'`
1539
+ * and `context.field` naming the field
1378
1540
  *
1379
1541
  * @example
1380
1542
  * ```ts
@@ -1383,12 +1545,32 @@ function computeClientKey(address) {
1383
1545
  * ```
1384
1546
  */
1385
1547
  function serializeEvent(message) {
1386
- const lines = [];
1387
- if (message.event !== void 0) lines.push(`event: ${message.event}`);
1388
- if (message.id !== void 0) lines.push(`id: ${message.id}`);
1389
- if (message.retry !== void 0) lines.push(`retry: ${message.retry}`);
1390
- for (const segment of message.data.split(/\r\n|\r|\n/)) lines.push(`data: ${segment}`);
1391
- return `${lines.join("\n")}\n\n`;
1548
+ const { event, id, retry } = message;
1549
+ if (event !== void 0 && /[\r\n]/.test(event)) throw new ServerError("EVENT", "an SSE event type must be one line", { field: "event" });
1550
+ if (id !== void 0 && /[\r\n\0]/.test(id)) throw new ServerError("EVENT", "an SSE id must be one line with no NUL", { field: "id" });
1551
+ if (retry !== void 0 && !(Number.isSafeInteger(retry) && retry >= 0)) throw new ServerError("EVENT", "an SSE retry must be a non-negative safe integer", { field: "retry" });
1552
+ return `${[
1553
+ ...event === void 0 ? [] : [`event: ${event}`],
1554
+ ...id === void 0 ? [] : [`id: ${id}`],
1555
+ ...retry === void 0 ? [] : [`retry: ${retry}`],
1556
+ ...message.data.split(SSE_LINE_PATTERN).map((segment) => `data: ${segment}`)
1557
+ ].join("\n")}\n\n`;
1558
+ }
1559
+ /**
1560
+ * Serializes a comment to the SSE wire, one `: ` line per line of `text`.
1561
+ *
1562
+ * @remarks
1563
+ * Splits `text` on `\r\n`, `\r`, and `\n`, so no line of the comment can
1564
+ * reach a parser as a field and no comment can dispatch an event.
1565
+ *
1566
+ * @example
1567
+ * ```ts
1568
+ * serializeComment('keep-alive') // ': keep-alive\n\n'
1569
+ * serializeComment('a\nb') // ': a\n: b\n\n'
1570
+ * ```
1571
+ */
1572
+ function serializeComment(text) {
1573
+ return `${text.split(SSE_LINE_PATTERN).map((line) => `: ${line}`).join("\n")}\n\n`;
1392
1574
  }
1393
1575
  /**
1394
1576
  * Checks whether a key is a prototype-pollution vector — `__proto__`,
@@ -1408,17 +1590,21 @@ function isDangerousKey(key) {
1408
1590
  return key === "__proto__" || key === "constructor" || key === "prototype";
1409
1591
  }
1410
1592
  /**
1411
- * Strips the prototype-pollution keys from a parsed value in place, recursively.
1593
+ * Strips the prototype-pollution keys from a parsed value in place, at every depth.
1412
1594
  *
1413
1595
  * @remarks
1414
1596
  * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
1415
1597
  * enumerable `__proto__` data property — but that own key becomes a
1416
1598
  * pollution gadget the moment a downstream deep-merge copies it onto a live
1417
1599
  * object. This walks the value and `delete`s any own {@link isDangerousKey}
1418
- * key at every depth, recursing into nested objects + array elements.
1600
+ * key at every depth, into nested records and array elements.
1419
1601
  * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1420
1602
  * freshly-parsed value (which nothing else holds yet).
1421
1603
  *
1604
+ * The walk keeps a worklist rather than the call stack, so a value nested as
1605
+ * deep as the body limit admits costs no stack depth, and it reads a node
1606
+ * reached twice once, so a self-referencing value terminates.
1607
+ *
1422
1608
  * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1423
1609
  * @returns The same `value`, with every dangerous key removed at every depth
1424
1610
  *
@@ -1429,19 +1615,21 @@ function isDangerousKey(key) {
1429
1615
  * ```
1430
1616
  */
1431
1617
  function scrubPrototype(value) {
1432
- if (Array.isArray(value)) {
1433
- for (const member of value) scrubPrototype(member);
1434
- return value;
1435
- }
1436
- if ((0, _orkestrel_contract.isRecord)(value)) {
1437
- for (const key of Object.keys(value)) {
1618
+ const nodes = /* @__PURE__ */ new Set([value]);
1619
+ for (const node of nodes) {
1620
+ if ((0, _orkestrel_contract.isArray)(node)) {
1621
+ for (const member of node) if ((0, _orkestrel_contract.isObject)(member) && ((0, _orkestrel_contract.isArray)(member) || (0, _orkestrel_contract.isRecord)(member))) nodes.add(member);
1622
+ continue;
1623
+ }
1624
+ if (!(0, _orkestrel_contract.isRecord)(node)) continue;
1625
+ for (const key of Object.keys(node)) {
1438
1626
  if (isDangerousKey(key)) {
1439
- Reflect.deleteProperty(value, key);
1627
+ Reflect.deleteProperty(node, key);
1440
1628
  continue;
1441
1629
  }
1442
- scrubPrototype(value[key]);
1630
+ const member = node[key];
1631
+ if ((0, _orkestrel_contract.isObject)(member) && ((0, _orkestrel_contract.isArray)(member) || (0, _orkestrel_contract.isRecord)(member))) nodes.add(member);
1443
1632
  }
1444
- return value;
1445
1633
  }
1446
1634
  return value;
1447
1635
  }
@@ -1453,7 +1641,9 @@ function scrubPrototype(value) {
1453
1641
  * throwing a {@link ContentTooLargeError} (413) the instant the running total
1454
1642
  * exceeds `limit` — before the rest of the stream is buffered — rather than
1455
1643
  * collecting an unbounded body. A bodyless request (`request.body === null`)
1456
- * resolves an empty array. A non-positive `limit` means unbounded.
1644
+ * resolves an empty array. A non-positive `limit` means unbounded. When
1645
+ * `request.signal` aborts before the call or while a read waits, the body is
1646
+ * cancelled with the signal's reason and the promise rejects with that reason.
1457
1647
  *
1458
1648
  * @param request - The `Request` to drain
1459
1649
  * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
@@ -1466,21 +1656,29 @@ function scrubPrototype(value) {
1466
1656
  * ```
1467
1657
  */
1468
1658
  async function collectRequestBody(request, limit) {
1659
+ const signal = request.signal;
1660
+ signal.throwIfAborted();
1469
1661
  if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1470
1662
  const reader = request.body.getReader();
1471
1663
  const chunks = [];
1472
- for (;;) {
1473
- const { done, value } = await reader.read();
1474
- if (done) break;
1475
- const total = (chunks.at(-1)?.total ?? 0) + value.byteLength;
1476
- if (limit > 0 && total > limit) {
1477
- await reader.cancel();
1478
- throw new ContentTooLargeError(limit);
1664
+ const relay = (0, node_events.addAbortListener)(signal, () => reader.cancel(signal.reason).catch(() => void 0));
1665
+ try {
1666
+ for (;;) {
1667
+ const { done, value } = await reader.read();
1668
+ signal.throwIfAborted();
1669
+ if (done) break;
1670
+ const total = (chunks.at(-1)?.total ?? 0) + value.byteLength;
1671
+ if (limit > 0 && total > limit) {
1672
+ await reader.cancel();
1673
+ throw new ContentTooLargeError(limit);
1674
+ }
1675
+ chunks.push({
1676
+ bytes: value,
1677
+ total
1678
+ });
1479
1679
  }
1480
- chunks.push({
1481
- bytes: value,
1482
- total
1483
- });
1680
+ } finally {
1681
+ relay[Symbol.dispose]();
1484
1682
  }
1485
1683
  const merged = new Uint8Array(chunks.at(-1)?.total ?? 0);
1486
1684
  chunks.reduce((offset, chunk) => {
@@ -1523,7 +1721,7 @@ function parseEncoding(header) {
1523
1721
  * @remarks
1524
1722
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1525
1723
  * `TransformStream` that aborts the pipe the instant the running decompressed
1526
- * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1724
+ * total exceeds `cap` — fail-before-materialize, because `DecompressionStream`
1527
1725
  * has no `maxOutputLength` knob. A cap breach surfaces
1528
1726
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1529
1727
  * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
@@ -1584,8 +1782,11 @@ async function decompressRequestBody(bytes, encoding, cap) {
1584
1782
  * `options.decompression`, default {@link
1585
1783
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1586
1784
  * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1587
- * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1588
- * scrubPrototype}); any other type decodes as UTF-8 text.
1785
+ * `parseJSON`, `application/x-www-form-urlencoded` is read through
1786
+ * `URLSearchParams` into a record whose repeated field keeps its last value,
1787
+ * and both are scrubbed of prototype-pollution keys ({@link scrubPrototype});
1788
+ * any other type decodes as UTF-8 text. The media type matches
1789
+ * case-insensitively and ignores its parameters.
1589
1790
  *
1590
1791
  * A malformed JSON body is total: it decodes rather than throwing, so a handler
1591
1792
  * that must reject one checks for `undefined` itself, and nothing in the returned
@@ -1593,8 +1794,9 @@ async function decompressRequestBody(bytes, encoding, cap) {
1593
1794
  *
1594
1795
  * @param request - The `Request` to read the body from
1595
1796
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1596
- * @returns The parsed JSON value, the raw text, or `undefined` — for an empty
1597
- * body, and for an `application/json` body whose text is not valid JSON
1797
+ * @returns The parsed JSON value, the decoded form record, the raw text, or
1798
+ * `undefined` — for an empty body, and for an `application/json` body whose
1799
+ * text is not valid JSON
1598
1800
  * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1599
1801
  * @throws {HTTPError} When the compressed body is corrupt (400)
1600
1802
  *
@@ -1615,6 +1817,7 @@ async function readBody(request, options) {
1615
1817
  const bareType = contentType === null ? "" : (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase();
1616
1818
  const text = new TextDecoder().decode(bytes);
1617
1819
  if (bareType === "application/json") return scrubPrototype((0, _orkestrel_contract.parseJSON)(text));
1820
+ if (bareType === "application/x-www-form-urlencoded") return scrubPrototype(Object.fromEntries(new URLSearchParams(text)));
1618
1821
  return text;
1619
1822
  }
1620
1823
  /**
@@ -1687,6 +1890,51 @@ async function discoverPort(preferred) {
1687
1890
  throw error;
1688
1891
  }
1689
1892
  }
1893
+ /**
1894
+ * Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the
1895
+ * `Response` constructor admits keeps that status, and every other value renders a 500 whose
1896
+ * message stays hidden unless `expose` is `true`.
1897
+ *
1898
+ * @remarks
1899
+ * The renderer is total: it returns a `Response` for every value and never throws.
1900
+ * - An `HTTPError` whose status the `Response` constructor admits renders that status with its
1901
+ * message as the body, and with no body for a null body status (204, 205, and 304).
1902
+ * - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status
1903
+ * no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a
1904
+ * status that is not an integer). Its body is `Internal Server Error`, or the error's own message
1905
+ * when `expose` is `true` and the value is an `Error`.
1906
+ * - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status
1907
+ * differs from its `status`. The server's boundary reports those values with their
1908
+ * `RequestLine`, except a throw after the peer disconnected, which is no fault and reports
1909
+ * nothing.
1910
+ *
1911
+ * @param error - The thrown value
1912
+ * @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it
1913
+ * carries `Internal Server Error`
1914
+ * @returns The response to send
1915
+ *
1916
+ * @example
1917
+ * ```ts
1918
+ * import { buildErrorResponse, HTTPError } from '@src/server'
1919
+ *
1920
+ * buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404
1921
+ * buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500
1922
+ * buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'
1923
+ * ```
1924
+ */
1925
+ function buildErrorResponse(error, expose) {
1926
+ if (isHTTPError(error)) {
1927
+ const rendered = (0, _orkestrel_contract.attempt)(() => {
1928
+ const status = error.status;
1929
+ const full = (0, _orkestrel_contract.attempt)(() => new Response(error.message, { status }));
1930
+ const response = full.success ? full.value : new Response(null, { status });
1931
+ return response.status === status ? response : void 0;
1932
+ });
1933
+ if (rendered.success && rendered.value !== void 0) return rendered.value;
1934
+ }
1935
+ const message = (0, _orkestrel_contract.attempt)(() => expose && (0, _orkestrel_contract.isError)(error) ? error.message : void 0);
1936
+ return new Response(message.success && (0, _orkestrel_contract.isString)(message.value) ? message.value : "Internal Server Error", { status: 500 });
1937
+ }
1690
1938
  // src/server/Negotiator.ts
1691
1939
  /**
1692
1940
  * Represents the content-negotiation machine over the weighted `Accept` family — a
@@ -1697,9 +1945,10 @@ async function discoverPort(preferred) {
1697
1945
  * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1698
1946
  * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1699
1947
  * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
1700
- * rest of the substrate uses — one parser, never two. `format` reads the
1701
- * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1702
- * the winner — or answers `406 Not Acceptable`.
1948
+ * rest of the substrate uses — one parser, never two. A media type matches
1949
+ * case-insensitively. `format` reads the request `Accept`, negotiates a
1950
+ * {@link FormatHandlerMap}'s keys, and invokes the winner — or answers
1951
+ * `406 Not Acceptable` — and sets `Vary: Accept` on either answer.
1703
1952
  *
1704
1953
  * @example
1705
1954
  * ```ts
@@ -1746,16 +1995,26 @@ var Negotiator = class {
1746
1995
  *
1747
1996
  * @remarks
1748
1997
  * Errors thrown by the negotiated handler propagate unmodified — the
1749
- * server boundary classifies them, never this negotiator.
1998
+ * server boundary classifies them, never this negotiator. The answer is a
1999
+ * copy of the handler's response carrying `Vary: Accept`.
1750
2000
  */
1751
2001
  async format(request, context, handlers) {
1752
2002
  const keys = Object.keys(handlers);
1753
2003
  const header = request.headers.get("accept");
1754
2004
  const type = header === null ? keys[0] : this.negotiate(header, keys);
1755
- if (type === void 0) return new Response("Not Acceptable", { status: 406 });
1756
- const handler = handlers[type];
1757
- if (handler === void 0) return new Response("Not Acceptable", { status: 406 });
1758
- return handler(request, context);
2005
+ const handler = type === void 0 ? void 0 : handlers[type];
2006
+ if (handler === void 0) return new Response("Not Acceptable", {
2007
+ status: 406,
2008
+ headers: { Vary: "Accept" }
2009
+ });
2010
+ const response = await handler(request, context);
2011
+ const headers = new Headers(response.headers);
2012
+ headers.set("Vary", mergeVary(headers.get("vary") ?? void 0, "Accept"));
2013
+ return new Response(response.body, {
2014
+ status: response.status,
2015
+ statusText: response.statusText,
2016
+ headers
2017
+ });
1759
2018
  }
1760
2019
  };
1761
2020
  // src/server/ServerBinding.ts
@@ -1804,9 +2063,9 @@ var ServerBinding = class {
1804
2063
  * bind is pending, and transitions `idle → starting → listening`. A
1805
2064
  * cancelled or expired bind closes its partial server and resets to `idle` for
1806
2065
  * another start. `stop()` transitions
1807
- * to `stopping`: fires a fresh-per-run stop signal so in-flight handlers
2066
+ * to `stopping`: aborts the signal of every in-flight request so handlers
1808
2067
  * observe cancellation (a request that arrives during the drain is served
1809
- * with that signal already aborted), drains in-flight requests and
2068
+ * with its signal already aborted), drains in-flight requests and
1810
2069
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1811
2070
  * busy-loop), then closes → `stopped`. After a clean drain the close
1812
2071
  * destroys every connection that carries no open request exchange, and a
@@ -1818,27 +2077,35 @@ var ServerBinding = class {
1818
2077
  * counted before the close. After an expired drain the close destroys every
1819
2078
  * socket. A `stop()` call made while a stop runs returns that stop's
1820
2079
  * promise. `destroy()` is the idempotent final teardown.
1821
- * - **Per request.** In-flight is tracked (finished on response `finish` or
1822
- * `close`); a `Request` is built through the router's `buildRequest`, its
1823
- * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
1824
- * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1825
- * `buildRequest`'s own abort, armed by request-side and response-side
1826
- * teardown, composes with the server's stop signal through `AbortSignal.any`,
1827
- * so a handler awaiting `request.signal` observes either); `context.state` is built through
1828
- * {@link ServerOptions.state} from the connection facts; the composed
1829
- * middleware onion runs, terminating in `dispatcher.handle`; the result is
1830
- * written back through `sendResponse`.
2080
+ * - **Per request.** The exchange's own `AbortController` joins the
2081
+ * in-flight registry until the response's `close`; the one
2082
+ * `Request` of the exchange is built through the router's `buildRequest`
2083
+ * with that controller's signal, so `request.signal` aborts on a peer
2084
+ * disconnect, on `context.abort(reason)`, or on `stop()`, and no request
2085
+ * signal links to a signal that outlives the exchange; `context.state` is
2086
+ * built through {@link ServerOptions.state} from the connection facts, which
2087
+ * `context.connection` carries as the same object; the composed middleware
2088
+ * onion runs, terminating in `dispatcher.handle`; the result is written
2089
+ * back through `sendResponse`.
1831
2090
  * - **The built-in boundary** wraps the whole per-request chain, including
1832
2091
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1833
2092
  * throw (for example, a malformed `Host` header) to a silent `400` with no
1834
- * `error` emit; everything after (`Request` reconstruction, connection
2093
+ * `error` emit; everything after (connection
1835
2094
  * facts, `state`, the composed onion, and `dispatcher.handle`) runs
1836
- * behind the outer boundary — a thrown `HTTPError` renders as its status +
1837
- * message; any other throw renders `500` (message hidden unless
1838
- * `expose`), `report` is invoked (its own throw swallowed), and `error` is
1839
- * emitted. A server-owned last resort wraps the final `sendResponse`
1840
- * write itself: if even that fails, the connection is destroyed rather
1841
- * than left to escape as an unhandled error.
2095
+ * behind the outer boundary, which renders a throw through
2096
+ * `buildErrorResponse`: an `HTTPError` whose status `Response` admits
2097
+ * keeps that status, with no body for 204, 205, and 304, and every other
2098
+ * throw renders `500` (message hidden unless `expose`). Each fault, every
2099
+ * throw except an `HTTPError` whose status the response carries and a
2100
+ * throw after a peer disconnect the server read first (the peer's FIN or a
2101
+ * reset), reaches `error` and `report` with its
2102
+ * `RequestLine`; a fault on the inner phase's `400` path carries none,
2103
+ * because no `Request` exists there. A `report` that throws or rejects is
2104
+ * contained, except a rejected native promise whose species constructor
2105
+ * cannot build a promise, which reaches `unhandledRejection` (see
2106
+ * `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,
2107
+ * and a terminal catch over the whole exchange, the `400` path included,
2108
+ * holds a throw from any step.
1842
2109
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1843
2110
  * throwing handler is treated as declined and surfaced on `error`, an
1844
2111
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
@@ -1856,6 +2123,7 @@ var Server = class {
1856
2123
  #middleware;
1857
2124
  #upgradeHandlers = [];
1858
2125
  #upgraded = /* @__PURE__ */ new Set();
2126
+ #requests = /* @__PURE__ */ new Set();
1859
2127
  #exchanges = /* @__PURE__ */ new Map();
1860
2128
  #emitter;
1861
2129
  #host;
@@ -1864,14 +2132,13 @@ var Server = class {
1864
2132
  #limit;
1865
2133
  #expose;
1866
2134
  #report;
1867
- #timeouts;
2135
+ #startup;
2136
+ #options;
1868
2137
  #sockets;
1869
2138
  #http;
1870
- #abort = (0, _orkestrel_abort.createAbort)();
1871
2139
  #wakeup = (0, _orkestrel_abort.createAbort)();
1872
2140
  #status = "idle";
1873
2141
  #port;
1874
- #pending = 0;
1875
2142
  #stopping;
1876
2143
  constructor(options) {
1877
2144
  if (!(0, _orkestrel_contract.isFunction)(options.state)) throw new TypeError("ServerOptions.state must be a function");
@@ -1881,9 +2148,14 @@ var Server = class {
1881
2148
  const limit = options.limit ?? 1048576;
1882
2149
  if (!(0, _orkestrel_contract.isFiniteNumber)(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
1883
2150
  const timeouts = options.timeouts ?? {};
1884
- if (timeouts.start !== void 0 && !(0, _orkestrel_timeout.isTimeoutDuration)(timeouts.start)) throw new TypeError("ServerOptions.timeouts.start must be an integer from 0 through 2_147_483_647");
1885
- for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!(0, _orkestrel_contract.isFiniteNumber)(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
1886
- if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
2151
+ for (const [name, value] of Object.entries(timeouts)) {
2152
+ const keepalive = name === "keepalive";
2153
+ if (value !== void 0 && !((0, _orkestrel_timeout.isTimeoutDuration)(value) && (!keepalive || (0, _orkestrel_timeout.isTimeoutDuration)(value + 1e3)))) throw new TypeError(`ServerOptions.timeouts.${name} must be an integer from 0 through ${keepalive ? "2_147_482_647" : "2_147_483_647"}`);
2154
+ }
2155
+ const request = timeouts.request ?? 3e5;
2156
+ const headers = timeouts.headers ?? Math.min(6e4, request);
2157
+ if (request > 0 && headers > request) throw new TypeError("ServerOptions.timeouts.headers must not exceed ServerOptions.timeouts.request (300_000 when omitted) while timeouts.request is positive");
2158
+ const checked = [headers, request].filter((ms) => ms > 0);
1887
2159
  const sockets = options.sockets ?? {};
1888
2160
  for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!(0, _orkestrel_contract.isInteger)(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1889
2161
  this.#id = crypto.randomUUID();
@@ -1896,7 +2168,13 @@ var Server = class {
1896
2168
  this.#limit = limit;
1897
2169
  this.#expose = options.expose ?? false;
1898
2170
  this.#report = options.report;
1899
- this.#timeouts = timeouts;
2171
+ this.#startup = timeouts.start;
2172
+ this.#options = {
2173
+ headersTimeout: headers,
2174
+ requestTimeout: request,
2175
+ ...timeouts.keepalive === void 0 ? {} : { keepAliveTimeout: timeouts.keepalive },
2176
+ ...checked.length === 0 ? {} : { connectionsCheckingInterval: Math.ceil(Math.min(...checked) / 2) }
2177
+ };
1900
2178
  this.#sockets = sockets;
1901
2179
  this.#emitter = new _orkestrel_emitter.Emitter({
1902
2180
  ...options.on === void 0 ? {} : { on: options.on },
@@ -1932,11 +2210,7 @@ var Server = class {
1932
2210
  start(signal) {
1933
2211
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
1934
2212
  this.#status = "starting";
1935
- this.#abort = (0, _orkestrel_abort.createAbort)();
1936
- const server = (0, node_http.createServer)((request, response) => this.#handle(request, response));
1937
- if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1938
- if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
1939
- if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
2213
+ const server = (0, node_http.createServer)(this.#options, (request, response) => this.#handle(request, response));
1940
2214
  if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
1941
2215
  if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1942
2216
  if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
@@ -1959,7 +2233,7 @@ var Server = class {
1959
2233
  this.#emitter.destroy();
1960
2234
  return;
1961
2235
  }
1962
- if (!this.#abort.aborted) this.#abort.abort();
2236
+ for (const exchange of this.#requests) exchange.abort();
1963
2237
  const server = this.#http;
1964
2238
  if (server !== void 0) await this.#close(server, true);
1965
2239
  this.#http = void 0;
@@ -1971,12 +2245,12 @@ var Server = class {
1971
2245
  this.#status = "stopping";
1972
2246
  this.#emitter.emit("stop");
1973
2247
  const server = this.#http;
1974
- this.#abort.abort();
2248
+ for (const exchange of this.#requests) exchange.abort();
1975
2249
  const deadline = (0, _orkestrel_timeout.createTimeout)({ ms: this.#drain });
1976
2250
  deadline.start();
1977
2251
  try {
1978
2252
  await this.#drainPending(deadline.signal);
1979
- const pending = this.#pending;
2253
+ const pending = this.#requests.size;
1980
2254
  const upgraded = this.#upgraded.size;
1981
2255
  this.#emitter.emit("drain", pending, upgraded);
1982
2256
  if (server !== void 0) {
@@ -1999,79 +2273,105 @@ var Server = class {
1999
2273
  message.socket.destroy();
2000
2274
  return;
2001
2275
  }
2002
- const finish = this.#trackStart();
2003
- response.once("finish", finish);
2004
- response.once("close", finish);
2005
- this.#trackExchange(message, response);
2006
- this.#accept(message, response);
2007
- }
2008
- async #accept(message, response) {
2009
- const created = (0, _orkestrel_contract.attempt)(() => (0, _orkestrel_router_server.buildRequest)(message, { response }));
2010
- if (!created.success) {
2011
- await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
2012
- return;
2276
+ const exchange = new AbortController();
2277
+ const disconnect = new AbortController();
2278
+ const release = this.#register(exchange);
2279
+ if (this.#status === "stopping") exchange.abort();
2280
+ const socket = message.socket;
2281
+ response.once("close", () => this.#latch(socket, response, disconnect, release));
2282
+ this.#trackExchange(message, response, () => {
2283
+ this.#latch(socket, response, disconnect, release);
2284
+ exchange.abort();
2285
+ });
2286
+ this.#accept(message, response, exchange, disconnect.signal);
2287
+ }
2288
+ #latch(socket, response, disconnect, release) {
2289
+ const failure = socket.errored;
2290
+ const reset = failure !== null && "code" in failure && failure.code === "ECONNRESET";
2291
+ if (!response.writableEnded && response.errored === null && (socket.readableEnded || reset)) disconnect.abort();
2292
+ release();
2293
+ }
2294
+ async #accept(message, response, exchange, disconnect) {
2295
+ try {
2296
+ const created = (0, _orkestrel_contract.attempt)(() => (0, _orkestrel_router_server.buildRequest)(message, {
2297
+ response,
2298
+ signal: exchange.signal
2299
+ }));
2300
+ if (created.success) await this.#serve(created.value, message, response, exchange, disconnect);
2301
+ else await this.#respond(buildErrorResponse(new HTTPError(400, "invalid request"), false), response);
2302
+ } catch (error) {
2303
+ response.destroy();
2304
+ this.#fault(error, void 0);
2013
2305
  }
2014
- const raw = created.value;
2015
- const method = raw.method;
2016
- const url = new URL(raw.url);
2306
+ }
2307
+ async #serve(request, message, response, exchange, disconnect) {
2308
+ const line = {
2309
+ method: request.method,
2310
+ url: new URL(request.url)
2311
+ };
2017
2312
  const start = performance.now();
2018
2313
  try {
2019
- const linked = (0, _orkestrel_abort.linkSignal)(raw.signal, this.#abort.signal);
2020
- const request = new Request(raw, { signal: linked });
2021
- this.#emitter.emit("request", method, url.pathname);
2314
+ this.#emitter.emit("request", line.method, line.url.pathname);
2315
+ const result = await this.#run(request, line, message, exchange, disconnect);
2316
+ if (await this.#respond(result, response, line, disconnect) && !disconnect.aborted) this.#emitter.emit("response", {
2317
+ method: line.method,
2318
+ pathname: line.url.pathname,
2319
+ status: result.status,
2320
+ ms: Math.round(performance.now() - start)
2321
+ });
2322
+ } catch (error) {
2323
+ response.destroy();
2324
+ this.#fault(error, line);
2325
+ }
2326
+ }
2327
+ async #run(request, line, message, exchange, disconnect) {
2328
+ try {
2022
2329
  const ip = message.socket.remoteAddress;
2023
2330
  const connection = {
2024
2331
  ...ip === void 0 ? {} : { ip },
2025
2332
  encrypted: (0, _orkestrel_router_server.isEncryptedSocket)(message.socket)
2026
2333
  };
2027
2334
  const context = {
2028
- url,
2029
- method,
2335
+ url: line.url,
2336
+ method: line.method,
2030
2337
  state: this.#state(connection),
2031
- body: this.#createBody(request)
2338
+ connection,
2339
+ body: this.#createBody(request),
2340
+ abort: exchange.abort.bind(exchange)
2032
2341
  };
2033
2342
  const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
2034
- await this.#respond(result, response);
2035
- this.#emitter.emit("response", {
2036
- method,
2037
- pathname: url.pathname,
2038
- status: result.status,
2039
- ms: Math.round(performance.now() - start)
2040
- });
2343
+ const status = result.status;
2344
+ if ((0, _orkestrel_contract.isInteger)(status) && status >= 200 && status <= 599) return result;
2345
+ throw new HTTPError(status, `a handler returned status ${String(status)}`);
2041
2346
  } catch (error) {
2042
- const mapped = this.#boundary(error);
2043
- if (!isHTTPError(error)) {
2044
- this.#emitter.emit("error", error, {
2045
- method,
2046
- url
2047
- });
2048
- if (this.#report !== void 0) try {
2049
- this.#report(error, {
2050
- method,
2051
- url
2052
- });
2053
- } catch {}
2054
- }
2055
- await this.#respond(mapped, response);
2056
- this.#emitter.emit("response", {
2057
- method,
2058
- pathname: url.pathname,
2059
- status: mapped.status,
2060
- ms: Math.round(performance.now() - start)
2061
- });
2347
+ return this.#boundary(error, line, disconnect.aborted);
2062
2348
  }
2063
2349
  }
2064
- async #respond(result, response) {
2350
+ async #respond(result, response, line, disconnect) {
2065
2351
  try {
2066
2352
  await (0, _orkestrel_router_server.sendResponse)(result, response);
2067
- } catch {
2353
+ } catch (error) {
2068
2354
  response.destroy();
2355
+ if (disconnect?.aborted !== true) this.#fault(error, line);
2356
+ return false;
2069
2357
  }
2070
- }
2071
- #boundary(error) {
2072
- if (isHTTPError(error)) return new Response(error.message, { status: error.status });
2073
- const message = this.#expose && (0, _orkestrel_contract.isError)(error) ? error.message : "Internal Server Error";
2074
- return new Response(message, { status: 500 });
2358
+ return response.writableFinished;
2359
+ }
2360
+ #boundary(error, line, disconnected) {
2361
+ const rendered = buildErrorResponse(error, this.#expose);
2362
+ const carried = (0, _orkestrel_contract.attempt)(() => isHTTPError(error) && error.status === rendered.status);
2363
+ if (!disconnected && !(carried.success && carried.value)) this.#fault(error, line);
2364
+ return rendered;
2365
+ }
2366
+ #fault(error, line) {
2367
+ if (line === void 0) this.#emitter.emit("error", error);
2368
+ else this.#emitter.emit("error", error, line);
2369
+ const report = this.#report;
2370
+ if (report === void 0) return;
2371
+ const reported = (0, _orkestrel_contract.attempt)(() => report(error, line));
2372
+ if (!reported.success) return;
2373
+ const value = reported.value;
2374
+ (0, _orkestrel_contract.attempt)(() => (0, _orkestrel_contract.isPromise)(value) ? Promise.prototype.then.call(value, void 0, () => void 0) : Promise.resolve(value).catch(() => void 0));
2075
2375
  }
2076
2376
  #onUpgrade(request, socket, head) {
2077
2377
  if (this.#closed) {
@@ -2091,7 +2391,7 @@ var Server = class {
2091
2391
  this.#emitter.emit("upgrade", request, handled);
2092
2392
  }
2093
2393
  async #listen(server, signal) {
2094
- const deadline = this.#timeouts.start === void 0 ? void 0 : (0, _orkestrel_timeout.createTimeout)({ ms: this.#timeouts.start });
2394
+ const deadline = this.#startup === void 0 ? void 0 : (0, _orkestrel_timeout.createTimeout)({ ms: this.#startup });
2095
2395
  const startup = deadline === void 0 ? signal : (0, _orkestrel_abort.linkSignal)(deadline.signal, signal);
2096
2396
  const binding = (0, _orkestrel_abort.createAbort)();
2097
2397
  const relay = startup === void 0 ? void 0 : (0, node_events.addAbortListener)(startup, () => binding.abort(startup.reason));
@@ -2142,7 +2442,7 @@ var Server = class {
2142
2442
  return new Promise((resolve) => {
2143
2443
  server.close(() => resolve());
2144
2444
  if (force) this.#cut(server);
2145
- else for (const [socket, open] of this.#exchanges) if (open === 0) socket.destroy();
2445
+ else for (const [socket, open] of this.#exchanges) if (open.size === 0) socket.destroy();
2146
2446
  });
2147
2447
  }
2148
2448
  #cut(server) {
@@ -2150,25 +2450,27 @@ var Server = class {
2150
2450
  for (const socket of this.#upgraded) socket.destroy();
2151
2451
  }
2152
2452
  #trackConnection(socket) {
2153
- this.#exchanges.set(socket, 0);
2154
- socket.once("close", () => this.#exchanges.delete(socket));
2453
+ const open = /* @__PURE__ */ new Map();
2454
+ this.#exchanges.set(socket, open);
2455
+ socket.once("close", () => {
2456
+ for (const [response, settle] of open) if (response.socket === null) settle();
2457
+ this.#exchanges.delete(socket);
2458
+ });
2155
2459
  }
2156
- async #trackExchange(message, response) {
2460
+ async #trackExchange(message, response, settle) {
2157
2461
  const socket = message.socket;
2158
2462
  const open = this.#exchanges.get(socket);
2159
2463
  if (open === void 0) return;
2160
- this.#exchanges.set(socket, open + 1);
2161
- await Promise.allSettled([(0, node_stream_promises.finished)(message), (0, node_stream_promises.finished)(response)]);
2162
- const left = this.#exchanges.get(socket);
2163
- if (left === void 0) return;
2164
- this.#exchanges.set(socket, left - 1);
2165
- if (left === 1 && this.#closed) socket.destroy();
2464
+ open.set(response, settle);
2465
+ await Promise.all([new Promise((resolve) => message.once("close", resolve)), new Promise((resolve) => response.once("close", resolve))]);
2466
+ open.delete(response);
2467
+ if (open.size === 0 && this.#exchanges.get(socket) === open && this.#closed) socket.destroy();
2166
2468
  }
2167
2469
  get #closed() {
2168
2470
  return this.#status === "stopping" && this.#http?.listening === false;
2169
2471
  }
2170
2472
  get #inflight() {
2171
- return this.#pending + this.#upgraded.size;
2473
+ return this.#requests.size + this.#upgraded.size;
2172
2474
  }
2173
2475
  #enter() {
2174
2476
  if (this.#inflight === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
@@ -2176,14 +2478,11 @@ var Server = class {
2176
2478
  #settle() {
2177
2479
  if (this.#inflight === 0) this.#wakeup.abort();
2178
2480
  }
2179
- #trackStart() {
2481
+ #register(exchange) {
2180
2482
  this.#enter();
2181
- this.#pending += 1;
2182
- const completions = [void 0].values();
2483
+ this.#requests.add(exchange);
2183
2484
  return () => {
2184
- if (completions.next().done) return;
2185
- this.#pending -= 1;
2186
- this.#settle();
2485
+ if (this.#requests.delete(exchange)) this.#settle();
2187
2486
  };
2188
2487
  }
2189
2488
  #trackSocket(socket) {
@@ -2200,6 +2499,42 @@ var Server = class {
2200
2499
  await (0, node_events.once)(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
2201
2500
  }
2202
2501
  };
2502
+ // src/server/Signer.ts
2503
+ /**
2504
+ * Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at
2505
+ * construction and reuses it on every call. Implements exactly {@link SignerInterface}.
2506
+ *
2507
+ * @remarks
2508
+ * The constructor normalizes the secret through {@link normalizeSecret}, so it
2509
+ * throws a {@link ServerError} of code `'SECRET'` for a secret that is not a
2510
+ * string or a list of strings, an empty list, or a list holding a blank entry.
2511
+ * `verify` compares signature bytes only through `timingSafeEqual`, after a
2512
+ * length check.
2513
+ *
2514
+ * @example
2515
+ * ```ts
2516
+ * import { Signer } from '@orkestrel/server'
2517
+ *
2518
+ * const signer = new Signer(['current-secret', 'previous-secret'])
2519
+ * await signer.verify('payload', await signer.sign('payload')) // true
2520
+ * ```
2521
+ */
2522
+ var Signer = class {
2523
+ #keys;
2524
+ constructor(secret) {
2525
+ const [current, ...older] = normalizeSecret(secret);
2526
+ this.#keys = [(0, node_crypto.createSecretKey)(current, "utf8"), ...older.map((entry) => (0, node_crypto.createSecretKey)(entry, "utf8"))];
2527
+ }
2528
+ async sign(message) {
2529
+ const [key] = this.#keys;
2530
+ return (0, _orkestrel_codec.encodeBase64URL)((0, node_crypto.createHmac)("sha256", key).update(message, "utf8").digest());
2531
+ }
2532
+ async verify(message, signature) {
2533
+ const bytes = (0, _orkestrel_codec.decodeBase64URL)(signature);
2534
+ if (bytes === void 0 || bytes.byteLength !== 32) return false;
2535
+ return this.#keys.some((key) => (0, node_crypto.timingSafeEqual)((0, node_crypto.createHmac)("sha256", key).update(message, "utf8").digest(), bytes));
2536
+ }
2537
+ };
2203
2538
  // src/server/Stream.ts
2204
2539
  /**
2205
2540
  * Represents the Server-Sent-Events handle over an open, fetch-standard streaming
@@ -2215,13 +2550,18 @@ var Server = class {
2215
2550
  * wakeup, so the whole handle is one entity rather than a closure over four
2216
2551
  * bindings.
2217
2552
  *
2553
+ * The stream opens with one comment line ({@link serializeComment}), so the
2554
+ * response pump has a first chunk and the headers leave before any event.
2218
2555
  * `write` serializes one message ({@link serializeEvent}), enqueues it, and
2219
- * returns whether the controller still has positive desired size. A producer
2556
+ * returns whether the controller still has positive desired size; on an open
2557
+ * stream it throws the `ServerError` `serializeEvent` raises for a refused
2558
+ * field and enqueues nothing. A producer
2220
2559
  * receiving `false` awaits `drain()`; that promise resolves on the next
2221
2560
  * consumer pull restoring capacity, or on stream closure. `comment` writes a
2222
- * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
2223
- * stream. Every method is a safe no-op once `closed` (ended by `end()`, or
2224
- * the consumer cancelled the stream), so a late write never throws.
2561
+ * `: text` keep-alive line per line of its text, which a conforming SSE parser
2562
+ * ignores; `end` closes the stream. Every method is a safe no-op while `closed`
2563
+ * (ended by `end()`, or the consumer cancelled the stream), so a late write
2564
+ * never throws.
2225
2565
  *
2226
2566
  * The readiness signal reflects only the process-local `ReadableStream`
2227
2567
  * queue — it is not proof that a remote peer consumed bytes. When the response
@@ -2230,8 +2570,9 @@ var Server = class {
2230
2570
  * its buffering. Ignoring the return value preserves an unconditional-enqueue
2231
2571
  * producer. The default stream strategy counts chunks rather than their byte
2232
2572
  * length, so a byte-bounded producer must also cap each message. Return
2233
- * `response` before awaiting a `false` write, because the consumer cannot pull
2234
- * until it receives the response.
2573
+ * `response` before awaiting a `false` write or `drain()`, because the consumer
2574
+ * cannot pull until it receives the response, and the opening comment fills
2575
+ * the queue, so a `drain()` before any write also waits on that pull.
2235
2576
  *
2236
2577
  * @example
2237
2578
  * ```ts
@@ -2277,7 +2618,7 @@ var Stream = class {
2277
2618
  return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
2278
2619
  }
2279
2620
  comment(text) {
2280
- this.#enqueue(`: ${text}\n\n`);
2621
+ this.#enqueue(serializeComment(text));
2281
2622
  }
2282
2623
  drain() {
2283
2624
  const desired = this.#controller?.desiredSize;
@@ -2293,6 +2634,7 @@ var Stream = class {
2293
2634
  }
2294
2635
  #attach(controller) {
2295
2636
  this.#controller = controller;
2637
+ controller.enqueue(this.#encoder.encode(serializeComment("")));
2296
2638
  }
2297
2639
  #pull(controller) {
2298
2640
  if (controller.desiredSize === null || controller.desiredSize <= 0) return;
@@ -2379,6 +2721,27 @@ function createServer(options) {
2379
2721
  return new Server(options);
2380
2722
  }
2381
2723
  /**
2724
+ * Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each
2725
+ * created at this call.
2726
+ *
2727
+ * @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}
2728
+ * @returns A {@link SignerInterface} whose first key signs and whose every key verifies
2729
+ * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,
2730
+ * when the list is empty, or when any entry is blank
2731
+ *
2732
+ * @example
2733
+ * ```ts
2734
+ * import { createSigner, signToken, verifyToken } from '@orkestrel/server'
2735
+ *
2736
+ * const signer = createSigner(['current-secret', 'previous-secret'])
2737
+ * const token = await signToken('session-7f3a', { signer, ttl: 60_000 })
2738
+ * await verifyToken(token, signer) // 'session-7f3a'
2739
+ * ```
2740
+ */
2741
+ function createSigner(secret) {
2742
+ return new Signer(secret);
2743
+ }
2744
+ /**
2382
2745
  * Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose
2383
2746
  * `response` is a fetch-standard streaming `Response` a route returns.
2384
2747
  *
@@ -2408,18 +2771,25 @@ exports.DEFAULT_BODY_LIMIT = DEFAULT_BODY_LIMIT;
2408
2771
  exports.DEFAULT_DECOMPRESSED_LIMIT = DEFAULT_DECOMPRESSED_LIMIT;
2409
2772
  exports.DEFAULT_DRAIN_MS = DEFAULT_DRAIN_MS;
2410
2773
  exports.DEFAULT_ENCODINGS = DEFAULT_ENCODINGS;
2774
+ exports.DEFAULT_HEADERS_TIMEOUT_MS = DEFAULT_HEADERS_TIMEOUT_MS;
2775
+ exports.DEFAULT_REQUEST_TIMEOUT_MS = DEFAULT_REQUEST_TIMEOUT_MS;
2411
2776
  exports.HTTPError = HTTPError;
2412
2777
  exports.HTTP_ERROR_BRAND = HTTP_ERROR_BRAND;
2413
2778
  exports.Negotiator = Negotiator;
2779
+ exports.RANGE_BOUND_PATTERN = RANGE_BOUND_PATTERN;
2414
2780
  exports.REQUEST_ID_PATTERN = REQUEST_ID_PATTERN;
2415
2781
  exports.SERVER_ERROR_BRAND = SERVER_ERROR_BRAND;
2416
2782
  exports.SSE_HEADERS = SSE_HEADERS;
2783
+ exports.SSE_LINE_PATTERN = SSE_LINE_PATTERN;
2417
2784
  exports.Server = Server;
2418
2785
  exports.ServerBinding = ServerBinding;
2419
2786
  exports.ServerError = ServerError;
2787
+ exports.Signer = Signer;
2420
2788
  exports.Stream = Stream;
2789
+ exports.buildErrorResponse = buildErrorResponse;
2421
2790
  exports.clearCookie = clearCookie;
2422
2791
  exports.collectRequestBody = collectRequestBody;
2792
+ exports.compareDigits = compareDigits;
2423
2793
  exports.compose = compose;
2424
2794
  exports.computeBodyETag = computeBodyETag;
2425
2795
  exports.computeClientKey = computeClientKey;
@@ -2428,6 +2798,7 @@ exports.computeIPv6Network = computeIPv6Network;
2428
2798
  exports.computeLanguageQuality = computeLanguageQuality;
2429
2799
  exports.createNegotiator = createNegotiator;
2430
2800
  exports.createServer = createServer;
2801
+ exports.createSigner = createSigner;
2431
2802
  exports.createStream = createStream;
2432
2803
  exports.decodeCookieValue = decodeCookieValue;
2433
2804
  exports.decodeTokenPayload = decodeTokenPayload;
@@ -2448,6 +2819,7 @@ exports.matchMediaType = matchMediaType;
2448
2819
  exports.matchesETag = matchesETag;
2449
2820
  exports.mergeVary = mergeVary;
2450
2821
  exports.negotiateEncoding = negotiateEncoding;
2822
+ exports.normalizeResponse = normalizeResponse;
2451
2823
  exports.normalizeSecret = normalizeSecret;
2452
2824
  exports.parseAcceptHeader = parseAcceptHeader;
2453
2825
  exports.parseCookies = parseCookies;
@@ -2461,9 +2833,12 @@ exports.resolveOrigin = resolveOrigin;
2461
2833
  exports.resolveSecure = resolveSecure;
2462
2834
  exports.resolveSecurityHeader = resolveSecurityHeader;
2463
2835
  exports.scrubPrototype = scrubPrototype;
2836
+ exports.serializeComment = serializeComment;
2464
2837
  exports.serializeCookie = serializeCookie;
2465
2838
  exports.serializeEvent = serializeEvent;
2466
2839
  exports.signToken = signToken;
2840
+ exports.stripOWS = stripOWS;
2841
+ exports.supportsMutation = supportsMutation;
2467
2842
  exports.unwrapETag = unwrapETag;
2468
2843
  exports.verifyToken = verifyToken;
2469
2844
  exports.wrapMiddleware = wrapMiddleware;