@orkestrel/scaffold 0.0.138 → 0.0.139

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  > A typed HTTP server for the `@orkestrel` line: a node-bound `Server` lifecycle entity
4
4
  > that composes a middleware onion around a consumed `@orkestrel/router` dispatcher,
5
- > beside the `HTTPError` vocabulary and a shared substrate for cookies, WebCrypto
5
+ > beside the `HTTPError` vocabulary and a shared substrate for cookies, HMAC-signed
6
6
  > tokens, content negotiation, ETag and Range, security headers, Server-Sent Events,
7
7
  > and the body pipeline.
8
8
 
@@ -62,6 +62,7 @@ Cross-face and substrate usage appear under [Patterns](#patterns).
62
62
  | ------------------ | -------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
63
63
  | `createNegotiator` | function | `() => NegotiatorInterface` | Creates a `NegotiatorInterface` — the reusable content-negotiation machine over the weighted `Accept` family. |
64
64
  | `createServer` | function | `<TState>(options: ServerOptions<TState>) => ServerInterface<TState>` | Creates a `ServerInterface` — the node face's HTTP server facade over a consumed `@orkestrel/router` dispatcher. |
65
+ | `createSigner` | function | `(secret: TokenSecret) => SignerInterface` | Creates a `SignerInterface` that holds one HMAC-SHA256 key per secret, each created at this call. |
65
66
  | `createStream` | function | `(options?: StreamOptions) => SSEStreamInterface` | Creates an `SSEStreamInterface` — a generic Server-Sent-Events stream whose `response` is a fetch-standard streaming `Response` a route returns. |
66
67
 
67
68
  ### Startup ownership
@@ -80,62 +81,72 @@ cleanup finish before the start event is emitted.
80
81
  | Name | Kind | Signature | Summary |
81
82
  | ---------------------------- | ----- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
82
83
  | `DEFAULT_DRAIN_MS` | const | `10000` | Names the default graceful-stop deadline `stop()` gives in-flight requests and claimed upgraded sockets, `10_000` ms. |
84
+ | `DEFAULT_REQUEST_TIMEOUT_MS` | const | `300000` | Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when `timeouts.request` is omitted. |
85
+ | `DEFAULT_HEADERS_TIMEOUT_MS` | const | `60000` | Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the request timeout. |
83
86
  | `DEFAULT_BODY_LIMIT` | const | `1048576` | Names the default maximum request body size `readBody` accepts before a 413, `1_048_576` bytes. |
84
87
  | `DEFAULT_DECOMPRESSED_LIMIT` | const | `16777216` | Names the default maximum decompressed request body size, `16_777_216` bytes — the zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when it transparently decompresses a `Content-Encoding` request body. |
85
88
  | `SSE_HEADERS` | const | `Readonly<Record<string, string>>` | Holds the SSE response headers a `Stream` sets on its response, merged under any caller `headers` so a caller repeating one of these keys replaces its value. |
86
89
  | `REQUEST_ID_PATTERN` | const | `Readonly<RegExp>` | Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID` to match, `^[A-Za-z0-9_-]{1,200}$`. |
90
+ | `RANGE_BOUND_PATTERN` | const | `Readonly<RegExp>` | Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`. |
91
+ | `SSE_LINE_PATTERN` | const | `Readonly<RegExp>` | Defines the line terminators of the SSE wire, `\r\n`, `\r`, and `\n`, which `serializeEvent` and `serializeComment` split text on. |
87
92
  | `COMPRESSIBLE_TYPES` | const | `ReadonlySet<string>` | Holds the bare `Content-Type` values `isCompressibleType` treats as compressible, beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that helper also applies. |
88
93
  | `HTTP_ERROR_BRAND` | const | `unique symbol` | Names the `Symbol.for`-interned brand `HTTPError` carries, `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across package copies. A consumer never sets it by hand. |
89
94
  | `DEFAULT_ENCODINGS` | const | `readonly Encoding[]` | Lists the default `Encoding` content-codings the substrate offers, in preference order — `gzip` then `deflate`. |
90
95
 
91
96
  ### Helpers
92
97
 
93
- | Name | Kind | Signature | Summary |
94
- | ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
95
- | `compose` | function | `<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>) => (request: Request, context: MiddlewareContext<TState>) => Promise<Response>` | Composes an ordered chain of `MiddlewareHandler` layers around a `terminal` handler into one request handler — the frozen middleware seam. |
96
- | `wrapMiddleware` | function | `<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>) => (request: Request, context: MiddlewareContext<TState>) => Promise<Response>` | Wraps one middleware layer around its downstream handler, enforcing the one-call `next` invariant. |
97
- | `parseCookies` | function | `(header: string \| undefined) => Record<string, string>` | Parses a raw `Cookie:` request header into a `name → value` lookup. |
98
- | `isCookieName` | function | `(value: string) => boolean` | Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of cookie-token characters with no surrounding or interior whitespace. |
99
- | `decodeCookieValue` | function | `(raw: string) => string` | Decodes a cookie value with `decodeURIComponent`, falling back to the raw text when the value is not valid percent-encoding. |
100
- | `isCookieAttribute` | function | `(value: string) => boolean` | Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value — the guard `serializeCookie` applies to a `Domain` and a `Path` before it emits them. |
101
- | `serializeCookie` | function | `(name: string, value: string, options?: CookieOptions) => string` | Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes. |
102
- | `resolveSecure` | function | `(secure: boolean \| undefined, encrypted: boolean) => boolean` | Resolves a cookie's effective `Secure` flag from its `CookieOptions` `secure` setting and whether the request arrived over TLS. |
103
- | `writeSignedCookie` | function | `(headers: Headers, name: string, value: string, secret: TokenSecret, options?: CookieOptions) => Promise<void>` | Writes a signed cookie — HMAC-signs `value` with `signToken` and appends it as a `Set-Cookie` (the inverse of `readSignedCookie`). |
104
- | `readSignedCookie` | function | `(request: Request, name: string, secret: TokenSecret) => Promise<string \| undefined>` | Reads and verifies a signed cookie off a request — total, returning the embedded value or `undefined` (the inverse of `writeSignedCookie`). |
105
- | `clearCookie` | function | `(headers: Headers, name: string, options?: CookieOptions) => void` | Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`). |
106
- | `signToken` | function | `(value: string, options: TokenOptions) => Promise<string>` | Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`. |
107
- | `verifyToken` | function | `(token: string, secret: TokenSecret) => Promise<string \| undefined>` | Verifies a stateless token and returns its embedded value — total, never throws. |
108
- | `decodeTokenPayload` | function | `(encoded: string) => string \| undefined` | Decodes and narrows a signed token's base64url JSON payload, honoring its expiry — the shared decode step `verifyToken` applies after a signature match. |
109
- | `normalizeSecret` | function | `(secret: TokenSecret) => readonly string[]` | Normalizes a `TokenSecret` to a concrete list of usable secrets — the list behind both `signToken` and `verifyToken`. |
110
- | `parseAcceptHeader` | function | `(header: string) => readonly AcceptEntry[]` | Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header into its q-sorted entries. |
111
- | `computeCodingQuality` | function | `(entries: readonly AcceptEntry[], coding: string) => number` | Computes the client's quality (q) for one content-coding from the parsed `Accept-Encoding` entries — the scoring leaf `resolveCoding` runs over each offered coding. |
112
- | `resolveCoding` | function | `<T extends string>(entries: readonly AcceptEntry[], available: readonly T[]) => T \| undefined` | Picks the highest-scoring content-coding the server offers against already parsed `Accept-Encoding` entries — the shared selection leaf behind `negotiateEncoding` and a `Negotiator`'s `encoding` axis. |
113
- | `negotiateEncoding` | function | `<T extends string>(header: string, available: readonly T[]) => T \| undefined` | Selects the best content-coding for a raw `Accept-Encoding` header from the codings the server offers. |
114
- | `matchMediaType` | function | `(entries: readonly AcceptEntry[], candidate: string) => MediaMatch \| undefined` | Reports the rank and quality of one `candidate` media type against the parsed `Accept` entries — the generic media-type primitive the `Negotiator`'s `negotiate` uses to score each `available` candidate. |
115
- | `computeLanguageQuality` | function | `(entries: readonly AcceptEntry[], candidate: string) => number` | Computes the client's quality for one `candidate` language from the parsed `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language` axis runs over each offered tag. |
116
- | `isCompressibleType` | function | `(type: string) => boolean` | Checks whether a `Content-Type` is worth compressing. |
117
- | `computeBodyETag` | function | `(body: Uint8Array<ArrayBuffer>, weak?: boolean) => Promise<string>` | Computes a content `ETag` over a fully-buffered response body by using WebCrypto. |
118
- | `unwrapETag` | function | `(tag: string) => string` | Strips the weak indicator (`W/`) from an entity-tag, returning its opaque comparison body — the reduction `matchesETag` applies to each side before the RFC 7232 §2.3.2 weak comparison. |
119
- | `matchesETag` | function | `(header: string, etag: string) => boolean` | Checks whether a request's `If-None-Match` header matches a resource's current `ETag` — the RFC 7232 §2.3.2 weak comparison. |
120
- | `parseRange` | function | `(header: string \| undefined, size: number) => RangeSpec \| undefined` | Parses an HTTP `Range` request header against a known resource `size` — total, returning a `RangeSpec` or `undefined`. |
121
- | `resolveOrigin` | function | `(origin: string \| readonly string[], requestOrigin: string \| undefined) => string \| undefined` | Resolves the `Access-Control-Allow-Origin` value for a request. |
122
- | `mergeVary` | function | `(existing: string \| undefined, value: string) => string` | Merges a `Vary` value into an existing `Vary` header without duplication. |
123
- | `resolveSecurityHeader` | function | `(value: string \| false \| undefined, fallback: string) => string \| undefined` | Resolves one opt-out, value-bearing security header. |
124
- | `isValidRequestId` | function | `(value: string) => boolean` | Checks whether a client-supplied `X-Request-ID` is safe to echo into a response header and `context.state`. |
125
- | `computeIPv6Network` | function | `(address: string) => string \| undefined` | Computes the `/64` network of a full IPv6 address, or `undefined` when the input is not a plain IPv6 address to collapse. |
126
- | `computeClientKey` | function | `(address: string) => string` | Collapses a client IP into its rate-limit bucket key — an IPv6 address to its `/64` network, an IPv4 (or IPv4-mapped) address unchanged. |
127
- | `serializeEvent` | function | `(message: SSEMessage) => string` | Serializes one `SSEMessage` to the SSE wire. |
128
- | `isDangerousKey` | function | `(key: string) => boolean` | Checks whether a key is a prototype-pollution vector — `__proto__`, `constructor`, or `prototype`, each of which can reach and mutate `Object.prototype` when it is assigned onto a normal object. |
129
- | `scrubPrototype` | function | `(value: unknown) => unknown` | Strips the prototype-pollution keys from a parsed value in place, recursively. |
130
- | `collectRequestBody` | function | `(request: Request, limit: number) => Promise<Uint8Array<ArrayBuffer>>` | Collects a `Request` body into a single `Uint8Array`, enforcing a size limit. |
131
- | `parseEncoding` | function | `(header: string \| null) => Exclude<Encoding, 'identity'> \| undefined` | Parses a raw `Content-Encoding` header value into a decompressible `Encoding` — the boundary `readBody` coerces through to decide whether a request body needs transparent decompression. |
132
- | `decompressRequestBody` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number) => Promise<Uint8Array<ArrayBuffer>>` | Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence transparently through `DecompressionStream`, capping the decompressed output — the zip-bomb defense. |
133
- | `readBody` | function | `(request: Request, options?: BodyOptions) => Promise<unknown>` | Collects and decodes a `Request` body — the shared body-collection pipeline surfaced to middleware and handlers as the middleware context's cached `body()`. An empty body and a malformed `application/json` body each decode to `undefined`. |
134
- | `isHTTPError` | function | `(value: unknown) => value is HTTPError` | Narrows an unknown caught value to an `HTTPError`, including a subclass such as `ContentTooLargeError`, and recognizes an instance from another copy of this package through its own identity brand. |
135
- | `isServerError` | function | `(value: unknown) => value is ServerError` | Narrows an unknown caught value to a `ServerError` — the code-bearing refusal of a call the caller programmed. |
136
- | `isAddressInfo` | function | `(value: unknown) => value is AddressInfo` | Checks whether a `node:net` `server.address()` return is the structured `AddressInfo` (carrying a numeric `port`) rather than a pipe `string` or `null` — the total, never-throwing narrow `discoverPort` and the `Server`'s own port resolution read the bound port through. |
137
- | `probePort` | function | `(port: number) => Promise<number>` | Binds and closes a throwaway TCP server to resolve one available port. |
138
- | `discoverPort` | function | `(preferred?: number) => Promise<number>` | Finds a free TCP port — binds a throwaway `node:net` server on a `preferred` port where one is given and on an ephemeral port otherwise, reads the bound port, closes the server, and resolves that port. |
98
+ | Name | Kind | Signature | Summary |
99
+ | ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `compose` | function | `<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>) => (request: Request, context: MiddlewareContext<TState>) => Promise<Response>` | Composes an ordered chain of `MiddlewareHandler` layers around a `terminal` handler into one request handler — the middleware seam. |
101
+ | `wrapMiddleware` | function | `<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>, known?: Map<Response, Response>) => (request: Request, context: MiddlewareContext<TState>) => Promise<Response>` | Wraps one middleware layer around its downstream handler, enforcing the one-call `next` invariant. |
102
+ | `normalizeResponse` | function | `(response: Response, known?: Map<Response, Response>) => Response` | Returns a response whose headers a middleware can set: a copy of `response` when its headers are immutable and its status lies from 200 through 599, and `response` itself otherwise. |
103
+ | `supportsMutation` | function | `(headers: Headers) => boolean` | Checks whether a `Headers` object accepts changes, leaving its entries as they were. |
104
+ | `parseCookies` | function | `(header: string \| undefined) => Record<string, string>` | Parses a raw `Cookie:` request header into a `name → value` lookup. |
105
+ | `isCookieName` | function | `(value: string) => boolean` | Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of cookie-token characters with no surrounding or interior whitespace. |
106
+ | `decodeCookieValue` | function | `(raw: string) => string` | Decodes a cookie value with `decodeURIComponent`, falling back to the raw text when the value is not valid percent-encoding. |
107
+ | `isCookieAttribute` | function | `(value: string) => boolean` | Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value — the guard `serializeCookie` applies to a `Domain` and a `Path` before it emits them. |
108
+ | `serializeCookie` | function | `(name: string, value: string, options?: CookieOptions) => string` | Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes. |
109
+ | `resolveSecure` | function | `(secure: boolean \| undefined, encrypted: boolean) => boolean` | Resolves a cookie's effective `Secure` flag from its `CookieOptions` `secure` setting and whether the request arrived over TLS. |
110
+ | `writeSignedCookie` | function | `(headers: Headers, name: string, value: string, signer: SignerInterface, options?: CookieOptions) => Promise<void>` | Writes a signed cookie — HMAC-signs `value` with `signToken` and appends it as a `Set-Cookie` (the inverse of `readSignedCookie`). |
111
+ | `readSignedCookie` | function | `(request: Request, name: string, signer: SignerInterface) => Promise<string \| undefined>` | Reads and verifies a signed cookie off a request, returning the embedded value or `undefined` (the inverse of `writeSignedCookie`). |
112
+ | `clearCookie` | function | `(headers: Headers, name: string, options?: CookieOptions) => void` | Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`). |
113
+ | `signToken` | function | `(value: string, options: TokenOptions) => Promise<string>` | Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`. |
114
+ | `verifyToken` | function | `(token: string, signer: SignerInterface) => Promise<string \| undefined>` | Verifies a stateless token and returns its embedded value, or `undefined` for a malformed, tampered, or expired token. |
115
+ | `decodeTokenPayload` | function | `(encoded: string) => string \| undefined` | Decodes and narrows a signed token's base64url JSON payload, honoring its expiry — the shared decode step `verifyToken` applies after a signature match. |
116
+ | `normalizeSecret` | function | `(secret: TokenSecret) => readonly [string, ...string[]]` | Normalizes a `TokenSecret` to its `[current, ...older]` list — the list a signer creates its keys from — refusing a malformed secret. |
117
+ | `parseAcceptHeader` | function | `(header: string) => readonly AcceptEntry[]` | Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header into its q-sorted entries. |
118
+ | `computeCodingQuality` | function | `(entries: readonly AcceptEntry[], coding: string) => number` | Computes the client's quality (q) for one content-coding from the parsed `Accept-Encoding` entries — the scoring leaf `resolveCoding` runs over each offered coding. |
119
+ | `resolveCoding` | function | `<T extends string>(entries: readonly AcceptEntry[], available: readonly T[]) => T \| undefined` | Picks the highest-scoring content-coding the server offers against already parsed `Accept-Encoding` entries — the shared selection leaf behind `negotiateEncoding` and a `Negotiator`'s `encoding` axis. |
120
+ | `negotiateEncoding` | function | `<T extends string>(header: string, available: readonly T[]) => T \| undefined` | Selects the best content-coding for a raw `Accept-Encoding` header from the codings the server offers. |
121
+ | `matchMediaType` | function | `(entries: readonly AcceptEntry[], candidate: string) => MediaMatch \| undefined` | Reports the rank and quality of one `candidate` media type against the parsed `Accept` entries — the generic media-type primitive the `Negotiator`'s `negotiate` uses to score each `available` candidate. |
122
+ | `computeLanguageQuality` | function | `(entries: readonly AcceptEntry[], candidate: string) => number` | Computes the client's quality for one `candidate` language from the parsed `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language` axis runs over each offered tag. |
123
+ | `isCompressibleType` | function | `(type: string) => boolean` | Checks whether a `Content-Type` is worth compressing. |
124
+ | `computeBodyETag` | function | `(body: Uint8Array<ArrayBuffer>, weak?: boolean) => Promise<string>` | Computes a content `ETag` over a fully-buffered response body by using WebCrypto. |
125
+ | `unwrapETag` | function | `(tag: string) => string` | Strips the weak indicator (`W/`) from an entity-tag, returning its opaque comparison body — the reduction `matchesETag` applies to each side before the RFC 7232 §2.3.2 weak comparison. |
126
+ | `matchesETag` | function | `(header: string, etag: string) => boolean` | Checks whether a request's `If-None-Match` header matches a resource's current `ETag` — the RFC 7232 §2.3.2 weak comparison. |
127
+ | `parseRange` | function | `(header: string \| undefined, size: number) => RangeSpec \| undefined` | Parses an HTTP `Range` request header against a known resource `size` — total, returning a `RangeSpec` or `undefined`. |
128
+ | `compareDigits` | function | `(left: string, right: string) => number` | Compares two `1*DIGIT` strings by their decimal value, at any length. |
129
+ | `stripOWS` | function | `(text: string) => string` | Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other character — from both ends of a text, in time linear in its length. |
130
+ | `resolveOrigin` | function | `(origin: string \| readonly string[], requestOrigin: string \| undefined) => string \| undefined` | Resolves the `Access-Control-Allow-Origin` value for a request. |
131
+ | `mergeVary` | function | `(existing: string \| undefined, value: string) => string` | Merges a `Vary` value into an existing `Vary` header without duplication. |
132
+ | `resolveSecurityHeader` | function | `(value: string \| false \| undefined, fallback: string) => string \| undefined` | Resolves one opt-out, value-bearing security header. |
133
+ | `isValidRequestId` | function | `(value: string) => boolean` | Checks whether a client-supplied `X-Request-ID` is safe to echo into a response header and `context.state`. |
134
+ | `computeIPv6Network` | function | `(address: string) => string \| undefined` | Computes the `/64` network of a full IPv6 address, or `undefined` when the input is not a plain IPv6 address to collapse. |
135
+ | `computeClientKey` | function | `(address: string) => string` | Collapses a client IP into its rate-limit bucket key — an IPv6 address to its `/64` network, an IPv4 (or IPv4-mapped) address unchanged. |
136
+ | `serializeEvent` | function | `(message: SSEMessage) => string` | Serializes one `SSEMessage` to the SSE wire. |
137
+ | `serializeComment` | function | `(text: string) => string` | Serializes a comment to the SSE wire, one `: ` line per line of `text`. |
138
+ | `isDangerousKey` | function | `(key: string) => boolean` | Checks whether a key is a prototype-pollution vector — `__proto__`, `constructor`, or `prototype`, each of which can reach and mutate `Object.prototype` when it is assigned onto a normal object. |
139
+ | `scrubPrototype` | function | `(value: unknown) => unknown` | Strips the prototype-pollution keys from a parsed value in place, at every depth. |
140
+ | `collectRequestBody` | function | `(request: Request, limit: number) => Promise<Uint8Array<ArrayBuffer>>` | Collects a `Request` body into a single `Uint8Array`, enforcing a size limit. |
141
+ | `parseEncoding` | function | `(header: string \| null) => Exclude<Encoding, 'identity'> \| undefined` | Parses a raw `Content-Encoding` header value into a decompressible `Encoding` — the boundary `readBody` coerces through to decide whether a request body needs transparent decompression. |
142
+ | `decompressRequestBody` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number) => Promise<Uint8Array<ArrayBuffer>>` | Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence transparently through `DecompressionStream`, capping the decompressed output — the zip-bomb defense. |
143
+ | `readBody` | function | `(request: Request, options?: BodyOptions) => Promise<unknown>` | Collects and decodes a `Request` body — the shared body-collection pipeline surfaced to middleware and handlers as the middleware context's cached `body()`. An empty body and a malformed `application/json` body each decode to `undefined`. |
144
+ | `isHTTPError` | function | `(value: unknown) => value is HTTPError` | Narrows an unknown caught value to an `HTTPError`, including a subclass such as `ContentTooLargeError`, and recognizes an instance from another copy of this package through its own identity brand. |
145
+ | `isServerError` | function | `(value: unknown) => value is ServerError` | Narrows an unknown caught value to a `ServerError` — the code-bearing refusal of a call the caller programmed. |
146
+ | `isAddressInfo` | function | `(value: unknown) => value is AddressInfo` | Checks whether a `node:net` `server.address()` return is the structured `AddressInfo` (carrying a numeric `port`) rather than a pipe `string` or `null` — the total, never-throwing narrow `discoverPort` and the `Server`'s own port resolution read the bound port through. |
147
+ | `probePort` | function | `(port: number) => Promise<number>` | Binds and closes a throwaway TCP server to resolve one available port. |
148
+ | `discoverPort` | function | `(preferred?: number) => Promise<number>` | Finds a free TCP port — binds a throwaway `node:net` server on a `preferred` port where one is given and on an ephemeral port otherwise, reads the bound port, closes the server, and resolves that port. |
149
+ | `buildErrorResponse` | function | `(error: unknown, expose: boolean) => Response` | Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the `Response` constructor admits keeps that status, and every other value renders a 500 whose message stays hidden unless `expose` is `true`. |
139
150
 
140
151
  ### Classes
141
152
 
@@ -143,41 +154,43 @@ cleanup finish before the start event is emitted.
143
154
  | ---------------------- | ----- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
144
155
  | `HTTPError` | class | `new (status: number, message: string, context?: Readonly<Record<string, unknown>>) => HTTPError` | Represents an error a handler (or middleware) throws to produce an HTTP response of a specific status. |
145
156
  | `ContentTooLargeError` | class | `new (limit: number) => ContentTooLargeError` | Represents the `HTTPError` thrown when a request body exceeds the body pipeline's size limit — a `413 Content Too Large`. |
146
- | `ServerError` | class | `new (code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>) => ServerError` | Represents the error this package raises when a caller programmed a call the entity refuses, carrying `'STATUS'` or `'NEXT'` as its code. |
157
+ | `ServerError` | class | `new (code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>) => ServerError` | Represents the error this package raises when a caller programmed a call the entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code. |
147
158
  | `Negotiator` | class | `new () => NegotiatorInterface` | Represents the content-negotiation machine over the weighted `Accept` family — a reusable, cross-middleware entity rather than a middleware. Implements exactly `NegotiatorInterface`. |
148
159
  | `Server` | class | `new <TState>(options: ServerOptions<TState>) => ServerInterface<TState>` | Represents the HTTP server facade — an observable `node:http` lifecycle composing this module's own middleware onion around a consumed `@orkestrel/router` dispatcher. Implements exactly `ServerInterface`. |
149
160
  | `Stream` | class | `new (options?: StreamOptions) => SSEStreamInterface` | Represents the Server-Sent-Events handle over an open, fetch-standard streaming `Response`. Implements exactly `SSEStreamInterface`. |
161
+ | `Signer` | class | `new (secret: TokenSecret) => SignerInterface` | Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at construction and reuses it on every call. Implements exactly `SignerInterface`. |
150
162
 
151
163
  ### Types
152
164
 
153
- | Name | Kind | Signature | Summary |
154
- | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
155
- | `MiddlewareContext` | interface | `{ url, method, state, body() }` | Represents the composition context — plain data, one per request, shared by every middleware and, as `state`, by the route handlers behind the dispatcher. |
156
- | `NextFunction` | type | `(request?: Request) => Promise<Response>` | Represents the downstream continuation a `MiddlewareHandler` invokes to run the rest of the onion — guarded so a second call within one invocation rejects. |
157
- | `MiddlewareHandler` | type | `(request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response \| Promise<Response>` | Represents one link in the middleware onion — runs around the rest of the chain. |
158
- | `Connection` | interface | `{ ip?, encrypted }` | Represents the per-request connection facts the server face injects — the only data that genuinely exists solely on the socket, surfaced so middleware and a consumer's `state` factory stay core-pure. |
159
- | `TokenSecret` | type | `string \| readonly string[]` | Represents a secret, or a `[current, ...older]` rotation list, for signing and verifying a stateless, HMAC-signed token. |
160
- | `TokenOptions` | interface | `{ secret, ttl? }` | Options for `signToken` — how a stateless, HMAC-signed token is minted. |
161
- | `CookieOptions` | interface | `{ path?, domain?, maxAge?, httpOnly?, secure?, sameSite? }` | Represents the `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie transport built over it). |
162
- | `AcceptEntry` | interface | `{ value, q }` | Represents one parsed entry of a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header — a value and its quality weight, the element type `parseAcceptHeader` returns (sorted by `q` descending). |
163
- | `MediaMatch` | interface | `{ q, rank }` | Rates one candidate media type against a parsed `Accept` header — the quality and specificity `matchMediaType` reports for the best matching `AcceptEntry`. |
164
- | `Encoding` | type | `'gzip' \| 'deflate' \| 'identity'` | Represents a content-coding the substrate compresses or decompresses with. Its members are the `Content-Encoding` and `Accept-Encoding` token vocabulary the substrate understands. |
165
- | `FormatHandlerMap` | type | `Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response \| Promise<Response>>>` | Represents a map of media type → handler for `NegotiatorInterface.format` — the content-negotiation dispatch table. |
166
- | `NegotiatorInterface` | interface | `{ negotiate(), encoding(), language(), format() }` | Represents content negotiation over the weighted `Accept` family — a reusable, cross-middleware machine (not itself a middleware). |
167
- | `SSEMessage` | interface | `{ data, event?, id?, retry? }` | Represents one Server-Sent Event to serialize to the wire. |
168
- | `StreamOptions` | interface | `{ status?, headers? }` | Options for an `SSEStreamInterface` — how `createStream` opens the streaming response. |
169
- | `SSEStreamInterface` | interface | `{ response, closed, write(), comment(), drain(), end() }` | Represents a handle to write Server-Sent Events to an open, fetch-standard streaming `Response` — the generic streaming surface `createStream` returns over a `ReadableStream`. |
170
- | `RangeSpec` | type | `{ readonly satisfiable: true; readonly start: number; readonly end: number; } \| { readonly satisfiable: false; }` | Represents the parsed outcome of an HTTP `Range` request header. |
171
- | `BodyOptions` | interface | `{ limit?, decompression? }` | Options for `readBody` — how the shared body-collection pipeline caps and decompresses a request body. |
172
- | `ServerStatus` | type | `'idle' \| 'starting' \| 'listening' \| 'stopping' \| 'stopped'` | Represents the `Server`'s lifecycle state. |
173
- | `ServerErrorCode` | type | `'STATUS' \| 'NEXT'` | Represents the machine-readable category a `ServerError` carries — `'STATUS'` for a lifecycle call the current status forbids, `'NEXT'` for a middleware that called its `next` a second time. |
174
- | `RequestLine` | interface | `{ method, url }` | Identifies the request a server-level fault came from — its method and its parsed URL. |
175
- | `ResponseRecord` | interface | `{ method, pathname, status, ms }` | Records one finished request — the payload `ServerEventMap.response` carries. |
176
- | `ServerEventMap` | type | `{ readonly start: readonly [port: number]; readonly request: readonly [method: string, pathname: string]; readonly upgrade: readonly [request: IncomingMessage, handled: boolean]; readonly error: readonly [error: unknown, request?: RequestLine]; readonly stop: readonly []; readonly drain: readonly [pending: number, upgraded: number]; readonly response: readonly [event: ResponseRecord]; }` | Represents the `Server`'s observable lifecycle events. |
177
- | `UpgradeHandler` | type | `(request: IncomingMessage, socket: Duplex, head: Buffer) => boolean` | Represents a raw `node:http` protocol-upgrade claimant — registered through `ServerInterface.upgrade`. |
178
- | `ConnectionStateFunction` | type | `(connection: Connection) => TState` | Derives a consumer's per-request `TState` from the adapter-injected `Connection` — `ServerOptions.state`, invoked once per request before the middleware onion runs. |
179
- | `ServerOptions` | interface | `{ dispatcher, state, middleware?, host?, port?, drain?, limit?, expose?, report?, timeouts?, sockets?, on?, error? }` | Options for `createServer` — the dispatcher and per-request state factory the server requires, plus its listener, drain, boundary, timeout, socket-cap, and emitter knobs. |
180
- | `ServerInterface` | interface | `{ id, status, port, address, dispatcher, emitter, use(), upgrade(), start(), stop(), destroy() }` | Represents the HTTP server facade — an observable `node:http` lifecycle that composes a middleware onion (this module's own middleware seam) around a consumed `@orkestrel/router` `DispatcherInterface`. |
165
+ | Name | Kind | Signature | Summary |
166
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
167
+ | `MiddlewareContext` | interface | `{ url, method, state, connection, body(), abort() }` | Represents the composition context — plain data, one per request, shared by every middleware and, as `state`, by the route handlers behind the dispatcher. |
168
+ | `NextFunction` | type | `() => Promise<Response>` | Represents the downstream continuation a `MiddlewareHandler` invokes to run the rest of the onion — guarded so a second call within one invocation rejects. |
169
+ | `MiddlewareHandler` | type | `(request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response \| Promise<Response>` | Represents one link in the middleware onion — runs around the rest of the chain. |
170
+ | `Connection` | interface | `{ ip?, encrypted }` | Represents the per-request connection facts the server face injects — the only data that genuinely exists solely on the socket, surfaced so middleware and a consumer's `state` factory stay core-pure. |
171
+ | `TokenSecret` | type | `string \| readonly string[]` | Represents a secret, or a `[current, ...older]` rotation list, for signing and verifying a stateless, HMAC-signed token. |
172
+ | `SignerInterface` | interface | `{ sign(), verify() }` | Represents an HMAC-SHA256 signer over the keys of one `TokenSecret`, held in `[current, ...older]` order. |
173
+ | `TokenOptions` | interface | `{ signer, ttl? }` | Options for `signToken` — how a stateless, HMAC-signed token is minted. |
174
+ | `CookieOptions` | interface | `{ path?, domain?, maxAge?, httpOnly?, secure?, sameSite? }` | Represents the `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie transport built over it). |
175
+ | `AcceptEntry` | interface | `{ value, q }` | Represents one parsed entry of a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header — a value and its quality weight, the element type `parseAcceptHeader` returns (sorted by `q` descending). |
176
+ | `MediaMatch` | interface | `{ q, rank }` | Rates one candidate media type against a parsed `Accept` header — the quality and specificity `matchMediaType` reports for the best matching `AcceptEntry`. |
177
+ | `Encoding` | type | `'gzip' \| 'deflate' \| 'identity'` | Represents a content-coding the substrate compresses or decompresses with. Its members are the `Content-Encoding` and `Accept-Encoding` token vocabulary the substrate understands. |
178
+ | `FormatHandlerMap` | type | `Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response \| Promise<Response>>>` | Represents a map of media type → handler for `NegotiatorInterface.format` — the content-negotiation dispatch table. |
179
+ | `NegotiatorInterface` | interface | `{ negotiate(), encoding(), language(), format() }` | Represents content negotiation over the weighted `Accept` family — a reusable, cross-middleware machine (not itself a middleware). |
180
+ | `SSEMessage` | interface | `{ data, event?, id?, retry? }` | Represents one Server-Sent Event to serialize to the wire. |
181
+ | `StreamOptions` | interface | `{ status?, headers? }` | Options for an `SSEStreamInterface` — how `createStream` opens the streaming response. |
182
+ | `SSEStreamInterface` | interface | `{ response, closed, write(), comment(), drain(), end() }` | Represents a handle to write Server-Sent Events to an open, fetch-standard streaming `Response` — the generic streaming surface `createStream` returns over a `ReadableStream`. |
183
+ | `RangeSpec` | type | `{ readonly satisfiable: true; readonly start: number; readonly end: number; } \| { readonly satisfiable: false; }` | Represents the parsed outcome of an HTTP `Range` request header. |
184
+ | `BodyOptions` | interface | `{ limit?, decompression? }` | Options for `readBody` — how the shared body-collection pipeline caps and decompresses a request body. |
185
+ | `ServerStatus` | type | `'idle' \| 'starting' \| 'listening' \| 'stopping' \| 'stopped'` | Represents the `Server`'s lifecycle state. |
186
+ | `ServerErrorCode` | type | `'STATUS' \| 'NEXT' \| 'EVENT' \| 'SECRET'` | Represents the machine-readable category a `ServerError` carries — `'STATUS'` for a forbidden lifecycle call, `'NEXT'` for a second `next` call or one with an argument, `'EVENT'` for an SSE field the wire cannot carry, `'SECRET'` for a malformed signer secret. |
187
+ | `RequestLine` | interface | `{ method, url }` | Identifies the request a server-level fault came from — its method and its parsed URL. |
188
+ | `ResponseRecord` | interface | `{ method, pathname, status, ms }` | Records one finished request — the payload `ServerEventMap.response` carries. |
189
+ | `ServerEventMap` | type | `{ readonly start: readonly [port: number]; readonly request: readonly [method: string, pathname: string]; readonly upgrade: readonly [request: IncomingMessage, handled: boolean]; readonly error: readonly [error: unknown, request?: RequestLine]; readonly stop: readonly []; readonly drain: readonly [pending: number, upgraded: number]; readonly response: readonly [event: ResponseRecord]; }` | Represents the `Server`'s observable lifecycle events. |
190
+ | `UpgradeHandler` | type | `(request: IncomingMessage, socket: Duplex, head: Buffer) => boolean` | Represents a raw `node:http` protocol-upgrade claimant — registered through `ServerInterface.upgrade`. |
191
+ | `ConnectionStateFunction` | type | `(connection: Connection) => TState` | Derives a consumer's per-request `TState` from the adapter-injected `Connection` — `ServerOptions.state`, invoked once per request before the middleware onion runs. |
192
+ | `ServerOptions` | interface | `{ dispatcher, state, middleware?, host?, port?, drain?, limit?, expose?, report?, timeouts?, sockets?, on?, error? }` | Options for `createServer` — the dispatcher and per-request state factory the server requires, plus its listener, drain, boundary, timeout, socket-cap, and emitter knobs. |
193
+ | `ServerInterface` | interface | `{ id, status, port, address, dispatcher, emitter, use(), upgrade(), start(), stop(), destroy() }` | Represents the HTTP server facade — an observable `node:http` lifecycle that composes a middleware onion (this module's own middleware seam) around a consumed `@orkestrel/router` `DispatcherInterface`. |
181
194
 
182
195
  Each interface's `readonly` data members stay Surface rows, and its call-signature
183
196
  members are documented under [Methods](#methods). `ServerInterface.address` is the
@@ -197,18 +210,22 @@ The error guards and request readers expose these primitives.
197
210
 
198
211
  ## Methods
199
212
 
200
- The public methods of `NegotiatorInterface`, `SSEStreamInterface`, and
201
- `ServerInterface` — every call-signature member listed (their `readonly` data
202
- members stay Surface rows). `Negotiator`, `Server`, and `Stream` implement
203
- their interfaces exactly, so their tables also double as each class's
204
- instance-method surface.
213
+ The public methods of `NegotiatorInterface`, `SSEStreamInterface`,
214
+ `ServerInterface`, and `SignerInterface` — every call-signature member listed
215
+ (their `readonly` data members stay Surface rows). `Negotiator`, `Server`,
216
+ `Stream`, and `Signer` implement their interfaces exactly, so their tables also
217
+ double as each class's instance-method surface.
205
218
 
206
219
  #### `NegotiatorInterface`
207
220
 
208
221
  `negotiate` is the generic media-type primitive; `encoding` / `language` are
209
222
  its sibling axes over the same q-value parser; `format` is the dispatcher —
210
223
  it reads the request `Accept`, negotiates a `FormatHandlerMap`'s keys, and
211
- invokes the winner, or answers `406`.
224
+ invokes the winner, or answers `406`. A media type matches case-insensitively,
225
+ so a key `Application/JSON` answers `Accept: application/json`. Every `format`
226
+ answer, the `406` included, carries `Vary: Accept` merged into any `Vary` the
227
+ handler set; the handler's response is returned as a copy, so a response with
228
+ immutable headers, such as `Response.redirect`, carries it too.
212
229
 
213
230
  The axes diverge on an absent, empty, or unparseable header. `encoding`
214
231
  resolves to `undefined` — no compression — rather than to the first offered
@@ -224,8 +241,14 @@ coding, because an absent `Accept-Encoding` makes identity the correct answer;
224
241
 
225
242
  #### `SSEStreamInterface`
226
243
 
227
- `write` always accepts an event while open and returns whether the local
228
- `ReadableStream` queue still has positive desired size afterward. A producer
244
+ The stream opens with one comment line, so the response pump has a first chunk
245
+ and the headers leave before the first event. `write` accepts every event
246
+ `serializeEvent` admits while open and returns whether the local
247
+ `ReadableStream` queue still has positive desired size afterward; for an
248
+ `event` or `id` with a line break, an `id` with a NUL, or a `retry` that is not
249
+ a non-negative safe integer, it throws a `ServerError` with code `'EVENT'` and
250
+ enqueues nothing. `comment` writes one comment line per line of its text, so a
251
+ comment never reaches a parser as a field or an event. A producer
229
252
  receiving `false` parks on `drain` before writing again. This is process-local
230
253
  queue state, not proof that the remote peer consumed bytes; the router's
231
254
  drain-honoring response pump makes socket pressure stop pulls so the local
@@ -233,15 +256,16 @@ queue can faithfully signal that transport pressure. Ignoring the boolean
233
256
  preserves the prior unconditional-enqueue behavior. The default queue strategy
234
257
  counts chunks rather than their byte lengths, so a producer needing a byte
235
258
  bound must also cap each individual event. The route must return `response`
236
- before its producer awaits a `false` write, because no consumer can pull the
237
- body before receiving that response.
259
+ before its producer awaits a `false` write or `drain()`, because no consumer
260
+ can pull the body before receiving that response; the opening comment fills
261
+ the queue, so a `drain()` before any write also waits on that pull.
238
262
 
239
263
  | Method | Returns | Summary |
240
264
  | --------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
241
- | `write` | `boolean` | Serializes and enqueues one `SSEMessage` to the wire, reporting whether the process-local queue still has capacity afterward — `false` also once the stream is closed. |
242
- | `comment` | `void` | Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores, and a no-op once the stream is closed. |
265
+ | `write` | `boolean` | Serializes and enqueues one `SSEMessage` to the wire, reporting whether the process-local queue still has capacity afterward — `false` also after the stream closes. |
266
+ | `comment` | `void` | Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores, and a no-op after the stream closes. |
243
267
  | `drain` | `Promise<void>` | Parks until the process-local stream queue has capacity again — resolving on the consumer pull that restores it, or immediately when capacity is already available or the stream is closed, and never polling. |
244
- | `end` | `void` | Ends the stream, completing the response — a no-op once already `closed`, and it settles any parked producer. |
268
+ | `end` | `void` | Ends the stream, completing the response — a no-op after the stream closes, and it settles any parked producer. |
245
269
 
246
270
  #### `ServerInterface`
247
271
 
@@ -253,13 +277,33 @@ terminal, idempotent teardown. An upgraded socket a handler claimed never holds
253
277
  `stop` or `destroy` forever: the `stop` method drains it up to the `drain`
254
278
  deadline and then destroys it, and the `destroy` method destroys it at once.
255
279
 
256
- | Method | Returns | Summary |
257
- | --------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
258
- | `use` | `void` | Appends one middleware, or an array of them in order, to the onion, outer-to-inner in call order. |
259
- | `upgrade` | `void` | Registers an `UpgradeHandler` claimant that runs in registration order; a claimed socket is tracked until it closes. |
260
- | `start` | `Promise<number>` | Binds the configured `host` and `port`, or an ephemeral port, under an optional caller `AbortSignal`, and resolves the actually-bound port. |
261
- | `stop` | `Promise<void>` | Stops gracefully within the `drain` deadline: fires the stop signal, drains in-flight requests and claimed upgraded sockets, then closes the listener; after a clean drain it ends each connection when no request exchange is open on it, and when the deadline expires it destroys every socket still open. |
262
- | `destroy` | `Promise<void>` | Tears down for good: force-closes the listener and every socket, then the emitter — terminal and idempotent from any state. |
280
+ | Method | Returns | Summary |
281
+ | --------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
282
+ | `use` | `void` | Appends one middleware, or an array of them in order, to the onion, outer-to-inner in call order. |
283
+ | `upgrade` | `void` | Registers an `UpgradeHandler` claimant that runs in registration order; a claimed socket is tracked until it closes. |
284
+ | `start` | `Promise<number>` | Binds the configured `host` and `port`, or an ephemeral port, under an optional caller `AbortSignal`, and resolves the actually-bound port. |
285
+ | `stop` | `Promise<void>` | Stops gracefully within the `drain` deadline: aborts every in-flight request's signal, drains in-flight requests and claimed upgraded sockets, then closes the listener; after a clean drain it ends each connection when no request exchange is open on it, and when the deadline expires it destroys every socket still open. |
286
+ | `destroy` | `Promise<void>` | Tears down for good: force-closes the listener and every socket, then the emitter — terminal and idempotent from any state. |
287
+
288
+ #### `SignerInterface`
289
+
290
+ `sign` uses the first key; `verify` walks the keys in `[current, ...older]`
291
+ order and returns at the first match. Neither creates a key: `createSigner`
292
+ creates every key at construction.
293
+
294
+ ```ts
295
+ import { createSigner } from '@orkestrel/server'
296
+
297
+ const signer = createSigner(['current-secret', 'previous-secret'])
298
+ const signature = await signer.sign('payload')
299
+ await signer.verify('payload', signature) // true
300
+ await signer.verify('payload', 'not-a-signature') // false — refused before any key is read
301
+ ```
302
+
303
+ | Method | Returns | Summary |
304
+ | -------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
305
+ | `sign` | `Promise<string>` | Signs `message` with the first (current) key — the base64url HMAC-SHA256 of its UTF-8 bytes. |
306
+ | `verify` | `Promise<boolean>` | Checks whether `signature` is the canonical base64url HMAC-SHA256 of `message` under any held key, walking the keys in order and returning at the first match. |
263
307
 
264
308
  ## Contract
265
309
 
@@ -270,22 +314,23 @@ These invariants hold across `src/server` ↔ `server.md`.
270
314
  source directory, and every export appears as a Surface row — exhaustive,
271
315
  both directions.
272
316
  2. **Doc ↔ source method bijection.** The `## Methods` tables list exactly
273
- `NegotiatorInterface`'s, `SSEStreamInterface`'s, and `ServerInterface`'s public
274
- methods — exhaustive, both directions — and `Negotiator` / `Stream` /
275
- `Server` expose the same public methods, no more.
317
+ `NegotiatorInterface`'s, `SSEStreamInterface`'s, `ServerInterface`'s, and
318
+ `SignerInterface`'s public methods — exhaustive, both directions — and
319
+ `Negotiator` / `Stream` / `Server` / `Signer` expose the same public methods,
320
+ no more.
276
321
  3. **Status machine + bound address + restart-fresh-abort.**
277
322
  `idle → starting → listening → stopping → stopped`; `start()` from
278
323
  `listening`/`starting`/`stopping` rejects with a `ServerError` of code
279
324
  `'STATUS'`, carrying that status in its `context` and narrowed by
280
- `isServerError`; each `start()` mints a fresh stop signal, so a restarted
281
- server is never born aborted; `address` is the real bound `AddressInfo`
325
+ `isServerError`; a request served by a restarted server is never born
326
+ aborted; `address` is the real bound `AddressInfo`
282
327
  after a successful start and `undefined` before start and after stop or
283
328
  destroy; `stop()`/`destroy()` are idempotent no-ops from a state with
284
329
  nothing to tear down, so a `stop()` call from `idle`, `starting`, or
285
330
  `stopped` while no stop runs resolves at once; a `stop()` call made while
286
331
  a stop runs returns that stop's promise and resolves with it after the
287
332
  close, including a call made from a `stop` event listener or from a
288
- listener on the stop signal; `EADDRINUSE` rejects `start()` outright — no
333
+ listener on an aborted request signal; `EADDRINUSE` rejects `start()` outright — no
289
334
  silent ephemeral fallback (use `discoverPort` up front for a
290
335
  guaranteed-free port). A `start()` call made after `destroy()` while an
291
336
  earlier `stop()` call has not yet resolved can be reset to `stopped` when
@@ -300,17 +345,17 @@ These invariants hold across `src/server` ↔ `server.md`.
300
345
  with that signal's `reason`. A later `start()` is therefore permitted.
301
346
  Aborting the caller signal after a successful start does not stop a live
302
347
  server.
303
- 5. **Graceful drain is event-driven, never a busy-loop.** `stop()` fires the
304
- stop signal, arms a `@orkestrel/timeout` deadline, and parks on the
348
+ 5. **Graceful drain is event-driven, never a busy-loop.** `stop()` aborts
349
+ every in-flight request's signal, arms a `@orkestrel/timeout` deadline, and parks on the
305
350
  drainable count reaching zero or the deadline firing (a wake-park, not
306
351
  polling); it then emits `drain` with the still-pending counts and closes
307
352
  the listener. The server counts the open request exchanges on each
308
353
  connection, because a pipelining client can hold several: an exchange
309
354
  opens when a request reaches the handler and stays open until its request
310
- message has ended or closed and its response has finished or closed.
311
- The `error` listeners that this tracking attaches to the message and the
312
- response stay attached, so a later error on either raises no uncaught
313
- exception.
355
+ message and its response have closed, which each does after it ends or is
356
+ destroyed. The server attaches one `close` listener to the message and two
357
+ to the response, for this count and the in-flight registry, and each
358
+ leaves when it fires, so none outlives the exchange.
314
359
  After a clean drain the close destroys every connection with no open
315
360
  exchange. That covers an idle keep-alive connection. It covers a
316
361
  connection that never sent a request: Node doesn't count it as idle, and
@@ -323,9 +368,10 @@ These invariants hold across `src/server` ↔ `server.md`.
323
368
  while its body still uploads: destroying it can reset the connection and
324
369
  lose that response. The server ends that connection when its last
325
370
  exchange completes, and the `stop()` call resolves after that connection
326
- closes. Each body byte restarts Node's keep-alive socket timer, so no Node
327
- timeout bounds an upload that keeps sending. The deadline that bounds the
328
- drain therefore stays armed through the clean close's wait: when it
371
+ closes. Node's `request` timeout bounds an upload that keeps sending after
372
+ its response, unless `timeouts.request` is `0`, when no Node timeout bounds
373
+ it. The deadline that bounds the drain therefore stays armed through the
374
+ clean close's wait: when it
329
375
  expires before the server's `close` event, the server destroys every
330
376
  socket still open, as an expired drain does, so no connection holds the
331
377
  `stop()` call past the `drain` deadline. The `drain` event has already
@@ -381,27 +427,69 @@ These invariants hold across `src/server` ↔ `server.md`.
381
427
  `report` call, and no `response` emit, because nothing downstream ever ran
382
428
  and no parsed `Request` exists yet to derive its facts from. The outer
383
429
  phase covers everything after — a throwing `this.#state(connection)`
384
- through the middleware/dispatcher run — where a thrown `HTTPError` renders
385
- as its own status + message; any
386
- other throw renders `500` with its message hidden unless `expose` is set,
387
- `report` is invoked with the caught error plus the originating request's
388
- `{ method, url }` (its own throw swallowed so reporting can never crash
389
- the response), and `error` is emitted with that same `{ method, url }` as
390
- its second argument. Beneath this single seam sits one server-owned last
391
- resort: if writing the mapped response itself throws, the connection is
392
- destroyed rather than left half-written or crashing the process — the
393
- middleware package may still ship a richer boundary that short-circuits
394
- earlier. On both the success path and this outer-boundary error path, a
395
- `response` event fires once the response has been sent, carrying
396
- `{ method, pathname, status, ms }` — so observability covers every request
397
- that reached the middleware pipeline, exactly once, regardless of outcome.
398
- A request rejected at the inner `buildRequest` boundary is the one
399
- exception: it emits no `response` at all.
430
+ through the middleware/dispatcher run — and renders a throw through
431
+ `buildErrorResponse`, the one renderer a middleware boundary can call too:
432
+ - A thrown `HTTPError` whose status `Response` admits renders as its own
433
+ status and message, and a null body status (204, 205, or 304) renders
434
+ with no body.
435
+ - Any other throw renders `500` with its message hidden unless `expose` is
436
+ set. That includes an `HTTPError` whose status no `Response` carries,
437
+ such as 101, 600, `NaN`, or 200.5, and a returned response whose status
438
+ lies outside 200 through 599, such as the 0 of `Response.error()`.
439
+ - Each fault reaches the `error` event and the `report` sink once, with the
440
+ same `(error, RequestLine)`: every throw except an `HTTPError` whose
441
+ status the response carries and a throw after a peer disconnect the
442
+ server read before the throw. A
443
+ fault on the inner phase's `400` path, a failed write included, reaches
444
+ both with no `RequestLine`, because no `Request` exists there.
445
+ - A `report` sink that throws, or returns a promise that rejects, is
446
+ contained, and the response still goes out. A rejected native promise
447
+ whose species constructor cannot build a promise stays out of reach:
448
+ its `constructor` lookup throws or yields a value that is neither
449
+ `undefined` nor an object, its `Symbol.species` lookup throws or yields
450
+ a value that is neither `undefined`, `null`, nor a constructor, or that
451
+ constructor throws or never passes its executor callable resolve and
452
+ reject functions. Such a promise refuses every reaction, so its
453
+ rejection reaches `unhandledRejection`, which ends the process under
454
+ Node's default unhandled-rejection mode.
455
+ - A write that fails, at a header Node refuses or in the body after the
456
+ headers went out, destroys the connection, so the client reads an abort,
457
+ and is a fault, unless the peer disconnected first.
458
+ - A peer disconnect the server read before the throw, the peer's FIN or a
459
+ reset, is no fault: a throw after it emits no `error` and calls no
460
+ `report`. A `stop()` cut, `destroy()`, and Node's 408 close are no peer
461
+ disconnect, so a throw after one is a fault. A peer disconnect the server
462
+ never read is reported the same way: a peer that leaves while the route
463
+ leaves its body unread, under `timeouts.request: 0`, is a fault. A queued
464
+ exchange of a pipelining client, whose response Node never closes, settles
465
+ when its connection closes: its `request.signal` aborts, and a throw after a
466
+ peer disconnect is no fault.
467
+ - A terminal catch over the whole exchange, the inner phase's `400`
468
+ included, holds a throw from any step, the renderer and the write
469
+ included, so no exchange rejects.
470
+
471
+ A `response` event fires once for each response that finished, carrying
472
+ `{ method, pathname, status, ms }`: `status` is the status the server
473
+ wrote, and `ms` is the time from the exchange's acceptance to the last
474
+ byte of its body, in whole milliseconds. `response` fires after Node hands
475
+ the last byte to the operating system, so a peer that resets before it reads
476
+ the answer leaves the record. A response whose peer disconnected
477
+ first, a body-less answer included, a failed write, and the inner phase's
478
+ `400` fire none. An exchange the server aborted through `context.abort` and
479
+ then answered still fires one.
480
+
481
+ In 0.0.28, the boundary rendered every thrown `HTTPError` with its own
482
+ status, so a status the `Response` constructor refuses, such as 101 or
483
+ 600, threw out of the boundary and nothing caught it. `report` received
484
+ only a throw that was not an `HTTPError`, and a promise it returned went
485
+ unhandled. A failed write destroyed the connection with no `error` emit
486
+ and no `report` call, and it still fired `response`.
487
+
400
488
  7. **Upgrade fan-out is isolated, first-claimer-wins.** Registered
401
489
  `UpgradeHandler`s run in registration order; the first to return `true`
402
490
  claims the socket and stops the fan-out; a handler that throws is treated as
403
491
  declined (the throw surfaces on `error` with no request context — `error`'s
404
- second argument is `undefined` on the upgrade path, since no fetch
492
+ second argument is `undefined` on the upgrade path, because no fetch
405
493
  `Request` exists there, only a raw `IncomingMessage` — and never crashes
406
494
  the process) and the fan-out continues; an upgrade nothing claims destroys
407
495
  the socket so it never leaks a dangling connection. A claimed socket is
@@ -414,50 +502,132 @@ These invariants hold across `src/server` ↔ `server.md`.
414
502
  `limit`), transparently decompresses a `gzip`/`deflate` body through a
