@orkestrel/scaffold 0.0.137 → 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.
Files changed (33) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +489 -23
  2. package/dist/bin/main.js +6 -6
  3. package/dist/host/agents/skills/orkestrel-journey/SKILL.md +33 -27
  4. package/dist/host/agents/skills/orkestrel-journey/references/captures.md +37 -16
  5. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  6. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +628 -41
  7. package/dist/host/agents/skills/orkestrel-polish/references/capture-harness.md +5 -0
  8. package/dist/host/claude/agents/orkestrel.md +54 -54
  9. package/dist/host/claude/rules/typescript.md +4 -1
  10. package/dist/host/claude/rules/workspace.md +6 -4
  11. package/dist/host/guides/capture.md +442 -313
  12. package/dist/host/guides/contract.md +314 -210
  13. package/dist/host/guides/middleware.md +489 -259
  14. package/dist/host/guides/process.md +139 -53
  15. package/dist/host/guides/router.md +282 -165
  16. package/dist/host/guides/scaffold.md +35 -23
  17. package/dist/host/guides/server.md +417 -181
  18. package/dist/host/guides/test.md +353 -232
  19. package/dist/host/manifest.json +18 -18
  20. package/dist/host/scripts/browsers.sh +0 -0
  21. package/dist/host/scripts/codex.sh +0 -0
  22. package/dist/host/scripts/cursor.sh +0 -0
  23. package/dist/host/scripts/deps.sh +0 -0
  24. package/dist/host/scripts/npm.sh +0 -0
  25. package/dist/host/scripts/ollama.sh +0 -0
  26. package/dist/host/tests/config.test.ts +19 -27
  27. package/dist/src/core/index.cjs +139 -60
  28. package/dist/src/core/index.cjs.map +1 -1
  29. package/dist/src/core/index.d.cts +1 -1
  30. package/dist/src/core/index.d.ts +1 -1
  31. package/dist/src/core/index.js +139 -60
  32. package/dist/src/core/index.js.map +1 -1
  33. package/package.json +6 -6
@@ -4,19 +4,24 @@
4
4
  > `create{Noun}(options) => MiddlewareHandler<TState>` factories for error
5
5
  > boundaries, telemetry, compression, security headers, CORS, deadlines,
6
6
  > trusted-proxy client facts, ETag, bearer authentication, rate limiting, body
7
- > parsing, sessions, and CSRF in the fetch-native core, plus in-memory assets,
8
- > static files, streaming multipart uploads, and a `node:zlib` compression
9
- > sibling in the node face.
7
+ > parsing, sessions, and CSRF over web-standard `Request` and `Response`, plus
8
+ > in-memory assets, static files, streaming multipart uploads, and a
9
+ > `node:zlib` compression sibling on Node.
10
10
 
11
- This is the package's one guide, and it covers the core and the node face
12
- together. Every battery composes the frozen `@orkestrel/server` middleware seam
11
+ This is the package's one guide. The package publishes one server-only entry,
12
+ and every battery returns the `@orkestrel/server` `MiddlewareHandler`. Every
13
+ battery composes the frozen `@orkestrel/server` middleware seam
13
14
  (`MiddlewareHandler`, `MiddlewareContext`, `compose`) and its substrate —
14
15
  cookies, WebCrypto tokens, negotiation, conditionals, and security primitives.
15
16
  This package never re-implements that seam, and it supplies mechanism rather
16
- than product policy. Source: [`src/core`](../src/core),
17
- [`src/server`](../src/server). Surfaced through the `@orkestrel/middleware` and
18
- `@orkestrel/middleware/server` barrels (aliased `@src/core` and `@src/server`
19
- inside this repo).
17
+ than product policy. Source: [`src/server`](../src/server). Surfaced through
18
+ the `@orkestrel/middleware` barrel (aliased `@src/server` inside this repo).
19
+ Before 0.0.35, the package published two entries: the host-independent core at
20
+ `@orkestrel/middleware`, and `createAssets`, `createStatic`, `createMultipart`,
21
+ `createNodeCompression`, and the rest of the node face (its helpers, parsers,
22
+ errors, and asset store) at `@orkestrel/middleware/server`. From 0.0.35, the `./server` subpath is gone and
23
+ no alias replaces it: move every import from `@orkestrel/middleware/server` to
24
+ `@orkestrel/middleware`. The move removed and renamed no symbol.
20
25
 
21
26
  ## Surface
22
27
 
@@ -26,7 +31,7 @@ seam.
26
31
 
27
32
  ### Mount a battery
28
33
 
29
- The fence composes an error boundary and the security battery over `compose`, then answers with the request identifier `createSecurity` stashed on `context.state`.
34
+ The fence composes the security battery outside an error boundary over `compose`, then answers with the request identifier `createSecurity` stashed on `context.state`.
30
35
 
31
36
  ```ts
32
37
  import { createBoundary, createSecurity } from '@orkestrel/middleware'
@@ -38,118 +43,118 @@ interface State extends IdentifierState {}
38
43
  const boundary = createBoundary({ expose: false })
39
44
  const security = createSecurity({ hsts: true })
40
45
 
41
- const handle = compose<State>([boundary, security], async (_request, context) => {
46
+ const handle = compose<State>([security, boundary], async (_request, context) => {
42
47
  return Response.json({ identifier: context.state.identifier })
43
48
  })
44
49
  ```
45
50
 
46
- ### Middlewares — core
47
-
48
- | Name | Kind | Signature | Summary |
49
- | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
50
- | `createBoundary` | function | `<TState>(options?: BoundaryOptions) => MiddlewareHandler<TState>` | Creates the outermost error-rendering battery — catches a downstream throw and renders it as a `Response`. |
51
- | `createTelemetry` | function | `<TState>(options: TelemetryOptions) => MiddlewareHandler<TState>` | Creates the access-log/timing seam — records one `TelemetryEntry` per request after the response settles. |
52
- | `createCompression` | function | `<TState>(options?: CompressionOptions) => MiddlewareHandler<TState>` | Creates the response-body compression battery — negotiates and compresses a buffered response body over the runtime's feature-detected `CompressionStream` codings. |
53
- | `createSecurity` | function | `<TState extends IdentifierState>(options?: SecurityOptions) => MiddlewareHandler<TState>` | Creates the security-headers + request-identifier battery — sets each documented header default, and mints or echoes a request identifier. |
54
- | `createCors` | function | `<TState>(options?: CorsOptions) => MiddlewareHandler<TState>` | Creates the Cross-Origin Resource Sharing battery — answers a preflight itself, and reflects an allow-listed origin or serves the configured wildcard. |
55
- | `createDeadline` | function | `<TState>(options: DeadlineOptions) => MiddlewareHandler<TState>` | Creates the application-level per-request deadline battery. |
56
- | `createForwarded` | function | `<TState extends ClientState & ConnectionState>(options: ForwardedOptions) => MiddlewareHandler<TState>` | Creates the trusted-proxy client-IP resolver battery — walks `X-Forwarded-For` past the hops its options declare trusted. |
57
- | `createETag` | function | `<TState>(options?: ETagOptions) => MiddlewareHandler<TState>` | Creates the dynamic response `ETag` + conditional GET battery (RFC 7232). |
58
- | `createBearer` | function | `<TState extends BearerState<TCredential>, TCredential = string>(options: BearerOptions<TCredential>) => MiddlewareHandler<TState>` | Creates the bearer-token authentication battery — reads the token from its header, resolves its credential through `verify`, and answers each `401` with a `WWW-Authenticate` challenge. |
59
- | `createLimiter` | function | `<TState extends BearerState<unknown> & ClientState & ConnectionState>(options: LimiterOptions<TState>) => MiddlewareHandler<TState>` | Creates the fixed-window rate-limiting battery — checks a key's budget before consuming it, so one window admits exactly `max` requests. |
60
- | `createBody` | function | `<TState extends BodyState = BodyState>() => MiddlewareHandler<TState>` | Creates the body-driving battery — eagerly awaits the cached `context.body()` so its throws (or a malformed-JSON `undefined`) surface before the handler runs, and stashes the resolved value onto `BodyState.body`. |
61
- | `createSession` | function | `<S extends SessionInterface = SessionInterface, TState extends SessionState & ConnectionState = SessionState & ConnectionState>(options: SessionOptions<S, TState>) => MiddlewareHandler<TState>` | Creates the generic session battery — resolves, mints, and persists a session across the request, with a mid-handler `regenerate`/`destroy` control handle. |
62
- | `createCSRF` | function | `<TState extends CSRFState & SessionState & ConnectionState>(options: CSRFOptions) => MiddlewareHandler<TState>` | Creates the session-bound double-submit CSRF protection battery. |
63
- | `only` | function | `<TState>(paths: string \| readonly string[], handler: MiddlewareHandler<TState>) => MiddlewareHandler<TState>` | Scopes a battery to a set of exact pathnames and nowhere else — outside that set it steps aside through `next()`. |
64
- | `except` | function | `<TState>(paths: string \| readonly string[], handler: MiddlewareHandler<TState>) => MiddlewareHandler<TState>` | Scopes a battery to every pathname outside a set of exact ones — on that set it steps aside through `next()`. |
51
+ ### Middlewares — web-standard
52
+
53
+ | Name | Kind | Signature | Summary |
54
+ | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
55
+ | `createBoundary` | function | `<TState>(options?: BoundaryOptions) => MiddlewareHandler<TState>` | Creates the error-rendering battery — catches a downstream throw and renders it as a `Response`. |
56
+ | `createTelemetry` | function | `<TState>(options: TelemetryOptions) => MiddlewareHandler<TState>` | Creates the access-log/timing seam — records one `TelemetryEntry` per request after the response settles. |
57
+ | `createCompression` | function | `<TState>(options?: CompressionOptions) => MiddlewareHandler<TState>` | Creates the response-body compression battery — negotiates and compresses a buffered response body over the runtime's feature-detected `CompressionStream` codings. |
58
+ | `createSecurity` | function | `<TState extends IdentifierState>(options?: SecurityOptions) => MiddlewareHandler<TState>` | Creates the security-headers + request-identifier battery — sets each documented header default, and mints or echoes a request identifier. |
59
+ | `createCORS` | function | `<TState>(options?: CORSOptions) => MiddlewareHandler<TState>` | Creates the Cross-Origin Resource Sharing battery — answers a preflight itself, and reflects an allow-listed origin or serves the configured wildcard. |
60
+ | `createDeadline` | function | `<TState>(options: DeadlineOptions) => MiddlewareHandler<TState>` | Creates the application-level per-request deadline battery. |
61
+ | `createForwarded` | function | `<TState extends ClientState>(options: ForwardedOptions) => MiddlewareHandler<TState>` | Creates the trusted-proxy client-IP resolver battery — walks `X-Forwarded-For` past the hops its options declare trusted. |
62
+ | `createETag` | function | `<TState>(options?: ETagOptions) => MiddlewareHandler<TState>` | Creates the dynamic response `ETag` + conditional GET battery (RFC 7232). |
63
+ | `createBearer` | function | `<TState extends BearerState<TCredential>, TCredential = string>(options: BearerOptions<TCredential>) => MiddlewareHandler<TState>` | Creates the bearer-token authentication battery — reads the token from its header, resolves its credential through `verify`, and answers each `401` with a `WWW-Authenticate` challenge. |
64
+ | `createLimiter` | function | `<TState extends BearerState<unknown> & ClientState>(options: LimiterOptions<TState>) => MiddlewareHandler<TState>` | Creates the fixed-window rate-limiting battery — checks a key's budget before consuming it, so one window admits exactly `max` requests. |
65
+ | `createBody` | function | `<TState extends BodyState = BodyState>() => MiddlewareHandler<TState>` | Creates the body-driving battery — eagerly awaits the cached `context.body()` so its throws (or a malformed-JSON `undefined`) surface before the handler runs, and stashes the resolved value onto `BodyState.body`. |
66
+ | `createSession` | function | `<S extends SessionInterface = SessionInterface, TState extends SessionState = SessionState>(options: SessionOptions<S, TState>) => MiddlewareHandler<TState>` | Creates the generic session battery — resolves, mints, and persists a session across the request, with a mid-handler `regenerate`/`destroy` control handle. |
67
+ | `createCSRF` | function | `<TState extends CSRFState & SessionState>(options: CSRFOptions) => MiddlewareHandler<TState>` | Creates the CSRF protection battery: a signed double submit bound to the session the client holds, or to the battery's own nonce cookie when it holds none. |
68
+ | `only` | function | `<TState>(paths: string \| readonly string[], handler: MiddlewareHandler<TState>) => MiddlewareHandler<TState>` | Scopes a battery to the paths its route patterns match and nowhere else — outside them it steps aside through `next()`. |
69
+ | `except` | function | `<TState>(paths: string \| readonly string[], handler: MiddlewareHandler<TState>) => MiddlewareHandler<TState>` | Scopes a battery to every path its route patterns do not match — on the matched paths it steps aside through `next()`. |
65
70
 
66
71
  ### Middlewares — node
67
72
 
68
- | Name | Kind | Signature | Summary |
69
- | ----------------------- | -------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
70
- | `createAssets` | function | `<TState>(options: AssetOptions) => MiddlewareHandler<TState>` | Serves validated in-memory assets with identity/Brotli negotiation. |
71
- | `createStatic` | function | `<TState>(options: StaticOptions) => MiddlewareHandler<TState>` | Serves static files from `options.root` over `node:fs` — the node-bound static-file battery, answering conditional, ranged, and SPA-fallback requests. |
72
- | `createMultipart` | function | `<TState extends MultipartState>(options?: MultipartOptions) => MiddlewareHandler<TState>` | Parses a streamed `multipart/form-data` request body and stashes its `MultipartBody` on `context.state.multipart` — the node-bound streaming multipart battery. |
73
- | `createNodeCompression` | function | `<TState>(options?: NodeCompressionOptions) => MiddlewareHandler<TState>` | Compresses response bodies through `node:zlib`, guaranteed on any Node runtime rather than dependent on the WHATWG `CompressionStream` global. This battery is the node-bound sibling of the core face's feature-detected `createCompression`, and both compose the same `compressResponse` skeleton. |
73
+ | Name | Kind | Signature | Summary |
74
+ | ----------------------- | -------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | `createAssets` | function | `<TState>(options: AssetOptions) => MiddlewareHandler<TState>` | Serves validated in-memory assets with identity/Brotli negotiation. |
76
+ | `createStatic` | function | `<TState>(options: StaticOptions) => MiddlewareHandler<TState>` | Serves static files from `options.root` over `node:fs` — the node-bound static-file battery, answering conditional, ranged, and SPA-fallback requests. |
77
+ | `createMultipart` | function | `<TState extends MultipartState>(options?: MultipartOptions) => MiddlewareHandler<TState>` | Parses a streamed `multipart/form-data` request body and stashes its `MultipartBody` on `context.state.multipart` — the node-bound streaming multipart battery. |
78
+ | `createNodeCompression` | function | `<TState>(options?: NodeCompressionOptions) => MiddlewareHandler<TState>` | Compresses response bodies through `node:zlib`, which every Node runtime bundles, instead of relying on the WHATWG `CompressionStream` global. This battery is the node-bound sibling of the feature-detected `createCompression`, and both compose the same `compressResponse` skeleton. |
74
79
 
