@orkestrel/server 0.0.17 → 0.0.19
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.
- package/README.md +15 -11
- package/dist/src/server/index.cjs +595 -441
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +778 -531
- package/dist/src/server/index.d.ts +778 -531
- package/dist/src/server/index.js +587 -435
- package/dist/src/server/index.js.map +1 -1
- package/package.json +18 -20
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import { AddressInfo } from 'node:net';
|
|
2
|
-
import { DispatcherInterface } from '@orkestrel/router';
|
|
3
|
-
import { Duplex } from 'node:stream';
|
|
4
|
-
import { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
5
|
-
import { EmitterHooks } from '@orkestrel/emitter';
|
|
6
|
-
import { EmitterInterface } from '@orkestrel/emitter';
|
|
7
|
-
import { IncomingMessage } from 'node:http';
|
|
1
|
+
import type { AddressInfo } from 'node:net';
|
|
2
|
+
import type { DispatcherInterface } from '@orkestrel/router';
|
|
3
|
+
import type { Duplex } from 'node:stream';
|
|
4
|
+
import type { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
5
|
+
import type { EmitterHooks } from '@orkestrel/emitter';
|
|
6
|
+
import type { EmitterInterface } from '@orkestrel/emitter';
|
|
7
|
+
import type { IncomingMessage } from 'node:http';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
* header — a value and its quality weight, the element type
|
|
12
|
-
* returns (sorted by `q` descending).
|
|
10
|
+
* Represents one parsed entry of a weighted `Accept` / `Accept-Encoding` /
|
|
11
|
+
* `Accept-Language` header — a value and its quality weight, the element type
|
|
12
|
+
* `parseAcceptHeader` returns (sorted by `q` descending).
|
|
13
13
|
*
|
|
14
14
|
* @remarks
|
|
15
15
|
* `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
|
|
16
16
|
* wildcard). `q` is the quality weight in `[0, 1]` (the `;q=` parameter,
|
|
17
|
-
* default `1` when absent); a `;q=0` entry explicitly
|
|
17
|
+
* default `1` when absent); a `;q=0` entry explicitly rejects that token — a
|
|
18
18
|
* parser keeps it (so a caller can honor the rejection) rather than
|
|
19
19
|
* dropping it.
|
|
20
20
|
*/
|
|
@@ -23,29 +23,6 @@ export declare interface AcceptEntry {
|
|
|
23
23
|
readonly q: number;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
/**
|
|
27
|
-
* Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
|
|
28
|
-
* clobbering a prior one.
|
|
29
|
-
*
|
|
30
|
-
* @remarks
|
|
31
|
-
* `Headers.append` already accumulates repeated headers (unlike node's
|
|
32
|
-
* `setHeader`), so this is a thin, self-documenting wrapper naming the
|
|
33
|
-
* cookie-append intent — the primitive {@link writeSignedCookie} /
|
|
34
|
-
* {@link clearCookie} use.
|
|
35
|
-
*
|
|
36
|
-
* @param headers - The response `Headers` to write into
|
|
37
|
-
* @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
|
|
38
|
-
*
|
|
39
|
-
* @example
|
|
40
|
-
* ```ts
|
|
41
|
-
* const headers = new Headers()
|
|
42
|
-
* appendCookie(headers, serializeCookie('a', '1'))
|
|
43
|
-
* appendCookie(headers, serializeCookie('b', '2'))
|
|
44
|
-
* headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
|
|
45
|
-
* ```
|
|
46
|
-
*/
|
|
47
|
-
export declare function appendCookie(headers: Headers, cookie: string): void;
|
|
48
|
-
|
|
49
26
|
/**
|
|
50
27
|
* Options for `readBody` — how the shared body-collection pipeline caps and
|
|
51
28
|
* decompresses a request body.
|
|
@@ -53,14 +30,14 @@ export declare function appendCookie(headers: Headers, cookie: string): void;
|
|
|
53
30
|
* @param limit - The maximum request body size in bytes; a larger body
|
|
54
31
|
* throws a {@link import('./errors.js').ContentTooLargeError} (413).
|
|
55
32
|
* Defaults to {@link DEFAULT_BODY_LIMIT}.
|
|
56
|
-
* @param decompression - The maximum
|
|
33
|
+
* @param decompression - The maximum decompressed body size in bytes (the
|
|
57
34
|
* zip-bomb cap) for a `Content-Encoding: gzip` / `deflate` request body. A
|
|
58
|
-
* highly-compressible payload small
|
|
35
|
+
* highly-compressible payload small on the wire (under `limit`) can inflate
|
|
59
36
|
* enormously, so a byte-counting `TransformStream` aborts the pipe the
|
|
60
37
|
* instant decompressed output would exceed this. Defaults to {@link
|
|
61
38
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT} (16 MiB) —
|
|
62
|
-
*
|
|
63
|
-
*
|
|
39
|
+
* independent of `limit`, not aligned with it; a non-positive value means
|
|
40
|
+
* uncapped decompressed output — use only when `limit` already bounds the
|
|
64
41
|
* compressed input.
|
|
65
42
|
*/
|
|
66
43
|
export declare interface BodyOptions {
|
|
@@ -69,12 +46,12 @@ export declare interface BodyOptions {
|
|
|
69
46
|
}
|
|
70
47
|
|
|
71
48
|
/**
|
|
72
|
-
*
|
|
49
|
+
* Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
|
|
73
50
|
*
|
|
74
51
|
* @remarks
|
|
75
52
|
* Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
|
|
76
53
|
* same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
|
|
77
|
-
* a cookie when those
|
|
54
|
+
* a cookie when those match the one it set).
|
|
78
55
|
*
|
|
79
56
|
* @param headers - The response `Headers` to write into
|
|
80
57
|
* @param name - The cookie name to clear
|
|
@@ -89,57 +66,12 @@ export declare interface BodyOptions {
|
|
|
89
66
|
export declare function clearCookie(headers: Headers, name: string, options?: CookieOptions): void;
|
|
90
67
|
|
|
91
68
|
/**
|
|
92
|
-
*
|
|
93
|
-
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
94
|
-
*
|
|
95
|
-
* @remarks
|
|
96
|
-
* A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
|
|
97
|
-
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
98
|
-
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
99
|
-
* {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
100
|
-
* a malformed string) is kept unchanged.
|
|
101
|
-
*
|
|
102
|
-
* @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
|
|
103
|
-
* @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
|
|
104
|
-
*
|
|
105
|
-
* @example
|
|
106
|
-
* ```ts
|
|
107
|
-
* clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
|
|
108
|
-
* clientRateKey('192.0.2.1') // '192.0.2.1'
|
|
109
|
-
* ```
|
|
110
|
-
*/
|
|
111
|
-
export declare function clientRateKey(address: string): string;
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* The client's quality (q) for one content-coding from the parsed
|
|
115
|
-
* `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
|
|
116
|
-
* server-preference selection.
|
|
117
|
-
*
|
|
118
|
-
* @remarks
|
|
119
|
-
* Prefers an EXACT named match (including an explicit `;q=0` rejection);
|
|
120
|
-
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
121
|
-
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
122
|
-
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
123
|
-
*
|
|
124
|
-
* @param entries - The parsed {@link AcceptEntry} list
|
|
125
|
-
* @param coding - The candidate coding to score
|
|
126
|
-
* @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
127
|
-
*
|
|
128
|
-
* @example
|
|
129
|
-
* ```ts
|
|
130
|
-
* codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
|
|
131
|
-
* codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
|
|
132
|
-
* ```
|
|
133
|
-
*/
|
|
134
|
-
export declare function codingQuality(entries: readonly AcceptEntry[], coding: string): number;
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
|
|
69
|
+
* Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
|
|
138
70
|
*
|
|
139
71
|
* @remarks
|
|
140
72
|
* Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
|
|
141
73
|
* throwing a {@link ContentTooLargeError} (413) the instant the running total
|
|
142
|
-
* exceeds `limit` —
|
|
74
|
+
* exceeds `limit` — before the rest of the stream is buffered — rather than
|
|
143
75
|
* collecting an unbounded body. A bodyless request (`request.body === null`)
|
|
144
76
|
* resolves an empty array. A non-positive `limit` means unbounded.
|
|
145
77
|
*
|
|
@@ -156,18 +88,18 @@ export declare function codingQuality(entries: readonly AcceptEntry[], coding: s
|
|
|
156
88
|
export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
157
89
|
|
|
158
90
|
/**
|
|
159
|
-
*
|
|
160
|
-
* handler into one request handler — the frozen middleware seam
|
|
91
|
+
* Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
|
|
92
|
+
* handler into one request handler — the frozen middleware seam.
|
|
161
93
|
*
|
|
162
94
|
* @remarks
|
|
163
|
-
* `middleware[0]` runs
|
|
164
|
-
* runs `middleware[1]`, and so on until the
|
|
95
|
+
* `middleware[0]` runs outermost: it is invoked first, and its call to `next`
|
|
96
|
+
* runs `middleware[1]`, and so on until the last middleware's `next` invokes
|
|
165
97
|
* `terminal`. Each middleware's `next` may be called with a substituted
|
|
166
98
|
* `Request` (the downstream chain then sees that request instead of the
|
|
167
99
|
* original), called with no argument (the original request continues
|
|
168
|
-
* downstream), or
|
|
100
|
+
* downstream), or not called at all (a short-circuit — the middleware's own
|
|
169
101
|
* returned `Response` is sent, and everything downstream never runs). A
|
|
170
|
-
*
|
|
102
|
+
* second call to the same `next` within one middleware invocation rejects —
|
|
171
103
|
* each link runs the chain at most once, so a middleware cannot fork the
|
|
172
104
|
* request into two divergent downstream runs.
|
|
173
105
|
*
|
|
@@ -190,31 +122,33 @@ export declare function collectRequestBody(request: Request, limit: number): Pro
|
|
|
190
122
|
export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
|
|
191
123
|
|
|
192
124
|
/**
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
125
|
+
* Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
|
|
126
|
+
* beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
|
|
127
|
+
* helper also applies.
|
|
196
128
|
*
|
|
197
129
|
* @remarks
|
|
198
130
|
* The text-shaped application types worth compressing (JSON / JavaScript /
|
|
199
|
-
* XML / SVG / WASM / a few document formats) —
|
|
131
|
+
* XML / SVG / WASM / a few document formats) — never already-compressed
|
|
200
132
|
* binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
|
|
201
|
-
* `woff2`), which gzip/deflate would only bloat.
|
|
202
|
-
*
|
|
133
|
+
* `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
|
|
134
|
+
* withholds `add` / `delete` / `clear` from the shared default, so a consumer
|
|
135
|
+
* reads it without reaching a mutator.
|
|
203
136
|
*/
|
|
204
137
|
export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
|
|
205
138
|
|
|
206
139
|
/**
|
|
207
|
-
*
|
|
140
|
+
* Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
|
|
208
141
|
*
|
|
209
142
|
* @remarks
|
|
210
143
|
* Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
|
|
211
|
-
* digest as a
|
|
212
|
-
* default, encoding-
|
|
213
|
-
* re-encoding (gzip) and still matches on revalidation — or a
|
|
144
|
+
* digest as a weak validator (`W/"<hash>"`) when `weak` is `true` — the
|
|
145
|
+
* default, encoding-agnostic, so the tag survives a downstream content
|
|
146
|
+
* re-encoding (gzip) and still matches on revalidation — or a strong one
|
|
214
147
|
* (`"<hash>"`, byte-identity) when `weak` is `false`.
|
|
215
148
|
*
|
|
216
149
|
* @param body - The full (uncompressed) response body to hash
|
|
217
|
-
* @param weak - `true`
|
|
150
|
+
* @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
|
|
151
|
+
* `false`, returns a strong `"…"` one.
|
|
218
152
|
* @returns The `ETag` header value
|
|
219
153
|
*
|
|
220
154
|
* @example
|
|
@@ -225,7 +159,98 @@ export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
|
|
|
225
159
|
export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
|
|
226
160
|
|
|
227
161
|
/**
|
|
228
|
-
*
|
|
162
|
+
* Collapses a client IP into its rate-limit bucket key — an IPv6 address to
|
|
163
|
+
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
164
|
+
*
|
|
165
|
+
* @remarks
|
|
166
|
+
* A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
|
|
167
|
+
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
168
|
+
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
169
|
+
* {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
170
|
+
* a malformed string) is kept unchanged.
|
|
171
|
+
*
|
|
172
|
+
* @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
|
|
173
|
+
* @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```ts
|
|
177
|
+
* computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
|
|
178
|
+
* computeClientKey('192.0.2.1') // '192.0.2.1'
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
export declare function computeClientKey(address: string): string;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Computes the client's quality (q) for one content-coding from the parsed
|
|
185
|
+
* `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
|
|
186
|
+
* each offered coding.
|
|
187
|
+
*
|
|
188
|
+
* @remarks
|
|
189
|
+
* Prefers an exact named match (including an explicit `;q=0` rejection);
|
|
190
|
+
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
191
|
+
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
192
|
+
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
193
|
+
*
|
|
194
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
195
|
+
* @param coding - The candidate coding to score
|
|
196
|
+
* @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```ts
|
|
200
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
|
|
201
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export declare function computeCodingQuality(entries: readonly AcceptEntry[], coding: string): number;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Computes the `/64` network of a full IPv6 address, or `undefined` when the
|
|
208
|
+
* input is not a plain IPv6 address to collapse.
|
|
209
|
+
*
|
|
210
|
+
* @remarks
|
|
211
|
+
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
212
|
+
* is the identity) or any string that does not expand to exactly eight
|
|
213
|
+
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
214
|
+
* first four (the `/64` prefix), normalizes each (lower-case, no leading
|
|
215
|
+
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
216
|
+
* first. Total — a malformed address returns `undefined`.
|
|
217
|
+
*
|
|
218
|
+
* @param address - The candidate IPv6 address
|
|
219
|
+
* @returns The `/64` network string, or `undefined` when not a plain IPv6 address
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
224
|
+
* computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
export declare function computeIPv6Network(address: string): string | undefined;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Computes the client's quality for one `candidate` language from the parsed
|
|
231
|
+
* `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
|
|
232
|
+
* axis runs over each offered tag.
|
|
233
|
+
*
|
|
234
|
+
* @remarks
|
|
235
|
+
* Prefers an exact match, then a primary-tag prefix match (`en` accepts
|
|
236
|
+
* `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
|
|
237
|
+
* is an explicit rejection).
|
|
238
|
+
*
|
|
239
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
240
|
+
* @param candidate - The candidate language tag to score (for example `'en-US'`)
|
|
241
|
+
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
|
|
246
|
+
* computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
|
|
247
|
+
* computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
export declare function computeLanguageQuality(entries: readonly AcceptEntry[], candidate: string): number;
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Represents the per-request connection facts the server face injects — the only data
|
|
229
254
|
* that genuinely exists solely on the socket, surfaced so middleware and a
|
|
230
255
|
* consumer's `state` factory stay core-pure.
|
|
231
256
|
*
|
|
@@ -236,22 +261,22 @@ export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: bo
|
|
|
236
261
|
* - `encrypted` — whether the connection is TLS, for an auto-`Secure` cookie
|
|
237
262
|
* decision ({@link CookieOptions.secure} left `undefined`).
|
|
238
263
|
*/
|
|
239
|
-
export declare interface
|
|
264
|
+
export declare interface Connection {
|
|
240
265
|
readonly ip?: string;
|
|
241
266
|
readonly encrypted: boolean;
|
|
242
267
|
}
|
|
243
268
|
|
|
244
269
|
/**
|
|
245
270
|
* Derives a consumer's per-request `TState` from the adapter-injected
|
|
246
|
-
* {@link
|
|
271
|
+
* {@link Connection} — `ServerOptions.state`, invoked once per request
|
|
247
272
|
* before the middleware onion runs.
|
|
248
273
|
*
|
|
249
274
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
250
275
|
*/
|
|
251
|
-
export declare type ConnectionStateFunction<TState> = (connection:
|
|
276
|
+
export declare type ConnectionStateFunction<TState> = (connection: Connection) => TState;
|
|
252
277
|
|
|
253
278
|
/**
|
|
254
|
-
*
|
|
279
|
+
* Represents the {@link HTTPError} thrown when a request body exceeds the body
|
|
255
280
|
* pipeline's size limit — a `413 Content Too Large`.
|
|
256
281
|
*
|
|
257
282
|
* @remarks
|
|
@@ -276,19 +301,19 @@ export declare class ContentTooLargeError extends HTTPError {
|
|
|
276
301
|
}
|
|
277
302
|
|
|
278
303
|
/**
|
|
279
|
-
*
|
|
304
|
+
* Represents the `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie
|
|
280
305
|
* transport built over it).
|
|
281
306
|
*
|
|
282
307
|
* @param path - The `Path` directive; defaults to `'/'`.
|
|
283
308
|
* @param domain - The `Domain` directive; omitted ⇒ a host-only cookie.
|
|
284
|
-
* @param maxAge - The `Max-Age` directive in
|
|
309
|
+
* @param maxAge - The `Max-Age` directive in seconds (the wire unit, not a
|
|
285
310
|
* millisecond `ttl`); `0` expires the cookie immediately.
|
|
286
311
|
* @param httpOnly - The `HttpOnly` directive; defaults to `true`.
|
|
287
312
|
* @param secure - The `Secure` directive: `true` forces it, `false`
|
|
288
313
|
* suppresses it, and omitted/`undefined` (the default) derives it from the
|
|
289
|
-
* connection
|
|
314
|
+
* connection through {@link import('./helpers.js').resolveSecure} — `Secure` on
|
|
290
315
|
* a TLS connection, off over plaintext HTTP ({@link
|
|
291
|
-
*
|
|
316
|
+
* Connection.encrypted}). A `sameSite: 'None'` cookie is always
|
|
292
317
|
* `Secure` regardless (the spec requires it).
|
|
293
318
|
* @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
|
|
294
319
|
*/
|
|
@@ -302,54 +327,93 @@ export declare interface CookieOptions {
|
|
|
302
327
|
}
|
|
303
328
|
|
|
304
329
|
/**
|
|
305
|
-
*
|
|
330
|
+
* Creates a {@link NegotiatorInterface} — the reusable content-negotiation
|
|
306
331
|
* machine over the weighted `Accept` family.
|
|
307
332
|
*
|
|
308
|
-
* @remarks
|
|
309
|
-
* Prefer this over `new Negotiator()` at call sites that only need the
|
|
310
|
-
* interface.
|
|
311
|
-
*
|
|
312
333
|
* @returns A {@link NegotiatorInterface}
|
|
313
334
|
*
|
|
314
335
|
* @example
|
|
315
336
|
* ```ts
|
|
337
|
+
* import type { MiddlewareContext } from '@src/server'
|
|
316
338
|
* import { createNegotiator } from '@src/server'
|
|
317
339
|
*
|
|
340
|
+
* declare const context: MiddlewareContext<Record<string, never>>
|
|
341
|
+
*
|
|
318
342
|
* const negotiator = createNegotiator()
|
|
319
|
-
* negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
|
|
320
|
-
* // '
|
|
343
|
+
* negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'
|
|
344
|
+
* negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
|
|
345
|
+
* negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'
|
|
346
|
+
* await negotiator.format(new Request('http://x'), context, {
|
|
347
|
+
* 'application/json': (_request, _context) => Response.json({ ok: true }),
|
|
348
|
+
* })
|
|
321
349
|
* ```
|
|
322
350
|
*/
|
|
323
351
|
export declare function createNegotiator(): NegotiatorInterface;
|
|
324
352
|
|
|
325
353
|
/**
|
|
326
|
-
*
|
|
354
|
+
* Creates a {@link ServerInterface} — the node face's HTTP server facade over
|
|
327
355
|
* a consumed `@orkestrel/router` dispatcher.
|
|
328
356
|
*
|
|
329
357
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
330
358
|
* @param options - {@link ServerOptions}
|
|
331
359
|
* @returns A {@link ServerInterface}, not yet started
|
|
332
360
|
*
|
|
333
|
-
* @example
|
|
361
|
+
* @example Quickstart: dispatcher, middleware, lifecycle
|
|
334
362
|
* ```ts
|
|
335
|
-
* import {
|
|
363
|
+
* import type { MiddlewareHandler } from '@orkestrel/server'
|
|
364
|
+
* import { createServer } from '@orkestrel/server'
|
|
336
365
|
* import { createDispatcher } from '@orkestrel/router'
|
|
337
366
|
*
|
|
338
|
-
*
|
|
367
|
+
* interface State {
|
|
368
|
+
* readonly requestId: string
|
|
369
|
+
* readonly ip: string | undefined
|
|
370
|
+
* }
|
|
371
|
+
*
|
|
372
|
+
* const dispatcher = createDispatcher<State>()
|
|
339
373
|
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
340
374
|
*
|
|
341
|
-
* const
|
|
375
|
+
* const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {
|
|
376
|
+
* const response = await next()
|
|
377
|
+
* response.headers.set('X-Request-ID', context.state.requestId)
|
|
378
|
+
* return response
|
|
379
|
+
* }
|
|
380
|
+
*
|
|
381
|
+
* const server = createServer<State>({
|
|
342
382
|
* dispatcher,
|
|
343
|
-
* state: (connection) => ({ ip: connection.ip }),
|
|
383
|
+
* state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
|
|
344
384
|
* })
|
|
385
|
+
* server.use(logRequestId)
|
|
345
386
|
* const port = await server.start()
|
|
346
387
|
* await server.stop()
|
|
388
|
+
* await server.destroy()
|
|
347
389
|
* ```
|
|
348
390
|
*/
|
|
349
391
|
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
350
392
|
|
|
351
393
|
/**
|
|
352
|
-
*
|
|
394
|
+
* Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
|
|
395
|
+
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
396
|
+
*
|
|
397
|
+
* @param options - {@link StreamOptions}
|
|
398
|
+
* @returns A {@link StreamInterface} whose stream is open
|
|
399
|
+
*
|
|
400
|
+
* @example
|
|
401
|
+
* ```ts
|
|
402
|
+
* import { createStream } from '@src/server'
|
|
403
|
+
*
|
|
404
|
+
* const stream = createStream()
|
|
405
|
+
* void Promise.resolve().then(async () => {
|
|
406
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
407
|
+
* stream.comment('keep-alive')
|
|
408
|
+
* stream.end()
|
|
409
|
+
* })
|
|
410
|
+
* // return stream.response from the route handler
|
|
411
|
+
* ```
|
|
412
|
+
*/
|
|
413
|
+
export declare function createStream(options?: StreamOptions): StreamInterface;
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Decodes a cookie value with `decodeURIComponent`, falling back to the raw
|
|
353
417
|
* text when the value is not valid percent-encoding.
|
|
354
418
|
*
|
|
355
419
|
* @param raw - The raw (trimmed) cookie value
|
|
@@ -364,15 +428,15 @@ export declare function createServer<TState>(options: ServerOptions<TState>): Se
|
|
|
364
428
|
export declare function decodeCookieValue(raw: string): string;
|
|
365
429
|
|
|
366
430
|
/**
|
|
367
|
-
*
|
|
431
|
+
* Decodes and narrows a signed token's base64url JSON payload, honoring its
|
|
368
432
|
* expiry — the shared decode step {@link verifyToken} applies after a
|
|
369
433
|
* signature match.
|
|
370
434
|
*
|
|
371
435
|
* @remarks
|
|
372
436
|
* Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
|
|
373
437
|
* non-canonical base64url segment answers `undefined` rather than throwing),
|
|
374
|
-
* reads it as UTF-8 JSON, narrows it to a record with a string `value`
|
|
375
|
-
*
|
|
438
|
+
* reads it as UTF-8 JSON, narrows it to a record with a string `value` without
|
|
439
|
+
* `as`, and rejects an expired `exp`. Total — any
|
|
376
440
|
* decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
|
|
377
441
|
* throws, and its `catch` answers `undefined` too.
|
|
378
442
|
*
|
|
@@ -382,15 +446,15 @@ export declare function decodeCookieValue(raw: string): string;
|
|
|
382
446
|
export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
383
447
|
|
|
384
448
|
/**
|
|
385
|
-
*
|
|
386
|
-
*
|
|
449
|
+
* Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
|
|
450
|
+
* transparently through `DecompressionStream`, capping the decompressed output —
|
|
387
451
|
* the zip-bomb defense.
|
|
388
452
|
*
|
|
389
453
|
* @remarks
|
|
390
454
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
391
|
-
* `TransformStream` that
|
|
455
|
+
* `TransformStream` that aborts the pipe the instant the running decompressed
|
|
392
456
|
* total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
|
|
393
|
-
* has no `maxOutputLength` knob
|
|
457
|
+
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
394
458
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
395
459
|
* compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
|
|
396
460
|
* (never conflated with the cap). A non-positive `cap` means uncapped.
|
|
@@ -404,36 +468,42 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
|
|
|
404
468
|
*/
|
|
405
469
|
export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
406
470
|
|
|
407
|
-
/**
|
|
471
|
+
/**
|
|
472
|
+
* Names the default maximum request body size `readBody` accepts before a 413,
|
|
473
|
+
* `1_048_576` bytes.
|
|
474
|
+
*/
|
|
408
475
|
export declare const DEFAULT_BODY_LIMIT = 1048576;
|
|
409
476
|
|
|
410
477
|
/**
|
|
411
|
-
*
|
|
412
|
-
* the body pipeline's byte-counting `TransformStream` enforces when
|
|
413
|
-
* transparently
|
|
478
|
+
* Names the default maximum decompressed request body size, `16_777_216` bytes — the
|
|
479
|
+
* zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when
|
|
480
|
+
* it transparently decompresses a `Content-Encoding` request body.
|
|
414
481
|
*
|
|
415
482
|
* @remarks
|
|
416
483
|
* A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
|
|
417
484
|
* can inflate by many orders of magnitude — a classic decompression bomb.
|
|
418
|
-
* Capping the decompressed byte count makes the pipe
|
|
419
|
-
* output would exceed this,
|
|
485
|
+
* Capping the decompressed byte count makes the pipe abort the moment the
|
|
486
|
+
* output would exceed this, before the full bomb is materialized, so the
|
|
420
487
|
* inflation can never exhaust memory. Defaults to `16 MiB` — a generous
|
|
421
488
|
* ceiling for a legitimate compressed JSON / form body, far below an OOM. A
|
|
422
|
-
* consumer raises it
|
|
489
|
+
* consumer raises it through {@link import('./types.js').BodyOptions}
|
|
423
490
|
* `decompression` for a workload that genuinely ships larger decompressed
|
|
424
491
|
* bodies.
|
|
425
492
|
*/
|
|
426
493
|
export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
|
|
427
494
|
|
|
428
|
-
/**
|
|
495
|
+
/**
|
|
496
|
+
* Names the default graceful-stop deadline `stop()` gives in-flight requests and
|
|
497
|
+
* claimed upgraded sockets, `10_000` ms.
|
|
498
|
+
*/
|
|
429
499
|
export declare const DEFAULT_DRAIN_MS = 10000;
|
|
430
500
|
|
|
431
501
|
/**
|
|
432
|
-
*
|
|
433
|
-
*
|
|
502
|
+
* Lists the default {@link Encoding} content-codings the substrate offers, in
|
|
503
|
+
* preference order — `gzip` then `deflate`.
|
|
434
504
|
*
|
|
435
505
|
* @remarks
|
|
436
|
-
* `identity` (no compression) is always implicitly acceptable and is
|
|
506
|
+
* `identity` (no compression) is always implicitly acceptable and is not
|
|
437
507
|
* listed here — it is the fall-through when a client accepts none of these.
|
|
438
508
|
* Brotli is omitted per the core's `CompressionStream`-only decision (see
|
|
439
509
|
* {@link Encoding}). Frozen so a consumer can read but never mutate the
|
|
@@ -442,22 +512,28 @@ export declare const DEFAULT_DRAIN_MS = 10000;
|
|
|
442
512
|
export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
443
513
|
|
|
444
514
|
/**
|
|
445
|
-
*
|
|
446
|
-
*
|
|
515
|
+
* Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
|
|
516
|
+
* port where one is given and on an ephemeral port otherwise, reads the bound
|
|
517
|
+
* port, closes the server, and resolves that port.
|
|
447
518
|
*
|
|
448
519
|
* @remarks
|
|
449
520
|
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
450
|
-
* and returns it. With a `preferred` port it tries
|
|
451
|
-
* returns it when free; if already in use (`EADDRINUSE`) it
|
|
521
|
+
* and returns it. With a `preferred` port it tries that port first and
|
|
522
|
+
* returns it when free; if already in use (`EADDRINUSE`) it falls back to an
|
|
452
523
|
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
453
524
|
* port. It binds then immediately closes a probe server, so the returned
|
|
454
525
|
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
455
526
|
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
456
|
-
* `preferred` port (
|
|
527
|
+
* `preferred` port (for example, a permission fault). A listener whose address is not
|
|
528
|
+
* an {@link import('node:net').AddressInfo} — a pipe listener, which this
|
|
529
|
+
* package's options cannot request — rejects with a `TypeError` rather than
|
|
530
|
+
* reporting `0`, because `0` is this package's own request for an ephemeral
|
|
531
|
+
* port and never means an unknown one.
|
|
457
532
|
*
|
|
458
533
|
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
459
534
|
* fall back to an ephemeral port
|
|
460
535
|
* @returns A free TCP port number
|
|
536
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
461
537
|
*
|
|
462
538
|
* @example
|
|
463
539
|
* ```ts
|
|
@@ -469,48 +545,28 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
|
|
|
469
545
|
export declare function discoverPort(preferred?: number): Promise<number>;
|
|
470
546
|
|
|
471
547
|
/**
|
|
472
|
-
*
|
|
473
|
-
* `Content-Encoding`
|
|
548
|
+
* Represents a content-coding the substrate compresses or decompresses with. Its
|
|
549
|
+
* members are the `Content-Encoding` and `Accept-Encoding` token vocabulary the
|
|
550
|
+
* substrate understands.
|
|
474
551
|
*
|
|
475
552
|
* @remarks
|
|
476
553
|
* `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
|
|
477
554
|
* (web-standard, no external codec); `identity` is the no-op "uncompressed"
|
|
478
555
|
* coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
|
|
479
|
-
* is deliberately
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
* behavioral toggle (AGENTS §4.4).
|
|
556
|
+
* is deliberately omitted here — Brotli parity is the middleware package's
|
|
557
|
+
* node-entry decision, not this core's. A constrained set of external-spec
|
|
558
|
+
* literals, so it stays a union, not a behavioral toggle.
|
|
483
559
|
*/
|
|
484
560
|
export declare type Encoding = 'gzip' | 'deflate' | 'identity';
|
|
485
561
|
|
|
486
562
|
/**
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
* @param controller - The stream controller, when the stream has started
|
|
490
|
-
* @param encoder - The encoder used for the stream's byte representation
|
|
491
|
-
* @param closed - Whether the stream has already ended or been cancelled
|
|
492
|
-
* @param text - The text to encode and enqueue
|
|
493
|
-
* @returns Nothing
|
|
494
|
-
*
|
|
495
|
-
* @example
|
|
496
|
-
* ```ts
|
|
497
|
-
* const body = new ReadableStream<Uint8Array>({
|
|
498
|
-
* start(controller) {
|
|
499
|
-
* enqueueStreamText(controller, new TextEncoder(), false, 'hello')
|
|
500
|
-
* },
|
|
501
|
-
* })
|
|
502
|
-
* ```
|
|
503
|
-
*/
|
|
504
|
-
export declare function enqueueStreamText(controller: ReadableStreamDefaultController<Uint8Array> | undefined, encoder: TextEncoder, closed: boolean, text: string): void;
|
|
505
|
-
|
|
506
|
-
/**
|
|
507
|
-
* A map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
563
|
+
* Represents a map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
508
564
|
* content-negotiation dispatch table.
|
|
509
565
|
*
|
|
510
566
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
511
567
|
*
|
|
512
568
|
* @remarks
|
|
513
|
-
* Each key is a media type the route can
|
|
569
|
+
* Each key is a media type the route can produce (`application/json`,
|
|
514
570
|
* `text/html`, …) and each value the responder that returns that
|
|
515
571
|
* representation as a `Response`. `format` negotiates the client's preferred
|
|
516
572
|
* key from the request `Accept` header and invokes the matching handler, or
|
|
@@ -522,33 +578,35 @@ export declare function enqueueStreamText(controller: ReadableStreamDefaultContr
|
|
|
522
578
|
export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
|
|
523
579
|
|
|
524
580
|
/**
|
|
525
|
-
*
|
|
526
|
-
*
|
|
527
|
-
*
|
|
528
|
-
* `instanceof` alone fails because the two copies' `HTTPError` constructors
|
|
529
|
-
* are distinct objects.
|
|
581
|
+
* Names the `Symbol.for`-interned brand `HTTPError` carries,
|
|
582
|
+
* `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
|
|
583
|
+
* package copies. A consumer never sets it by hand.
|
|
530
584
|
*
|
|
531
585
|
* @remarks
|
|
532
|
-
*
|
|
533
|
-
*
|
|
586
|
+
* The brand exists for the dual-package hazard — a version-skewed or
|
|
587
|
+
* workspace-linked duplicate install — where `instanceof` alone fails because
|
|
588
|
+
* each copy's `HTTPError` constructor is a distinct object.
|
|
589
|
+
* `Symbol.for` interns the symbol on the global symbol registry, so every
|
|
590
|
+
* copy of this package that evaluates this key resolves the same symbol
|
|
534
591
|
* instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
|
|
535
592
|
* unequal symbol per copy and defeat the whole point of a cross-copy brand.
|
|
536
593
|
*/
|
|
537
594
|
export declare const HTTP_ERROR_BRAND: unique symbol;
|
|
538
595
|
|
|
539
596
|
/**
|
|
540
|
-
*
|
|
597
|
+
* Represents an error a handler (or middleware) throws to produce an HTTP response of a
|
|
541
598
|
* specific status.
|
|
542
599
|
*
|
|
543
600
|
* @remarks
|
|
544
601
|
* Carries the HTTP `status` to send and an optional `context` record (the
|
|
545
602
|
* offending field / value). The server's built-in error boundary catches it
|
|
546
603
|
* and renders a response of `status` with the error's `message` as the body
|
|
547
|
-
* — so an `HTTPError`'s message is
|
|
604
|
+
* — so an `HTTPError`'s message is always client-facing (it is the handler's
|
|
548
605
|
* deliberate signal), unlike a generic throw whose message is hidden unless
|
|
549
606
|
* `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
|
|
550
607
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
551
|
-
* {@link isHTTPError}.
|
|
608
|
+
* {@link isHTTPError}. The machine-readable discriminator is `status`; there is
|
|
609
|
+
* no separate `code`.
|
|
552
610
|
*
|
|
553
611
|
* @example
|
|
554
612
|
* ```ts
|
|
@@ -569,36 +627,17 @@ export declare class HTTPError extends Error {
|
|
|
569
627
|
}
|
|
570
628
|
|
|
571
629
|
/**
|
|
572
|
-
*
|
|
573
|
-
* input is not a plain IPv6 address to collapse.
|
|
574
|
-
*
|
|
575
|
-
* @remarks
|
|
576
|
-
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
577
|
-
* is the identity) or any string that does not expand to exactly eight
|
|
578
|
-
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
579
|
-
* first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
|
|
580
|
-
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
581
|
-
* first. Total — a malformed address returns `undefined`.
|
|
582
|
-
*
|
|
583
|
-
* @param address - The candidate IPv6 address
|
|
584
|
-
* @returns The `/64` network string, or `undefined` when not a plain IPv6 address
|
|
585
|
-
*
|
|
586
|
-
* @example
|
|
587
|
-
* ```ts
|
|
588
|
-
* ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
589
|
-
* ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
590
|
-
* ```
|
|
591
|
-
*/
|
|
592
|
-
export declare function ipv6Network(address: string): string | undefined;
|
|
593
|
-
|
|
594
|
-
/**
|
|
595
|
-
* Whether a `node:net` `server.address()` return is the structured
|
|
630
|
+
* Checks whether a `node:net` `server.address()` return is the structured
|
|
596
631
|
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
597
|
-
* or `null` — the total, never-throwing narrow
|
|
632
|
+
* or `null` — the total, never-throwing narrow `discoverPort`
|
|
598
633
|
* and the `Server`'s own port resolution read the bound port through.
|
|
599
634
|
*
|
|
635
|
+
* @remarks
|
|
636
|
+
* Checks the `address`, `family`, and `port` members `node:net` declares as
|
|
637
|
+
* `string`, `string`, and `number`.
|
|
638
|
+
*
|
|
600
639
|
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
601
|
-
* @returns
|
|
640
|
+
* @returns True if `value` is an `AddressInfo`; false otherwise
|
|
602
641
|
*
|
|
603
642
|
* @example
|
|
604
643
|
* ```ts
|
|
@@ -611,17 +650,17 @@ export declare function ipv6Network(address: string): string | undefined;
|
|
|
611
650
|
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
612
651
|
|
|
613
652
|
/**
|
|
614
|
-
*
|
|
653
|
+
* Checks whether a `Content-Type` is worth compressing.
|
|
615
654
|
*
|
|
616
655
|
* @remarks
|
|
617
656
|
* Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
|
|
618
657
|
* type, a `+json`/`+xml` structured suffix, or one of the explicit
|
|
619
658
|
* {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
|
|
620
|
-
* binary (`image/png`, `application/zip`) is
|
|
621
|
-
* absent/empty type is not compressible.
|
|
659
|
+
* binary (`image/png`, `application/zip`) is not compressible. An
|
|
660
|
+
* absent/empty type is not compressible. Total.
|
|
622
661
|
*
|
|
623
662
|
* @param type - The response `Content-Type` header value (with or without parameters)
|
|
624
|
-
* @returns
|
|
663
|
+
* @returns True if the type is text-shaped and worth compressing; false otherwise
|
|
625
664
|
*
|
|
626
665
|
* @example
|
|
627
666
|
* ```ts
|
|
@@ -632,9 +671,9 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
|
632
671
|
export declare function isCompressibleType(type: string): boolean;
|
|
633
672
|
|
|
634
673
|
/**
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
674
|
+
* Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —
|
|
675
|
+
* the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it
|
|
676
|
+
* emits them.
|
|
638
677
|
*
|
|
639
678
|
* @remarks
|
|
640
679
|
* Rejects a value carrying a `;` (splits attributes), a `,` (can split a
|
|
@@ -643,7 +682,7 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
643
682
|
* directive. Total — never throws (a bad value returns `false`).
|
|
644
683
|
*
|
|
645
684
|
* @param value - The candidate attribute value (a `Domain` or `Path`)
|
|
646
|
-
* @returns
|
|
685
|
+
* @returns True if `value` carries no separator / whitespace / control char; false otherwise
|
|
647
686
|
*
|
|
648
687
|
* @example
|
|
649
688
|
* ```ts
|
|
@@ -654,8 +693,8 @@ export declare function isCompressibleType(type: string): boolean;
|
|
|
654
693
|
export declare function isCookieAttribute(value: string): boolean;
|
|
655
694
|
|
|
656
695
|
/**
|
|
657
|
-
*
|
|
658
|
-
* cookie-token
|
|
696
|
+
* Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
|
|
697
|
+
* cookie-token characters with no surrounding or interior whitespace.
|
|
659
698
|
*
|
|
660
699
|
* @remarks
|
|
661
700
|
* A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
|
|
@@ -664,7 +703,7 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
664
703
|
* `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
|
|
665
704
|
*
|
|
666
705
|
* @param value - The candidate cookie name
|
|
667
|
-
* @returns
|
|
706
|
+
* @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
|
|
668
707
|
*
|
|
669
708
|
* @example
|
|
670
709
|
* ```ts
|
|
@@ -675,12 +714,12 @@ export declare function isCookieAttribute(value: string): boolean;
|
|
|
675
714
|
export declare function isCookieName(value: string): boolean;
|
|
676
715
|
|
|
677
716
|
/**
|
|
678
|
-
*
|
|
679
|
-
* or `prototype
|
|
680
|
-
*
|
|
717
|
+
* Checks whether a key is a prototype-pollution vector — `__proto__`,
|
|
718
|
+
* `constructor`, or `prototype`, each of which can reach and mutate
|
|
719
|
+
* `Object.prototype` when it is assigned onto a normal object.
|
|
681
720
|
*
|
|
682
721
|
* @param key - The candidate object key
|
|
683
|
-
* @returns
|
|
722
|
+
* @returns True if `key` is one of the three prototype-pollution keys; false otherwise
|
|
684
723
|
*
|
|
685
724
|
* @example
|
|
686
725
|
* ```ts
|
|
@@ -691,21 +730,22 @@ export declare function isCookieName(value: string): boolean;
|
|
|
691
730
|
export declare function isDangerousKey(key: string): boolean;
|
|
692
731
|
|
|
693
732
|
/**
|
|
694
|
-
*
|
|
695
|
-
*
|
|
733
|
+
* Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
|
|
734
|
+
* as {@link ContentTooLargeError}, and recognizes an instance from another copy of
|
|
735
|
+
* this package through a structural brand fallback.
|
|
696
736
|
*
|
|
697
737
|
* @param value - The value to test (typically a `catch` binding)
|
|
698
|
-
* @returns
|
|
738
|
+
* @returns True if `value` is an {@link HTTPError}; false otherwise
|
|
699
739
|
*
|
|
700
740
|
* @remarks
|
|
701
741
|
* Tries `instanceof` first, then falls back to a total structural check for
|
|
702
|
-
* an instance built by a
|
|
742
|
+
* an instance built by a different copy of this package (the dual-package
|
|
703
743
|
* hazard — version skew, a linked workspace duplicate) whose `HTTPError`
|
|
704
744
|
* constructor is a distinct object from this copy's: the value must carry
|
|
705
|
-
* the cross-copy brand (interned
|
|
706
|
-
* same key)
|
|
745
|
+
* the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
|
|
746
|
+
* same key) and expose the exact fields the server's error boundary reads off
|
|
707
747
|
* a recognized `HTTPError` — a numeric `status` and a string `message`. A
|
|
708
|
-
* plain object that merely carries a `status`
|
|
748
|
+
* plain object that merely carries a `status` without the brand is rejected.
|
|
709
749
|
*
|
|
710
750
|
* @example
|
|
711
751
|
* ```ts
|
|
@@ -721,64 +761,72 @@ export declare function isDangerousKey(key: string): boolean;
|
|
|
721
761
|
export declare function isHTTPError(value: unknown): value is HTTPError;
|
|
722
762
|
|
|
723
763
|
/**
|
|
724
|
-
*
|
|
725
|
-
*
|
|
764
|
+
* Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
|
|
765
|
+
* of a call the caller programmed.
|
|
726
766
|
*
|
|
727
|
-
* @
|
|
728
|
-
*
|
|
729
|
-
* untrusted one is a header-injection + log-injection + DoS vector. This
|
|
730
|
-
* refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
|
|
731
|
-
* (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
|
|
732
|
-
* TOTAL — never throws.
|
|
767
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
768
|
+
* @returns True if `value` is a {@link ServerError}; false otherwise
|
|
733
769
|
*
|
|
734
|
-
* @
|
|
735
|
-
*
|
|
770
|
+
* @remarks
|
|
771
|
+
* Recognizes an instance built by this copy of the package. A `ServerError`
|
|
772
|
+
* is raised by a `Server` to the caller that invoked it directly, so both sides
|
|
773
|
+
* hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
|
|
774
|
+
* consumer here.
|
|
736
775
|
*
|
|
737
776
|
* @example
|
|
738
777
|
* ```ts
|
|
739
|
-
*
|
|
740
|
-
*
|
|
778
|
+
* import { createServer, isServerError } from '@src/server'
|
|
779
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
780
|
+
*
|
|
781
|
+
* const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
|
|
782
|
+
* await server.start()
|
|
783
|
+
* try {
|
|
784
|
+
* await server.start()
|
|
785
|
+
* } catch (error) {
|
|
786
|
+
* if (isServerError(error)) console.log(error.code) // 'STATUS'
|
|
787
|
+
* }
|
|
788
|
+
* await server.stop()
|
|
741
789
|
* ```
|
|
742
790
|
*/
|
|
743
|
-
export declare function
|
|
791
|
+
export declare function isServerError(value: unknown): value is ServerError;
|
|
744
792
|
|
|
745
793
|
/**
|
|
746
|
-
*
|
|
747
|
-
*
|
|
794
|
+
* Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
|
|
795
|
+
* header and `context.state`.
|
|
748
796
|
*
|
|
749
797
|
* @remarks
|
|
750
|
-
*
|
|
751
|
-
*
|
|
752
|
-
*
|
|
798
|
+
* A request id is echoed raw into a response header and log lines, so an
|
|
799
|
+
* untrusted one is a header-injection + log-injection + DoS vector. This
|
|
800
|
+
* refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
|
|
801
|
+
* (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
|
|
802
|
+
* Total — never throws.
|
|
753
803
|
*
|
|
754
|
-
* @param
|
|
755
|
-
* @
|
|
756
|
-
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
804
|
+
* @param value - The candidate incoming request id
|
|
805
|
+
* @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
|
|
757
806
|
*
|
|
758
807
|
* @example
|
|
759
808
|
* ```ts
|
|
760
|
-
*
|
|
761
|
-
*
|
|
762
|
-
* languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
809
|
+
* isValidRequestId('req_abc-123') // true
|
|
810
|
+
* isValidRequestId('bad\r\nheader') // false
|
|
763
811
|
* ```
|
|
764
812
|
*/
|
|
765
|
-
export declare function
|
|
813
|
+
export declare function isValidRequestId(value: string): boolean;
|
|
766
814
|
|
|
767
815
|
/**
|
|
768
|
-
*
|
|
769
|
-
* `ETag` — the RFC 7232 §2.3.2
|
|
816
|
+
* Checks whether a request's `If-None-Match` header matches a resource's current
|
|
817
|
+
* `ETag` — the RFC 7232 §2.3.2 weak comparison.
|
|
770
818
|
*
|
|
771
819
|
* @remarks
|
|
772
|
-
* `If-None-Match` is a
|
|
773
|
-
* listed tag matches), or the `*` wildcard (matches
|
|
820
|
+
* `If-None-Match` is a comma-separated list of entity-tags (matches if any
|
|
821
|
+
* listed tag matches), or the `*` wildcard (matches any current
|
|
774
822
|
* representation — only a list of exactly `*` is the wildcard). Comparison is
|
|
775
|
-
*
|
|
776
|
-
*
|
|
823
|
+
* weak: `W/"abc"` and `"abc"` are equal (each side's weak prefix is stripped
|
|
824
|
+
* through {@link unwrapETag} before comparing the opaque body). Total — a
|
|
777
825
|
* malformed/empty header matches nothing, never throws.
|
|
778
826
|
*
|
|
779
827
|
* @param header - The raw `If-None-Match` header value
|
|
780
828
|
* @param etag - The resource's current `ETag`
|
|
781
|
-
* @returns
|
|
829
|
+
* @returns True if the conditional matches (the caller answers `304`); false otherwise
|
|
782
830
|
*
|
|
783
831
|
* @example
|
|
784
832
|
* ```ts
|
|
@@ -789,7 +837,7 @@ export declare function languageQuality(entries: readonly AcceptEntry[], candida
|
|
|
789
837
|
export declare function matchesETag(header: string, etag: string): boolean;
|
|
790
838
|
|
|
791
839
|
/**
|
|
792
|
-
*
|
|
840
|
+
* Reports the rank and quality of one `candidate` media type against the parsed `Accept`
|
|
793
841
|
* entries — the generic media-type primitive the `Negotiator`'s `negotiate`
|
|
794
842
|
* uses to score each `available` candidate.
|
|
795
843
|
*
|
|
@@ -803,8 +851,8 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
803
851
|
* rank tie the highest `q` wins.
|
|
804
852
|
*
|
|
805
853
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
806
|
-
* @param candidate - The candidate media type to score (
|
|
807
|
-
* @returns The
|
|
854
|
+
* @param candidate - The candidate media type to score (for example `'text/html'`)
|
|
855
|
+
* @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
|
|
808
856
|
*
|
|
809
857
|
* @example
|
|
810
858
|
* ```ts
|
|
@@ -814,13 +862,26 @@ export declare function matchesETag(header: string, etag: string): boolean;
|
|
|
814
862
|
* matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
|
|
815
863
|
* ```
|
|
816
864
|
*/
|
|
817
|
-
export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string):
|
|
865
|
+
export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string): MediaMatch | undefined;
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* Rates one candidate media type against a parsed `Accept` header — the
|
|
869
|
+
* quality and specificity `matchMediaType` reports for the best matching
|
|
870
|
+
* {@link AcceptEntry}.
|
|
871
|
+
*
|
|
872
|
+
* @remarks
|
|
873
|
+
* `q` is the client's quality weight in `[0, 1]`. `rank` is the specificity of
|
|
874
|
+
* the entry that matched: `0` for an exact type, `1` for a subtype wildcard
|
|
875
|
+
* (`type/*`), `2` for the any-range (`* / *`). A lower `rank` wins, and a
|
|
876
|
+
* higher `q` breaks a rank tie.
|
|
877
|
+
*/
|
|
878
|
+
export declare interface MediaMatch {
|
|
818
879
|
readonly q: number;
|
|
819
880
|
readonly rank: number;
|
|
820
|
-
}
|
|
881
|
+
}
|
|
821
882
|
|
|
822
883
|
/**
|
|
823
|
-
*
|
|
884
|
+
* Merges a `Vary` value into an existing `Vary` header without duplication.
|
|
824
885
|
*
|
|
825
886
|
* @remarks
|
|
826
887
|
* Splits `existing` on `,`, trims each member, and appends `value` only when
|
|
@@ -842,8 +903,8 @@ export declare function matchMediaType(entries: readonly AcceptEntry[], candidat
|
|
|
842
903
|
export declare function mergeVary(existing: string | undefined, value: string): string;
|
|
843
904
|
|
|
844
905
|
/**
|
|
845
|
-
*
|
|
846
|
-
* middleware
|
|
906
|
+
* Represents the composition context — plain data, one per request, shared by every
|
|
907
|
+
* middleware and, as `state`, by the route handlers behind the dispatcher.
|
|
847
908
|
*
|
|
848
909
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
849
910
|
*
|
|
@@ -852,7 +913,7 @@ export declare function mergeVary(existing: string | undefined, value: string):
|
|
|
852
913
|
* a middleware never re-parses it).
|
|
853
914
|
* - `method` — the raw request verb; the dispatcher (not this seam) narrows it
|
|
854
915
|
* to a known {@link import('@orkestrel/router').Method}.
|
|
855
|
-
* - `state` —
|
|
916
|
+
* - `state` — the shared bag threaded from the adapter's `state` factory,
|
|
856
917
|
* through every middleware, into `dispatcher.handle`'s `state` — the same
|
|
857
918
|
* object a route handler reads as `context.state`.
|
|
858
919
|
* - `body()` — lazily collect the request body (byte-limited, transparently
|
|
@@ -876,14 +937,14 @@ export declare interface MiddlewareContext<TState> {
|
|
|
876
937
|
}
|
|
877
938
|
|
|
878
939
|
/**
|
|
879
|
-
*
|
|
940
|
+
* Represents one link in the middleware onion — runs around the rest of the chain.
|
|
880
941
|
*
|
|
881
942
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
882
943
|
*
|
|
883
944
|
* @remarks
|
|
884
945
|
* Transform the request (call `next(newRequest)`), transform the response
|
|
885
946
|
* (`await next()` then modify the result), short-circuit (return a `Response`
|
|
886
|
-
* without calling `next`), or thread data
|
|
947
|
+
* without calling `next`), or thread data through `context.state` — no mutable
|
|
887
948
|
* framework object anywhere, only fetch-standard `Request`/`Response`.
|
|
888
949
|
*
|
|
889
950
|
* @example
|
|
@@ -898,15 +959,15 @@ export declare interface MiddlewareContext<TState> {
|
|
|
898
959
|
export declare type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
|
|
899
960
|
|
|
900
961
|
/**
|
|
901
|
-
*
|
|
962
|
+
* Selects the best content-coding for a raw `Accept-Encoding` header from the
|
|
902
963
|
* codings the server offers.
|
|
903
964
|
*
|
|
904
965
|
* @remarks
|
|
905
|
-
* Parses the header ({@link parseAcceptHeader}) and
|
|
906
|
-
*
|
|
907
|
-
* the
|
|
908
|
-
* client
|
|
909
|
-
*
|
|
966
|
+
* Parses the header ({@link parseAcceptHeader}) and hands the entries to
|
|
967
|
+
* {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
|
|
968
|
+
* the two doors onto this axis cannot drift. Returns `undefined` when the
|
|
969
|
+
* client accepts none of `available` (identity — no compression). Total on
|
|
970
|
+
* hostile input.
|
|
910
971
|
*
|
|
911
972
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
912
973
|
* @param header - The raw `Accept-Encoding` header value
|
|
@@ -921,14 +982,14 @@ export declare type MiddlewareHandler<TState> = (request: Request, context: Midd
|
|
|
921
982
|
export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
|
|
922
983
|
|
|
923
984
|
/**
|
|
924
|
-
*
|
|
925
|
-
* reusable, cross-middleware
|
|
985
|
+
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
986
|
+
* reusable, cross-middleware entity rather than a middleware. Implements exactly
|
|
926
987
|
* {@link NegotiatorInterface}.
|
|
927
988
|
*
|
|
928
989
|
* @remarks
|
|
929
990
|
* `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
|
|
930
991
|
* any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
|
|
931
|
-
* sibling axes and
|
|
992
|
+
* sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
|
|
932
993
|
* rest of the substrate uses — one parser, never two. `format` reads the
|
|
933
994
|
* request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
|
|
934
995
|
* the winner — or answers `406 Not Acceptable`.
|
|
@@ -945,15 +1006,18 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
945
1006
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
946
1007
|
language(header: string, available: readonly string[]): string | undefined;
|
|
947
1008
|
/**
|
|
1009
|
+
* Dispatches the request to the handler its `Accept` header negotiates,
|
|
1010
|
+
* answering 406 when none matches.
|
|
1011
|
+
*
|
|
948
1012
|
* @remarks
|
|
949
|
-
* Errors thrown by the negotiated handler propagate
|
|
1013
|
+
* Errors thrown by the negotiated handler propagate unmodified — the
|
|
950
1014
|
* server boundary classifies them, never this negotiator.
|
|
951
1015
|
*/
|
|
952
1016
|
format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
|
|
953
1017
|
}
|
|
954
1018
|
|
|
955
1019
|
/**
|
|
956
|
-
*
|
|
1020
|
+
* Represents content negotiation over the weighted `Accept` family — a reusable,
|
|
957
1021
|
* cross-middleware machine (not itself a middleware).
|
|
958
1022
|
*
|
|
959
1023
|
* @remarks
|
|
@@ -975,37 +1039,46 @@ export declare class Negotiator implements NegotiatorInterface {
|
|
|
975
1039
|
*/
|
|
976
1040
|
export declare interface NegotiatorInterface {
|
|
977
1041
|
/**
|
|
978
|
-
*
|
|
1042
|
+
* Picks the best `available` value for a weighted `Accept`-style `header` —
|
|
979
1043
|
* the generic media-type primitive (`encoding` / `language` build on it).
|
|
980
1044
|
*
|
|
981
|
-
* @param header - The raw weighted header value (
|
|
1045
|
+
* @param header - The raw weighted header value (for example `text/html, application/json;q=0.9`)
|
|
982
1046
|
* @param available - The values the server can produce, in preference (tie-break) order
|
|
983
1047
|
* @returns The best acceptable value, or `undefined` when none is
|
|
984
1048
|
*/
|
|
985
1049
|
negotiate(header: string, available: readonly string[]): string | undefined;
|
|
986
1050
|
/**
|
|
987
|
-
*
|
|
988
|
-
* —
|
|
1051
|
+
* Picks the best `available` content-coding for an `Accept-Encoding` header
|
|
1052
|
+
* — the coding axis of the same q-value parser (a bare `*` wildcard ⇒ the
|
|
1053
|
+
* first `available`).
|
|
989
1054
|
*
|
|
990
|
-
* @param header - The raw `Accept-Encoding` header value (
|
|
1055
|
+
* @param header - The raw `Accept-Encoding` header value (for example `gzip;q=1.0, deflate;q=0.8`)
|
|
991
1056
|
* @param available - The codings the server offers, in preference order
|
|
992
1057
|
* @returns The best acceptable coding, or `undefined` when none is
|
|
1058
|
+
*
|
|
1059
|
+
* @remarks
|
|
1060
|
+
* An absent, empty, or unparseable header resolves to `undefined` — no
|
|
1061
|
+
* compression — rather than to the first offered coding, because an absent
|
|
1062
|
+
* `Accept-Encoding` makes identity the correct answer.
|
|
1063
|
+
* {@link NegotiatorInterface.negotiate} and
|
|
1064
|
+
* {@link NegotiatorInterface.language} fall back to the first offered value
|
|
1065
|
+
* instead.
|
|
993
1066
|
*/
|
|
994
1067
|
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
995
1068
|
/**
|
|
996
|
-
*
|
|
1069
|
+
* Picks the best `available` language for an `Accept-Language` header —
|
|
997
1070
|
* `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
|
|
998
1071
|
* bare `*` wildcard.
|
|
999
1072
|
*
|
|
1000
|
-
* @param header - The raw `Accept-Language` header value (
|
|
1073
|
+
* @param header - The raw `Accept-Language` header value (for example `en-US, en;q=0.8, fr;q=0.5`)
|
|
1001
1074
|
* @param available - The languages the server offers, in preference order
|
|
1002
1075
|
* @returns The best acceptable language, or `undefined` when none is
|
|
1003
1076
|
*/
|
|
1004
1077
|
language(header: string, available: readonly string[]): string | undefined;
|
|
1005
1078
|
/**
|
|
1006
|
-
*
|
|
1007
|
-
* the request `Accept`,
|
|
1008
|
-
* winner; `406` when none is acceptable.
|
|
1079
|
+
* Dispatches to the handler whose media type the client most prefers —
|
|
1080
|
+
* reads the request `Accept`, negotiates against `handlers`' keys, and
|
|
1081
|
+
* invokes the winner; `406` when none is acceptable.
|
|
1009
1082
|
*
|
|
1010
1083
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1011
1084
|
* @param request - The in-flight `Request`
|
|
@@ -1017,13 +1090,13 @@ export declare interface NegotiatorInterface {
|
|
|
1017
1090
|
}
|
|
1018
1091
|
|
|
1019
1092
|
/**
|
|
1020
|
-
*
|
|
1021
|
-
* rest of the onion.
|
|
1093
|
+
* Represents the downstream continuation a {@link MiddlewareHandler} invokes to run the
|
|
1094
|
+
* rest of the onion — guarded so a second call within one invocation rejects.
|
|
1022
1095
|
*
|
|
1023
1096
|
* @remarks
|
|
1024
1097
|
* Call it (optionally with a substituted `Request`) to run the downstream
|
|
1025
1098
|
* chain and receive its `Response`; omit the call entirely to short-circuit
|
|
1026
|
-
* with a `Response` built by this middleware instead. A
|
|
1099
|
+
* with a `Response` built by this middleware instead. A second call rejects
|
|
1027
1100
|
* (the double-`next` guard) — each middleware runs the chain at most once.
|
|
1028
1101
|
*
|
|
1029
1102
|
* @param request - An optional replacement `Request` to hand downstream
|
|
@@ -1033,13 +1106,13 @@ export declare interface NegotiatorInterface {
|
|
|
1033
1106
|
export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
1034
1107
|
|
|
1035
1108
|
/**
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1109
|
+
* Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
|
|
1110
|
+
* behind both {@link signToken} and {@link verifyToken}.
|
|
1038
1111
|
*
|
|
1039
1112
|
* @remarks
|
|
1040
1113
|
* A single string becomes a one-element list; a rotation list is copied. Any
|
|
1041
|
-
* blank/whitespace-only entry is
|
|
1042
|
-
* emptiness test; each kept secret is stored
|
|
1114
|
+
* blank/whitespace-only entry is dropped (`.trim()` is used only for that
|
|
1115
|
+
* emptiness test; each kept secret is stored verbatim). The first kept
|
|
1043
1116
|
* element is the signing secret; all kept are accepted on verify.
|
|
1044
1117
|
*
|
|
1045
1118
|
* @param secret - The {@link TokenSecret} (a single string, or a rotation list)
|
|
@@ -1053,59 +1126,17 @@ export declare type NextFunction = (request?: Request) => Promise<Response>;
|
|
|
1053
1126
|
export declare function normalizeSecret(secret: TokenSecret): readonly string[];
|
|
1054
1127
|
|
|
1055
1128
|
/**
|
|
1056
|
-
*
|
|
1057
|
-
* whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
|
|
1058
|
-
*
|
|
1059
|
-
* @remarks
|
|
1060
|
-
* Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
|
|
1061
|
-
* merged under any `options.headers` (a seam-owned key is never overridden),
|
|
1062
|
-
* at `options.status` (default `200`). The returned {@link StreamInterface}'s
|
|
1063
|
-
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1064
|
-
* returns whether the controller still has positive desired size. A producer
|
|
1065
|
-
* receiving `false` can await `drain()`; its event-driven promise resolves on
|
|
1066
|
-
* the next consumer pull that restores capacity, or on stream closure.
|
|
1067
|
-
* `comment` writes a `: text` keep-alive line a conforming parser ignores;
|
|
1068
|
-
* `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
|
|
1069
|
-
* by `end()`, or the consumer cancelled the stream), so a late write never
|
|
1070
|
-
* throws.
|
|
1071
|
-
*
|
|
1072
|
-
* This readiness reflects only the process-local `ReadableStream` queue — it
|
|
1073
|
-
* is not proof that a remote peer consumed bytes. When the response pump
|
|
1074
|
-
* honors its socket sink's drain state, socket pressure stops body pulls and
|
|
1075
|
-
* therefore keeps this queue full, allowing a cooperative producer to bound
|
|
1076
|
-
* buffering. Ignoring the return value preserves the prior unconditional-
|
|
1077
|
-
* enqueue behavior. The default stream strategy counts chunks rather than
|
|
1078
|
-
* their byte length, so a byte-bounded producer must also cap each message.
|
|
1079
|
-
* Return `response` before awaiting a `false` write, because the consumer
|
|
1080
|
-
* cannot pull until it receives the response.
|
|
1081
|
-
*
|
|
1082
|
-
* @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
|
|
1083
|
-
* @returns The {@link StreamInterface} handle
|
|
1084
|
-
*
|
|
1085
|
-
* @example
|
|
1086
|
-
* ```ts
|
|
1087
|
-
* const stream = openStream()
|
|
1088
|
-
* void Promise.resolve().then(async () => {
|
|
1089
|
-
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
1090
|
-
* stream.end()
|
|
1091
|
-
* })
|
|
1092
|
-
* // return stream.response from the route handler
|
|
1093
|
-
* ```
|
|
1094
|
-
*/
|
|
1095
|
-
export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
1096
|
-
|
|
1097
|
-
/**
|
|
1098
|
-
* Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1129
|
+
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
1099
1130
|
* into its q-sorted entries.
|
|
1100
1131
|
*
|
|
1101
1132
|
* @remarks
|
|
1102
1133
|
* Splits on `,`; for each part takes the token before the first `;`
|
|
1103
1134
|
* (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
|
|
1104
1135
|
* quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
|
|
1105
|
-
* back to `1`). A `;q=0` entry is
|
|
1106
|
-
* honor). The result is sorted by `q`
|
|
1136
|
+
* back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must
|
|
1137
|
+
* honor). The result is sorted by `q` descending, a stable sort preserving
|
|
1107
1138
|
* the header's own order within a tie — a single pass with no backtracking,
|
|
1108
|
-
* so parsing stays linear in the header length (ReDoS-safe).
|
|
1139
|
+
* so parsing stays linear in the header length (ReDoS-safe). Total — an
|
|
1109
1140
|
* empty/malformed header yields `[]`/best-effort entries, never throws.
|
|
1110
1141
|
*
|
|
1111
1142
|
* @param header - The raw weighted header value
|
|
@@ -1120,17 +1151,17 @@ export declare function openStream(options?: StreamOptions): StreamInterface;
|
|
|
1120
1151
|
export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
|
|
1121
1152
|
|
|
1122
1153
|
/**
|
|
1123
|
-
*
|
|
1154
|
+
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
1124
1155
|
*
|
|
1125
1156
|
* @remarks
|
|
1126
|
-
* Splits on `;`; the
|
|
1157
|
+
* Splits on `;`; the first segment keeps any leading whitespace (a genuine
|
|
1127
1158
|
* cookie-pair separator never precedes it), while every later segment has its
|
|
1128
1159
|
* inter-pair separator (ASCII space/tab) stripped before parsing — so a
|
|
1129
|
-
* whitespace-
|
|
1160
|
+
* whitespace-padded name (`' __Host-x=evil'`) is rejected by
|
|
1130
1161
|
* {@link isCookieName} rather than silently reconciling into a
|
|
1131
1162
|
* prefix-protected `__Host-` name. A pair without `=`, or with an invalid
|
|
1132
|
-
* name, is skipped; a later duplicate name wins.
|
|
1133
|
-
* malformed header yields an empty record, never throws
|
|
1163
|
+
* name, is skipped; a later duplicate name wins. Total — an absent/empty/
|
|
1164
|
+
* malformed header yields an empty record, never throws.
|
|
1134
1165
|
*
|
|
1135
1166
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
1136
1167
|
* @returns A record of every parsed cookie, `name → decoded value`
|
|
@@ -1143,18 +1174,41 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
|
|
|
1143
1174
|
export declare function parseCookies(header: string | undefined): Record<string, string>;
|
|
1144
1175
|
|
|
1145
1176
|
/**
|
|
1146
|
-
*
|
|
1147
|
-
*
|
|
1177
|
+
* Parses a raw `Content-Encoding` header value into a decompressible
|
|
1178
|
+
* {@link Encoding} — the boundary {@link readBody} coerces through to decide
|
|
1179
|
+
* whether a request body needs transparent decompression.
|
|
1180
|
+
*
|
|
1181
|
+
* @remarks
|
|
1182
|
+
* Lower-cases + trims and returns the matching {@link Encoding} only for
|
|
1183
|
+
* `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
|
|
1184
|
+
* absent header, `identity`, an unknown value, or a
|
|
1185
|
+
* comma-joined multi-coding all yield `undefined` (the body is read as-is).
|
|
1186
|
+
* Total — never asserts the loose `string | null` header.
|
|
1187
|
+
*
|
|
1188
|
+
* @param header - The raw `Content-Encoding` header value
|
|
1189
|
+
* @returns The single decompressible {@link Encoding}, or `undefined` when none applies
|
|
1190
|
+
*
|
|
1191
|
+
* @example
|
|
1192
|
+
* ```ts
|
|
1193
|
+
* parseEncoding('gzip') // 'gzip'
|
|
1194
|
+
* parseEncoding('br') // undefined — unsupported by DecompressionStream
|
|
1195
|
+
* ```
|
|
1196
|
+
*/
|
|
1197
|
+
export declare function parseEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined;
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* Parses an HTTP `Range` request header against a known resource `size` —
|
|
1201
|
+
* total, returning a {@link RangeSpec} or `undefined`.
|
|
1148
1202
|
*
|
|
1149
1203
|
* @remarks
|
|
1150
1204
|
* Handles the three single-range `bytes=` forms — closed (`start-end`), open
|
|
1151
1205
|
* (`start-`), and suffix (`-suffixLength`) — clamping the window to
|
|
1152
|
-
* `[0, size - 1]` (the HTTP
|
|
1206
|
+
* `[0, size - 1]` (the HTTP inclusive-end convention). Returns
|
|
1153
1207
|
* `{ satisfiable: true, start, end }` for an overlapping range,
|
|
1154
1208
|
* `{ satisfiable: false }` for a range wholly past the resource, and
|
|
1155
|
-
* `undefined` for the "serve the whole resource" case: an
|
|
1156
|
-
* non-`bytes` unit, a
|
|
1157
|
-
* supported), or any malformed/non-finite bound.
|
|
1209
|
+
* `undefined` for the "serve the whole resource" case: an absent header, a
|
|
1210
|
+
* non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
|
|
1211
|
+
* supported), or any malformed/non-finite bound. Never throws on a hostile
|
|
1158
1212
|
* header.
|
|
1159
1213
|
*
|
|
1160
1214
|
* @param header - The raw `Range` header value
|
|
@@ -1170,10 +1224,17 @@ export declare function parseCookies(header: string | undefined): Record<string,
|
|
|
1170
1224
|
export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
|
|
1171
1225
|
|
|
1172
1226
|
/**
|
|
1173
|
-
*
|
|
1227
|
+
* Binds and closes a throwaway TCP server to resolve one available port.
|
|
1228
|
+
*
|
|
1229
|
+
* @remarks
|
|
1230
|
+
* The probe always closes, including on the rejection path. A listener whose
|
|
1231
|
+
* address is not an {@link import('node:net').AddressInfo} — a pipe listener,
|
|
1232
|
+
* which a numeric `port` cannot request — has no port to report, so this
|
|
1233
|
+
* rejects rather than substituting a number.
|
|
1174
1234
|
*
|
|
1175
1235
|
* @param port - The requested port, with `0` selecting an ephemeral port
|
|
1176
1236
|
* @returns The bound port after the probe server has closed
|
|
1237
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
1177
1238
|
*
|
|
1178
1239
|
* @example
|
|
1179
1240
|
* ```ts
|
|
@@ -1183,22 +1244,22 @@ export declare function parseRange(header: string | undefined, size: number): Ra
|
|
|
1183
1244
|
export declare function probePort(port: number): Promise<number>;
|
|
1184
1245
|
|
|
1185
1246
|
/**
|
|
1186
|
-
*
|
|
1247
|
+
* Represents the parsed outcome of an HTTP `Range` request header.
|
|
1187
1248
|
*
|
|
1188
1249
|
* @remarks
|
|
1189
|
-
* A `Range: bytes=start-end` against a known resource `size` resolves to
|
|
1250
|
+
* A `Range: bytes=start-end` against a known resource `size` resolves to one
|
|
1190
1251
|
* of two shapes, discriminated by `satisfiable` (the axis is whether the
|
|
1191
1252
|
* requested span overlaps the resource):
|
|
1192
1253
|
*
|
|
1193
1254
|
* - **`satisfiable: true`** — a concrete, clamped byte window `[start, end]`
|
|
1194
|
-
* (
|
|
1255
|
+
* (inclusive, the HTTP wire convention), normalized from the header's
|
|
1195
1256
|
* open / suffix / closed forms against `size`.
|
|
1196
1257
|
* - **`satisfiable: false`** — the range lies wholly outside the resource.
|
|
1197
1258
|
*
|
|
1198
|
-
* `parseRange` returns `undefined` for an
|
|
1259
|
+
* `parseRange` returns `undefined` for an absent / unparseable / multi-range
|
|
1199
1260
|
* / non-`bytes` header — the "no range, serve the whole resource" case — so
|
|
1200
1261
|
* the three outcomes (full / partial / unsatisfiable) are distinguished
|
|
1201
|
-
* without a separate flag. It is
|
|
1262
|
+
* without a separate flag. It is total — a hostile header never throws.
|
|
1202
1263
|
*/
|
|
1203
1264
|
export declare type RangeSpec = {
|
|
1204
1265
|
readonly satisfiable: true;
|
|
@@ -1209,9 +1270,10 @@ export declare type RangeSpec = {
|
|
|
1209
1270
|
};
|
|
1210
1271
|
|
|
1211
1272
|
/**
|
|
1212
|
-
*
|
|
1273
|
+
* Collects and decodes a `Request` body — the shared body-collection pipeline
|
|
1213
1274
|
* surfaced to middleware and handlers as the middleware context's cached
|
|
1214
|
-
* `body()`.
|
|
1275
|
+
* `body()`. An empty body and a malformed `application/json` body each decode to
|
|
1276
|
+
* `undefined`.
|
|
1215
1277
|
*
|
|
1216
1278
|
* @remarks
|
|
1217
1279
|
* Collects the wire body capped at `options.limit` bytes ({@link
|
|
@@ -1220,14 +1282,18 @@ export declare type RangeSpec = {
|
|
|
1220
1282
|
* through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
|
|
1221
1283
|
* `options.decompression`, default {@link
|
|
1222
1284
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1223
|
-
* content type: `application/json` is parsed
|
|
1285
|
+
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1224
1286
|
* `parseJSON` and scrubbed of prototype-pollution keys ({@link
|
|
1225
|
-
* scrubPrototype}); any other type decodes as UTF-8 text
|
|
1226
|
-
*
|
|
1287
|
+
* scrubPrototype}); any other type decodes as UTF-8 text.
|
|
1288
|
+
*
|
|
1289
|
+
* A malformed JSON body is total: it decodes rather than throwing, so a handler
|
|
1290
|
+
* that must reject one checks for `undefined` itself, and nothing in the returned
|
|
1291
|
+
* value tells an empty body from a malformed one.
|
|
1227
1292
|
*
|
|
1228
1293
|
* @param request - The `Request` to read the body from
|
|
1229
1294
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
1230
|
-
* @returns The parsed JSON value, the raw text, or `undefined` for an empty
|
|
1295
|
+
* @returns The parsed JSON value, the raw text, or `undefined` — for an empty
|
|
1296
|
+
* body, and for an `application/json` body whose text is not valid JSON
|
|
1231
1297
|
* @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
|
|
1232
1298
|
* @throws {HTTPError} When the compressed body is corrupt (400)
|
|
1233
1299
|
*
|
|
@@ -1239,13 +1305,13 @@ export declare type RangeSpec = {
|
|
|
1239
1305
|
export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
|
|
1240
1306
|
|
|
1241
1307
|
/**
|
|
1242
|
-
*
|
|
1308
|
+
* Reads and verifies a signed cookie off a request — total, returning the
|
|
1243
1309
|
* embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
1244
1310
|
*
|
|
1245
1311
|
* @remarks
|
|
1246
1312
|
* Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
|
|
1247
1313
|
* and verifies it with {@link verifyToken} against `secret` (a rotation list
|
|
1248
|
-
* accepts a cookie signed by any of its secrets).
|
|
1314
|
+
* accepts a cookie signed by any of its secrets). Any failure — an absent
|
|
1249
1315
|
* cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
|
|
1250
1316
|
*
|
|
1251
1317
|
* @param request - The `Request` to read the `Cookie` header from
|
|
@@ -1261,47 +1327,70 @@ export declare function readBody(request: Request, options?: BodyOptions): Promi
|
|
|
1261
1327
|
export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1262
1328
|
|
|
1263
1329
|
/**
|
|
1264
|
-
*
|
|
1265
|
-
* to match
|
|
1266
|
-
*
|
|
1267
|
-
*
|
|
1268
|
-
*
|
|
1269
|
-
*
|
|
1330
|
+
* Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
|
|
1331
|
+
* to match, `^[A-Za-z0-9_-]{1,200}$`.
|
|
1332
|
+
*
|
|
1333
|
+
* @remarks
|
|
1334
|
+
* An incoming id carrying CRLF, a log-injection payload, a control character,
|
|
1335
|
+
* or more characters than the pattern admits fails the match and is rejected —
|
|
1336
|
+
* a fresh id is minted instead — so it never rides into a response header or
|
|
1337
|
+
* `context.state`. Frozen so a consumer can read but never mutate the shared
|
|
1338
|
+
* default.
|
|
1270
1339
|
*/
|
|
1271
1340
|
export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
|
|
1272
1341
|
|
|
1273
1342
|
/**
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
* whether a request body needs transparent decompression.
|
|
1343
|
+
* Identifies the request a server-level fault came from — its method and its
|
|
1344
|
+
* parsed URL.
|
|
1277
1345
|
*
|
|
1278
1346
|
* @remarks
|
|
1279
|
-
*
|
|
1280
|
-
*
|
|
1281
|
-
* the
|
|
1282
|
-
*
|
|
1283
|
-
|
|
1347
|
+
* Carried by {@link ServerEventMap.error}'s optional second element and by
|
|
1348
|
+
* {@link ServerOptions.report}'s optional second parameter, and present only
|
|
1349
|
+
* when the fault happened on the per-request path — an upgrade-handler throw
|
|
1350
|
+
* or a listen failure has no fetch `Request` to derive it from.
|
|
1351
|
+
*/
|
|
1352
|
+
export declare interface RequestLine {
|
|
1353
|
+
readonly method: string;
|
|
1354
|
+
readonly url: URL;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
/**
|
|
1358
|
+
* Picks the highest-scoring content-coding the server offers against already
|
|
1359
|
+
* parsed `Accept-Encoding` entries — the shared selection leaf behind
|
|
1360
|
+
* {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
|
|
1284
1361
|
*
|
|
1285
|
-
* @
|
|
1286
|
-
*
|
|
1362
|
+
* @remarks
|
|
1363
|
+
* The single selection leaf behind both doors onto this axis —
|
|
1364
|
+
* {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
|
|
1365
|
+
* entity — so the scoring loop has one implementation. Scores each `available`
|
|
1366
|
+
* coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
|
|
1367
|
+
* keeps the earlier-offered coding on a client-side tie, which is what makes
|
|
1368
|
+
* `available` the server's preference order. An empty `available` list, and a
|
|
1369
|
+
* list the client rejects outright, both yield `undefined` (identity — no
|
|
1370
|
+
* compression). Total on hostile input.
|
|
1371
|
+
*
|
|
1372
|
+
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
1373
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
1374
|
+
* @param available - The codings the server offers, in preference (tie-break) order
|
|
1375
|
+
* @returns The winning coding, or `undefined` when none of `available` is acceptable
|
|
1287
1376
|
*
|
|
1288
1377
|
* @example
|
|
1289
1378
|
* ```ts
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1379
|
+
* resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
|
|
1380
|
+
* resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
|
|
1292
1381
|
* ```
|
|
1293
1382
|
*/
|
|
1294
|
-
export declare function
|
|
1383
|
+
export declare function resolveCoding<T extends string>(entries: readonly AcceptEntry[], available: readonly T[]): T | undefined;
|
|
1295
1384
|
|
|
1296
1385
|
/**
|
|
1297
|
-
*
|
|
1386
|
+
* Resolves the `Access-Control-Allow-Origin` value for a request.
|
|
1298
1387
|
*
|
|
1299
1388
|
* @remarks
|
|
1300
1389
|
* `'*'` and a single origin string pass straight through. An allow-list
|
|
1301
1390
|
* echoes the request's `Origin` only when it is present in the list, else
|
|
1302
|
-
* `undefined` (no header set).
|
|
1391
|
+
* `undefined` (no header set). Security: the literal `'null'` origin — sent
|
|
1303
1392
|
* by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
|
|
1304
|
-
*
|
|
1393
|
+
* never reflected even if `'null'` were listed, closing the hostile-context
|
|
1305
1394
|
* cross-origin-access hole.
|
|
1306
1395
|
*
|
|
1307
1396
|
* @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
|
|
@@ -1317,7 +1406,7 @@ export declare function requestEncoding(header: string | null): Exclude<Encoding
|
|
|
1317
1406
|
export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
|
|
1318
1407
|
|
|
1319
1408
|
/**
|
|
1320
|
-
*
|
|
1409
|
+
* Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
|
|
1321
1410
|
* `secure` setting and whether the request arrived over TLS.
|
|
1322
1411
|
*
|
|
1323
1412
|
* @remarks
|
|
@@ -1327,7 +1416,10 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1327
1416
|
* gets `Secure` automatically while local-dev HTTP still works.
|
|
1328
1417
|
*
|
|
1329
1418
|
* @param secure - The {@link CookieOptions} `secure` setting
|
|
1330
|
-
* @param encrypted - The connection's TLS flag
|
|
1419
|
+
* @param encrypted - The connection's TLS flag
|
|
1420
|
+
* ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
|
|
1421
|
+
* `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
|
|
1422
|
+
* no `Secure` attribute.
|
|
1331
1423
|
* @returns The concrete `Secure` flag to emit
|
|
1332
1424
|
*
|
|
1333
1425
|
* @example
|
|
@@ -1340,11 +1432,11 @@ export declare function resolveOrigin(origin: string | readonly string[], reques
|
|
|
1340
1432
|
export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
|
|
1341
1433
|
|
|
1342
1434
|
/**
|
|
1343
|
-
*
|
|
1435
|
+
* Resolves one opt-out, value-bearing security header.
|
|
1344
1436
|
*
|
|
1345
1437
|
* @remarks
|
|
1346
1438
|
* The shared "a `string` value, or `false` to omit, or a default when unset"
|
|
1347
|
-
* resolution (
|
|
1439
|
+
* resolution (a value-or-off union, not a behavioral toggle):
|
|
1348
1440
|
* `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
|
|
1349
1441
|
* override, `undefined` (unset) ⇒ `fallback` (the secure default).
|
|
1350
1442
|
*
|
|
@@ -1362,12 +1454,27 @@ export declare function resolveSecure(secure: boolean | undefined, encrypted: bo
|
|
|
1362
1454
|
export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
|
|
1363
1455
|
|
|
1364
1456
|
/**
|
|
1365
|
-
*
|
|
1366
|
-
*
|
|
1457
|
+
* Records one finished request — the payload {@link ServerEventMap.response}
|
|
1458
|
+
* carries.
|
|
1459
|
+
*
|
|
1460
|
+
* @remarks
|
|
1461
|
+
* `method` and `pathname` come from the parsed request, `status` is the status
|
|
1462
|
+
* actually sent (on the success path or the outer-boundary error path), and
|
|
1463
|
+
* `ms` is the elapsed time in whole milliseconds.
|
|
1464
|
+
*/
|
|
1465
|
+
export declare interface ResponseRecord {
|
|
1466
|
+
readonly method: string;
|
|
1467
|
+
readonly pathname: string;
|
|
1468
|
+
readonly status: number;
|
|
1469
|
+
readonly ms: number;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
/**
|
|
1473
|
+
* Strips the prototype-pollution keys from a parsed value in place, recursively.
|
|
1367
1474
|
*
|
|
1368
1475
|
* @remarks
|
|
1369
|
-
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an
|
|
1370
|
-
* enumerable `__proto__`
|
|
1476
|
+
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
|
|
1477
|
+
* enumerable `__proto__` data property — but that own key becomes a
|
|
1371
1478
|
* pollution gadget the moment a downstream deep-merge copies it onto a live
|
|
1372
1479
|
* object. This walks the value and `delete`s any own {@link isDangerousKey}
|
|
1373
1480
|
* key at every depth, recursing into nested objects + array elements.
|
|
@@ -1386,18 +1493,17 @@ export declare function resolveSecurityHeader(value: string | false | undefined,
|
|
|
1386
1493
|
export declare function scrubPrototype(value: unknown): unknown;
|
|
1387
1494
|
|
|
1388
1495
|
/**
|
|
1389
|
-
*
|
|
1496
|
+
* Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
|
|
1390
1497
|
*
|
|
1391
1498
|
* @remarks
|
|
1392
1499
|
* URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
|
|
1393
1500
|
* appends the present {@link CookieOptions} attributes in canonical order:
|
|
1394
1501
|
* `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
|
|
1395
|
-
* (default
|
|
1396
|
-
* with {@link isCookieAttribute} and
|
|
1397
|
-
* injection attempt (a programmer misconfiguration
|
|
1398
|
-
* silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
|
|
1502
|
+
* (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated
|
|
1503
|
+
* with {@link isCookieAttribute} and throw an {@link HTTPError} on an
|
|
1504
|
+
* injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of
|
|
1399
1505
|
* the `secure` option (the spec requires it); an un-resolved `undefined`
|
|
1400
|
-
* `secure` here falls to
|
|
1506
|
+
* `secure` here falls to off — request-aware callers resolve it first through
|
|
1401
1507
|
* {@link resolveSecure}.
|
|
1402
1508
|
*
|
|
1403
1509
|
* @param name - The cookie name
|
|
@@ -1414,10 +1520,10 @@ export declare function scrubPrototype(value: unknown): unknown;
|
|
|
1414
1520
|
export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
1415
1521
|
|
|
1416
1522
|
/**
|
|
1417
|
-
*
|
|
1523
|
+
* Serializes one {@link SSEMessage} to the SSE wire.
|
|
1418
1524
|
*
|
|
1419
1525
|
* @remarks
|
|
1420
|
-
* Emits an `event:`/`id:`/`retry:` line for each present field, then
|
|
1526
|
+
* Emits an `event:`/`id:`/`retry:` line for each present field, then one
|
|
1421
1527
|
* `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
|
|
1422
1528
|
* (so a consuming parser's multi-`data` concat reproduces the original
|
|
1423
1529
|
* `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
|
|
@@ -1435,39 +1541,39 @@ export declare function serializeCookie(name: string, value: string, options?: C
|
|
|
1435
1541
|
export declare function serializeEvent(message: SSEMessage): string;
|
|
1436
1542
|
|
|
1437
1543
|
/**
|
|
1438
|
-
*
|
|
1544
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle composing this
|
|
1439
1545
|
* module's own middleware onion around a consumed `@orkestrel/router`
|
|
1440
|
-
* dispatcher.
|
|
1546
|
+
* dispatcher. Implements exactly {@link ServerInterface}.
|
|
1441
1547
|
*
|
|
1442
1548
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1443
1549
|
*
|
|
1444
1550
|
* @remarks
|
|
1445
|
-
* - **Lifecycle
|
|
1551
|
+
* - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
|
|
1446
1552
|
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1447
|
-
* ServerOptions.port} (omitted/`0` port ⇒
|
|
1553
|
+
* ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
|
|
1448
1554
|
* bound address), exposes that {@link AddressInfo} through `address`, observes
|
|
1449
1555
|
* caller cancellation plus the configured `timeouts.start` deadline while the
|
|
1450
1556
|
* bind is pending, and transitions `idle → starting → listening`. A
|
|
1451
1557
|
* cancelled or expired bind closes its partial server and resets to `idle` for
|
|
1452
1558
|
* another start. `stop()` transitions
|
|
1453
1559
|
* to `stopping`: refuses new connections, fires a fresh-per-run stop signal
|
|
1454
|
-
* so in-flight handlers observe cancellation, drains in-flight requests
|
|
1560
|
+
* so in-flight handlers observe cancellation, drains in-flight requests and
|
|
1455
1561
|
* claimed upgraded sockets up to the `drain` deadline (event-driven, no
|
|
1456
1562
|
* busy-loop), then closes → `stopped`, forcing whatever the deadline caught
|
|
1457
1563
|
* still open. `destroy()` is the idempotent final teardown.
|
|
1458
1564
|
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1459
|
-
* `close`); a `Request` is built
|
|
1460
|
-
* `signal`
|
|
1565
|
+
* `close`); a `Request` is built through the router's `buildRequest`, its
|
|
1566
|
+
* `signal` linked to this run's stop signal through `@orkestrel/abort`'s
|
|
1461
1567
|
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1462
|
-
* `buildRequest`'s own abort, armed by
|
|
1463
|
-
* teardown, composes with the server's stop signal
|
|
1464
|
-
* so a handler awaiting `request.signal` observes
|
|
1568
|
+
* `buildRequest`'s own abort, armed by request-side and response-side
|
|
1569
|
+
* teardown, composes with the server's stop signal through `AbortSignal.any`,
|
|
1570
|
+
* so a handler awaiting `request.signal` observes either); `context.state` is built through
|
|
1465
1571
|
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1466
1572
|
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1467
|
-
* written back
|
|
1468
|
-
* - **The built-in boundary** wraps the
|
|
1573
|
+
* written back through `sendResponse`.
|
|
1574
|
+
* - **The built-in boundary** wraps the whole per-request chain, including
|
|
1469
1575
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1470
|
-
* throw (
|
|
1576
|
+
* throw (for example, a malformed `Host` header) to a silent `400` with no
|
|
1471
1577
|
* `error` emit; everything after (`Request` reconstruction, connection
|
|
1472
1578
|
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1473
1579
|
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
@@ -1479,17 +1585,17 @@ export declare function serializeEvent(message: SSEMessage): string;
|
|
|
1479
1585
|
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1480
1586
|
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1481
1587
|
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
1482
|
-
* A
|
|
1588
|
+
* A claimed socket joins `#upgraded` until it closes: the claimant still
|
|
1483
1589
|
* owns it, and the tracking exists because node detaches an upgraded socket
|
|
1484
1590
|
* from the set its own close calls walk, so nothing else can end it.
|
|
1485
|
-
* - **Observable
|
|
1591
|
+
* - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1486
1592
|
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1487
|
-
* routes it to the `error`
|
|
1593
|
+
* routes it to the `error` option rather than to the domain `error` event.
|
|
1488
1594
|
*/
|
|
1489
1595
|
export declare class Server<TState> implements ServerInterface<TState> {
|
|
1490
1596
|
#private;
|
|
1491
|
-
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
1492
1597
|
constructor(options: ServerOptions<TState>);
|
|
1598
|
+
get id(): string;
|
|
1493
1599
|
get status(): ServerStatus;
|
|
1494
1600
|
get port(): number | undefined;
|
|
1495
1601
|
get address(): AddressInfo | undefined;
|
|
@@ -1504,7 +1610,56 @@ export declare class Server<TState> implements ServerInterface<TState> {
|
|
|
1504
1610
|
}
|
|
1505
1611
|
|
|
1506
1612
|
/**
|
|
1507
|
-
*
|
|
1613
|
+
* Represents the error this package raises when a caller programmed a call the
|
|
1614
|
+
* entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
|
|
1615
|
+
*
|
|
1616
|
+
* @remarks
|
|
1617
|
+
* Carries a machine-readable {@link ServerErrorCode} and an optional `context`
|
|
1618
|
+
* record naming the offending facts. This is a programmer error, so it carries
|
|
1619
|
+
* no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
|
|
1620
|
+
* invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
|
|
1621
|
+
* middleware into the request boundary, which reaches it as a generic 500 with
|
|
1622
|
+
* the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
|
|
1623
|
+
* client-facing fault instead. Narrow a caught value with
|
|
1624
|
+
* {@link isServerError}.
|
|
1625
|
+
*
|
|
1626
|
+
* @example
|
|
1627
|
+
* ```ts
|
|
1628
|
+
* import { ServerError } from '@src/server'
|
|
1629
|
+
*
|
|
1630
|
+
* const error = new ServerError('STATUS', "server cannot start from 'listening'", {
|
|
1631
|
+
* status: 'listening',
|
|
1632
|
+
* })
|
|
1633
|
+
* error.code // 'STATUS'
|
|
1634
|
+
* ```
|
|
1635
|
+
*/
|
|
1636
|
+
export declare class ServerError extends Error {
|
|
1637
|
+
readonly code: ServerErrorCode;
|
|
1638
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
1639
|
+
constructor(code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>);
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
/**
|
|
1643
|
+
* Represents the machine-readable category a
|
|
1644
|
+
* {@link import('./errors.js').ServerError} carries — `'STATUS'` for a lifecycle
|
|
1645
|
+
* call the current status forbids, `'NEXT'` for a middleware that called its `next`
|
|
1646
|
+
* a second time.
|
|
1647
|
+
*
|
|
1648
|
+
* @remarks
|
|
1649
|
+
* A `ServerError` reports a call the caller programmed and the substrate
|
|
1650
|
+
* refuses, not a client-facing fault — {@link import('./errors.js').HTTPError}
|
|
1651
|
+
* owns the latter and keys on `status` instead. The categories are disjoint, so
|
|
1652
|
+
* a `catch` narrowed by {@link import('./errors.js').isServerError} reads `code`
|
|
1653
|
+
* to tell them apart.
|
|
1654
|
+
*/
|
|
1655
|
+
export declare type ServerErrorCode =
|
|
1656
|
+
/** Identifies a lifecycle call the current {@link ServerStatus} forbids. */
|
|
1657
|
+
'STATUS'
|
|
1658
|
+
/** Identifies a middleware that called its `next` a second time within one invocation. */
|
|
1659
|
+
| 'NEXT';
|
|
1660
|
+
|
|
1661
|
+
/**
|
|
1662
|
+
* Represents the `Server`'s observable lifecycle events.
|
|
1508
1663
|
*
|
|
1509
1664
|
* @remarks
|
|
1510
1665
|
* - `start` — `listen()` resolved; carries the actually-bound port (an
|
|
@@ -1519,43 +1674,33 @@ export declare class Server<TState> implements ServerInterface<TState> {
|
|
|
1519
1674
|
* the per-request path; `undefined` for an upgrade-handler throw (no fetch
|
|
1520
1675
|
* `Request` exists on that path — only a raw `IncomingMessage`) or a listen
|
|
1521
1676
|
* failure.
|
|
1522
|
-
* - `stop` — `stop()` began (status
|
|
1677
|
+
* - `stop` — `stop()` began (status moved to `'stopping'`). An upgrade
|
|
1523
1678
|
* handler that owns a long-lived socket closes it from here, so the drain
|
|
1524
|
-
*
|
|
1679
|
+
* settles instead of running out the deadline.
|
|
1525
1680
|
* - `drain` — the graceful drain settled (deadline hit or all finished);
|
|
1526
|
-
* carries the still-pending request count
|
|
1681
|
+
* carries the still-pending request count and the still-attached upgraded
|
|
1527
1682
|
* socket count. Both `0` is a clean drain; either non-zero means the close
|
|
1528
|
-
* that follows was
|
|
1683
|
+
* that follows was forced and cut that work.
|
|
1529
1684
|
* - `response` — fired after the response has been sent, for every request
|
|
1530
1685
|
* that reaches the middleware pipeline (the success path and the
|
|
1531
1686
|
* outer-boundary error path); carries the method, parsed pathname, final
|
|
1532
1687
|
* status, and elapsed time in milliseconds. A request rejected at the
|
|
1533
|
-
* `buildRequest`
|
|
1534
|
-
* header) emits no `response` — no parsed `Request` exists yet to derive
|
|
1688
|
+
* `buildRequest` inner boundary (a plain `400`, for example a malformed
|
|
1689
|
+
* `Host` header) emits no `response` — no parsed `Request` exists yet to derive
|
|
1535
1690
|
* its facts from.
|
|
1536
1691
|
*/
|
|
1537
1692
|
export declare type ServerEventMap = {
|
|
1538
1693
|
readonly start: readonly [port: number];
|
|
1539
1694
|
readonly request: readonly [method: string, pathname: string];
|
|
1540
1695
|
readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
|
|
1541
|
-
readonly error: readonly [error: unknown, request?:
|
|
1542
|
-
method: string;
|
|
1543
|
-
url: URL;
|
|
1544
|
-
}];
|
|
1696
|
+
readonly error: readonly [error: unknown, request?: RequestLine];
|
|
1545
1697
|
readonly stop: readonly [];
|
|
1546
1698
|
readonly drain: readonly [pending: number, upgraded: number];
|
|
1547
|
-
readonly response: readonly [
|
|
1548
|
-
event: {
|
|
1549
|
-
method: string;
|
|
1550
|
-
pathname: string;
|
|
1551
|
-
status: number;
|
|
1552
|
-
ms: number;
|
|
1553
|
-
}
|
|
1554
|
-
];
|
|
1699
|
+
readonly response: readonly [event: ResponseRecord];
|
|
1555
1700
|
};
|
|
1556
1701
|
|
|
1557
1702
|
/**
|
|
1558
|
-
*
|
|
1703
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle that composes
|
|
1559
1704
|
* a middleware onion (this module's own middleware seam) around a consumed
|
|
1560
1705
|
* `@orkestrel/router` {@link DispatcherInterface}.
|
|
1561
1706
|
*
|
|
@@ -1564,7 +1709,7 @@ export declare type ServerEventMap = {
|
|
|
1564
1709
|
* @remarks
|
|
1565
1710
|
* `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
|
|
1566
1711
|
* both configurable before or after `start()`. `start(signal?)` binds the
|
|
1567
|
-
* configured `host`/`port` (an omitted/`0` port ⇒ an
|
|
1712
|
+
* configured `host`/`port` (an omitted/`0` port ⇒ an ephemeral port, resolved
|
|
1568
1713
|
* from the bound address), exposes that {@link AddressInfo} through `address`,
|
|
1569
1714
|
* observes caller cancellation plus `timeouts.start` while binding, and resolves
|
|
1570
1715
|
* the actually-bound port. A cancelled or expired bind closes its partial server
|
|
@@ -1572,37 +1717,72 @@ export declare type ServerEventMap = {
|
|
|
1572
1717
|
* connections, fires the stop signal so in-flight handlers can observe it,
|
|
1573
1718
|
* drains in-flight requests and claimed upgraded sockets up to the configured
|
|
1574
1719
|
* deadline, then closes — forcing whatever is left. `destroy()` is the final
|
|
1575
|
-
* idempotent teardown. Per request: a `Request` is built
|
|
1720
|
+
* idempotent teardown. Per request: a `Request` is built through the router's
|
|
1576
1721
|
* `buildRequest` (its signal linked to the server's stop signal), the composed
|
|
1577
1722
|
* middleware onion runs terminating in `dispatcher.handle`, and the result is
|
|
1578
|
-
* written back
|
|
1723
|
+
* written back through `sendResponse` — every escaping throw is caught by the
|
|
1579
1724
|
* built-in boundary (`HTTPError` → its status; anything else → a
|
|
1580
1725
|
* hidden-unless-`expose` `500`) so a handler error can never crash the process.
|
|
1581
1726
|
*/
|
|
1582
1727
|
export declare interface ServerInterface<TState> {
|
|
1728
|
+
/** Holds the instance's correlation id, minted once per `Server` and stable for its lifetime. */
|
|
1583
1729
|
readonly id: string;
|
|
1730
|
+
/** Reports the current lifecycle phase — see {@link ServerStatus}. */
|
|
1584
1731
|
readonly status: ServerStatus;
|
|
1732
|
+
/**
|
|
1733
|
+
* Holds the bound listener's TCP port — the `port` of {@link address} — or
|
|
1734
|
+
* `undefined` while no listener is active.
|
|
1735
|
+
*/
|
|
1585
1736
|
readonly port: number | undefined;
|
|
1586
|
-
/**
|
|
1737
|
+
/** Holds the bound listener address, or `undefined` while no listener is active. */
|
|
1587
1738
|
readonly address: AddressInfo | undefined;
|
|
1739
|
+
/** Holds the `@orkestrel/router` dispatcher the composed middleware onion terminates into. */
|
|
1588
1740
|
readonly dispatcher: DispatcherInterface<TState>;
|
|
1741
|
+
/** Holds the lifecycle emitter over {@link ServerEventMap}. */
|
|
1589
1742
|
readonly emitter: EmitterInterface<ServerEventMap>;
|
|
1743
|
+
/**
|
|
1744
|
+
* Appends one middleware, or an array of them in order, to the onion, outer-to-inner
|
|
1745
|
+
* in call order.
|
|
1746
|
+
*
|
|
1747
|
+
* @param middleware - One handler, or the ordered array of handlers to append
|
|
1748
|
+
*
|
|
1749
|
+
* @remarks
|
|
1750
|
+
* Callable before or after `start()`; an appended handler runs on the next
|
|
1751
|
+
* request the composed onion serves.
|
|
1752
|
+
*/
|
|
1590
1753
|
use(middleware: MiddlewareHandler<TState>): void;
|
|
1591
1754
|
use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
|
|
1755
|
+
/**
|
|
1756
|
+
* Registers an {@link UpgradeHandler} claimant that runs in registration order; a
|
|
1757
|
+
* claimed socket is tracked until it closes.
|
|
1758
|
+
*
|
|
1759
|
+
* @param handler - The claimant; the first to return `true` claims the socket
|
|
1760
|
+
*/
|
|
1592
1761
|
upgrade(handler: UpgradeHandler): void;
|
|
1593
1762
|
/**
|
|
1594
|
-
*
|
|
1763
|
+
* Binds the configured `host` and `port`, or an ephemeral port, under an optional
|
|
1764
|
+
* caller `AbortSignal`, and resolves the actually-bound port.
|
|
1595
1765
|
*
|
|
1596
1766
|
* @param signal - Optional caller cancellation observed only while startup
|
|
1597
1767
|
* is pending; aborting after this method resolves does not stop the server.
|
|
1598
1768
|
* @returns The actually-bound TCP port
|
|
1769
|
+
*
|
|
1770
|
+
* @remarks
|
|
1771
|
+
* Rejects with a {@link import('./errors.js').ServerError} of code
|
|
1772
|
+
* `'STATUS'` when the current {@link ServerStatus} is neither `'idle'` nor
|
|
1773
|
+
* `'stopped'`, carrying that status in its `context`. Narrow it with
|
|
1774
|
+
* {@link import('./errors.js').isServerError}. A listener whose address is
|
|
1775
|
+
* not an `AddressInfo` — a pipe listener, which this package's options
|
|
1776
|
+
* cannot request — closes the partial listener and rejects with a
|
|
1777
|
+
* `TypeError` rather than reporting `0`.
|
|
1599
1778
|
*/
|
|
1600
1779
|
start(signal?: AbortSignal): Promise<number>;
|
|
1601
1780
|
/**
|
|
1602
|
-
*
|
|
1781
|
+
* Stops gracefully: refuses new connections, fires the stop signal, drains in-flight
|
|
1782
|
+
* requests and claimed upgraded sockets up to the `drain` deadline, then closes.
|
|
1603
1783
|
*
|
|
1604
1784
|
* @remarks
|
|
1605
|
-
* Drainable work is every in-flight request
|
|
1785
|
+
* Drainable work is every in-flight request plus every upgraded socket a
|
|
1606
1786
|
* handler claimed. The drain parks on that work reaching zero or the
|
|
1607
1787
|
* `drain` deadline expiring, emits `drain` with both remaining counts, and
|
|
1608
1788
|
* then closes — dropping idle keep-alive sockets on a clean drain, and
|
|
@@ -1614,7 +1794,8 @@ export declare interface ServerInterface<TState> {
|
|
|
1614
1794
|
*/
|
|
1615
1795
|
stop(): Promise<void>;
|
|
1616
1796
|
/**
|
|
1617
|
-
*
|
|
1797
|
+
* Tears down for good: force-closes the listener and every socket, then the emitter —
|
|
1798
|
+
* terminal and idempotent from any state.
|
|
1618
1799
|
*
|
|
1619
1800
|
* @returns Resolves once nothing is left open; idempotent from any state
|
|
1620
1801
|
*/
|
|
@@ -1622,7 +1803,9 @@ export declare interface ServerInterface<TState> {
|
|
|
1622
1803
|
}
|
|
1623
1804
|
|
|
1624
1805
|
/**
|
|
1625
|
-
* Options for `createServer
|
|
1806
|
+
* Options for `createServer` — the dispatcher and per-request state factory the
|
|
1807
|
+
* server requires, plus its listener, drain, boundary, timeout, socket-cap, and
|
|
1808
|
+
* emitter knobs.
|
|
1626
1809
|
*
|
|
1627
1810
|
* @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
|
|
1628
1811
|
* composed middleware onion terminates into — bring-your-own router (the
|
|
@@ -1632,16 +1815,16 @@ export declare interface ServerInterface<TState> {
|
|
|
1632
1815
|
* is never implicitly trusted here; a deployment behind a trusted proxy
|
|
1633
1816
|
* derives its own client key in this function or in middleware.
|
|
1634
1817
|
* @param middleware - Initial middleware, run in array order (outer-first);
|
|
1635
|
-
* more may be added later
|
|
1818
|
+
* more may be added later by using `use`.
|
|
1636
1819
|
* @param host - The network interface `start()` binds to (`node:http`
|
|
1637
1820
|
* `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
|
|
1638
1821
|
* @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
|
|
1639
|
-
*
|
|
1822
|
+
* ephemeral, OS-assigned free port (the default); `start()` always resolves
|
|
1640
1823
|
* the actually-bound port. A port already in use rejects `start()` with
|
|
1641
1824
|
* `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
|
|
1642
1825
|
* guaranteed-free port up front).
|
|
1643
1826
|
* @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
|
|
1644
|
-
* server stops accepting new connections and gives in-flight requests
|
|
1827
|
+
* server stops accepting new connections and gives in-flight requests and
|
|
1645
1828
|
* claimed upgraded sockets this long to finish before forcing every
|
|
1646
1829
|
* remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
|
|
1647
1830
|
* non-negative finite number. A long-lived upgraded socket that nothing
|
|
@@ -1672,9 +1855,9 @@ export declare interface ServerInterface<TState> {
|
|
|
1672
1855
|
* to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
|
|
1673
1856
|
* `maxRequestsPerSocket` (`0` disables the limit). Every present value must
|
|
1674
1857
|
* be a non-negative integer. Omitted leaves preserve node's defaults.
|
|
1675
|
-
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
|
|
1676
|
-
*
|
|
1677
|
-
* @param error - The emitter's listener-error handler
|
|
1858
|
+
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap},
|
|
1859
|
+
* wiring initial lifecycle listeners at construction.
|
|
1860
|
+
* @param error - The emitter's listener-error handler — a
|
|
1678
1861
|
* listener throw routes here, never to the domain `error` event.
|
|
1679
1862
|
*/
|
|
1680
1863
|
export declare interface ServerOptions<TState> {
|
|
@@ -1686,10 +1869,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1686
1869
|
readonly drain?: number;
|
|
1687
1870
|
readonly limit?: number;
|
|
1688
1871
|
readonly expose?: boolean;
|
|
1689
|
-
readonly report?: (error: unknown, request?:
|
|
1690
|
-
method: string;
|
|
1691
|
-
url: URL;
|
|
1692
|
-
}) => void;
|
|
1872
|
+
readonly report?: (error: unknown, request?: RequestLine) => void;
|
|
1693
1873
|
readonly timeouts?: {
|
|
1694
1874
|
readonly start?: number;
|
|
1695
1875
|
readonly request?: number;
|
|
@@ -1706,7 +1886,7 @@ export declare interface ServerOptions<TState> {
|
|
|
1706
1886
|
}
|
|
1707
1887
|
|
|
1708
1888
|
/**
|
|
1709
|
-
*
|
|
1889
|
+
* Represents the `Server`'s lifecycle state.
|
|
1710
1890
|
*
|
|
1711
1891
|
* @remarks
|
|
1712
1892
|
* `idle` (never started, or a fresh instance) → `starting` (binding the
|
|
@@ -1718,17 +1898,17 @@ export declare interface ServerOptions<TState> {
|
|
|
1718
1898
|
export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
|
|
1719
1899
|
|
|
1720
1900
|
/**
|
|
1721
|
-
*
|
|
1901
|
+
* Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
|
|
1722
1902
|
*
|
|
1723
1903
|
* @remarks
|
|
1724
1904
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
1725
1905
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
1726
1906
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
1727
|
-
* the signature), signed
|
|
1907
|
+
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
|
|
1728
1908
|
* {@link TokenSecret} (the current secret, or the head of a rotation list).
|
|
1729
|
-
* Blank/whitespace-only secrets are
|
|
1730
|
-
* misconfigured secret with no usable entry
|
|
1731
|
-
* (`500`) — fail-closed, a programmer error
|
|
1909
|
+
* Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
|
|
1910
|
+
* misconfigured secret with no usable entry throws an {@link HTTPError}
|
|
1911
|
+
* (`500`) — fail-closed, a programmer error. Verify with
|
|
1732
1912
|
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
1733
1913
|
*
|
|
1734
1914
|
* @param value - The opaque value to embed (a session id, a deployment marker)
|
|
@@ -1745,26 +1925,27 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
|
|
|
1745
1925
|
export declare function signToken(value: string, options: TokenOptions): Promise<string>;
|
|
1746
1926
|
|
|
1747
1927
|
/**
|
|
1748
|
-
*
|
|
1928
|
+
* Holds the SSE response headers a `Stream` sets on its response, merged under any
|
|
1929
|
+
* caller `headers` so a caller repeating one of these keys replaces its value.
|
|
1749
1930
|
*
|
|
1750
1931
|
* @remarks
|
|
1751
1932
|
* `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
|
|
1752
1933
|
* keeps a proxy from caching the stream; `keep-alive` holds the connection
|
|
1753
1934
|
* open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
|
|
1754
1935
|
* events flush promptly rather than batching. Frozen so a consumer can read
|
|
1755
|
-
* but never mutate the shared default;
|
|
1756
|
-
* {@link import('./types.js').StreamOptions.headers}
|
|
1936
|
+
* but never mutate the shared default; the merged keys are
|
|
1937
|
+
* {@link import('./types.js').StreamOptions.headers}.
|
|
1757
1938
|
*/
|
|
1758
1939
|
export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
1759
1940
|
|
|
1760
1941
|
/**
|
|
1761
|
-
*
|
|
1942
|
+
* Represents one Server-Sent Event to serialize to the wire.
|
|
1762
1943
|
*
|
|
1763
1944
|
* @remarks
|
|
1764
1945
|
* - `data` — the event payload (required). Serialized as one or more `data:`
|
|
1765
|
-
* lines: the value is split on `\n` into a `data:` line
|
|
1946
|
+
* lines: the value is split on `\n` into a `data:` line per segment, so it
|
|
1766
1947
|
* round-trips through a consumer's multi-`data` concat.
|
|
1767
|
-
* - `event` — the optional event
|
|
1948
|
+
* - `event` — the optional event type, emitted as an `event:` line; omitted
|
|
1768
1949
|
* ⇒ the consumer's default (`message`).
|
|
1769
1950
|
* - `id` — the optional last-event-id, emitted as an `id:` line.
|
|
1770
1951
|
* - `retry` — the optional reconnection time in milliseconds, emitted as a
|
|
@@ -1772,16 +1953,72 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
|
|
|
1772
1953
|
*/
|
|
1773
1954
|
export declare interface SSEMessage {
|
|
1774
1955
|
readonly data: string;
|
|
1775
|
-
/**
|
|
1956
|
+
/** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
|
|
1776
1957
|
readonly event?: string;
|
|
1777
|
-
/**
|
|
1958
|
+
/** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
|
|
1778
1959
|
readonly id?: string;
|
|
1779
1960
|
readonly retry?: number;
|
|
1780
1961
|
}
|
|
1781
1962
|
|
|
1782
1963
|
/**
|
|
1783
|
-
*
|
|
1784
|
-
* `Response
|
|
1964
|
+
* Represents the Server-Sent-Events handle over an open, fetch-standard streaming
|
|
1965
|
+
* `Response`. Implements exactly {@link StreamInterface}.
|
|
1966
|
+
*
|
|
1967
|
+
* @remarks
|
|
1968
|
+
* Builds the `Response` at construction from
|
|
1969
|
+
* {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
|
|
1970
|
+
* merged over them, at `options.status` (default `200`). A caller repeating one
|
|
1971
|
+
* of those keys therefore replaces the seam's value, in any casing. The
|
|
1972
|
+
* instance owns the stream's
|
|
1973
|
+
* controller, its text encoder, the closed flag, and the parked producer's
|
|
1974
|
+
* wakeup, so the whole handle is one entity rather than a closure over four
|
|
1975
|
+
* bindings.
|
|
1976
|
+
*
|
|
1977
|
+
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1978
|
+
* returns whether the controller still has positive desired size. A producer
|
|
1979
|
+
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
1980
|
+
* consumer pull restoring capacity, or on stream closure. `comment` writes a
|
|
1981
|
+
* `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
|
|
1982
|
+
* stream. Every method is a safe no-op once `closed` (ended by `end()`, or
|
|
1983
|
+
* the consumer cancelled the stream), so a late write never throws.
|
|
1984
|
+
*
|
|
1985
|
+
* The readiness signal reflects only the process-local `ReadableStream`
|
|
1986
|
+
* queue — it is not proof that a remote peer consumed bytes. When the response
|
|
1987
|
+
* pump honors its socket sink's drain state, socket pressure stops body pulls
|
|
1988
|
+
* and therefore keeps this queue full, letting a cooperative producer bound
|
|
1989
|
+
* its buffering. Ignoring the return value preserves an unconditional-enqueue
|
|
1990
|
+
* producer. The default stream strategy counts chunks rather than their byte
|
|
1991
|
+
* length, so a byte-bounded producer must also cap each message. Return
|
|
1992
|
+
* `response` before awaiting a `false` write, because the consumer cannot pull
|
|
1993
|
+
* until it receives the response.
|
|
1994
|
+
*
|
|
1995
|
+
* @example
|
|
1996
|
+
* ```ts
|
|
1997
|
+
* import { Stream } from '@src/server'
|
|
1998
|
+
*
|
|
1999
|
+
* const stream = new Stream()
|
|
2000
|
+
* void Promise.resolve().then(async () => {
|
|
2001
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
2002
|
+
* stream.comment('keep-alive')
|
|
2003
|
+
* stream.end()
|
|
2004
|
+
* })
|
|
2005
|
+
* // return stream.response from the route handler
|
|
2006
|
+
* ```
|
|
2007
|
+
*/
|
|
2008
|
+
export declare class Stream implements StreamInterface {
|
|
2009
|
+
#private;
|
|
2010
|
+
constructor(options?: StreamOptions);
|
|
2011
|
+
get response(): Response;
|
|
2012
|
+
get closed(): boolean;
|
|
2013
|
+
write(message: SSEMessage): boolean;
|
|
2014
|
+
comment(text: string): void;
|
|
2015
|
+
drain(): Promise<void>;
|
|
2016
|
+
end(): void;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/**
|
|
2020
|
+
* Represents a handle to write Server-Sent Events to an open, fetch-standard streaming
|
|
2021
|
+
* `Response` — the generic streaming surface `createStream` returns over a
|
|
1785
2022
|
* `ReadableStream`.
|
|
1786
2023
|
*
|
|
1787
2024
|
* @remarks
|
|
@@ -1793,7 +2030,7 @@ export declare interface SSEMessage {
|
|
|
1793
2030
|
* queue still has capacity; a producer that receives `false` parks on
|
|
1794
2031
|
* `drain()` before writing again. `comment` writes a `: text` keep-alive line
|
|
1795
2032
|
* (ignored by a conforming SSE parser — no spurious event); `end` closes the
|
|
1796
|
-
* stream. Every method is a
|
|
2033
|
+
* stream. Every method is a safe no-op once `closed` is `true`, so a late
|
|
1797
2034
|
* `write` never throws.
|
|
1798
2035
|
*
|
|
1799
2036
|
* The readiness signal is deliberately local: it reflects the
|
|
@@ -1802,34 +2039,39 @@ export declare interface SSEMessage {
|
|
|
1802
2039
|
* the process-local socket sink is backpressured, so a cooperative producer
|
|
1803
2040
|
* can bound its contribution to transport buffering without polling. A caller
|
|
1804
2041
|
* that ignores the boolean keeps the prior unconditional-enqueue behavior.
|
|
1805
|
-
* The stream's default strategy measures queued
|
|
2042
|
+
* The stream's default strategy measures queued chunks, not their byte length,
|
|
1806
2043
|
* so a producer seeking a byte bound must also bound each individual message.
|
|
1807
2044
|
* Return `response` before awaiting a `false` write: the consumer cannot pull
|
|
1808
2045
|
* until it receives the response.
|
|
1809
2046
|
*/
|
|
1810
2047
|
export declare interface StreamInterface {
|
|
1811
|
-
/**
|
|
2048
|
+
/** Holds the streaming `Response` to return from the route handler. */
|
|
1812
2049
|
readonly response: Response;
|
|
1813
|
-
/**
|
|
2050
|
+
/** Reports whether the underlying stream is done (ended, or the consumer disconnected). */
|
|
1814
2051
|
readonly closed: boolean;
|
|
1815
2052
|
/**
|
|
1816
|
-
*
|
|
2053
|
+
* Serializes and enqueues one {@link SSEMessage} to the wire, reporting whether the
|
|
2054
|
+
* process-local queue still has capacity afterward — `false` also once the stream
|
|
2055
|
+
* is closed.
|
|
1817
2056
|
*
|
|
1818
2057
|
* @param message - The event to send (its `data` split on `\n` into `data:` lines)
|
|
1819
|
-
* @returns
|
|
1820
|
-
* accepting the event;
|
|
1821
|
-
* closed. A `false` event was still accepted unless `closed` was already
|
|
2058
|
+
* @returns True if the process-local stream queue has capacity after
|
|
2059
|
+
* accepting the event; false otherwise — the queue is full or the stream
|
|
2060
|
+
* is closed. A `false` event was still accepted unless `closed` was already
|
|
1822
2061
|
* `true`; await {@link drain} before producing another event.
|
|
1823
2062
|
*/
|
|
1824
2063
|
write(message: SSEMessage): boolean;
|
|
1825
2064
|
/**
|
|
1826
|
-
*
|
|
2065
|
+
* Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores,
|
|
2066
|
+
* and a no-op once the stream is closed.
|
|
1827
2067
|
*
|
|
1828
2068
|
* @param text - The comment text (sent after the `: ` prefix)
|
|
1829
2069
|
*/
|
|
1830
2070
|
comment(text: string): void;
|
|
1831
2071
|
/**
|
|
1832
|
-
*
|
|
2072
|
+
* Parks until the process-local stream queue has capacity again — resolving on the
|
|
2073
|
+
* consumer pull that restores it, or immediately when capacity is already available
|
|
2074
|
+
* or the stream is closed, and never polling.
|
|
1833
2075
|
*
|
|
1834
2076
|
* @returns A promise that resolves when a consumer pull restores positive
|
|
1835
2077
|
* desired size, or immediately when capacity is already available or the
|
|
@@ -1837,18 +2079,22 @@ export declare interface StreamInterface {
|
|
|
1837
2079
|
* not prove that a remote peer consumed the queued bytes.
|
|
1838
2080
|
*/
|
|
1839
2081
|
drain(): Promise<void>;
|
|
1840
|
-
/**
|
|
2082
|
+
/**
|
|
2083
|
+
* Ends the stream, completing the response — a no-op once already `closed`, and it
|
|
2084
|
+
* settles any parked producer.
|
|
2085
|
+
*/
|
|
1841
2086
|
end(): void;
|
|
1842
2087
|
}
|
|
1843
2088
|
|
|
1844
2089
|
/**
|
|
1845
|
-
* Options for
|
|
2090
|
+
* Options for a {@link StreamInterface} — how `createStream` opens the
|
|
2091
|
+
* streaming response.
|
|
1846
2092
|
*
|
|
1847
2093
|
* @param status - The HTTP status the streaming response is opened with;
|
|
1848
2094
|
* defaults to `200`.
|
|
1849
|
-
* @param headers - Extra response headers merged
|
|
1850
|
-
* seam always sets ({@link SSE_HEADERS})
|
|
1851
|
-
*
|
|
2095
|
+
* @param headers - Extra response headers merged over the SSE headers the
|
|
2096
|
+
* seam always sets ({@link SSE_HEADERS}); a caller repeating one of those
|
|
2097
|
+
* keys replaces the seam's value, in any casing.
|
|
1852
2098
|
*/
|
|
1853
2099
|
export declare interface StreamOptions {
|
|
1854
2100
|
readonly status?: number;
|
|
@@ -1859,10 +2105,10 @@ export declare interface StreamOptions {
|
|
|
1859
2105
|
* Options for `signToken` — how a stateless, HMAC-signed token is minted.
|
|
1860
2106
|
*
|
|
1861
2107
|
* @param secret - The {@link TokenSecret} to sign with; `signToken` always
|
|
1862
|
-
* uses the
|
|
2108
|
+
* uses the first secret (a single string, or the current head of a
|
|
1863
2109
|
* rotation list). An empty rotation list is a misconfiguration and throws.
|
|
1864
2110
|
* @param ttl - An optional lifetime in milliseconds. When set, the expiry
|
|
1865
|
-
* timestamp is bound
|
|
2111
|
+
* timestamp is bound into the signed payload (HMAC-covered, tamper-proof);
|
|
1866
2112
|
* `verifyToken` rejects the token once that instant has passed. Omitted ⇒
|
|
1867
2113
|
* the token never expires.
|
|
1868
2114
|
*/
|
|
@@ -1872,21 +2118,21 @@ export declare interface TokenOptions {
|
|
|
1872
2118
|
}
|
|
1873
2119
|
|
|
1874
2120
|
/**
|
|
1875
|
-
*
|
|
1876
|
-
* token.
|
|
2121
|
+
* Represents a secret, or a `[current, ...older]` rotation list, for signing and
|
|
2122
|
+
* verifying a stateless, HMAC-signed token.
|
|
1877
2123
|
*
|
|
1878
2124
|
* @remarks
|
|
1879
2125
|
* A single `string` is the lone secret. A `readonly string[]` is a rotation
|
|
1880
2126
|
* list in `[current, ...older]` order: `signToken` always signs with the
|
|
1881
|
-
*
|
|
1882
|
-
* secret in the list — so a key rotates by prepending the
|
|
2127
|
+
* first (current) secret, while `verifyToken` accepts a token signed by any
|
|
2128
|
+
* secret in the list — so a key rotates by prepending the fresh one and keeping
|
|
1883
2129
|
* the old until every outstanding token has expired, with zero downtime.
|
|
1884
2130
|
*/
|
|
1885
2131
|
export declare type TokenSecret = string | readonly string[];
|
|
1886
2132
|
|
|
1887
2133
|
/**
|
|
1888
|
-
*
|
|
1889
|
-
* comparison body — the reduction {@link matchesETag} applies to
|
|
2134
|
+
* Strips the weak indicator (`W/`) from an entity-tag, returning its opaque
|
|
2135
|
+
* comparison body — the reduction {@link matchesETag} applies to each side
|
|
1890
2136
|
* before the RFC 7232 §2.3.2 weak comparison.
|
|
1891
2137
|
*
|
|
1892
2138
|
* @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
|
|
@@ -1900,19 +2146,19 @@ export declare type TokenSecret = string | readonly string[];
|
|
|
1900
2146
|
export declare function unwrapETag(tag: string): string;
|
|
1901
2147
|
|
|
1902
2148
|
/**
|
|
1903
|
-
*
|
|
2149
|
+
* Represents a raw `node:http` protocol-upgrade claimant — registered through
|
|
1904
2150
|
* {@link ServerInterface.upgrade}.
|
|
1905
2151
|
*
|
|
1906
2152
|
* @remarks
|
|
1907
|
-
* Fan-out semantics
|
|
1908
|
-
* order, the
|
|
1909
|
-
* fan-out; a handler that
|
|
1910
|
-
* on the `error` event) and the fan-out continues; if
|
|
2153
|
+
* Fan-out semantics: handlers run in registration
|
|
2154
|
+
* order, the first to return `true` claims (owns) the socket and stops the
|
|
2155
|
+
* fan-out; a handler that throws is treated as declined (the throw surfaces
|
|
2156
|
+
* on the `error` event) and the fan-out continues; if none claim it, the
|
|
1911
2157
|
* socket is destroyed so an unhandled upgrade never leaks a dangling
|
|
1912
2158
|
* connection. `request` / `socket` / `head` are node's own raw values, handed
|
|
1913
|
-
* over verbatim — no assertion at this boundary
|
|
2159
|
+
* over verbatim — no assertion at this boundary.
|
|
1914
2160
|
*
|
|
1915
|
-
* A
|
|
2161
|
+
* A claimed socket is tracked until it closes. The handler still owns it —
|
|
1916
2162
|
* the server only watches — but `stop()` now drains that socket like an
|
|
1917
2163
|
* in-flight request and destroys it if the `drain` deadline expires first.
|
|
1918
2164
|
* Node detaches an upgraded socket from its own connection set, so neither
|
|
@@ -1925,25 +2171,25 @@ export declare function unwrapETag(tag: string): string;
|
|
|
1925
2171
|
* @param request - The raw `node:http` upgrade request
|
|
1926
2172
|
* @param socket - The raw, now-detached `Duplex` connection
|
|
1927
2173
|
* @param head - The first packet of the upgraded stream, if any
|
|
1928
|
-
* @returns
|
|
1929
|
-
*
|
|
2174
|
+
* @returns True if the handler claims the socket (this handler now owns
|
|
2175
|
+
* it); false otherwise, declining so a later handler can try
|
|
1930
2176
|
*/
|
|
1931
2177
|
export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
1932
2178
|
|
|
1933
2179
|
/**
|
|
1934
|
-
*
|
|
2180
|
+
* Verifies a stateless token and returns its embedded value — total, never throws.
|
|
1935
2181
|
*
|
|
1936
2182
|
* @remarks
|
|
1937
|
-
* The inverse of {@link signToken}: splits the token on its
|
|
2183
|
+
* The inverse of {@link signToken}: splits the token on its last `.` (so a
|
|
1938
2184
|
* value containing dots survives), decodes the signature with
|
|
1939
2185
|
* `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
|
|
1940
2186
|
* base64url is refused there, before any key import — and checks the payload's
|
|
1941
|
-
* HMAC-SHA256 signature against
|
|
2187
|
+
* HMAC-SHA256 signature against each {@link TokenSecret} candidate through
|
|
1942
2188
|
* `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
|
|
1943
|
-
* retired
|
|
2189
|
+
* retired), accepting the token on the first match (the
|
|
1944
2190
|
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
1945
|
-
* `typeof`, never `as`
|
|
1946
|
-
*
|
|
2191
|
+
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
2192
|
+
* token. Any failure — a malformed token, a bad signature,
|
|
1947
2193
|
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
1948
2194
|
* yields `undefined` rather than throwing.
|
|
1949
2195
|
*
|
|
@@ -1959,7 +2205,8 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
|
|
|
1959
2205
|
export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
|
|
1960
2206
|
|
|
1961
2207
|
/**
|
|
1962
|
-
*
|
|
2208
|
+
* Wraps one middleware layer around its downstream handler, enforcing the one-call
|
|
2209
|
+
* `next` invariant.
|
|
1963
2210
|
*
|
|
1964
2211
|
* @remarks
|
|
1965
2212
|
* The returned handler enforces the one-call `next` invariant while preserving
|
|
@@ -1981,15 +2228,15 @@ export declare function verifyToken(token: string, secret: TokenSecret): Promise
|
|
|
1981
2228
|
export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
|
|
1982
2229
|
|
|
1983
2230
|
/**
|
|
1984
|
-
*
|
|
1985
|
-
* it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
2231
|
+
* Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
|
|
2232
|
+
* appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
1986
2233
|
*
|
|
1987
2234
|
* @remarks
|
|
1988
2235
|
* The cookie value is `await signToken(value, { secret })`
|
|
1989
2236
|
* (`<payload>.<signature>`), so a signed cookie is a stateless token in a
|
|
1990
2237
|
* cookie — the same secret rotation and tamper rejection, no second HMAC
|
|
1991
|
-
* scheme. Appends (never clobbers)
|
|
1992
|
-
*
|
|
2238
|
+
* scheme. Appends (never clobbers) through `Headers.append`, which accumulates
|
|
2239
|
+
* repeated headers. Async — WebCrypto signing is asynchronous.
|
|
1993
2240
|
*
|
|
1994
2241
|
* @param headers - The response `Headers` to write into
|
|
1995
2242
|
* @param name - The cookie name
|