415
503
  byte-counting `TransformStream` that aborts the instant decompressed output
416
504
  would exceed `decompression` (fail before materializing a decompression
417
- bomb, since `DecompressionStream` has no `maxOutputLength`), and scrubs
418
- `__proto__`/`constructor`/`prototype` keys from a parsed JSON body
419
- (`scrubPrototype`) before it is ever handed to application code.
505
+ bomb, because `DecompressionStream` has no `maxOutputLength`), decodes an
506
+ `application/x-www-form-urlencoded` body to a record whose repeated field
507
+ keeps its last value, and scrubs `__proto__`/`constructor`/`prototype` keys
508
+ from a parsed JSON or urlencoded body (`scrubPrototype`) before it is ever
509
+ handed to application code. The scrub walks a worklist rather than the call
510
+ stack, so a JSON body nested as deep as `limit` admits decodes without a
511
+ stack overflow; any other content type decodes to text.
420
512
  9. **Cookie + token jewels preserved.** `parseCookies` rejects a
421
513
  whitespace-padded name so a `' __Host-x'` never reconciles into a
422
- protected `__Host-` name; `serializeCookie` throws on a `Domain`/`Path`
514
+ protected `__Host-` name, and returns a null-prototype record, so a cookie
515
+ named `constructor`, `toString`, or `__proto__` reads as an ordinary cookie
516
+ and `readSignedCookie` resolves `undefined` for such a name when it is
517
+ absent; `parseRange` reads the RFC 9110 § 14.1 grammar
518
+ `range-unit "=" OWS range-set`: the unit matches `bytes`
519
+ case-insensitively, `range-set` follows the § 5.6.1 list rule (empty
520
+ elements skipped), OWS is a space or a tab and stands only around the field
521
+ value, after `=`, and around a `,`, and each bound is `1*DIGIT` of any
522
+ length, compared without `Number`. A non-member, such as `bytes=0x10-`,
523
+ `bytes=5 -9`, `bytes=20-garbage`, or a `last-pos` below its `first-pos`, is
524
+ ignored and the whole resource is served, as § 14.2 allows, and so is more
525
+ than one range and a non-zero suffix range on an empty resource, which
526
+ selects no window; `bytes=-0` is unsatisfiable. OWS is stripped with
527
+ `stripOWS`, so the read stays linear in the header's length, a long run of
528
+ spaces included; `serializeCookie` throws on a `Domain`/`Path`
423
529
  injection attempt rather than silently dropping it; a `sameSite: 'None'`