75
80
  ### Types
76
81
 
77
- | Name | Kind | Signature | Summary |
78
- | --------------------------- | --------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
79
- | `BoundaryOptions` | interface | `{ expose?, report? }` | Configures `createBoundary` — the outermost error-rendering battery. |
80
- | `TelemetryEntry` | interface | `{ method, pathname, status, duration }` | Represents one access-log-style entry `createTelemetry` records after a response settles — the access-log/timing seam's payload shape. |
81
- | `TelemetryOptions` | interface | `{ record }` | Configures `createTelemetry` — the request timing/access-log seam. |
82
- | `CompressionOptions` | interface | `{ threshold?, encodings?, filter? }` | Configures `createCompression` — response-body compression. |
83
- | `CompressResponseOptions` | interface | `{ threshold, filter?, encodings, compress }` | Describes the already-resolved settings `compressResponse` runs its shared negotiate → skip → threshold → compress skeleton against — the shape each of `createCompression` and `createNodeCompression` builds from its own option bag. |
84
- | `SecurityIdentifierOptions` | type | `{ readonly trust?: boolean; } \| false` | Describes `createSecurity`'s `identifier` sub-option — request-id minting/echo policy, or `false` to disable the feature entirely. |
85
- | `SecurityOptions` | interface | `{ frame?, csp?, referrer?, permissions?, coop?, corp?, cluster?, coep?, hsts?, identifier? }` | Configures `createSecurity` — the security-headers + request-id battery. |
86
- | `CorsOptions` | interface | `{ origin?, methods?, headers? }` | Configures `createCors` — Cross-Origin Resource Sharing. |
87
- | `DeadlineOptions` | interface | `{ ms, status? }` | Configures `createDeadline` — the application-level per-request deadline. |
88
- | `ForwardedOptions` | type | `{ readonly proxies: number; } \| { readonly trusted: readonly string[]; }` | Configures `createForwarded` — the trusted-proxy client-IP resolver. |
89
- | `ETagOptions` | interface | `{ weak? }` | Configures `createETag` — dynamic response ETag + conditional GET. |
90
- | `BearerOptions` | interface | `{ verify, header?, scheme?, challenge? }` | Configures `createBearer` — bearer-token authentication. |
91
- | `BearerVerifyFunction` | type | `(token: string, request: Request) => TCredential \| undefined \| Promise<TCredential \| undefined>` | Verifies a presented bearer token and resolves its credential, or `undefined` to refuse it. |
92
- | `LimiterOptions` | interface | `{ store?, max, window, capacity?, key?, message?, clock?, policy?, evict? }` | Configures `createLimiter` — fixed-window rate limiting. |
93
- | `BearerState` | interface | `{ token? }` | Describes the bearer-authentication state slice `createBearer` stashes on `context.state` once a token verifies. |
94
- | `IdentifierState` | interface | `{ identifier? }` | Describes the request-identifier state slice `createSecurity` stashes when its `identifier` option is enabled. |
95
- | `Client` | interface | `{ ip? }` | Describes the resolved client connection facts `createForwarded` stashes. |
96
- | `ClientState` | interface | `{ client? }` | Describes the client-facts state slice `createForwarded` stashes. |
97
- | `ConnectionState` | interface | `{ connection? }` | Describes the connection-facts state slice `createLimiter`'s default key derivation falls back to when neither `BearerState` nor `ClientState` is present — the raw socket peer surfaced on `context.state` by the server's `state` option. |
98
- | `SessionInterface` | interface | `{ id, state, set(), delete(), clear() }` | Represents a server-managed session's public surface — an id, its live state, and the mutators that write it. |
99
- | `SessionControlInterface` | interface | `{ destroyed, successor, regenerate(), destroy() }` | Describes the mid-handler control handle `createSession` stashes alongside the session itself — the OWASP anti-fixation / logout primitives. |
100
- | `SessionState` | interface | `{ session?, control? }` | Describes the session state slice `createSession` stashes. |
101
- | `BodyState` | interface | `{ body? }` | Describes the body state slice `createBody` stashes. |
102
- | `SessionStoreInterface` | interface | `{ get(), set(), delete() }` | Describes the pluggable session persistence seam `createSession`'s `store` option implements — a point-access store keyed by session id. |
103
- | `SessionTransportInterface` | interface | `{ read(), write(), clear() }` | Describes the transport seam `createSession`'s `transport` option implements — how a session id travels to and from the client (a signed cookie, a header, …). |
104
- | `SessionOptions` | interface | `{ transport, store?, ttl?, lifetime?, capacity?, evict?, create?, mint?, required?, clock? }` | Configures `createSession` — the generic session battery. |
105
- | `CookieTransportOptions` | interface | `{ name?, secret, cookie? }` | Configures `createCookieTransport` — the signed-cookie `SessionTransportInterface`. |
106
- | `HeaderTransportOptions` | interface | `{ header? }` | Configures `createHeaderTransport` — the bare-header `SessionTransportInterface`. |
107
- | `MemorySessionStoreOptions` | interface | `{ capacity?, evict? }` | Configures `createMemorySessionStore` — the default in-process `SessionStoreInterface`. |
108
- | `SessionLimits` | interface | `{ ttl?, lifetime? }` | Describes the idle and absolute-lifetime thresholds a session store enforces — `sessionExpired`'s limits argument and both shipped stores' construction options. |
109
- | `SessionCursors` | interface | `{ seen, created }` | Describes the per-session instants a store stamps and `sessionExpired` measures against. |
110
- | `SessionRow` | interface | `{ id, session }` | Represents one persisted session row — an opaque snapshot column plus the store-owned idle/absolute-lifetime cursors, the shape a `DatabaseSessionStore`'s backing table holds. |
111
- | `SessionEntry` | interface | `{ session }` | Represents one in-process session entry — the payload `MemorySessionStore` holds against an id, alongside the same cursors a persisted row carries. |
112
- | `SessionSnapshot` | interface | `{ id, state }` | Represents a session's serializable projection — the value `snapshotSession` produces and a durable store's `set` writes. |
113
- | `SessionRestoreFunction` | type | `(value: unknown) => SessionInterface \| undefined` | Rebuilds a session entity from an untrusted stored snapshot, or resolves `undefined` when the value is malformed. |
114
- | `CSRFState` | interface | `{ csrf? }` | Describes the CSRF state slice `createCSRF` stashes — the raw token a safe-method response exposes for a subsequent mutating request to submit back. |
115
- | `CSRFOptions` | interface | `{ secret, cookie?, header?, field?, safe? }` | Configures `createCSRF` — session-bound double-submit CSRF protection. |
116
- | `MultipartFile` | interface | `{ field, name, size, mime, validated, status, path }` | Represents one staged multipart upload's public record — the shape the node-face `createMultipart` battery (`@orkestrel/middleware/server`) produces per uploaded file. |
117
- | `MultipartBody` | interface | `{ files, fields }` | Describes the parsed multipart request body `createMultipart` stashes — files keyed by their field name, plus every plain text field. |
118
- | `MultipartState` | interface | `{ multipart? }` | Describes the multipart state slice `createMultipart` stashes. |
119
- | `AssetRepresentation` | interface | `{ body, encoding? }` | Describes one in-memory asset representation returned by an `AssetSourceInterface`. |
120
- | `AssetSourceInterface` | interface | `{ read() }` | Reads in-memory assets by decoded, browser-build-relative path. |
121
- | `AssetOptions` | interface | `{ source, store? }` | Configures `createAssets` — in-memory identity/Brotli asset serving. |
122
- | `StaticOptions` | interface | `{ root, prefix?, index?, dotfiles?, cache?, etag?, fallback? }` | Configures `createStatic` — node `fs`-backed static file serving. |
123
- | `MultipartLimitsInput` | interface | `{ file?, field?, total? }` | Describes the caller's partial `MultipartLimits` — `createMultipart`'s `limits` option, with every member optional. |
124
- | `MultipartLimits` | interface | `{ file, field, total }` | Describes the per-category size/count caps `createMultipart` enforces mid-stream — the effective limits, every documented default already applied. |
125
- | `MultipartOptions` | interface | `{ limits?, allowed?, directory? }` | Configures `createMultipart` — node `fs`/`os`/`crypto`-backed streaming multipart upload parsing. |
126
- | `NodeCompressionOptions` | interface | `{ threshold?, filter? }` | Configures `createNodeCompression` — `node:zlib`-backed response compression. |
127
- | `MultipartErrorCode` | type | `'limit' \| 'malformed' \| 'rejected'` | Names the reason `createMultipart` rejected a request — the machine-readable code `MultipartError` carries and maps onto its HTTP status: `'limit'` → 413, `'malformed'` → 400, `'rejected'` → 415. |
128
- | `UploadStatus` | type | `'staged' \| 'moved'` | Names the lifecycle stage of one staged upload's temp file. |
129
- | `UploadedFile` | interface | `{ status }` | Describes one uploaded file's post-parse record — the node-bound, richer sibling of the pure core's `MultipartFile` (identical fields, `status` narrowed to `UploadStatus`). Structurally assignable into `MultipartFile` so a `createMultipart`-built `MultipartBody` satisfies the shared core shape. |
130
- | `PartHeaders` | interface | `{ name, filename, mime }` | Describes one multipart part's parsed header block — `parsePartHeaders`'s return shape. |
131
- | `ByteRange` | interface | `{ start, end }` | Describes one inclusive byte range over a file — `streamFile`'s optional `range` argument and the shape `createStatic` builds for a satisfiable `Range` request. |
82
+ | Name | Kind | Signature | Summary |
83
+ | --------------------------- | --------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
+ | `ForeignContract` | interface | `{ expected, is }` | Describes a foreign implementation contract an options key admits — the members its published interface declares, checked as that interface declares them. |
85
+ | `BoundaryOptions` | interface | `{ expose?, report? }` | Configures `createBoundary` — the error-rendering battery. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
86
+ | `TelemetryEntry` | interface | `{ method, pathname, status, duration }` | Represents one access-log-style entry `createTelemetry` records after a response settles — the access-log/timing seam's payload shape. |
87
+ | `TelemetryOptions` | interface | `{ record }` | Configures `createTelemetry` — the request timing/access-log seam. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
88
+ | `CompressionOptions` | interface | `{ threshold?, encodings?, filter? }` | Configures `createCompression` — response-body compression. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
89
+ | `CompressResponseOptions` | interface | `{ threshold, filter?, encodings, compress }` | Describes the already-resolved settings `compressResponse` runs its shared negotiate → skip → threshold → compress skeleton against — the shape each of `createCompression` and `createNodeCompression` builds from its own option bag. |
90
+ | `SecurityIdentifierOptions` | type | `{ readonly trust?: boolean; } \| false` | Describes `createSecurity`'s `identifier` sub-option — request-id minting/echo policy, or `false` to disable the feature entirely. |
91
+ | `SecurityOptions` | interface | `{ frame?, csp?, referrer?, permissions?, coop?, corp?, cluster?, coep?, hsts?, identifier? }` | Configures `createSecurity` — the security-headers + request-id battery. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
92
+ | `CORSOptions` | interface | `{ origin?, methods?, headers? }` | Configures `createCORS` — Cross-Origin Resource Sharing. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
93
+ | `DeadlineOptions` | interface | `{ ms, status? }` | Configures `createDeadline` — the application-level per-request deadline. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
94
+ | `ForwardedOptions` | type | `{ readonly proxies: number; } \| { readonly trusted: readonly string[]; }` | Configures `createForwarded` — the trusted-proxy client-IP resolver. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
95
+ | `ETagOptions` | interface | `{ weak? }` | Configures `createETag` — dynamic response ETag + conditional GET. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
96
+ | `BearerOptions` | interface | `{ verify, header?, scheme?, challenge? }` | Configures `createBearer` — bearer-token authentication. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
97
+ | `BearerVerifyFunction` | type | `(token: string, request: Request) => TCredential \| undefined \| Promise<TCredential \| undefined>` | Verifies a presented bearer token and resolves its credential, or `undefined` to refuse it. |
98
+ | `LimiterOptions` | interface | `{ store?, max, window, capacity?, key?, message?, clock?, policy?, evict? }` | Configures `createLimiter` — fixed-window rate limiting. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
99
+ | `BearerState` | interface | `{ token? }` | Describes the bearer-authentication state slice `createBearer` stashes on `context.state` after a token verifies. |
100
+ | `IdentifierState` | interface | `{ identifier? }` | Describes the request-identifier state slice `createSecurity` stashes when its `identifier` option is enabled. |
101
+ | `Client` | interface | `{ ip? }` | Describes the resolved client connection facts `createForwarded` stashes. |
102
+ | `ClientState` | interface | `{ client? }` | Describes the client-facts state slice `createForwarded` stashes. |
103
+ | `SessionInterface` | interface | `{ id, state, set(), delete(), clear() }` | Represents a server-managed session's public surface — an id, its live state, and the mutators that write it. |
104
+ | `SessionControlInterface` | interface | `{ destroyed, successor, fresh, regenerate(), destroy() }` | Describes the mid-handler control handle `createSession` stashes alongside the session itself — the OWASP anti-fixation / logout primitives. |
105
+ | `SessionState` | interface | `{ session?, control? }` | Describes the session state slice `createSession` stashes. |
106
+ | `BodyState` | interface | `{ body? }` | Describes the body state slice `createBody` stashes. |
107
+ | `SessionStoreInterface` | interface | `{ get(), set(), delete() }` | Describes the pluggable session persistence seam `createSession`'s `store` option implements — a point-access store keyed by session id. |
108
+ | `SessionTransportInterface` | interface | `{ read(), write(), clear() }` | Describes the transport seam `createSession`'s `transport` option implements — how a session id travels to and from the client (a signed cookie, a header, …). |
109
+ | `SessionOptions` | interface | `{ transport, store?, ttl?, lifetime?, capacity?, evict?, create?, mint?, required?, clock? }` | Configures `createSession` — the generic session battery. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
110
+ | `CookieTransportOptions` | interface | `{ name?, signer, cookie? }` | Configures `createCookieTransport` — the signed-cookie `SessionTransportInterface`. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
111
+ | `HeaderTransportOptions` | interface | `{ header? }` | Configures `createHeaderTransport` — the bare-header `SessionTransportInterface`. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
112
+ | `MemorySessionStoreOptions` | interface | `{ capacity?, evict? }` | Configures `createMemorySessionStore` — the default in-process `SessionStoreInterface`. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
113
+ | `SessionLimits` | interface | `{ ttl?, lifetime? }` | Describes the idle and absolute-lifetime thresholds a session store enforces — `sessionExpired`'s limits argument and both shipped stores' construction options. `createDatabaseSessionStore` admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
114
+ | `SessionCursors` | interface | `{ seen, created }` | Describes the per-session instants a store stamps and `sessionExpired` measures against. |
115
+ | `SessionRow` | interface | `{ id, session }` | Represents one persisted session row — an opaque snapshot column plus the store-owned idle/absolute-lifetime cursors, the shape a `DatabaseSessionStore`'s backing table holds. |
116
+ | `SessionEntry` | interface | `{ session }` | Represents one in-process session entry — the payload `MemorySessionStore` holds against an id, alongside the same cursors a persisted row carries. |
117
+ | `SessionSnapshot` | interface | `{ id, state }` | Represents a session's serializable projection — the value `snapshotSession` produces and a durable store's `set` writes. |
118
+ | `SessionRestoreFunction` | type | `(value: unknown) => SessionInterface \| undefined` | Rebuilds a session entity from an untrusted stored snapshot, or resolves `undefined` when the value is malformed. |
119
+ | `CSRFState` | interface | `{ csrf? }` | Describes the CSRF state slice `createCSRF` stashes — a token bound to the session the request arrived with, or to the battery's nonce, for the page to submit back. |
120
+ | `CSRFOptions` | interface | `{ signer, cookie?, header?, field?, safe? }` | Configures `createCSRF` — signed double-submit CSRF protection, bound to the session the client holds or to the battery's own nonce. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
121
+ | `MultipartFile` | interface | `{ field, name, size, mime, validated, status, path }` | Represents one staged multipart upload's public record — the shape the node-face `createMultipart` battery (`@orkestrel/middleware`) produces per uploaded file. |
122
+ | `MultipartBody` | interface | `{ files, fields }` | Describes the parsed multipart request body `createMultipart` stashes — files keyed by their field name, plus every plain text field. |
123
+ | `MultipartState` | interface | `{ multipart? }` | Describes the multipart state slice `createMultipart` stashes. |
124
+ | `AssetRepresentation` | interface | `{ body, encoding? }` | Describes one in-memory asset representation returned by an `AssetSourceInterface`. |
125
+ | `AssetSourceInterface` | interface | `{ read() }` | Reads in-memory assets by decoded, browser-build-relative path. |
126
+ | `AssetOptions` | interface | `{ source, store? }` | Configures `createAssets` — in-memory identity/Brotli asset serving. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
127
+ | `StaticOptions` | interface | `{ root, prefix?, index?, dotfiles?, cache?, etag?, fallback? }` | Configures `createStatic` — node `fs`-backed static file serving. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
128
+ | `MultipartLimitsInput` | interface | `{ file?, field?, total? }` | Describes the caller's partial `MultipartLimits` — `createMultipart`'s `limits` option, with every member optional. |
129
+ | `MultipartLimits` | interface | `{ file, field, total }` | Describes the per-category size/count caps `createMultipart` enforces mid-stream — the effective limits, every documented default already applied. |
130
+ | `MultipartOptions` | interface | `{ limits?, allowed?, directory? }` | Configures `createMultipart` — node `fs`/`os`/`crypto`-backed streaming multipart upload parsing. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
131
+ | `NodeCompressionOptions` | interface | `{ threshold?, filter? }` | Configures `createNodeCompression` — `node:zlib`-backed response compression. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
132
+ | `MultipartErrorCode` | type | `'limit' \| 'malformed' \| 'rejected'` | Names the reason `createMultipart` rejected a request — the machine-readable code `MultipartError` carries and maps onto its HTTP status: `'limit'` → 413, `'malformed'` → 400, `'rejected'` → 415. |
133
+ | `UploadStatus` | type | `'staged' \| 'moved'` | Names the lifecycle stage of one staged upload's temp file. |
134
+ | `UploadedFile` | interface | `{ status }` | Describes one uploaded file's post-parse record — the node-bound, richer sibling of `MultipartFile` (identical fields, `status` narrowed to `UploadStatus`). Structurally assignable into `MultipartFile` so a `createMultipart`-built `MultipartBody` satisfies the shared shape. |
135
+ | `PartHeaders` | interface | `{ name, filename, mime }` | Describes one multipart part's parsed header block — `parsePartHeaders`'s return shape. |
136
+ | `ByteRange` | interface | `{ start, end }` | Describes one inclusive byte range over a file — `streamFile`'s optional `range` argument and the shape `createStatic` builds for a satisfiable `Range` request. |
132
137
 