424
530
  cookie is always `Secure` regardless of the `secure` setting;
425
531
  `resolveSecure` derives `Secure` from the connection's TLS fact whenever
426
532
  `secure` is left `undefined` (omitted).
427
- `verifyToken` is total (malformed / tampered / expired / empty-rotation all
428
- yield `undefined`, never throw); the expiry is HMAC-covered inside the
429
- signed payload; a `TokenSecret` rotation list signs with the first secret
430
- and verifies against any of them; comparison is constant-time through
431
- `crypto.subtle.verify` (the old `safeCompare` is retired, not ported).
533
+ Every token helper takes a `SignerInterface`, never a secret. `createSigner`
534
+ creates one `node:crypto` key per secret at construction and none per call,
535
+ and it throws a `ServerError` of code `'SECRET'` when the secret is not a
536
+ string or a list of strings, when the list is empty, or when any entry is
537
+ blank, with no secret text in the message or `context`. A `TokenSecret`
538
+ rotation list signs with its first key and verifies against any of them;
539
+ `verify` walks the keys in order and returns at the first match, so a valid
540
+ token's timing reveals the position of the key that signed it, and an
541
+ invalid one reads every key. `verify` answers `false` before reading a key
542
+ for a signature that is not canonical base64url or does not decode to 32
543
+ bytes, and compares the bytes only through `timingSafeEqual`. `verifyToken`
544
+ resolves `undefined` for a malformed, tampered, or expired token; the
545
+ expiry is HMAC-covered inside the signed payload. `verifyToken` and
546
+ `readSignedCookie` reject only when the signer's `verify` rejects, which the
547
+ signer `createSigner` returns never does, so a consumer signer's outage
548
+ surfaces as an error, not as an invalid token. In 0.0.28, each token
549
+ helper took a `TokenSecret` in place of a signer, `TokenOptions` carried
550
+ `secret`, every call imported a WebCrypto key, and a blank secret entry
551
+ was dropped rather than refused.
432
552
  10. **Seam semantics: returning onion.** Each `MiddlewareHandler` receives a
433
553
  `next` that, called, runs the downstream chain and resolves its `Response`;
434
554
  not calling it short-circuits with the middleware's own `Response`; a
435
- second call to the same `next` within one invocation rejects with a
436
- `ServerError` of code `'NEXT'` (the double-`next` guard) — a middleware can
437
- transform the request (`next(newRequest)`), transform the response (mutate
438
- after `await next()`), or short-circuit, but never fork the chain. That
439
- rejection escapes into the request boundary, which carries no `status` for
440
- it and answers a generic 500.
555
+ second call to the same `next` within one invocation, or a call that
556
+ passes an argument, rejects with a `ServerError` of code `'NEXT'`, and a
557
+ refused call still spends the layer's one call — a
558
+ middleware can transform the response (mutate after `await next()`),
559
+ short-circuit, or abort the exchange (`context.abort(reason)`), but never
560
+ replace the request or fork the chain. Every layer and the terminal
561
+ receive the one `Request` the server built and the one context object.
562
+ That rejection escapes into the request boundary, which carries no
563
+ `status` for it and answers a generic 500. `next` resolves a response
564
+ whose headers are immutable and whose status lies from 200 through 599,
565
+ such as a `Response.redirect` or a `fetch` result, as a copy with the
566
+ same body, status, status text, and headers, so a layer can set headers
567
+ after `await next()`; it passes every other response through by identity.
568
+ In 0.0.28, `next` took an optional `Request` and ran the downstream chain
569
+ on it, so a layer could replace the request.
441
570
  11. **The bag is the router's state.** `compose`'s `terminal` is