133
138
  ### Store and response types
134
139
 
135
- | Name | Kind | Signature | Summary |
136
- | --------------------------- | --------- | --------------------------------- | ------------------------------------------------------------------------------ |
137
- | `StaticFile` | interface | `{ path, handle, info }` | Describes an opened static file and the facts read from its handle. |
138
- | `StaticResolution` | interface | `{ path, contained }` | Describes a canonical static path and whether it lies inside the serving root. |
139
- | `StaticPlan` | interface | `{ status, headers, range }` | Describes response headers and the optional byte interval of a static file. |
140
- | `LimiterLimits` | interface | `{ max, window }` | Describes the budget and duration used when a limiter window starts. |
141
- | `LimiterResult` | interface | `{ admitted, expiry }` | Reports an atomic admission decision and its window expiry instant. |
142
- | `LimiterEntry` | interface | `{ budget, expiry }` | Holds the budget and expiry instant of an in-memory limiter entry. |
143
- | `LimiterStoreInterface` | interface | `{ consume() }` | Provides atomic per-key fixed-window admission. |
144
- | `MemoryLimiterStoreOptions` | interface | `{ capacity?, evict? }` | Configures the in-memory limiter's capacity and eviction observation. |
145
- | `AssetRecord` | interface | `{ key, identity, brotli, etag }` | Holds copied asset representations and their shared identity validator. |
146
- | `AssetStoreInterface` | interface | `{ get(), set(), delete() }` | Provides asynchronous point access to cached asset representations. |
140
+ | Name | Kind | Signature | Summary |
141
+ | --------------------------- | --------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
142
+ | `StaticFile` | interface | `{ path, handle, info }` | Describes an opened static file and the facts read from its handle. |
143
+ | `StaticResolution` | interface | `{ path, contained }` | Describes a canonical static path and whether it lies inside the serving root. |
144
+ | `StaticPlan` | interface | `{ status, headers, range }` | Describes response headers and the optional byte interval of a static file. |
145
+ | `LimiterLimits` | interface | `{ max, window }` | Describes the budget and duration used when a limiter window starts. |
146
+ | `LimiterResult` | interface | `{ admitted, expiry }` | Reports an atomic admission decision and its window expiry instant. |
147
+ | `LimiterEntry` | interface | `{ budget, expiry }` | Holds the budget and expiry instant of an in-memory limiter entry. |
148
+ | `LimiterStoreInterface` | interface | `{ consume() }` | Provides atomic per-key fixed-window admission. |
149
+ | `MemoryLimiterStoreOptions` | interface | `{ capacity?, evict? }` | Configures the in-memory limiter's capacity and eviction observation. The factory admits the bag whole, and a refusal is a `ContractError`. The bag must be a plain object; a class instance refuses. |
150
+ | `AssetRecord` | interface | `{ key, identity, brotli, etag }` | Holds copied asset representations and their shared identity validator. |
151
+ | `AssetStoreInterface` | interface | `{ get(), set(), delete() }` | Provides asynchronous point access to cached asset representations. |
147
152
 
148
153
  ### Request control and stores
149
154
 
150
155
  | Name | Kind | Signature | Summary |
151
156
  | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
152
- | `SessionControl` | class | `new (session: SessionInterface, create?: (id: string) => SessionInterface) => SessionControlInterface` | Records one request's session regeneration or destruction intent. |
157
+ | `SessionControl` | class | `new (session: SessionInterface, create?: (id: string) => SessionInterface, fresh?: boolean) => SessionControlInterface` | Records one request's session regeneration or destruction intent. |
153
158
  | `MemoryLimiterStore` | class | `new (options?: MemoryLimiterStoreOptions) => LimiterStoreInterface` | Stores fixed-window budgets with atomic admission and bounded LRU retention. |
154
159
  | `MemoryAssetStore` | class | `new () => AssetStoreInterface` | Stores asset representations by key for the lifetime of the store. |
155
160
  | `createMemoryLimiterStore` | function | `(options?: MemoryLimiterStoreOptions) => LimiterStoreInterface` | Creates a bounded in-memory atomic limiter store. |
@@ -179,25 +184,32 @@ const handle = compose<State>([boundary, security], async (_request, context) =>
179
184
  | `DEFAULT_COEP` | const | `"require-corp"` | Holds `'require-corp'`, the value `createSecurity` sets for `Cross-Origin-Embedder-Policy` when `coep: true`. |
180
185
  | `DEFAULT_HSTS` | const | `"max-age=31536000; includeSubDomains"` | Holds `'max-age=31536000; includeSubDomains'`, the value `createSecurity` sets for `Strict-Transport-Security` when `hsts: true`. |
181
186
  | `DEFAULT_IDENTIFIER_HEADER` | const | `"x-request-id"` | Names `'x-request-id'`, the default header `createSecurity` mints or echoes a request identifier into. |
182
- | `DEFAULT_CORS_METHODS` | const | `readonly string[]` | Lists the default methods `createCors` advertises on a preflight response. |
183
- | `DEFAULT_CORS_HEADERS` | const | `readonly string[]` | Lists the default headers `createCors` advertises on a preflight response. |
187
+ | `DEFAULT_CORS_METHODS` | const | `readonly string[]` | Lists the default methods `createCORS` advertises on a preflight response. |
188
+ | `DEFAULT_CORS_HEADERS` | const | `readonly string[]` | Lists the default headers `createCORS` advertises on a preflight response. |
184
189
  | `DEFAULT_DEADLINE_STATUS` | const | `503` | Holds `503`, the default response status `createDeadline` returns when its deadline fires first. |
185
190
  | `DEFAULT_BEARER_HEADER` | const | `"authorization"` | Names `'authorization'`, the default header `createBearer` reads the token from. |
186
191
  | `DEFAULT_BEARER_SCHEME` | const | `"Bearer"` | Names `'Bearer'`, the default scheme prefix `createBearer` strips before verification. |
187
192
  | `CHALLENGE_TOKEN` | const | `Readonly<RegExp>` | Matches an RFC 9110 `token`, the form a challenge scheme and an auth-param name take. |
188
193
  | `CHALLENGE_VALUE` | const | `Readonly<RegExp>` | Matches the characters RFC 6750 § 3 admits in a quoted auth-param value: `%x20-21 / %x23-5B / %x5D-7E`. |
194
+ | `IPV4_ADDRESS` | const | `Readonly<RegExp>` | Matches a dotted-decimal IPv4 address: four decimal octets from 0 to 255, with no sign, hex digit, leading zero, or empty octet. |
195
+ | `IPV4_MAPPED_PREFIX` | const | `Readonly<RegExp>` | Matches the `::ffff:` prefix, in either case, of an IPv4-mapped IPv6 address written with its embedded dotted IPv4. |
196
+ | `CIDR_LENGTH` | const | `Readonly<RegExp>` | Matches an IPv4 CIDR prefix length `createForwarded`'s roster admits: a decimal from 8 to 32, with no sign or leading zero. |
189
197
  | `DEFAULT_LIMITER_CAPACITY` | const | `10000` | Holds `10_000`, the default maximum number of distinct rate-limit keys `createLimiter` tracks before LRU eviction. |
190
198
  | `DEFAULT_LIMITER_MESSAGE` | const | `"rate limit exceeded"` | Holds `'rate limit exceeded'`, the default 429 body message `createLimiter` sends when a key is over budget. |
191
- | `DEFAULT_SESSION_CAPACITY` | const | `10000` | Holds `10_000`, the default maximum number of distinct session ids `createMemorySessionStore` tracks before LRU (by last write) eviction. |
199
+ | `DEFAULT_SESSION_CAPACITY` | const | `10000` | Holds `10_000`, the default maximum number of distinct session ids `createMemorySessionStore` tracks before least-recently-used eviction. |
192
200
  | `DEFAULT_SESSION_COOKIE` | const | `"session"` | Names `'session'`, the default cookie `createCookieTransport` writes the signed session id under. |
193
201
  | `DEFAULT_SESSION_HEADER` | const | `"session-id"` | Names `'session-id'`, the default header `createHeaderTransport` carries the session id in. |
194
- | `DEFAULT_CSRF_COOKIE` | const | `"csrf"` | Names `'csrf'`, the default signed cookie `createCSRF` writes the CSRF token under. |
202
+ | `DEFAULT_CSRF_COOKIE` | const | `"csrf"` | Names `'csrf'`, the default cookie `createCSRF` keeps its nonce in when the client holds no session. |
203
+ | `CSRF_LABEL` | const | `"csrf:"` | Opens every message `createCSRF` signs; its `:` lies outside the base64url alphabet, so no base64url `signToken` payload equals a CSRF message. |
204
+ | `CSRF_NONCE_BYTES` | const | `32` | Holds `32`, the byte count of a CSRF nonce and of a CSRF token's random part. |
205
+ | `CSRF_NONCE_PATTERN` | const | `Readonly<RegExp>` | Matches a CSRF nonce or a CSRF token's random part: the 43 base64url characters that encode `CSRF_NONCE_BYTES` bytes. |
206
+ | `CSRF_FIELD_TYPES` | const | `readonly string[]` | Lists the media types whose body `createCSRF` reads its field from: the two the server decodes to a record. |
195
207
  | `DEFAULT_CSRF_HEADER` | const | `"x-csrf-token"` | Names `'x-csrf-token'`, the default header `createCSRF` reads a mutating request's submitted token from. |
196
208
  | `DEFAULT_CSRF_FIELD` | const | `"_csrf"` | Names `'_csrf'`, the default body field `createCSRF` falls back to reading a mutating request's submitted token from. |
197
209
  | `DEFAULT_CSRF_SAFE_METHODS` | const | `readonly string[]` | Lists `['GET', 'HEAD', 'OPTIONS']`, the default methods `createCSRF` treats as safe (mint instead of verify). |
198
210
  | `MULTIPART_STATUS` | const | `Readonly<Record<MultipartErrorCode, number>>` | Holds the HTTP status `createMultipart` renders for each `MultipartErrorCode`: `'limit'` is 413, `'malformed'` is 400, and `'rejected'` is 415. |
199
211
  | `MULTIPART_ERROR_BRAND` | const | `unique symbol` | Holds the `Symbol.for` brand `MultipartError` carries so `isMultipartError` recognizes an instance across duplicate copies of this package — a registry symbol rather than a module-local `Symbol()`, which would mint an unequal symbol per copy. |
200
- | `NODE_COMPRESSION_ENCODINGS` | const | `readonly Encoding[]` | Lists `['gzip', 'deflate']`, the content-codings `createNodeCompression` offers — what `node:zlib` guarantees on every Node runtime, so this face never feature-detects. |
212
+ | `NODE_COMPRESSION_ENCODINGS` | const | `readonly Encoding[]` | Lists `['gzip', 'deflate']`, the content-codings `createNodeCompression` offers — the codecs of `node:zlib`, which every Node runtime bundles, so this face never feature-detects. |
201
213
  | `DEFAULT_STATIC_INDEX` | const | `"index.html"` | Names `'index.html'`, `createStatic`'s default directory-index filename. |
202
214
  | `DEFAULT_STATIC_FALLBACK_EXCLUDE` | const | `"/api"` | Names `'/api'`, `createStatic`'s `fallback: true` default excluded path prefix. |
203
215
  | `DEFAULT_STATIC_DOTFILES` | const | `NonNullable<StaticOptions['dotfiles']>` | Names `'ignore'`, `createStatic`'s default policy for a path carrying a dotfile segment. |
@@ -209,51 +221,101 @@ const handle = compose<State>([boundary, security], async (_request, context) =>
209
221
  | `DEFAULT_MULTIPART_TOTAL` | const | `52428800` | Holds `52_428_800`, `createMultipart`'s default combined request-body byte-size cap. |
210
222
  | `MULTIPART_MAX_HEADER_BLOCK` | const | `16384` | Holds `16_384`, the maximum bytes a single multipart part's header block may occupy before it is malformed. |
211
223
  | `MULTIPART_MAX_PREAMBLE` | const | `65536` | Holds `65_536`, the maximum bytes scanned before the first multipart boundary is found before it is malformed. |
224
+ | `MULTIPART_MAX_BOUNDARY` | const | `70` | Holds `70`, the maximum length of a multipart boundary, which RFC 2046 § 5.1.1 fixes. |
212
225
  | `RESERVED_DEVICE_NAMES` | const | `ReadonlySet<string>` | Lists the Windows reserved device-name stems (CVE-2025-27210) — matched case-insensitively against the segment's stem (before its first `.`). |
213
226
  | `EXTENSION_TYPES` | const | `Readonly<Record<string, string>>` | Holds the file-extension (lowercase, with leading `.`) → MIME type lookup table for static serving. |
214
227
 
228
+ ### Contracts
229
+
230
+ | Name | Kind | Signature | Summary |
231
+ | ------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
232
+ | `BOUNDARY_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { expose?: boolean; report?: (...args: never[]) => unknown; }>>` | Admits `BoundaryOptions` whole for `createBoundary`: a boolean `expose` and a function `report`. |
233
+ | `TELEMETRY_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ record: (...args: never[]) => unknown; } & {}>>` | Admits `TelemetryOptions` whole for `createTelemetry`: a required function `record`. |
234
+ | `COMPRESSION_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { threshold?: number; encodings?: readonly ("deflate" \| "gzip" \| "identity")[]; filter?: (...args: never[]) => unknown; }>>` | Admits `CompressionOptions` whole for `createCompression`: a non-negative finite `threshold`, an `encodings` array of `Encoding` literals, and a function `filter`. |
235
+ | `NODE_COMPRESSION_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { threshold?: number; filter?: (...args: never[]) => unknown; }>>` | Admits `NodeCompressionOptions` whole for `createNodeCompression`: a non-negative finite `threshold` and a function `filter`. |
236
+ | `SECURITY_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { frame?: "DENY" \| "SAMEORIGIN" \| false; csp?: string \| false; referrer?: string \| false; permissions?: string \| false; coop?: string \| false; corp?: string \| false; cluster?: string \| false; coep?: string \| boolean; hsts?: string \| boolean; identifier?: false \| Readonly<{} & { trust?: boolean; }>; }>>` | Admits `SecurityOptions` whole for `createSecurity`: each header option is a string or `false`, `coep` and `hsts` are a string or a boolean, and `identifier` is `{ trust? }` or `false`. |
237
+ | `CORS_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { origin?: string \| readonly string[]; methods?: readonly string[]; headers?: readonly string[]; }>>` | Admits `CORSOptions` whole for `createCORS`: `origin` is a string or a string array, and `methods` and `headers` are string arrays. |
238
+ | `DEADLINE_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ ms: number; } & { status?: number; }>>` | Admits `DeadlineOptions` whole for `createDeadline`: an integer `ms` from 1 through 2147483647, the range `@orkestrel/timeout` enforces, and an integer `status` from 200 through 599. |
239
+ | `FORWARDED_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ proxies: number; } & {}> \| Readonly<{ trusted: readonly string[]; } & {}>>` | Admits `ForwardedOptions` whole for `createForwarded`: exactly one of an integer `proxies` of at least 1 or a `trusted` string array. |
240
+ | `ETAG_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { weak?: boolean; }>>` | Admits `ETagOptions` whole for `createETag`: a boolean `weak`. |
241
+ | `BEARER_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ verify: (...args: never[]) => unknown; } & { header?: string; scheme?: string; challenge?: { readonly [k: string]: string; }; }>>` | Admits `BearerOptions` whole for `createBearer`: a required function `verify`, string `header` and `scheme`, and a `challenge` record of strings. |
242
+ | `LIMITER_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ max: number; window: number; } & { store?: unknown; capacity?: number; key?: (...args: never[]) => unknown; message?: string; clock?: (...args: never[]) => unknown; policy?: boolean; evict?: (...args: never[]) => unknown; }>>` | Admits `LimiterOptions` whole for `createLimiter`: an integer `max` of at least 1, a positive finite `window`, an integer `capacity` of at least 1, and the declared functions; `store` is a foreign key that `LIMITER_STORE_FOREIGN` checks after admission. |
243
+ | `SESSION_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ transport: unknown; } & { store?: unknown; ttl?: number; lifetime?: number; capacity?: number; evict?: (...args: never[]) => unknown; create?: (...args: never[]) => unknown; mint?: (...args: never[]) => unknown; required?: boolean; clock?: (...args: never[]) => unknown; }>>` | Admits `SessionOptions` whole for `createSession`: positive finite `ttl` and `lifetime`, an integer `capacity` of at least 1, and the declared functions; `transport` and `store` are foreign keys that `SESSION_TRANSPORT_FOREIGN` and `SESSION_STORE_FOREIGN` check after admission. |
244
+ | `COOKIE_TRANSPORT_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ signer: unknown; } & { name?: string; cookie?: Readonly<{} & { path?: string; domain?: string; maxAge?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "Lax" \| "None" \| "Strict"; }>; }>>` | Admits `CookieTransportOptions` whole for `createCookieTransport`: a string `name`, a required `signer`, checked as a foreign key, and an owned `cookie` record of the six optional members `@orkestrel/server` declares: string `path` and `domain`, a finite number `maxAge` (a non-finite value writes `Max-Age=NaN` or `Max-Age=Infinity` into `Set-Cookie`), boolean `httpOnly` and `secure`, and a `sameSite` of `'Strict'`, `'Lax'`, or `'None'`. |
245
+ | `HEADER_TRANSPORT_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { header?: string; }>>` | Admits `HeaderTransportOptions` whole for `createHeaderTransport`: a string `header`. |
246
+ | `SESSION_LIMITS_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { ttl?: number; lifetime?: number; }>>` | Admits `SessionLimits` whole for `createDatabaseSessionStore`: positive finite `ttl` and `lifetime`. |
247
+ | `MEMORY_SESSION_STORE_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { ttl?: number; lifetime?: number; capacity?: number; evict?: (...args: never[]) => unknown; }>>` | Admits `MemorySessionStoreOptions` whole for `createMemorySessionStore`: positive finite `ttl` and `lifetime`, an integer `capacity` of at least 1, and a function `evict`. |
248
+ | `MEMORY_LIMITER_STORE_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { capacity?: number; evict?: (...args: never[]) => unknown; }>>` | Admits `MemoryLimiterStoreOptions` whole for `createMemoryLimiterStore`: an integer `capacity` of at least 1 and a function `evict`. |
249
+ | `CSRF_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ signer: unknown; } & { cookie?: string; header?: string; field?: string; safe?: readonly string[]; }>>` | Admits `CSRFOptions` whole for `createCSRF`: a required `signer` that `SIGNER_FOREIGN` checks after admission, string `cookie`, `header`, and `field`, and a `safe` string array. |
250
+ | `SCOPE_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ paths: string \| readonly string[]; handler: (...args: never[]) => unknown; } & {}>>` | Admits the arguments of `only` and `except` whole: `paths` is a string or a string array, and `handler` is a function. |
251
+ | `ASSET_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ source: unknown; } & { store?: unknown; }>>` | Admits `AssetOptions` whole for `createAssets`: both keys are foreign, so `ASSET_SOURCE_FOREIGN` and `ASSET_STORE_FOREIGN` check them after admission. |
252
+ | `STATIC_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ root: string; } & { prefix?: string; index?: string; dotfiles?: "allow" \| "deny" \| "ignore"; cache?: number; etag?: boolean; fallback?: boolean \| Readonly<{} & { exclude?: string; }>; }>>` | Admits `StaticOptions` whole for `createStatic`: a non-empty string `root`, a non-negative finite `cache`, a `dotfiles` literal, and a `fallback` that is a boolean or `{ exclude? }`. |
253
+ | `MULTIPART_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{} & { limits?: Readonly<{} & { file?: Readonly<{} & { size?: number; count?: number; }>; field?: Readonly<{} & { size?: number; count?: number; }>; total?: number; }>; allowed?: readonly string[]; directory?: string; }>>` | Admits `MultipartOptions` whole for `createMultipart`: non-negative finite sizes and totals, non-negative integer counts, a string array `allowed`, and a string `directory`. |
254
+ | `UPLOADED_FILE_CONTRACT` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ field: string; name: string; size: number; mime: string; validated: boolean; status: "moved" \| "staged"; path: string; } & {}>>` | Admits one `UploadedFile` whole for `createUploadedFile`: string `field`, `name`, `mime`, and `path`, a non-negative finite `size`, a boolean `validated`, and a `status` literal. |
255
+ | `LIMITER_STORE_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `LimiterOptions.store` declares: `consume`. |
256
+ | `SESSION_TRANSPORT_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `SessionOptions.transport` declares: `read`, `write`, and `clear`. |
257
+ | `SESSION_STORE_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `SessionOptions.store` declares: `get`, `set`, and `delete`. |
258
+ | `SIGNER_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `CookieTransportOptions.signer` and `CSRFOptions.signer` declare: `sign` and `verify`. |
259
+ | `ASSET_SOURCE_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `AssetOptions.source` declares: `read`. |
260
+ | `ASSET_STORE_FOREIGN` | const | `import("./types.js").ForeignContract` | Holds the members `AssetOptions.store` declares: `get`, `set`, and `delete`. |
261
+
262
+ ### Combinators
263
+
264
+ | Name | Kind | Signature | Summary |
265
+ | ---------------------- | -------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
266
+ | `buildForeignContract` | function | `(members: readonly string[]) => ForeignContract` | Builds a `ForeignContract` whose every declared member is a function — the contract an implementation key admits, such as a store, a transport, or a source. |
267
+
215
268
  ### Shapers
216
269
 
217
270
  | Name | Kind | Signature | Summary |
218
271
  | ---------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
219
272
  | `sessionColumns` | const | `{ id: import("@orkestrel/contract").StringShape; session: import("@orkestrel/contract").JSONShape; seen: import("@orkestrel/contract").NumberShape; created: import("@orkestrel/contract").NumberShape; }` | Holds the `@orkestrel/database` column shape for a `SessionRow` table. Pass it as-is to `createDatabase({ tables: { sessions: sessionColumns } })` so an app declaring a durable session table never hand-writes the shape. |
220
273
 
221
- ### Helpers — core
222
-
223
- | Name | Kind | Signature | Summary |
224
- | ----------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
225
- | `resolveKey` | function | `(state: BearerState<unknown> & ClientState & ConnectionState) => string` | Derives `createLimiter`'s default rate-limit bucket key from a request's resolved identity facts. |
226
- | `renderChallenge` | function | `(scheme: string, parameters?: Readonly<Record<string, string>>) => string` | Renders a `WWW-Authenticate` challenge as the scheme alone, or the scheme followed by quoted auth-params in the record's own key order. |
227
- | `resolveOptInHeader` | function | `(value: string \| boolean \| undefined, fallback: string) => string \| undefined` | Resolves an opt-in, value-bearing security header — `string \| boolean` (off by default, `true` uses the secure default), the shape `createSecurity`'s `coep`/`hsts` options use, distinct from the plain value-or-`false` shape `resolveSecurityHeader` (the peer substrate) handles. |
228
- | `buildRetryAfter` | function | `(expiry: number, now: number) => string` | Builds the `Retry-After` header value — whole seconds until a window reset, floored at a minimum of `1`. |
229
- | `buildRateLimitField` | function | `(remaining: number, expiry: number, now: number) => string` | Builds the draft `RateLimit` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
230
- | `buildRateLimitPolicyField` | function | `(max: number, window: number) => string` | Builds the draft `RateLimit-Policy` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
231
- | `matchesTrustedEntry` | function | `(address: string, entry: string) => boolean` | Checks whether a candidate address is a bare (non-CIDR) trusted-hop match — an exact string match, or a simple prefix-CIDR match for IPv4 (`/8`–`/32`). An IPv6 entry matches by exact string only — there is no IPv6 CIDR support. |
232
- | `resolveForwardedFor` | function | `(header: string \| undefined, trust: ForwardedOptions) => string \| undefined` | Walks `X-Forwarded-For` right-to-left and resolves the first untrusted hop address — `createForwarded`'s core algorithm. |
233
- | `detectEncodings` | function | `(candidates: readonly Encoding[]) => readonly Encoding[]` | Feature-detects which of `candidates` the runtime's `CompressionStream` actually supports — `createCompression`'s construction-time intersection. |
234
- | `compressBytes` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>) => Promise<Uint8Array<ArrayBuffer>>` | Compresses bytes with the host-independent `CompressionStream` primitive. |
235
- | `matchesUnbufferableResponse` | function | `(method: string, response: Response, skipHeader: string) => boolean` | Checks whether a response must skip the compression and ETag buffering pipeline — the shared cheap-skip predicate both batteries apply before ever touching `response.arrayBuffer()`, true for a `HEAD` request, a `204`/`304` or otherwise bodyless response, an `event-stream` response, and a response already carrying the header the caller is about to set. |
236
- | `isCompressionNegotiated` | function | `(encoding: Encoding \| undefined) => encoding is Exclude<Encoding, 'identity'>` | Checks whether a negotiated `Accept-Encoding` outcome is worth acting on — `createCompression`'s negotiation-eligibility half of the skip list. |
237
- | `rebuildResponse` | function | `(body: ConstructorParameters<typeof Response>[0], response: Response, headers?: ConstructorParameters<typeof Headers>[0]) => Response` | Rebuilds a `Response` around a replacement body while preserving its status/statusText — the buffered-response reconstruction shared by the compression and ETag batteries after they have consumed `response.arrayBuffer()`. |
238
- | `compressResponse` | function | `(request: Request, context: MiddlewareContext<unknown>, response: Response, options: CompressResponseOptions) => Promise<Response>` | Runs the shared negotiate → skip → threshold → compress → header-set skeleton `createCompression` and `createNodeCompression` compose — response-body compression over a caller-supplied set of feature-detected codings. |
239
- | `transferSessionState` | function | `(from: SessionInterface, to: SessionInterface) => void` | Copies every entry of one session's `state` into another — the regenerate state-carry `createSession`'s `control.regenerate()` applies. |
240
- | `sessionExpired` | function | `(cursors: SessionCursors, now: number, limits: SessionLimits) => boolean` | Checks whether a session has aged past its idle timeout or absolute lifetime as of `now` — the pure expiry predicate `MemorySessionStore` delegates to. |
241
- | `snapshotSession` | function | `(session: SessionInterface) => SessionSnapshot` | Snapshots a session's `state` into a plain, serializable record — the projection a durable store's `set` writes to disk. |
242
- | `validateSessionLimits` | function | `(limits: SessionLimits \| undefined) => void` | Validates a store's idle and absolute-lifetime thresholds, throwing when either is present and malformed — the shared construction gate `MemorySessionStore` and `DatabaseSessionStore` both apply, so one malformed `ttl` is refused identically by whichever store receives it. |
243
- | `isPreflight` | function | `(method: string, headers: Headers) => boolean` | Determines whether a request is a CORS preflight — an `OPTIONS` request carrying an `Access-Control-Request-Method` header. |
244
- | `buildClient` | function | `(ip: string \| undefined) => Client` | Builds the `Client` slice `createForwarded` stashes, from the resolved client IP — a leaf shaping helper. |
245
- | `equalsConstantTime` | function | `(a: string, b: string) => boolean` | Compares two strings in constant time — `createCSRF`'s double-submit token comparison, avoiding a timing oracle on the submitted-vs-cookie match. |
246
-
247
- ### Validators — core
274
+ ### Helpers — web-standard
275
+
276
+ | Name | Kind | Signature | Summary |
277
+ | -------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
278
+ | `resolveKey` | function | `(state: BearerState<unknown> & ClientState, connection: Connection) => string` | Derives `createLimiter`'s default rate-limit bucket key from a request's resolved identity facts. |
279
+ | `renderChallenge` | function | `(scheme: string, parameters?: Readonly<Record<string, string>>, door?: string) => string` | Renders a `WWW-Authenticate` challenge as the scheme alone, or the scheme followed by quoted auth-params in the record's own key order. |
280
+ | `resolveOptInHeader` | function | `(value: string \| boolean \| undefined, fallback: string) => string \| undefined` | Resolves an opt-in, value-bearing security header — `string \| boolean` (off by default, `true` uses the secure default), the shape `createSecurity`'s `coep`/`hsts` options use, distinct from the plain value-or-`false` shape `resolveSecurityHeader` (the peer substrate) handles. |
281
+ | `buildRetryAfter` | function | `(expiry: number, now: number) => string` | Builds the `Retry-After` header value — whole seconds until a window reset, floored at a minimum of `1`. |
282
+ | `buildRateLimitField` | function | `(remaining: number, expiry: number, now: number) => string` | Builds the draft `RateLimit` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
283
+ | `buildRateLimitPolicyField` | function | `(max: number, window: number) => string` | Builds the draft `RateLimit-Policy` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
284
+ | `matchesTrustedEntry` | function | `(address: string, entry: string) => boolean` | Checks whether a candidate address is a trusted-hop match — an exact match, or a prefix-CIDR match for IPv4 (`/8`–`/32`), with an IPv4-mapped address compared by its embedded IPv4. An IPv6 entry matches by exact string only — there is no IPv6 CIDR support. |
285
+ | `resolveForwardedFor` | function | `(header: string \| undefined, trust: ForwardedOptions, peer: string \| undefined) => string \| undefined` | Resolves the client address from `X-Forwarded-For` and the socket peer — `createForwarded`'s core algorithm. |
286
+ | `matchesScope` | function | `(patterns: readonly CompiledPath[], pathname: string) => boolean` | Checks whether a request pathname matches any compiled scope pattern — the test `only` and `except` apply, through the router's own `matchPath`. |
287
+ | `detectEncodings` | function | `(candidates: readonly Encoding[]) => readonly Encoding[]` | Feature-detects which of `candidates` the runtime's `CompressionStream` actually supports — `createCompression`'s construction-time intersection. |
288
+ | `compressBytes` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>) => Promise<Uint8Array<ArrayBuffer>>` | Compresses bytes with the host-independent `CompressionStream` primitive. |
289
+ | `matchesUnbufferableResponse` | function | `(method: string, response: Response, skipHeader: string) => boolean` | Checks whether a response must skip the compression and ETag buffering pipeline — the shared cheap-skip predicate both batteries apply before ever touching `response.arrayBuffer()`, true for a `HEAD` request, a `204`/`304` or otherwise bodyless response, an `event-stream` response, and a response already carrying the header the caller is about to set. |
290
+ | `matchesUntransformableResponse` | function | `(response: Response) => boolean` | Checks whether a response must keep its content coding — a `206 Partial Content`, whose `Content-Range` counts bytes of the identity representation, or a response whose `Cache-Control` carries the `no-transform` directive (RFC 9111 § 5.2.2.6). |
291
+ | `isCompressionNegotiated` | function | `(encoding: Encoding \| undefined) => encoding is Exclude<Encoding, 'identity'>` | Checks whether a negotiated `Accept-Encoding` outcome is worth acting on — `createCompression`'s negotiation-eligibility half of the skip list. |
292
+ | `rebuildResponse` | function | `(body: ConstructorParameters<typeof Response>[0], response: Response, headers?: ConstructorParameters<typeof Headers>[0]) => Response` | Rebuilds a `Response` around a replacement body while preserving its status/statusText — the buffered-response reconstruction shared by the compression and ETag batteries after they have consumed `response.arrayBuffer()`. |
293
+ | `compressResponse` | function | `(request: Request, context: MiddlewareContext<unknown>, response: Response, options: CompressResponseOptions) => Promise<Response>` | Runs the shared negotiate → skip → threshold → compress → header-set skeleton `createCompression` and `createNodeCompression` compose — response-body compression over a caller-supplied set of feature-detected codings. |
294
+ | `transferSessionState` | function | `(from: SessionInterface, to: SessionInterface) => void` | Copies every entry of one session's `state` into another — the regenerate state-carry `createSession`'s `control.regenerate()` applies. |
295
+ | `matchesSessionState` | function | `(before: ReadonlyMap<string, unknown>, after: ReadonlyMap<string, unknown>) => boolean` | Checks whether two session states hold the same keys, each bound to the same value by `Object.is` — the test `createSession` applies to decide whether a handler wrote to a session. |
296
+ | `generateNonce` | function | `() => string` | Generates a random nonce: 32 bytes from the platform's cryptographic source, as 43 base64url characters — the nonce `createCSRF` keeps in its cookie and a CSRF token's random part. |
297
+ | `signCSRFToken` | function | `(signer: SignerInterface, binding: string) => Promise<string>` | Signs a CSRF token bound to `binding`: `random.signature`, where `signature` is the signer's HMAC over `CSRF_LABEL`, `binding`, and `random`, so the token carries no form of the binding. |
298
+ | `verifyCSRFToken` | function | `(signer: SignerInterface, binding: string, token: string) => Promise<boolean>` | Verifies a CSRF token against `binding`: the token's random part must match `CSRF_NONCE_PATTERN`, and its signature must be the signer's HMAC over `CSRF_LABEL`, `binding`, and that random part, under any held key. |
299
+ | `sessionExpired` | function | `(cursors: SessionCursors, now: number, limits: SessionLimits) => boolean` | Checks whether a session has aged past its idle timeout or absolute lifetime as of `now` — the pure expiry predicate `MemorySessionStore` delegates to. |
300
+ | `snapshotSession` | function | `(session: SessionInterface) => SessionSnapshot` | Snapshots a session's `state` into a plain, serializable record — the projection a durable store's `set` writes to disk. |
301
+ | `admitForeign` | function | `(door: string, path: readonly string[], foreign: ForeignContract, value: unknown) => void` | Admits one foreign implementation key against the members its published interface declares, accepting a class instance and unknown members. |
302
+ | `admitOptions` | function | `<T>(door: string, contract: ContractInterface<T>, value: unknown) => void` | Admits an options bag whole against its compiled contract, refusing a missing required key, an undeclared key, and a value outside a declared range. |
303
+ | `isPreflight` | function | `(method: string, headers: Headers) => boolean` | Determines whether a request is a CORS preflight — an `OPTIONS` request carrying an `Access-Control-Request-Method` header. |
304
+ | `buildClient` | function | `(ip: string \| undefined) => Client` | Builds the `Client` slice `createForwarded` stashes, from the resolved client IP — a leaf shaping helper. |
305
+ | `equalsConstantTime` | function | `(a: string, b: string) => boolean` | Compares two strings in constant time when their lengths match, so a per-character mismatch never changes how long the comparison takes. |
306
+
307
+ ### Validators — web-standard
248
308
 