442
571
  `(request, context) => dispatcher.handle(request, context.state)` — the
443
572
  exact object every middleware wrote into `context.state` is what a route
444
573
  handler reads as `RouteContext.state`. No second plumbing.
445
574
  12. **Connection facts are injected once, at the adapter boundary.**
446
575
  `Connection` (`ip`, `encrypted`) is built per-request from the raw
447
- socket and handed to `ServerOptions.state` — `X-Forwarded-For` is never
576
+ socket and handed to `ServerOptions.state`; `context.connection` is that
577
+ same object, whatever the `state` factory keeps — `X-Forwarded-For` is never
448
578
  implicitly trusted; a deployment behind a trusted proxy derives its own
449
- client key explicitly in `state` or in middleware.
450
- 13. **The stop signal is observable inside a handler.** The `Request`'s
451
- `signal` (already tied to client disconnect by the router's
452
- `buildRequest`) is linked, through `@orkestrel/abort`'s `linkSignal`, to the
453
- server's per-run stop signal — so a handler awaiting `request.signal`
454
- observes either the client disconnecting or the server calling `stop()`,
455
- closing the old design's latent gap.
456
- 14. **Enterprise timeout knobs, Slowloris-guarded.** `timeouts.request` /
457
- `timeouts.headers` / `timeouts.keepalive` map onto `node:http`'s
458
- `requestTimeout` / `headersTimeout` / `keepAliveTimeout`; construction
459
- throws a `TypeError` when `headers` exceeds `keepalive` (the Slowloris
460
- footgun) — a guard at the boundary, never on the hot path.
579
+ client key explicitly in `state` or in middleware. In 0.0.28, the context
580
+ carried no `connection`, and only the `state` factory received the
581
+ `Connection`.
582
+ 13. **One abort signal per exchange.** The server builds one
583
+ `AbortController` per exchange and passes its signal to the router's
584
+ `buildRequest`, so `request.signal` aborts when the peer disconnects, when
585
+ a layer calls `context.abort(reason)` (with that `reason`; a second call
586
+ changes nothing), or when `stop()` runs, and on no other exchange's
587
+ account, including the next one on the same keep-alive connection. The
588
+ server keeps each in-flight exchange's controller in a registry until its
589
+ response closes; `stop()` aborts each one, a request that
590
+ arrives during the drain is served with its signal already aborted, and
591
+ the `drain` event's pending count is the registry's size. No request
592
+ signal links to a signal that outlives its exchange, so nothing per
593
+ request stays reachable after the exchange ends. In 0.0.28, the server
594
+ built a second `Request` whose signal linked the router's disconnect
595
+ signal to one stop signal per run, through the `linkSignal` function of
596
+ `@orkestrel/abort`, and the context carried no `abort`.
597
+ 14. **Receipt timeouts are delegated to `node:http`.** `start()` passes
598
+ `timeouts.headers`, `timeouts.request`, and `timeouts.keepalive` to
599
+ `node:http`'s `createServer` as its `headersTimeout`, `requestTimeout`,
600
+ and `keepAliveTimeout` options. `headers` bounds the receipt of the
601
+ request headers, `request` the receipt of the whole request, and
602
+ `keepalive` the idle wait of a kept-alive connection for its next
603
+ request, to which Node adds its `keepAliveTimeoutBuffer`, 1_000 ms by
604
+ default: a `keepalive` of 400 closes an idle connection after about
605
+ 1_400 ms. `0` disables each. An omitted one keeps Node's default:
606
+ `DEFAULT_REQUEST_TIMEOUT_MS` for `request`, the lesser of
607
+ `DEFAULT_HEADERS_TIMEOUT_MS` and `request` for `headers`, and Node's
608
+ `keepAliveTimeout` default for `keepalive`. When `headers` or `request`
609
+ passes while a response is being sent, Node closes the connection, which
610
+ cuts that response short; otherwise, including after a response has
611
+ finished while its upload continues, Node answers `408` and closes the
612
+ connection. The server sets Node's
613
+ `connectionsCheckingInterval` to `Math.ceil(m / 2)` milliseconds, where
614
+ `m` is the smaller positive of `headers` and `request` as Node applies
615
+ them, so each expires at most one such interval after it passes; with
616
+ neither positive, Node keeps its own interval. Construction refuses,
617
+ with a `TypeError` that names the key and its limit, a `headers` or
618
+ `request` that is not an integer from 0 through 2_147_483_647 and a
619
+ `keepalive` that is not an integer from 0 through 2_147_482_647, because
620
+ Node arms `keepalive` plus its buffer as one timer; and it refuses, with a
621
+ `TypeError` that names both keys, a `headers` above `request` while
622
+ `request` is positive: Node's own `headersTimeout ≤ requestTimeout`
623
+ relation. No server timeout bounds the response; a response deadline is
624
+ a middleware's, such as the `createDeadline` middleware of
625
+ `@orkestrel/middleware`, which aborts the exchange through
626
+ `context.abort`. In 0.0.28, the server set these three as properties of
627
+ the `node:http` server and left `connectionsCheckingInterval` at Node's
628
+ 30_000 ms, so a `headers` or `request` timeout expired up to 30_000 ms
629
+ after it passed; construction accepted any non-negative finite number and
630
+ refused a `headers` greater than `keepalive`.
461
631
  15. **Socket caps map without policy.** `sockets.connections` /