249
309
  Each guard in the following table is total: it accepts any input, returns `false` off-shape, and never throws.
250
310
 
251
- | Name | Kind | Signature | Summary |
252
- | ------------------ | -------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
253
- | `isSession` | function | `(value: unknown) => value is SessionInterface` | Determines whether a value implements `SessionInterface` — a total structural guard: an `id` string, a `state` `Map`, and the `set`, `delete`, and `clear` mutators. Prototype-agnostic — accepts a plain object, a null-prototype object, and a class instance (a real `Session`), because a restored or stored session is routinely a class instance rather than a literal. |
254
- | `isSessionControl` | function | `(value: unknown) => value is SessionControlInterface` | Determines whether a value implements `SessionControlInterface` — a total structural guard: callable `regenerate` and `destroy`. |
255
- | `isMultipartFile` | function | `(value: unknown) => value is MultipartFile` | Determines whether a value is one staged `MultipartFile` record — a total structural guard checking every required field's shape. |
256
- | `isMultipartBody` | function | `(value: unknown) => value is MultipartBody` | Determines whether a value implements `MultipartBody` — a total structural guard: `files` keyed by field name to arrays of `MultipartFile`, and a `fields` string record. |
311
+ | Name | Kind | Signature | Summary |
312
+ | ------------------ | -------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
313
+ | `isSession` | function | `(value: unknown) => value is SessionInterface` | Determines whether a value implements `SessionInterface` — a total structural guard: an `id` string, a `state` `Map`, and the `set`, `delete`, and `clear` mutators. Prototype-agnostic — accepts a plain object, a null-prototype object, and a class instance (a real `Session`), because a restored or stored session is routinely a class instance rather than a literal. |
314
+ | `isSessionControl` | function | `(value: unknown) => value is SessionControlInterface` | Determines whether a value implements `SessionControlInterface` — a total structural guard over every declared member: boolean `destroyed` and `fresh`, a `successor` that is `undefined` or satisfies `isSession`, and callable `regenerate` and `destroy`. Prototype-agnostic — accepts a plain object, a callable object, and a class instance (a real `SessionControl`), and ignores unknown members. A value missing a declared member answers false, and so does a member read that throws, as on a revoked proxy. |
315
+ | `isMultipartFile` | function | `(value: unknown) => value is MultipartFile` | Determines whether a value is one staged `MultipartFile` record — a total structural guard checking every required field's shape. |
316
+ | `isMultipartBody` | function | `(value: unknown) => value is MultipartBody` | Determines whether a value implements `MultipartBody` — a total structural guard: `files` keyed by field name to arrays of `MultipartFile`, and a `fields` string record. |
317
+
318
+ Before 0.0.35, `isSessionControl` refused every class instance, a real `SessionControl` included, and accepted any value with callable `regenerate` and `destroy`. From 0.0.35, it also requires `destroyed`, `successor`, and `fresh` at their declared types, so a value that carries only the two methods answers false.
257
319
 
258
320
  ### Helpers — node
259
321
 
@@ -270,16 +332,15 @@ Each guard in the following table is total: it accepts any input, returns `false
270
332
  | `computeFileETag` | function | `(size: number, mtimeMs: number) => string` | Computes a static file's weak ETag from its size and modification time. |
271
333
  | `detectMIME` | function | `(head: Uint8Array) => string \| undefined` | Sniffs a MIME type from a file's leading bytes against a small magic-byte table (jpeg, png, gif87a/89a, webp, pdf, zip). |
272
334
  | `matchesBytes` | function | `(bytes: Uint8Array, signature: readonly number[], offset?: number) => boolean` | Checks whether `bytes` contains `signature` at the requested offset. |
273
- | `compressNodeBytes` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>) => Promise<Uint8Array<ArrayBuffer>>` | Compresses response bytes with Node's guaranteed zlib gzip/deflate codecs. |
335
+ | `compressNodeBytes` | function | `(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>) => Promise<Uint8Array<ArrayBuffer>>` | Compresses response bytes with the gzip or deflate codec of `node:zlib`, which every Node runtime bundles. |
274
336
  | `extractMultipartBoundary` | function | `(contentType: string \| null) => string \| undefined` | Extracts the `boundary` parameter from a `Content-Type` header, or `undefined` when the request is not `multipart/form-data`. |
275
337
  | `parsePartHeaders` | function | `(block: string) => PartHeaders` | Parses one multipart part's raw header block into its `name` (from `Content-Disposition`), optional `filename`, and optional `Content-Type`. |
276
338
  | `resolveMultipartLimits` | function | `(limits: MultipartLimitsInput \| undefined) => MultipartLimits` | Resolves `createMultipart`'s effective `MultipartLimits`, applying every documented default to an omitted leaf. |
277
- | `createUploadedFile` | function | `(input: UploadedFile) => UploadedFile` | Builds a frozen `UploadedFile` record. |
278
339
  | `streamFile` | function | `(source: string \| FileHandle, range?: ByteRange) => ReadableStream<Uint8Array>` | Adapts a `node:fs` read stream over a file path (or an already-open `FileHandle`) into a DOM-compatible `ReadableStream<Uint8Array>` — the single shared node↔web stream bridge every static-file and uploaded-file response body routes through. |
279
340
  | `streamUploadedFile` | function | `(file: UploadedFile) => ReadableStream<Uint8Array>` | Opens a staged/moved uploaded file as a web `ReadableStream`. |
280
341
  | `readUploadedFile` | function | `(file: UploadedFile) => Promise<Uint8Array>` | Reads a staged/moved uploaded file's full contents into memory. |
281
342
  | `moveUploadedFile` | function | `(file: UploadedFile, destination: string) => Promise<UploadedFile>` | Moves a staged uploaded file to its final `destination`. |
282
- | `unlinkStagedFiles` | function | `(body: MultipartBody) => Promise<void>` | Attempts to unlink every still-`'staged'` file in a parsed `MultipartBody` — the fail-closed cleanup `createMultipart` runs when its downstream handler throws, mirroring `parseMultipartRequest`'s own cleanup pattern (a missing file is already gone; failures are swallowed). |
343
+ | `unlinkStagedFiles` | function | `(body: MultipartBody) => Promise<void>` | Attempts to unlink every still-`'staged'` file in a parsed `MultipartBody` — the cleanup `createMultipart` runs when its downstream handler settles, mirroring `parseMultipartRequest`'s own cleanup pattern (a missing file is already gone; failures are swallowed). |
283
344
 
284
345
  ### Parsers — node
285
346
 
@@ -305,6 +366,7 @@ omission is asserted rather than assumed, and adding it to the barrel would turn
305
366
 
306
367
  | Name | Kind | Signature | Summary |
307
368
  | ---------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
369
+ | `createUploadedFile` | function | `(input: UploadedFile) => UploadedFile` | Builds a frozen `UploadedFile` record. |
308
370
  | `createCookieTransport` | function | `(options: CookieTransportOptions) => SessionTransportInterface` | Creates a signed-cookie `SessionTransportInterface` — the session id travels as a `signToken`-signed cookie value. |
309
371
  | `createHeaderTransport` | function | `(options?: HeaderTransportOptions) => SessionTransportInterface` | Creates a bare-header `SessionTransportInterface` — the session id travels verbatim in a request/response header. |
310
372
  | `createMemorySessionStore` | function | `<S extends SessionInterface>(options?: MemorySessionStoreOptions) => SessionStoreInterface<S>` | Creates the default in-process `SessionStoreInterface` — a `Map`-backed store enforcing an idle timeout and an absolute lifetime. |
@@ -357,7 +419,10 @@ the write path.
357
419
  `regenerate` is the OWASP anti-fixation primitive (rotate the id, keep the
358
420
  state); `destroy` ends the session outright. Both record intent
359
421
  synchronously; the store I/O and transport write happen after `next()`
360
- returns (`destroy` supersedes a prior `regenerate`).
422
+ returns (`destroy` supersedes a prior `regenerate`). `fresh` is `true` for a
423
+ session minted on this request, which the client holds no credential for
424
+ until a write or a `regenerate` persists it; `createCSRF` reads it to bind a
425
+ token to the battery's nonce instead.
361
426
 
362
427
  | Method | Returns | Summary |
363
428
  | ------------ | ------- | --------------------------------------------------------------------------------- |
@@ -406,7 +471,7 @@ returning onion makes "before send" automatic).
406
471
 
407
472
  ## Contract
408
473
 
409
- These invariants hold across `src/core` / `src/server` ↔ `middleware.md`.
474
+ These invariants hold across `src/server` ↔ `middleware.md`.
410
475
 
411
476
  1. **Guide ↔ source bijection.** Every `function` / `class` / `interface` /
412
477
  `type` / `const` row in the `## Surface` tables is a real export of its
@@ -419,40 +484,88 @@ These invariants hold across `src/core` / `src/server` ↔ `middleware.md`.
419
484
 
420
485
  ### The ordering doctrine
421
486
 
422
- The canonical onion, outermost first, and the failure each position
487
+ The canonical onion, outermost first, is `createTelemetry`, `createNodeCompression`,
488
+ `createSecurity`, `createCORS`, `createBoundary`, `createDeadline`, `createForwarded`,
489
+ `createETag`, `createBearer`, `createLimiter`, `createBody`, `createSession`, and `createCSRF`.
490
+ Before 0.0.35, the canonical onion mounted `createCompression` where it mounts
491
+ `createNodeCompression`, and placed `createSecurity` and `createCORS` inside `createBoundary` and
492
+ `createDeadline`, so an error the boundary rendered from a throw, and the deadline's answer,
493
+ carried no security headers and no `Vary: Origin`. Each item names a position and the failure it
423
494
  prevents:
424
495
 
425
496
  3. **`createTelemetry` is outermost.** It sees the mapped status (after
426
497
  `createBoundary` renders) and measures honest wall-clock duration —
427
498
  anything mounted inside it would be excluded from the timing.
428
- 4. **`createCompression` sits outside `createBoundary`.** An error `Response`
499
+ 4. **Compression sits outside `createBoundary`.** An error `Response`
429
500
  the boundary renders from a caught throw still passes through
430
501
  compression — mount it inside instead and error bodies ship uncompressed.
502
+ Compression leaves a `206` response and a response whose `Cache-Control` carries
503
+ `no-transform` identity-coded (`matchesUntransformableResponse`), because the
504
+ `Content-Range` of a `206` counts bytes of the identity representation; before
505
+ 0.0.35 it compressed both. Mount `createNodeCompression`, as the canonical
506
+ onion does, and mount `createCompression` only on a host without
507
+ `node:zlib`: in the kernel readings of 2026-11-16 on middleware 0.0.33 and
508
+ Node 22.23.5, gzip through `CompressionStream` took 542 µs per 1 KiB
509
+ response against 327 µs through `node:zlib`, and 815 µs against 617 µs at
510
+ 64 KiB.
431
511
  5. **`createBoundary` is the renderer.** Everything mounted beneath it may
432
512
  throw `HTTPError` (or anything else) and have it mapped to a `Response`;
433
513
  nothing below it needs its own try/catch.
434
- 6. **`createDeadline` sits inside the boundary.** A downstream `AbortError`
435
- from the deadline firing is another throw the boundary maps cleanly
436
- — mounting it outside would bypass that rendering.
437
- 7. **`createSecurity` is a documented tradeoff, not a fixed position.** The
438
- canonical order places it inside the boundary, so an error `Response` a
439
- handler explicitly returns still carries security headers, but an error
440
- the boundary renders from a throw does not (`createSecurity`'s `next()`
441
- never resolves for a throw beneath it). A consumer who wants headers on
442
- every response, thrown errors included, mounts `createSecurity` above
443
- `createBoundary` instead — both orders are legitimate; pick the one your
444
- threat model wants.
445
- 8. **`createCors` claims preflights before the dispatcher's auto-`OPTIONS`.**
446
- Its `OPTIONS` short-circuit runs before the terminal `Dispatcher.handle`
447
- ever sees the request, by construction (any middleware position ahead of
448
- the terminal works — CORS needs only array membership, not a fragile
449
- slot).
514
+ 6. **`createDeadline` sits inside the boundary.** A deadline that fires calls
515
+ `context.abort(reason)`, answers `status` with no body, and discards
516
+ whatever the downstream returns or throws after that. Inside the boundary,
517
+ a throw a handler raises on the aborted `signal` stops at the deadline;
518
+ mounted outside, the boundary beneath it reports that throw as a fault. The
519
+ battery builds no `Request`, so it composes with `createBody` in either
520
+ order.
521
+ 7. **`createSecurity` sits outside `createBoundary` and `createDeadline`.**
522
+ Every response then carries the security headers: a returned response, a
523
+ redirect, an error the boundary renders from a throw, and the deadline's
524
+ answer. Mounted inside the boundary, `createSecurity`'s `next()` never
525
+ resolves for a throw beneath it, so the rendered error ships without the
526
+ headers.
527
+ 8. **`createCORS` sits outside `createBoundary` and `createDeadline`.** In
528
+ list mode every response then carries `Vary: Origin`, an error the
529
+ boundary renders from a throw and the deadline's answer included, so a
530
+ shared cache never serves one origin's answer to another. Its preflight
531
+ answer runs before the terminal `Dispatcher.handle` sees the `OPTIONS`
532
+ request, so it claims a preflight before the dispatcher's automatic
533
+ `OPTIONS`.
450
534
  9. **`createForwarded` resolves client facts before anything keys off
451
535
  them.** `createLimiter`'s default key and any session/telemetry logic
452
- that wants `ClientState.client.ip` must run downstream of it.
453
- 10. **`createETag` sits inside `createCompression`.** The hash is computed
536
+ that wants `ClientState.client.ip` must run downstream of it. It reads
537
+ `X-Forwarded-For` only and ignores a `Forwarded` header. With
538
+ `proxies: N`, each of the `N` proxies appends one hop, and the client is
539
+ the hop at index `length − N`: `proxies: 1` behind one appending proxy
540
+ resolves the rightmost hop, the address that proxy saw. A header with fewer
541
+ than `N` hops resolves the socket peer. `proxies` fits only when every
542
+ request arrives through exactly `N` proxies, because a request that reaches
543
+ the server directly names its own client. With `trusted`, the walk starts
544
+ at the socket peer, `context.connection.ip`, and moves left through every
545
+ address the roster matches; the first address outside the roster is the
546
+ client. An untrusted socket peer is the client, whatever its header says,
547
+ and when the peer and every hop match, the leftmost hop is the client.
548
+ The roster compares an IPv4-mapped address (`::ffff:10.0.0.6`, which Node
549
+ reports for an IPv4 client on a dual-stack listener) by its embedded IPv4,
550
+ and reads an IPv4 address only as four decimal octets from 0 to 255, so a
551
+ hop such as `0x0a.0.0.1` matches no IPv4 entry. The resolved address is not
552
+ validated: it is the peer or the hop as written, so a malformed hop, a hop
553
+ with a port (`198.51.100.66:4711`), or an IPv4-mapped hop resolves
554
+ unchanged. Before 0.0.35, `proxies: 1` resolved the hop left of the
555
+ rightmost one, and `trusted` began its walk at the rightmost hop instead of
556
+ the socket peer.
557
+ 10. **`createETag` sits inside compression.** The hash is computed
454
558
  over the uncompressed representation — hashing the compressed bytes
455
559
  would break revalidation the instant the negotiated coding changes.
560
+ Behind compression, a strong tag on a coded body gains `W/`, because one
561
+ tag across two codings is no strong validator (RFC 9110 § 8.8.1), and the
562
+ weak tag still revalidates. A `304` carries the tag and the `Vary` header
563
+ that the `200` response would have carried. The `304` that `createETag` answers states the
564
+ length of the `200` body it stands for, and compression drops that length
565
+ from a `304` whose `200` it would code. Before 0.0.35, a coded body kept
566
+ its strong tag, a `304` passed compression with the strong tag and no
567
+ `Vary: Accept-Encoding`, and the `304` that `createETag` answered carried
568
+ no `Content-Length`.
456
569
  11. **`createBearer` sits before `createLimiter`.** The limiter's default key
457
570
  derivation prefers a string `BearerState.token` (the `token:<value>` idiom)
458
571
  over a client-IP fallback — bearer must have already stashed it. An object
@@ -462,24 +575,30 @@ prevents:
462
575
  cached `context.body()` already resolved.
463
576
  13. **`createSession` sits before `createCSRF`.** CSRF's session-binding —
464
577
  the security acceptance bar's CSRF item — requires `context.state.session`
465
- to already be stashed.
578
+ and `context.state.control` to already be stashed.
466
579
 
467
580
  ### The security acceptance bar, as documented behavior
468
581
 