462
632
  `sockets.headers` / `sockets.requests` apply directly to node's
463
633
  `maxConnections` / `maxHeadersCount` / `maxRequestsPerSocket` before bind.
@@ -473,7 +643,9 @@ These invariants hold across `src/server` ↔ `server.md`.
473
643
  generic (non-`HTTPError`) throw's message is hidden behind a fixed
474
644
  `'Internal Server Error'` string unless `expose` is explicitly `true`; an
475
645
  `HTTPError`'s own `message` is always client-facing (it is the handler's
476
- deliberate signal), independent of `expose`.
646
+ deliberate signal), independent of `expose`, when `Response` admits its
647
+ status. An `HTTPError` whose status no `Response` carries renders as a
648
+ generic throw.
477
649
  18. **Error guards recognize independent package copies through an own identity brand.**
478
650
  A recognized value is a global Error with a derived prototype. Its own brand holds the
479
651
  value itself. The guard checks the declared status or code, message, and optional context.
@@ -549,8 +721,8 @@ const cors: MiddlewareHandler<State> = async (request, _context, next) => {
549
721
  if (request.method === 'OPTIONS') return new Response(null, { status: 204 })
550
722
  return next()
551
723
  }
552
- const auth: MiddlewareHandler<State> = async (request, context, next) => {
553
- return next(request)
724
+ const auth: MiddlewareHandler<State> = async (_request, _context, next) => {
725
+ return next()
554
726
  }
555
727
 
556
728
  const dispatcher = createDispatcher<State>()
@@ -561,6 +733,14 @@ const server = createServer<State>({
561
733
  })
562
734
  ```
563
735
 
736
+ The dispatcher of the `@orkestrel/router` release that 0.0.29 depends on
737
+ answers a path that matches with no route for the method with `405` and an
738
+ `Allow` header that lists `OPTIONS`. It answers a `HEAD` with no `HEAD` route
739
+ by running the `GET` handler, cancelling that response's body, and sending its
740
+ status and headers alone, and an `OPTIONS` with no `OPTIONS` route with `204`
741
+ and the same `Allow`. In 0.0.28, a `405`'s `Allow` left out `OPTIONS`, and an
742
+ automatic `HEAD` left the `GET` body uncancelled.
743
+
564
744
  ### Typed state slices
565
745
 
566
746
  Each middleware family publishes its own state-slice interface; a consumer
@@ -703,6 +883,7 @@ signed cookies, tokens, and capped decompression without a `Server`.
703
883
  import type { MiddlewareContext } from '@orkestrel/server'
704
884
  import {
705
885
  createNegotiator,
886
+ createSigner,
706
887
  decodeTokenPayload,
707
888
  decompressRequestBody,
708
889
  readSignedCookie,
@@ -721,16 +902,17 @@ await negotiator.format(new Request('http://x'), context, {
721
902
  'application/json': (_request, _context) => Response.json({ ok: true }),
722
903
  })
723
904
 
905
+ const signer = createSigner(['current-secret', 'previous-secret'])
724
906
  const headers = new Headers()
725
- await writeSignedCookie(headers, 'session', 'user-1', 'secret')
907
+ await writeSignedCookie(headers, 'session', 'user-1', signer)
726
908
  await readSignedCookie(
727
909
  new Request('http://x', { headers: { cookie: 'session=abc' } }),
728
910
  'session',
729
- 'secret',
911
+ signer,
730
912
  )
731
- await verifyToken('bad.token', 'secret') // undefined — total, never throws
913
+ await verifyToken('bad.token', signer) // undefined — a malformed token never rejects
732
914
 
733
- const token = await signToken('client', { secret: 'shh' })
915
+ const token = await signToken('client', { signer })
734
916
  decodeTokenPayload(token.split('.')[0]) // 'client' — the shared decode step verifyToken applies after a signature match
735
917
 
736
918
  const gzipped = new Uint8Array(
@@ -752,8 +934,8 @@ new TextDecoder().decode(body) // 'hi' — capped decompression, the zip-bomb de
752
934
  the dispatcher's own auto-`OPTIONS` runs last.
753
935
  - **Read `context.body()` through the cache, never `request.body` directly**
754
936
  — the stream is drained exactly once, capped and zip-bomb-safe.
755
- - **Thread `request.signal` into downstream work** — it fires on either
756
- client disconnect or server `stop()`.
937
+ - **Thread `request.signal` into downstream work** — it aborts on a client
938
+ disconnect, on `context.abort`, or on server `stop()`.
757
939
  - **Never derive a rate key from `X-Forwarded-For`** — use the injected
758
940
  `Connection.ip` (or your own trusted-proxy derivation).
759
941
  - **Publish a state-slice interface per middleware family** — intersect the
@@ -764,49 +946,102 @@ new TextDecoder().decode(body) // 'hi' — capped decompression, the zip-bomb de
764
946
  - **Close your upgraded sockets on the `stop` event** — the server tracks them
765
947
  so shutdown terminates, but only your handler speaks the protocol, so only
766
948
  it can close one cleanly before the deadline cuts it.
767
- - **Install a `report` sink for observability** — its own throw is swallowed,
768
- so it can never crash a response.
949
+ - **Install a `report` sink for observability** — its own throw and a promise
950
+ it returns that rejects are contained, so the response still goes out;
951
+ Contract item 6 names the rejected promises the server cannot adopt.
769
952
 
770
953
  ## Tests
771
954
 
772
955
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/server`
773
956
  bijection (value and type exports), the `NegotiatorInterface` / `SSEStreamInterface` /
774
- `ServerInterface` ↔ implementing-class method bijections, and the equality gate:
957
+ `ServerInterface` / `SignerInterface` ↔ implementing-class method bijections, and the equality gate:
775
958
  every `Summary` cell against its declaration's description paragraph, the titled
776
959
  `Substrate direct use — tokens, cookies, negotiation` fence against the `@example`
777
960
  block of that title (pinned so the titled pair cannot be retired silently), and the
778
961
  README pitch against this guide's tagline. It also runs the flagship fences and
779
962
  asserts the values their comments claim.
963
+ - [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) —
964
+ the exchange seam through a real `Server` over real sockets: one `Request` per
965
+ exchange (a deadline layer's abort reaches the terminal, and a body-reading layer
966
+ behind it reads the body), the `'NEXT'` refusal of every `next` argument,
967
+ `context.connection` under a `state` factory that ignores it, `context.abort` on
968
+ one exchange and on none beside it, the in-flight registry under `stop()`, the
969
+ live-object count after thousands of requests, and response normalization of a
970
+ redirect and a `fetch` result. Its boundary blocks answer every thrown
971
+ `HTTPError` status from 100 through 999 and each returned status as `Response`
972
+ admits it, run fit finding F3's table through the server and the renderer
973
+ alike, and drive a body failure after the headers, a peer disconnect before
974
+ the end, the `response` record, and the terminal catch. Its server matrix feeds a real `Server` and a bare
975
+ `node:http` control the same bytes over raw sockets and frames each answer with the
976
+ raw client's own parse: the `connectionsCheckingInterval` the live `node:http` server
977
+ reads under each timeout shape; a header drip and a body drip that outlast their
978
+ timeouts, each answered in the control's class no sooner than its timeout and within
979
+ one and a half times it plus a scheduling slack; an idle keep-alive connection, closed
980
+ in the control's class no sooner than `keepalive` and within `keepalive` plus Node's
981
+ buffer and the slack;
982
+ the routed `405`, automatic `HEAD`, and automatic `OPTIONS`; the
983
+ framing class of a pipelined pair, conflicting or duplicate framing headers, an
984
+ obsolete line fold, a bare LF, an oversized header block, and `100-continue` and
985
+ unknown `Expect` values, with no `request` or `response` event where Node answers
986
+ before the handler; and the server's own listeners per event on each message and
987
+ response, at most two at the handler's entry and none after the exchange ends.
780
988
  - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) —
781
- `compose` (outer-first ordering, double-`next` rejection, short-circuit,
782
- request substitution, response transformation), cookie parse/serialize/
989
+ `compose` (outer-first ordering, double-`next` rejection, the refusal of a
990
+ `next` argument, one request and context per chain, short-circuit,
991
+ response transformation), `normalizeResponse` and its run memo, `supportsMutation`, cookie parse/serialize/
783
992
  attribute-injection guards, `resolveSecure`, `clearCookie` (expiry and
784
993
  accumulation), `computeCodingQuality`/`resolveCoding`/`negotiateEncoding`,
785
- the `ETag` hex digest, and `discoverPort` (default, preferred, and
994
+ the `ETag` hex digest, the `parseRange` tables of grammar members and
995
+ non-members and its agreement with a reference recognizer of the RFC 9110
996
+ grammar over an exhaustive walk and a seeded population, `compareDigits`,
997
+ the cookie table of every `Object.prototype` name, the
998
+ `serializeEvent` refusal table and its read-back through `@orkestrel/sse`,
999
+ the scrub at the byte limit and on a self-referencing value, urlencoded
1000
+ bodies, and `discoverPort` (default, preferred, and
786
1001
  taken-preferred-falls-back cases).
1002
+ - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) also
1003
+ holds the token rows: base-build token bytes at one secret and at a rotation
1004
+ list, the `exp` clock bracket under a signature WebCrypto verifies, the
1005
+ malformed token table, the rejection a consumer signer's outage surfaces, and
1006
+ the `normalizeSecret` refusal.
1007
+ - [`tests/src/server/Signer.test.ts`](../tests/src/server/Signer.test.ts) —
1008
+ the `'SECRET'` refusal table and every value the `createHostileValues` function builds, one key creation per
1009
+ secret at construction and none per call (read by a recorder over the
1010
+ `node:crypto` exports), first-key signing against `createHmac`, rotation
1011
+ answers, the key walk's early return, and the malformed signature table,
1012
+ each answered before any key is read.
1013
+ [`tests/src/server/Signer.bench.ts`](../tests/src/server/Signer.bench.ts)
1014
+ reads the `node:crypto` engine against WebCrypto and runs under no gate.
787
1015
  - [`tests/src/server/validators.test.ts`](../tests/src/server/validators.test.ts) —