469
- 14. **CORS.** `Vary: Origin` is merged only on the reflect (allow-list) path,
470
- never on the `'*'` wildcard path; the literal `Origin: null` is never
471
- reflected even when the string `'null'` is allow-listed.
472
- 15. **Headers.** A hostile `X-Request-ID` (off-charset, oversize, or
582
+ 14. **CORS.** In list mode `Vary: Origin` is merged on every response and
583
+ preflight, from an allowed origin, a disallowed origin, or no `Origin`
584
+ alike, and never in `'*'` wildcard or fixed-string mode. A preflight from a
585
+ disallowed origin, or with no `Origin`, answers `204` with `Vary: Origin`
586
+ and no `Access-Control-*` header. The literal `Origin: null` is never
587
+ reflected even when the string `'null'` is allow-listed. Before 0.0.35,
588
+ list mode merged `Vary: Origin` only for an allowed origin, every preflight
589
+ carried `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers`,
590
+ and the battery and its options were named `createCors` and `CorsOptions`.
591
+ 15. **Headers.** A malformed `X-Request-ID` (off-charset, oversize, or
473
592
  CRLF-bearing) is never echoed — `createSecurity` mints a fresh
474
593
  `crypto.randomUUID()` instead; a custom `csp` string replaces the
475
594
  default wholesale (never merges); `X-Content-Type-Options: nosniff` is
476
595
  unconditional, with no opt-out.
477
596
  16. **Bearer.** `createBearer` returns a `401` for a missing, wrong-scheme, or empty token
478
597
  and for a credential `verify` refuses, and a throw from `verify` propagates
479
- unchanged. With `verify: (token) => verifyToken(token, secret)`, `verifyToken` is
480
- total over garbage, tampered, expired, or empty-rotation input — every failure
481
- renders `401`, never a crash; verification is constant-time through
482
- `crypto.subtle.verify`. The `401` is a returned response, so each outer
598
+ unchanged. With `verify: (token) => verifyToken(token, signer)`, `verifyToken` is
599
+ total over garbage, tampered, or expired input — every failure
600
+ renders `401`, never a crash; the signer that the `createSigner` function of
601
+ `@orkestrel/server` returns compares signature bytes only through `timingSafeEqual`. The `401` is a returned response, so each outer
483
602
  battery decorates it and `createBoundary`'s `report` never sees it; read
484
603
  refusals from `createTelemetry`'s status.
485
604
  17. **Limiter.** The key derivation never reads `X-Forwarded-For` itself (only
@@ -497,15 +616,26 @@ prevents:
497
616
  `prototype` scrub are the substrate's own `readBody` behavior
498
617
  (`ServerOptions.limit`) — this battery only drives the cache eagerly and
499
618
  maps its outcomes.
500
- 19. **Session.** The default `MemorySessionStore` enforces both an idle
619
+ 19. **Session.** `createSession` stores a session, and writes its
620
+ credential, only after a handler writes to it or regenerates it. A write
621
+ is a `set`, `delete`, or `clear` that leaves the state holding other keys,
622
+ or other values by `Object.is`, than it held when the handler started; a
623
+ `set` of the value a key already holds is none, so replace a value rather
624
+ than changing it in place when the store is durable. A request with no
625
+ credential gets a session with `control.fresh` true, and when the handler
626
+ writes nothing, the store and the response carry no trace of it: a flood
627
+ of such requests leaves every written session in place. Since 0.0.35 the
628
+ session cookie first appears on the response to the first write, where
629
+ earlier releases set it on the first response. The default `MemorySessionStore` enforces both an idle
501
630
  timeout (`ttl`, lazy eviction on `get`) and an absolute lifetime
502
631
  (`lifetime`, evicting even a continuously-touched session — `created`
503
632
  is stamped once at first `set` and preserved across every later
504
633
  re-persist); it is also capacity-capped (`capacity`, default
505
- `DEFAULT_SESSION_CAPACITY`) and evicts the least-recently-written id —
506
- every `set` (not `get`) refreshes recency — invoking the optional
507
- `evict` sink (throw-isolated) on a capacity eviction or an expired-entry
508
- prune, but never for an explicit `delete`; `control.regenerate()` rotates the id while carrying the
634
+ `DEFAULT_SESSION_CAPACITY`) and evicts the least recently used id —
635
+ every `set` and every live `get` refreshes recency — in time that does
636
+ not grow with the store's size, invoking the optional
637
+ `evict` sink (throw-isolated) on a capacity eviction or an expired read,
638
+ but never for an explicit `delete`; `control.regenerate()` rotates the id while carrying the
509
639
  session's `state` over and invalidating the old id; a signed cookie
510
640
  transport inherits the full substrate injection-hardening matrix
511
641
  (`__Host-` spoof rejection, `Domain`/`Path` injection throws,
@@ -514,13 +644,36 @@ prevents:
514
644
  answers `404` when `required` is set and no session resolves or mints, and
515
645
  a consumer ending a session on `DELETE` mounts its own handler over
516
646
  `control.destroy()`.
517
- 20. **CSRF.** With a session ahead, the minted token is bound to that
518
- session's id (`signToken(sessionId)`) — a mutating request's recovered
519
- bound id must equal its own session's id, so a token minted under
520
- session A replayed against session B is `403` even with matching
521
- double-submit halves; without a session, `createCSRF` falls back to
522
- signed-random double-submit (documented weaker — no cross-session
523
- binding is possible without one).
647
+ 20. **CSRF.** A token is `random.signature`, where `signature` is the
648
+ signer's HMAC over `CSRF_LABEL`, a binding, and `random`
649
+ (`signCSRFToken`), OWASP's signed double submit; it carries no form of the
650
+ binding. While the client holds a session (`state.session` with
651
+ `control.fresh` not true), the binding is the session id and the battery
652
+ writes no cookie, so a token minted under session A is `403` under
653
+ session B, and a nonce-bound token is `403` beside a session even with its
654
+ nonce cookie. While it holds none, the binding is the battery's own nonce:
655
+ a safe request without a valid nonce cookie mints one and sets it
656
+ HttpOnly, `SameSite=Lax`, and `Path=/` under `cookie`. Every request that
657
+ passes, safe or mutating, stashes a fresh token bound to the binding it
658
+ arrived with on `state.csrf`, so every tab's token verifies while the
659
+ session or the nonce holds. A mutating request submits its token in
660
+ `header`, or in `field` of an `application/json` or
661
+ `application/x-www-form-urlencoded` body; the battery reads no other body,
662
+ so a multipart form sends its token in the header, and its stream stays
663
+ unread for `createMultipart`. The token format changed in 0.0.35: a token
664
+ an earlier release issued stops verifying at the upgrade, so a page
665
+ rendered before it must reload before its next write. Before 0.0.35, the
666
+ `signToken` function signed the session id, or a random value without a
667
+ session, into the token, and every safe response wrote that token into a
668
+ script-readable cookie named by the `cookie` option, which a mutating
669
+ request's token had to equal. A handler that
670
+ starts a session (the first write to a fresh one), regenerates it, or
671
+ destroys it changes the binding: `state.csrf` in that handler holds a
672
+ token bound to the binding the request arrived with, and tokens minted
673
+ earlier stop verifying under the new one. Such a handler answers with a
674
+ redirect; § CSRF: redirect after a session change states the contract.
675
+ Before 0.0.35, the battery re-minted the token for a regenerated session,
676
+ and cleared it for a destroyed one, on the handler's own response.
524
677
  21. **Static.** Every served response is opened as a `FileHandle` and its
525
678
  headers (`Content-Length`/`ETag`) are computed from that same handle's
526
679
  `fstat` — the bytes `streamFile` later reads can never diverge from the
@@ -534,6 +687,13 @@ prevents:
534
687
  multi-range or malformed `Range` header serves the full body (`200`),
535
688
  never a partial guess; the SPA fallback shell path is a fixed,
536
689
  non-user-controlled join — never re-run through the traversal resolver.
690
+ A `Range` under any `If-Range` serves the full `200`, because no validator
691
+ the battery sends compares strongly. A `prefix` and a fallback `exclude`
692
+ hold one slash law: each compares case-sensitively, one trailing slash on
693
+ it is optional, so `/static/` covers `/static`, and it covers a path
694
+ beneath it only on a segment boundary. Before 0.0.35, a `Range` under
695
+ `If-Range` answered `206` whatever the validator, and a `prefix` or an
696
+ `exclude` written `/static/` did not cover `/static`.
537
697
  22. **Assets.** `createAssets` decodes a browser-relative key and refuses
538
698
  malformed escapes, backslashes, empty segments, `.`/`..`, and dotfiles
539
699
  before it calls `AssetSourceInterface.read`. A successful value is copied
@@ -560,22 +720,41 @@ prevents:
560
720
  never surfaced as an upload; staged files default to a
561
721
  process-owned `mkdtemp` directory under `os.tmpdir()` locked to mode
562
722
  `0o700`, with each staged file opened at mode `0o600` (both overridable
563
- through `options.directory`).
723
+ through `options.directory`). A file the `allowed` list refuses is
724
+ refused before a byte of it is staged. A boundary longer than
725
+ `MULTIPART_MAX_BOUNDARY` is refused `400` as malformed. A header block
726
+ exactly at `MULTIPART_MAX_HEADER_BLOCK` is admitted however its chunks
727
+ arrive. When the handler settles, by a return or a throw, `createMultipart`
728
+ unlinks every file still at its staged path, so a handler moves or reads
729
+ each file it keeps before it returns. Before 0.0.35, a normal return left
730
+ staged files on disk, a file the `allowed` list refused was written to disk
731
+ first, a boundary of any length was taken, and that header block was
732
+ refused when it arrived in small chunks.
564
733
  24. **Boundary.** `expose: false` leaks nothing (a non-`HTTPError` throw's
565
734
  message never reaches the body); an `HTTPError`'s own `message` always
566
735
  surfaces (it is the handler's deliberate signal); a `report` sink's own
567
736
  throw is swallowed and can never alter the response.
568
- 25. **`only`/`except` are not a security boundary.** Both match
569
- `context.url.pathname` exactly — a trailing slash (`/login/` vs `/login`),
570
- a case variant, or a percent-encoded path silently falls outside an
571
- `only()`-scoped path set, and a security battery scoped that way goes
572
- dark on that request with no signal. Prefer `except()` for security
573
- batteries (CSRF, bearer, rate limiting) — its failure mode is fail-closed
574
- (an unlisted or misspelled path still gets the battery; only the
575
- explicitly excluded paths lose it), where `only()`'s failure mode is
576
- fail-open. Whichever combinator is used, keep its path set in lockstep
577
- with the router's actual routes — a route added after the fact and not
578
- added to the set is silently unscoped.
737
+ 25. **`only`/`except` match through the router's path grammar.** Each path
738
+ is a route pattern compiled by `@orkestrel/router`'s `compilePath` and
739
+ matched against `context.url.pathname` by its `matchPath`. A pattern
740
+ matches case-sensitively whatever the dispatcher's `sensitive` option, with
741
+ one trailing slash optional, so `/admin` covers `/admin` and `/admin/`.
742
+ Under `createDispatcher({ sensitive: false })`, a case variant such as
743
+ `/ADMIN` dispatches to the `/admin` route, but it falls outside
744
+ `only('/admin', …)`, which skips its battery, and inside
745
+ `except('/admin', …)`, which runs it. A
746
+ pattern covers no path beneath it: `/admin` does not cover `/admin/users`.
747
+ To scope a subtree, list `/admin` and `/admin/*rest`; a `*name` wildcard
748
+ matches one or more characters across segments and must be the final
749
+ segment, and `:name` matches one segment. A wildcard before the final
750
+ segment refuses at construction with a `ContractError`. Before 0.0.35,
751
+ both compared the pathname by string equality, so `/admin/` fell outside
752
+ `only('/admin', …)` while the router still dispatched it. Prefer
753
+ `except()` for security batteries (CSRF, bearer, rate limiting): an
754
+ unlisted path still gets the battery, where an unlisted path under
755
+ `only()` goes without it. Keep the pattern set in lockstep with the
756
+ router's routes, because a route added later and left out of the set is
757
+ unscoped.
579
758
  26. **Challenge.** Every `401` `createBearer` returns carries a `WWW-Authenticate`
580
759
  challenge (RFC 9110 § 15.5.2). A missing, wrong-scheme, or empty token renders
581
760
  the configured `challenge` auth-params, and a refused credential adds
@@ -587,23 +766,23 @@ prevents:
587
766
 
588
767
  ## Patterns
589
768
 
590
- ### Canonical onion — fetch-native runtime
769
+ ### Canonical onion — over `compose`
591
770
 
592
771
  The full ordering doctrine, composed directly over `compose` (no `@orkestrel/server`
593
- `Server` required — any fetch-native runtime works):
772
+ `Server` required — these batteries read and return `Request` and `Response`):
594
773
 
595
774
  ```ts
596
775
  import {
597
776
  createBearer,
598
777
  createBody,
599
778
  createBoundary,
600
- createCompression,
601
- createCors,
779
+ createCORS,
602
780
  createCSRF,
603
781
  createDeadline,
604
782
  createETag,
605
783
  createForwarded,
606
784
  createLimiter,
785
+ createNodeCompression,
607
786
  createSecurity,
608
787
  createSession,
609
788
  createTelemetry,
@@ -616,26 +795,25 @@ import type {
616
795
  IdentifierState,
617
796
  SessionState,
618
797
  } from '@orkestrel/middleware'
619
- import { compose, verifyToken } from '@orkestrel/server'
798
+ import { compose, createSigner, verifyToken } from '@orkestrel/server'
620
799
 
621
- interface State extends BearerState, ClientState, CSRFState, IdentifierState, SessionState {
622
- readonly connection?: { readonly ip?: string }
623
- }
800
+ interface State extends BearerState, ClientState, CSRFState, IdentifierState, SessionState {}
624
801
 
802
+ const signer = createSigner('shh')
625
803
  const onion = [
626
804
  createTelemetry({ record: (entry) => console.log(entry) }),
627
- createCompression(),
805
+ createNodeCompression(),
806
+ createSecurity({ hsts: true }),
807
+ createCORS({ origin: ['https://app.example'] }),
628
808
  createBoundary({ expose: false }),
629
809
  createDeadline({ ms: 5_000 }),
630
- createSecurity({ hsts: true }),
631
- createCors({ origin: ['https://app.example'] }),
632
810
  createForwarded({ proxies: 1 }),
633
811
  createETag(),
634
- createBearer({ verify: (token) => verifyToken(token, 'shh') }),
812
+ createBearer({ verify: (token) => verifyToken(token, signer) }),
635
813
  createLimiter({ max: 100, window: 60_000 }),
636
814
  createBody(),
637
- createSession({ transport: createCookieTransport({ secret: 'shh' }) }),
638
- createCSRF({ secret: 'shh' }),
815
+ createSession({ transport: createCookieTransport({ signer }) }),
816
+ createCSRF({ signer }),
639
817
  ]
640
818
 
641
819
  const handle = compose<State>(onion, async (_request, context) => {
@@ -645,7 +823,7 @@ const handle = compose<State>(onion, async (_request, context) => {
645
823
 
646
824
  ### Canonical onion — behind `@orkestrel/server`
647
825
 
648
- The fence hands the same chain to `createServer` as its `middleware` option, so the server owns the listening socket and the dispatcher the chain terminates in.
826
+ The fence hands the same chain to `createServer` as its `middleware` option, so the server owns the listening socket and the dispatcher the chain terminates in. The batteries read connection facts (`ip`, `encrypted`) from `context.connection`, so the `state: () => ({})` factory carries none, and each calls `next()` with no argument.
649
827
 
650
828
  ```ts
651
829
  import { createBoundary, createSecurity } from '@orkestrel/middleware'
@@ -661,7 +839,7 @@ dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok
661
839
  const server = createServer<State>({
662
840
  dispatcher,
663
841
  state: () => ({}),
664
- middleware: [createBoundary(), createSecurity()],
842
+ middleware: [createSecurity(), createBoundary()],
665
843
  })
666
844
  const port = await server.start()
667
845
  await server.stop()
@@ -708,10 +886,17 @@ const session = createSession<import('@orkestrel/middleware').SessionInterface,
708
886
 
709
887
  // Inside a handler downstream of `session`:
710
888
  declare const context: { readonly state: State }
889
+ context.state.session?.set('user', 'u_1') // the first write stores the session and writes its id
711
890
  context.state.control?.regenerate() // rotate the id after a privilege change (anti-fixation)
712
891
  context.state.control?.destroy() // end the session outright
713
892
  ```
714
893
 
894
+ A request with no credential reaches the handler with a session whose `control.fresh` is
895
+ `true`. The battery stores it, and the transport writes its id, only after the handler writes
896
+ to it or regenerates it, so the session header or cookie first appears on the response to that
897
+ write. A request that reads a session and writes nothing leaves the store untouched beyond the
898
+ store's own `get`.
899
+
715
900
  ### Session store seam — direct calls
716
901
 
717
902
  The fence drives a memory store's `set`, `get`, and `delete` methods directly, with no middleware chain around them.
@@ -775,20 +960,45 @@ await transport.write(response, 'abc', false) // sets the session-id header
775
960
  transport.clear(response) // removes it
776
961
  ```
777
962
 
778
- ### CSRF: session-bound double-submit
963
+ ### CSRF: signed double submit over one signer
779
964
 
780
- The fence mounts the CSRF battery behind a cookie-transport session, which is what binds each minted token to that session's id.
965
+ The fence mounts the CSRF battery behind a cookie-transport session, which binds each token a held session mints to that session's id.
781
966
 
782
967
  ```ts
783
968
  import { createCSRF, createSession, createCookieTransport } from '@orkestrel/middleware'
969
+ import { createSigner } from '@orkestrel/server'
784
970
  import type { CSRFState, SessionState } from '@orkestrel/middleware'
785
971
 
786
972
  interface State extends SessionState, CSRFState {}
787
973
 
974
+ const signer = createSigner(['current-secret', 'previous-secret'])
788
975
  const session = createSession<import('@orkestrel/middleware').SessionInterface, State>({
789
- transport: createCookieTransport({ secret: 'session-secret' }),
976
+ transport: createCookieTransport({ signer }),
790
977
  })
791
- const csrf = createCSRF({ secret: 'csrf-secret' }) // session ahead binds the token to its id
978
+ const csrf = createCSRF({ signer }) // session ahead binds the token to its id
979
+ ```
980
+
981
+ No option takes a secret. `CookieTransportOptions.signer` and `CSRFOptions.signer` each take a
982
+ `SignerInterface`, and a bag that still carries `secret` refuses as an undeclared key. Create the
983
+ signer once per secret list with `createSigner` from `@orkestrel/server` and share it between the
984
+ batteries: `createSigner` creates every key at that call, so no request imports a key. One signer
985
+ is safe for both because a CSRF message opens with `CSRF_LABEL`, which no `signToken` payload can
986
+ equal, and a CSRF token sent as the session cookie resolves no session.
987
+
988
+ ### CSRF: redirect after a session change
989
+
990
+ A handler that starts a session (the first write to a fresh one), regenerates it, or destroys it
991
+ answers with a redirect to a page, such as a `303` to `/account`. The tokens the client holds
992
+ were bound to the session or nonce the request arrived with, and `state.csrf` in that handler
993
+ still is; the page the redirect loads renders a token bound to the session or nonce the client
994
+ then holds.
995
+
996
+ ```ts
997
+ import type { CSRFState, SessionState } from '@orkestrel/middleware'
998
+
999
+ declare const context: { readonly url: URL; readonly state: SessionState & CSRFState }
1000
+ context.state.control?.regenerate() // after a login check passes
1001
+ const response = Response.redirect(new URL('/account', context.url), 303)
792
1002
  ```
793
1003
 
794
1004
  ### Multipart: node face, sniffed-type allow-list
@@ -796,7 +1006,7 @@ const csrf = createCSRF({ secret: 'csrf-secret' }) // session ahead binds the to
796
1006
  The fence mounts the node-face multipart battery with a sniffed-type allow-list and narrows its parsed result on `context.state` through the shipped guards.
797
1007
 
798
1008
  ```ts
799
- import { createMultipart } from '@orkestrel/middleware/server'
1009
+ import { createMultipart } from '@orkestrel/middleware'
800
1010
  import { isMultipartBody, isMultipartFile } from '@orkestrel/middleware'
801
1011
  import type { MultipartState } from '@orkestrel/middleware'
802
1012
 
@@ -818,7 +1028,7 @@ if (isMultipartBody(context.state.multipart)) {
818
1028
  The fence resolves one partial limits input into the effective caps, with no battery around it.
819
1029
 
820
1030
  ```ts
821
- import { resolveMultipartLimits } from '@orkestrel/middleware/server'
1031
+ import { resolveMultipartLimits } from '@orkestrel/middleware'
822
1032
 
823
1033
  resolveMultipartLimits({ file: { size: 1_048_576 } }) // fills in every other default cap
824
1034
  ```
@@ -830,8 +1040,8 @@ Multipart processing reports no progress.
830
1040
  The fence implements an `AssetSourceInterface` over a single in-memory entry and hands it to `createAssets`.
831
1041
 
832
1042
  ```ts
833
- import type { AssetSourceInterface } from '@orkestrel/middleware/server'
834
- import { createAssets } from '@orkestrel/middleware/server'
1043
+ import type { AssetSourceInterface } from '@orkestrel/middleware'
1044
+ import { createAssets } from '@orkestrel/middleware'
835
1045
 
836
1046
  const source: AssetSourceInterface = {
837
1047
  read(path) {
@@ -860,7 +1070,7 @@ is never retained, so an absent key is read again on its next request.
860
1070
  The fence serves a directory over `node:fs` with the SPA fallback on, which answers an eligible miss with the shell.
861
1071
 
862
1072
  ```ts
863
- import { createStatic } from '@orkestrel/middleware/server'
1073
+ import { createStatic } from '@orkestrel/middleware'
864
1074
 
865
1075
  const serveApp = createStatic({ root: '/srv/public', fallback: true }) // excludes '/api' by default
866
1076
  ```
@@ -896,9 +1106,36 @@ still served through the fallback, because the operator configured that path.
896
1106
  way out.** `createSession` applies store I/O and transport writes after
897
1107
  `next()` resolves: `destroy()` → `store.delete` + `transport.clear`;
898
1108
  `regenerate()` → `store.set` the new session, `store.delete` the old,
899
- `transport.write` the new id; otherwise → `store.set` the resolved/minted
900
- session, `transport.write` only when freshly minted. `destroy()`
901
- supersedes a prior `regenerate()`.
1109
+ `transport.write` the new id; otherwise, after a write → `store.set` the
1110
+ resolved or minted session, `transport.write` only when it was minted on
1111
+ this request; otherwise nothing. `destroy()` supersedes a prior
1112
+ `regenerate()`.
1113
+
1114
+ ### Admission: option bags admitted whole
1115
+
1116
+ Every factory admits its options bag whole through the strict `admitValue` function of `@orkestrel/contract`, against the compiled contract its options interface declares, before it reads a default. The store classes `MemorySessionStore`, `MemoryLimiterStore`, and `DatabaseSessionStore` admit in their constructors, so a direct `new` call and the factory refuse alike, and their messages lead with the class name. A bag must be a plain object: a class instance, an array, `null`, and a primitive refuse. A bag refuses on an undeclared key such as `origins` for `createCORS`, on a missing required key, on a wrong type, on an explicit `undefined`, and on a number outside its range; a `status` lies from 200 through 599, a `ms` is an integer from 1 through 2147483647 (the range `@orkestrel/timeout` enforces), a size is a non-negative finite number, a count is a non-negative integer, and `NaN` refuses everywhere. An absent bag (`undefined`) admits as `{}`, so a factory with a required key refuses it at that key.
1117
+
1118
+ Each refusal is a `ContractError`, and the message leads with the factory name. A refusal from `admitOptions` reports the first fault's path in `context.path`, every fault in `cause`, and, for an undeclared key, the declared keys in the message. `createForwarded` admits a union of its two forms, so its refusal carries the root path `[]` and a message that lists both forms. A foreign-key check (`admitForeign`) reports the key as `context.path`, such as `['store']`, with a message of the form `createSession: options.store must be an object with function members get, set, delete`. `renderChallenge` and the `createBearer` refusal of a `challenge` that names `error` report `['scheme']` or `['challenge', name]` as `context.path`, and carry no `cause`.
1119
+
1120
+ An implementation key (`LimiterOptions.store`, `SessionOptions.transport`, `SessionOptions.store`, `CookieTransportOptions.signer`, `CSRFOptions.signer`, `AssetOptions.source`, and `AssetOptions.store`) is a foreign contract. The bag's contract carries it as present or absent, and `admitForeign` then checks each member the published interface declares, accepts a class instance and unknown members, and refuses a value that is not an object with every declared member a function, with a `ContractError` at the key. It reports the first implementation key that fails, in one sentence that names every member the interface declares, such as `get, set, delete`; it neither names the member that failed nor reports a fault for each member. The `cookie` record of `CookieTransportOptions` is an owned plain record the caller writes: the bag's contract admits its six members (`path`, `domain`, `maxAge`, `httpOnly`, `secure`, `sameSite`) and refuses any other key, so `maxage` refuses. `maxAge` is a finite number because a non-finite value writes `Max-Age=NaN` or `Max-Age=Infinity` into `Set-Cookie`.
1121
+
1122
+ ```ts
1123
+ import {
1124
+ admitForeign,
1125
+ admitOptions,
1126
+ buildForeignContract,
1127
+ CORS_CONTRACT,
1128
+ DEADLINE_CONTRACT,
1129
+ } from '@orkestrel/middleware'
1130
+
1131
+ admitOptions('createCORS', CORS_CONTRACT, { origin: ['https://app.example'] }) // returns
1132
+ admitOptions('createCORS', CORS_CONTRACT, { origins: ['https://app.example'] }) // throws a ContractError at ['origins']
1133
+ admitOptions('createDeadline', DEADLINE_CONTRACT, { ms: 1_000, status: 1000 }) // throws a ContractError at ['status']
1134
+
1135
+ const store = buildForeignContract(['get', 'set', 'delete'])
1136
+ admitForeign('createSession', ['store'], store, new Map()) // returns: a class instance with the members
1137
+ admitForeign('createSession', ['store'], store, {}) // throws a ContractError at ['store']
1138
+ ```
902
1139
 
903
1140
  ### Practices
904
1141
 
@@ -915,9 +1152,6 @@ still served through the fallback, because the operator configured that path.
915
1152
  depends on.
916
1153
  - **Install a `report` sink on `createBoundary`** for observability — its
917
1154
  own throw is swallowed, so it can never crash a response.
918
- - **Pick your `createSecurity` position deliberately** — inside the
919
- boundary (default; headers only on returned responses) or above it
920
- (headers on every response, thrown errors included) — see Contract §7.
921
1155
 
922
1156
  ### Session control intent
923
1157
 
@@ -925,6 +1159,7 @@ still served through the fallback, because the operator configured that path.
925
1159
  import { Session, SessionControl } from '@orkestrel/middleware'
926
1160
 
927
1161
  const control = new SessionControl(new Session('original'))
1162
+ console.log(control.fresh) // false
928
1163
  control.regenerate()
929
1164
  console.log(control.successor?.id)
930
1165
  control.destroy()
@@ -972,12 +1207,8 @@ import {
972
1207
  MemoryAssetStore,
973
1208
  readAssetRecord,
974
1209
  resolveAssetKey,
975
- } from '@orkestrel/middleware/server'
976
- import type {
977
- AssetRecord,
978
- AssetSourceInterface,
979
- AssetStoreInterface,
980
- } from '@orkestrel/middleware/server'
1210
+ } from '@orkestrel/middleware'
1211
+ import type { AssetRecord, AssetSourceInterface, AssetStoreInterface } from '@orkestrel/middleware'
981
1212
 
982
1213
  const source: AssetSourceInterface = {
983
1214
  read: (path) =>
@@ -1004,8 +1235,8 @@ a streamed response transfers ownership to `streamFile`.
1004
1235
  ```ts
1005
1236
  import { realpath } from 'node:fs/promises'
1006
1237
  import { join } from 'node:path'
1007
- import { openStaticFile, planStaticResponse, resolveStaticFile } from '@orkestrel/middleware/server'
1008
- import type { StaticFile, StaticPlan } from '@orkestrel/middleware/server'
1238
+ import { openStaticFile, planStaticResponse, resolveStaticFile } from '@orkestrel/middleware'
1239
+ import type { StaticFile, StaticPlan } from '@orkestrel/middleware'
1009
1240
 
1010
1241
  const root = await realpath('./public')
1011
1242
  const path = await resolveStaticFile(join(root, 'index.html'), root, 'index.html')
@@ -1037,44 +1268,42 @@ console.log(extractFieldToken({ csrf: 'credential' }, 'csrf'))
1037
1268
 
1038
1269
  ## Tests
1039
1270
 
1040
- - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` +
1271
+ - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔
1041
1272
  `src/server` bijection (value and type exports), the `AssetSourceInterface`,
1042
1273
  `SessionInterface`, `SessionControlInterface`, `SessionStoreInterface`, and
1043
1274
  `SessionTransportInterface` method bijections, and the equality gate: every `Summary`
1044
1275
  cell against its declaration's description paragraph, the titled `Mount a battery`
1045
1276
  fence against the `@example` block of that title (pinned so the titled pair cannot be
1046
1277
  retired silently), and the README pitch against this guide's tagline.
1047
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) —
1048
- `resolveKey` precedence, `buildRetryAfter`/`buildRateLimitField`/
1049
- `buildRateLimitPolicyField` exact wire strings, `matchesTrustedEntry`/
1050
- `resolveForwardedFor` matrices, `detectEncodings`, `compressBytes`, buffering-eligibility
1051
- predicates, `transferSessionState`, `isPreflight`, `buildClient`,
1052
- `validateSessionLimits`.
1053
- - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) —
1278
+ - [`tests/src/server/validators.test.ts`](../tests/src/server/validators.test.ts) —
1054
1279
  the `isSession`/`isSessionControl`/`isMultipartFile`/`isMultipartBody`
1055
- totality guards, each driven over a well-shaped value and over the hostile
1280
+ totality guards, each driven over a well-shaped value and over the malformed
1056
1281
  inputs it must answer `false` to.
1057
- - [`tests/src/core/Session.test.ts`](../tests/src/core/Session.test.ts) —
1282
+ - [`tests/src/server/Session.test.ts`](../tests/src/server/Session.test.ts) —
1058
1283
  the entity shape (`id`, an independent `state` view and its mutators per instance).
1059
- - [`tests/src/core/stores/MemorySessionStore.test.ts`](../tests/src/core/stores/MemorySessionStore.test.ts) —
1284
+ - [`tests/src/server/stores/MemorySessionStore.test.ts`](../tests/src/server/stores/MemorySessionStore.test.ts) —
1060
1285
  construction guards, get/set/delete, idle + absolute-lifetime eviction,
1061
- `created` stamped once and preserved across re-set.
1062
- - [`tests/src/core/stores/DatabaseSessionStore.test.ts`](../tests/src/core/stores/DatabaseSessionStore.test.ts) —
1286
+ `created` stamped once and preserved across re-set, recency refreshed by a
1287
+ live read, one eviction per insert at capacity, and the cost row that bounds
1288
+ the time of an insert at capacity in a store of 4n sessions against one of n.
1289
+ - [`tests/src/server/stores/DatabaseSessionStore.test.ts`](../tests/src/server/stores/DatabaseSessionStore.test.ts) —
1063
1290
  get/set/delete over a real `@orkestrel/database` memory-driver table, idle +
1064
1291
  absolute-lifetime eviction (including the underlying row's removal),
1065
1292
  `created` stamped once and preserved across re-set, guard rejection,
1066
1293
  construction guards, rebuild through the injected restore step, and the
1067
1294
  propagated `DRIVER` refusal of a row stored under the earlier cursor columns.
1068
- - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) —
1295
+ - [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) —
1069
1296
  `createCookieTransport`/`createHeaderTransport` round-trips over real
1070
1297
  `Request`/`Response`, `createMemorySessionStore` shallow mirror,
1071
1298
  `createRestoredSession` snapshot rebuilds and malformed refusals,
1072
1299
  `createDatabaseSessionStore` construction guard.
1073
- - [`tests/src/core/middlewares.test.ts`](../tests/src/core/middlewares.test.ts) —
1074
- every battery's defaults, options, skip conditions, and the security
1075
- acceptance bar's invariants; the canonical onion composed end-to-end.
1076
1300
  - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) —
1077
- traversal and SPA-fallback resolution, byte-signature matching, node zlib
1301
+ `resolveKey` precedence, `buildRetryAfter`/`buildRateLimitField`/
1302
+ `buildRateLimitPolicyField` exact wire strings, `matchesTrustedEntry`/
1303
+ `resolveForwardedFor` matrices, `detectEncodings`, `compressBytes`, buffering-eligibility
1304
+ predicates, `transferSessionState`, `matchesSessionState`, `generateNonce`,
1305
+ `signCSRFToken` and `verifyCSRFToken` over the malformed-token table, `isPreflight`, `buildClient`,
1306
+ `admitOptions` and `admitForeign`, traversal and SPA-fallback resolution, byte-signature matching, node zlib
1078
1307
  compression, multipart limit resolution, boundary extraction, part-header
1079
1308
  parsing, `streamFile`'s pull-driven backpressure and descriptor release, and
1080
1309
  the uploaded-file operations, including `moveUploadedFile`'s cross-device
@@ -1089,6 +1318,8 @@ console.log(extractFieldToken({ csrf: 'credential' }, 'csrf'))
1089
1318
  header-block cap, the total-bytes cap, the abort-mid-upload path, and the
1090
1319
  staged-file cleanup each throw performs.
1091
1320
  - [`tests/src/server/middlewares.test.ts`](../tests/src/server/middlewares.test.ts) —
1321
+ every battery's defaults, options, skip conditions, and the security
1322
+ acceptance bar's invariants; the canonical onion composed end-to-end;
1092
1323
  in-memory asset ownership, key refusal, identity/Brotli negotiation,
1093
1324
  conditional and HEAD responses, filesystem static serving, multipart
1094
1325
  middleware, and the server-face composition.
@@ -1100,6 +1331,5 @@ console.log(extractFieldToken({ csrf: 'credential' }, 'csrf'))
1100
1331
  package is built over. Its mirrored guide is [`server.md`](server.md).
1101
1332
  - `@orkestrel/contract` — the guards backing every construction boundary.
1102
1333
  - `@orkestrel/budget` — `createLimiter`'s per-key tally.
1103
- - `@orkestrel/abort` / `@orkestrel/timeout` — `createDeadline`'s
1104
- signal-linking and timer.
1334
+ - `@orkestrel/timeout` — `createDeadline`'s timer.
1105
1335
  - [`README.md`](README.md) — the guides index.