788
1016
  `isAddressInfo` narrowing over every shape `node:net`'s `server.address()`
789
1017
  returns.
790
1018
  - [`tests/src/server/Negotiator.test.ts`](../tests/src/server/Negotiator.test.ts) —
791
1019
  `negotiate`/`encoding`/`language`/`format`: exact vs subtype-wildcard vs
792
1020
  any-range precedence, `;q=0` rejection semantics, q-tie server-order
793
- break, `format`'s 406 fallback and handler dispatch, the empty-header
1021
+ break, `format`'s 406 fallback and handler dispatch, case-insensitive keys,
1022
+ `Vary: Accept` on every `format` answer, the empty-header
794
1023
  divergence between `encoding` and `negotiate`, and the proof that
795
1024
  `encoding` and `negotiateEncoding` agree because they run one selection leaf.
796
1025
  - [`tests/src/server/Stream.test.ts`](../tests/src/server/Stream.test.ts) —
797
- the opened SSE response and its header merge order, the serialized wire for
798
- events and comments, readiness/drain and ignore-the-signal behavior, and the
799
- ways the handle closes (`end`, and a consumer cancelling).
1026
+ the opened SSE response and its header merge order, the opening comment and
1027
+ the headers it sends through the router pump before any event, the
1028
+ serialized wire for events and comments, the refused fields, readiness/drain
1029
+ and ignore-the-signal behavior, and the ways the handle closes (`end`, and a
1030
+ consumer cancelling).
800
1031
  - [`tests/src/server/errors.test.ts`](../tests/src/server/errors.test.ts) —
801
1032
  `HTTPError`/`ContentTooLargeError` shape and `isHTTPError` narrowing, and
802
- `ServerError` shape with `isServerError` narrowing.
1033
+ `ServerError` shape with `isServerError` narrowing for every declared code.
803
1034
  - [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) —
804
- `createNegotiator`, `createServer`, and `createStream` round-trips + factory
1035
+ `createNegotiator`, `createServer`, `createSigner`, and `createStream` round-trips + factory
805
1036
  return-type assertions, `createServer` option threading and construction
806
1037
  guards, and `createStream` option threading.
807
1038
  - [`tests/src/server/Server.test.ts`](../tests/src/server/Server.test.ts) —
808
1039
  the status matrix, restart-fresh-abort, caller-cancelled / timed-out / clean
809
- bounded startup, `EADDRINUSE` honesty, host/port binds, ephemeral default,
1040
+ bounded startup, the edges of the `headers ≤ request` relation against
1041
+ `node:http`'s own refusal, the former `headers ≤ keepalive` refusals that
1042
+ construct and serve, the timeout values construction refuses with each key's limit,
1043
+ the `0` and limit values it accepts, and the `keepalive` edge one below Node's
1044
+ buffered-timer overflow, `EADDRINUSE` honesty, host/port binds, ephemeral default,
810
1045
  connection / header / per-socket request caps, graceful-vs-forced drain,
811
1046
  the clean stop that ends a never-used connection inside the deadline after
812
1047
  the request in flight beside it finishes, the clean stop that counts and
@@ -828,7 +1063,8 @@ new TextDecoder().decode(body) // 'hi' — capped decompression, the zip-bomb de
828
1063
  the deadline then cut, settled early when the claimant closes it, reported
829
1064
  on `drain`, and force-closed by `destroy()`) against a no-socket control,
830
1065
  20-parallel-none-dropped, connection facts threaded into state,
831
- `context.body()` caching, boundary mapping (`HTTPError`/other/`expose`), the
1066
+ `context.body()` caching, boundary mapping (`HTTPError`/other/`expose`), a
1067
+ `report` sink that throws, rejects, or returns a thenable that throws, the
832
1068
  stop-signal-reaches-handlers case, and the real slow-TCP proof that an SSE
833
1069
  producer parks at local queue pressure, resumes on drain, and stays bounded
834
1070
  when cooperative while ignored readiness retains unconditional enqueue.
@@ -840,8 +1076,8 @@ new TextDecoder().decode(body) // 'hi' — capped decompression, the zip-bomb de
840
1076
  documentation-as-contract.
841
1077
  - [`router.md`](router.md) — `@orkestrel/router`, the dispatcher this server
842
1078
  consumes and never re-implements.
843
- - [`abort.md`](abort.md) — `@orkestrel/abort`, the stop-signal/request-signal
844
- linking primitive.
1079
+ - [`abort.md`](abort.md) — `@orkestrel/abort`, the abort and signal-linking
1080
+ primitives behind the bounded startup and the drain's wake-park.
845
1081
  - [`emitter.md`](emitter.md) — `@orkestrel/emitter`, the `Server`'s lifecycle
846
1082
  event map.
847
1083
  - [`contract.md`](contract.md) — `@orkestrel/contract`, the guards backing