@orkestrel/server 0.0.18 → 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 +11 -7
- package/dist/src/server/index.cjs +193 -161
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +280 -230
- package/dist/src/server/index.d.ts +280 -230
- package/dist/src/server/index.js +193 -161
- package/dist/src/server/index.js.map +1 -1
- package/package.json +18 -19
package/dist/src/server/index.js
CHANGED
|
@@ -9,36 +9,40 @@ import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router
|
|
|
9
9
|
import { Emitter } from "@orkestrel/emitter";
|
|
10
10
|
//#region src/server/constants.ts
|
|
11
11
|
/**
|
|
12
|
-
* Names the default graceful-stop deadline (
|
|
13
|
-
*
|
|
12
|
+
* Names the default graceful-stop deadline `stop()` gives in-flight requests and
|
|
13
|
+
* claimed upgraded sockets, `10_000` ms.
|
|
14
14
|
*/
|
|
15
15
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
16
16
|
/**
|
|
17
|
-
* Names the `Symbol.for`-
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* `instanceof` alone fails because the two copies' `HTTPError` constructors
|
|
21
|
-
* are distinct objects.
|
|
17
|
+
* Names the `Symbol.for`-interned brand `HTTPError` carries,
|
|
18
|
+
* `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
|
|
19
|
+
* package copies. A consumer never sets it by hand.
|
|
22
20
|
*
|
|
23
21
|
* @remarks
|
|
24
|
-
*
|
|
25
|
-
*
|
|
22
|
+
* The brand exists for the dual-package hazard — a version-skewed or
|
|
23
|
+
* workspace-linked duplicate install — where `instanceof` alone fails because
|
|
24
|
+
* each copy's `HTTPError` constructor is a distinct object.
|
|
25
|
+
* `Symbol.for` interns the symbol on the global symbol registry, so every
|
|
26
|
+
* copy of this package that evaluates this key resolves the same symbol
|
|
26
27
|
* instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
|
|
27
28
|
* unequal symbol per copy and defeat the whole point of a cross-copy brand.
|
|
28
29
|
*/
|
|
29
30
|
var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
|
|
30
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* Names the default maximum request body size `readBody` accepts before a 413,
|
|
33
|
+
* `1_048_576` bytes.
|
|
34
|
+
*/
|
|
31
35
|
var DEFAULT_BODY_LIMIT = 1048576;
|
|
32
36
|
/**
|
|
33
|
-
* Names the default maximum
|
|
34
|
-
* the body pipeline's byte-counting `TransformStream` enforces when
|
|
35
|
-
* transparently
|
|
37
|
+
* Names the default maximum decompressed request body size, `16_777_216` bytes — the
|
|
38
|
+
* zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when
|
|
39
|
+
* it transparently decompresses a `Content-Encoding` request body.
|
|
36
40
|
*
|
|
37
41
|
* @remarks
|
|
38
42
|
* A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
|
|
39
43
|
* can inflate by many orders of magnitude — a classic decompression bomb.
|
|
40
|
-
* Capping the decompressed byte count makes the pipe
|
|
41
|
-
* output would exceed this,
|
|
44
|
+
* Capping the decompressed byte count makes the pipe abort the moment the
|
|
45
|
+
* output would exceed this, before the full bomb is materialized, so the
|
|
42
46
|
* inflation can never exhaust memory. Defaults to `16 MiB` — a generous
|
|
43
47
|
* ceiling for a legitimate compressed JSON / form body, far below an OOM. A
|
|
44
48
|
* consumer raises it through {@link import('./types.js').BodyOptions}
|
|
@@ -47,16 +51,16 @@ var DEFAULT_BODY_LIMIT = 1048576;
|
|
|
47
51
|
*/
|
|
48
52
|
var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
|
|
49
53
|
/**
|
|
50
|
-
* Holds the SSE response headers a `Stream`
|
|
54
|
+
* Holds the SSE response headers a `Stream` sets on its response, merged under any
|
|
55
|
+
* caller `headers` so a caller repeating one of these keys replaces its value.
|
|
51
56
|
*
|
|
52
57
|
* @remarks
|
|
53
58
|
* `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
|
|
54
59
|
* keeps a proxy from caching the stream; `keep-alive` holds the connection
|
|
55
60
|
* open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
|
|
56
61
|
* events flush promptly rather than batching. Frozen so a consumer can read
|
|
57
|
-
* but never mutate the shared default;
|
|
58
|
-
* {@link import('./types.js').StreamOptions.headers}
|
|
59
|
-
* repeating one of these keys replaces its value.
|
|
62
|
+
* but never mutate the shared default; the merged keys are
|
|
63
|
+
* {@link import('./types.js').StreamOptions.headers}.
|
|
60
64
|
*/
|
|
61
65
|
var SSE_HEADERS = Object.freeze({
|
|
62
66
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
@@ -66,20 +70,24 @@ var SSE_HEADERS = Object.freeze({
|
|
|
66
70
|
});
|
|
67
71
|
/**
|
|
68
72
|
* Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
|
|
69
|
-
* to match
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
+
* to match, `^[A-Za-z0-9_-]{1,200}$`.
|
|
74
|
+
*
|
|
75
|
+
* @remarks
|
|
76
|
+
* An incoming id carrying CRLF, a log-injection payload, a control character,
|
|
77
|
+
* or more characters than the pattern admits fails the match and is rejected —
|
|
78
|
+
* a fresh id is minted instead — so it never rides into a response header or
|
|
79
|
+
* `context.state`. Frozen so a consumer can read but never mutate the shared
|
|
80
|
+
* default.
|
|
73
81
|
*/
|
|
74
82
|
var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
|
|
75
83
|
/**
|
|
76
|
-
* Holds the
|
|
77
|
-
*
|
|
78
|
-
*
|
|
84
|
+
* Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
|
|
85
|
+
* beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
|
|
86
|
+
* helper also applies.
|
|
79
87
|
*
|
|
80
88
|
* @remarks
|
|
81
89
|
* The text-shaped application types worth compressing (JSON / JavaScript /
|
|
82
|
-
* XML / SVG / WASM / a few document formats) —
|
|
90
|
+
* XML / SVG / WASM / a few document formats) — never already-compressed
|
|
83
91
|
* binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
|
|
84
92
|
* `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
|
|
85
93
|
* withholds `add` / `delete` / `clear` from the shared default, so a consumer
|
|
@@ -101,10 +109,10 @@ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
|
|
|
101
109
|
]));
|
|
102
110
|
/**
|
|
103
111
|
* Lists the default {@link Encoding} content-codings the substrate offers, in
|
|
104
|
-
*
|
|
112
|
+
* preference order — `gzip` then `deflate`.
|
|
105
113
|
*
|
|
106
114
|
* @remarks
|
|
107
|
-
* `identity` (no compression) is always implicitly acceptable and is
|
|
115
|
+
* `identity` (no compression) is always implicitly acceptable and is not
|
|
108
116
|
* listed here — it is the fall-through when a client accepts none of these.
|
|
109
117
|
* Brotli is omitted per the core's `CompressionStream`-only decision (see
|
|
110
118
|
* {@link Encoding}). Frozen so a consumer can read but never mutate the
|
|
@@ -121,7 +129,7 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
|
|
|
121
129
|
* Carries the HTTP `status` to send and an optional `context` record (the
|
|
122
130
|
* offending field / value). The server's built-in error boundary catches it
|
|
123
131
|
* and renders a response of `status` with the error's `message` as the body
|
|
124
|
-
* — so an `HTTPError`'s message is
|
|
132
|
+
* — so an `HTTPError`'s message is always client-facing (it is the handler's
|
|
125
133
|
* deliberate signal), unlike a generic throw whose message is hidden unless
|
|
126
134
|
* `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
|
|
127
135
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
@@ -178,21 +186,22 @@ var ContentTooLargeError = class extends HTTPError {
|
|
|
178
186
|
}
|
|
179
187
|
};
|
|
180
188
|
/**
|
|
181
|
-
* Narrows an unknown caught value to an {@link HTTPError}
|
|
182
|
-
*
|
|
189
|
+
* Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
|
|
190
|
+
* as {@link ContentTooLargeError}, and recognizes an instance from another copy of
|
|
191
|
+
* this package through a structural brand fallback.
|
|
183
192
|
*
|
|
184
193
|
* @param value - The value to test (typically a `catch` binding)
|
|
185
194
|
* @returns True if `value` is an {@link HTTPError}; false otherwise
|
|
186
195
|
*
|
|
187
196
|
* @remarks
|
|
188
197
|
* Tries `instanceof` first, then falls back to a total structural check for
|
|
189
|
-
* an instance built by a
|
|
198
|
+
* an instance built by a different copy of this package (the dual-package
|
|
190
199
|
* hazard — version skew, a linked workspace duplicate) whose `HTTPError`
|
|
191
200
|
* constructor is a distinct object from this copy's: the value must carry
|
|
192
201
|
* the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
|
|
193
|
-
* same key)
|
|
202
|
+
* same key) and expose the exact fields the server's error boundary reads off
|
|
194
203
|
* a recognized `HTTPError` — a numeric `status` and a string `message`. A
|
|
195
|
-
* plain object that merely carries a `status`
|
|
204
|
+
* plain object that merely carries a `status` without the brand is rejected.
|
|
196
205
|
*
|
|
197
206
|
* @example
|
|
198
207
|
* ```ts
|
|
@@ -214,11 +223,11 @@ function isHTTPError(value) {
|
|
|
214
223
|
}
|
|
215
224
|
/**
|
|
216
225
|
* Represents the error this package raises when a caller programmed a call the
|
|
217
|
-
* entity refuses.
|
|
226
|
+
* entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
|
|
218
227
|
*
|
|
219
228
|
* @remarks
|
|
220
229
|
* Carries a machine-readable {@link ServerErrorCode} and an optional `context`
|
|
221
|
-
* record naming the offending facts. This is a
|
|
230
|
+
* record naming the offending facts. This is a programmer error, so it carries
|
|
222
231
|
* no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
|
|
223
232
|
* invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
|
|
224
233
|
* middleware into the request boundary, which reaches it as a generic 500 with
|
|
@@ -247,14 +256,15 @@ var ServerError = class extends Error {
|
|
|
247
256
|
}
|
|
248
257
|
};
|
|
249
258
|
/**
|
|
250
|
-
* Narrows an unknown caught value to a {@link ServerError}
|
|
259
|
+
* Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
|
|
260
|
+
* of a call the caller programmed.
|
|
251
261
|
*
|
|
252
262
|
* @param value - The value to test (typically a `catch` binding)
|
|
253
263
|
* @returns True if `value` is a {@link ServerError}; false otherwise
|
|
254
264
|
*
|
|
255
265
|
* @remarks
|
|
256
|
-
* Recognizes an instance built by
|
|
257
|
-
* is raised by a `Server` to the caller that
|
|
266
|
+
* Recognizes an instance built by this copy of the package. A `ServerError`
|
|
267
|
+
* is raised by a `Server` to the caller that invoked it directly, so both sides
|
|
258
268
|
* hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
|
|
259
269
|
* consumer here.
|
|
260
270
|
*
|
|
@@ -305,18 +315,18 @@ function isAddressInfo(value) {
|
|
|
305
315
|
//#endregion
|
|
306
316
|
//#region src/server/helpers.ts
|
|
307
317
|
/**
|
|
308
|
-
* Composes an ordered chain of {@link MiddlewareHandler}
|
|
318
|
+
* Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
|
|
309
319
|
* handler into one request handler — the frozen middleware seam.
|
|
310
320
|
*
|
|
311
321
|
* @remarks
|
|
312
|
-
* `middleware[0]` runs
|
|
313
|
-
* runs `middleware[1]`, and so on until the
|
|
322
|
+
* `middleware[0]` runs outermost: it is invoked first, and its call to `next`
|
|
323
|
+
* runs `middleware[1]`, and so on until the last middleware's `next` invokes
|
|
314
324
|
* `terminal`. Each middleware's `next` may be called with a substituted
|
|
315
325
|
* `Request` (the downstream chain then sees that request instead of the
|
|
316
326
|
* original), called with no argument (the original request continues
|
|
317
|
-
* downstream), or
|
|
327
|
+
* downstream), or not called at all (a short-circuit — the middleware's own
|
|
318
328
|
* returned `Response` is sent, and everything downstream never runs). A
|
|
319
|
-
*
|
|
329
|
+
* second call to the same `next` within one middleware invocation rejects —
|
|
320
330
|
* each link runs the chain at most once, so a middleware cannot fork the
|
|
321
331
|
* request into two divergent downstream runs.
|
|
322
332
|
*
|
|
@@ -340,7 +350,8 @@ function compose(middleware, terminal) {
|
|
|
340
350
|
return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
|
|
341
351
|
}
|
|
342
352
|
/**
|
|
343
|
-
* Wraps one middleware layer around its downstream handler
|
|
353
|
+
* Wraps one middleware layer around its downstream handler, enforcing the one-call
|
|
354
|
+
* `next` invariant.
|
|
344
355
|
*
|
|
345
356
|
* @remarks
|
|
346
357
|
* The returned handler enforces the one-call `next` invariant while preserving
|
|
@@ -373,13 +384,13 @@ function wrapMiddleware(layer, next) {
|
|
|
373
384
|
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
374
385
|
*
|
|
375
386
|
* @remarks
|
|
376
|
-
* Splits on `;`; the
|
|
387
|
+
* Splits on `;`; the first segment keeps any leading whitespace (a genuine
|
|
377
388
|
* cookie-pair separator never precedes it), while every later segment has its
|
|
378
389
|
* inter-pair separator (ASCII space/tab) stripped before parsing — so a
|
|
379
|
-
* whitespace-
|
|
390
|
+
* whitespace-padded name (`' __Host-x=evil'`) is rejected by
|
|
380
391
|
* {@link isCookieName} rather than silently reconciling into a
|
|
381
392
|
* prefix-protected `__Host-` name. A pair without `=`, or with an invalid
|
|
382
|
-
* name, is skipped; a later duplicate name wins.
|
|
393
|
+
* name, is skipped; a later duplicate name wins. Total — an absent/empty/
|
|
383
394
|
* malformed header yields an empty record, never throws.
|
|
384
395
|
*
|
|
385
396
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
@@ -406,8 +417,8 @@ function parseCookies(header) {
|
|
|
406
417
|
return out;
|
|
407
418
|
}
|
|
408
419
|
/**
|
|
409
|
-
* Checks whether a string is a valid RFC 6265 cookie
|
|
410
|
-
* cookie-token
|
|
420
|
+
* Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
|
|
421
|
+
* cookie-token characters with no surrounding or interior whitespace.
|
|
411
422
|
*
|
|
412
423
|
* @remarks
|
|
413
424
|
* A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
|
|
@@ -448,9 +459,9 @@ function decodeCookieValue(raw) {
|
|
|
448
459
|
}
|
|
449
460
|
}
|
|
450
461
|
/**
|
|
451
|
-
* Checks whether a string is safe to interpolate as a `Set-Cookie` attribute
|
|
452
|
-
*
|
|
453
|
-
*
|
|
462
|
+
* Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —
|
|
463
|
+
* the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it
|
|
464
|
+
* emits them.
|
|
454
465
|
*
|
|
455
466
|
* @remarks
|
|
456
467
|
* Rejects a value carrying a `;` (splits attributes), a `,` (can split a
|
|
@@ -482,11 +493,11 @@ function isCookieAttribute(value) {
|
|
|
482
493
|
* URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
|
|
483
494
|
* appends the present {@link CookieOptions} attributes in canonical order:
|
|
484
495
|
* `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
|
|
485
|
-
* (default
|
|
486
|
-
* with {@link isCookieAttribute} and
|
|
487
|
-
* injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is
|
|
496
|
+
* (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated
|
|
497
|
+
* with {@link isCookieAttribute} and throw an {@link HTTPError} on an
|
|
498
|
+
* injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of
|
|
488
499
|
* the `secure` option (the spec requires it); an un-resolved `undefined`
|
|
489
|
-
* `secure` here falls to
|
|
500
|
+
* `secure` here falls to off — request-aware callers resolve it first through
|
|
490
501
|
* {@link resolveSecure}.
|
|
491
502
|
*
|
|
492
503
|
* @param name - The cookie name
|
|
@@ -545,7 +556,7 @@ function resolveSecure(secure, encrypted) {
|
|
|
545
556
|
return encrypted;
|
|
546
557
|
}
|
|
547
558
|
/**
|
|
548
|
-
* Writes a
|
|
559
|
+
* Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
|
|
549
560
|
* appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
550
561
|
*
|
|
551
562
|
* @remarks
|
|
@@ -571,13 +582,13 @@ async function writeSignedCookie(headers, name, value, secret, options) {
|
|
|
571
582
|
headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
|
|
572
583
|
}
|
|
573
584
|
/**
|
|
574
|
-
* Reads
|
|
585
|
+
* Reads and verifies a signed cookie off a request — total, returning the
|
|
575
586
|
* embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
576
587
|
*
|
|
577
588
|
* @remarks
|
|
578
589
|
* Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
|
|
579
590
|
* and verifies it with {@link verifyToken} against `secret` (a rotation list
|
|
580
|
-
* accepts a cookie signed by any of its secrets).
|
|
591
|
+
* accepts a cookie signed by any of its secrets). Any failure — an absent
|
|
581
592
|
* cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
|
|
582
593
|
*
|
|
583
594
|
* @param request - The `Request` to read the `Cookie` header from
|
|
@@ -600,7 +611,7 @@ async function readSignedCookie(request, name, secret) {
|
|
|
600
611
|
* @remarks
|
|
601
612
|
* Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
|
|
602
613
|
* same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
|
|
603
|
-
* a cookie when those
|
|
614
|
+
* a cookie when those match the one it set).
|
|
604
615
|
*
|
|
605
616
|
* @param headers - The response `Headers` to write into
|
|
606
617
|
* @param name - The cookie name to clear
|
|
@@ -625,10 +636,10 @@ function clearCookie(headers, name, options) {
|
|
|
625
636
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
626
637
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
627
638
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
628
|
-
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the
|
|
639
|
+
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
|
|
629
640
|
* {@link TokenSecret} (the current secret, or the head of a rotation list).
|
|
630
|
-
* Blank/whitespace-only secrets are
|
|
631
|
-
* misconfigured secret with no usable entry
|
|
641
|
+
* Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
|
|
642
|
+
* misconfigured secret with no usable entry throws an {@link HTTPError}
|
|
632
643
|
* (`500`) — fail-closed, a programmer error. Verify with
|
|
633
644
|
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
634
645
|
*
|
|
@@ -659,19 +670,19 @@ async function signToken(value, options) {
|
|
|
659
670
|
return `${encoded}.${encodeBase64URL(new Uint8Array(signature))}`;
|
|
660
671
|
}
|
|
661
672
|
/**
|
|
662
|
-
* Verifies a stateless token and returns its embedded value —
|
|
673
|
+
* Verifies a stateless token and returns its embedded value — total, never throws.
|
|
663
674
|
*
|
|
664
675
|
* @remarks
|
|
665
|
-
* The inverse of {@link signToken}: splits the token on its
|
|
676
|
+
* The inverse of {@link signToken}: splits the token on its last `.` (so a
|
|
666
677
|
* value containing dots survives), decodes the signature with
|
|
667
678
|
* `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
|
|
668
679
|
* base64url is refused there, before any key import — and checks the payload's
|
|
669
|
-
* HMAC-SHA256 signature against
|
|
680
|
+
* HMAC-SHA256 signature against each {@link TokenSecret} candidate through
|
|
670
681
|
* `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
|
|
671
682
|
* retired), accepting the token on the first match (the
|
|
672
683
|
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
673
684
|
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
674
|
-
* token.
|
|
685
|
+
* token. Any failure — a malformed token, a bad signature,
|
|
675
686
|
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
676
687
|
* yields `undefined` rather than throwing.
|
|
677
688
|
*
|
|
@@ -707,7 +718,7 @@ async function verifyToken(token, secret) {
|
|
|
707
718
|
}
|
|
708
719
|
}
|
|
709
720
|
/**
|
|
710
|
-
* Decodes
|
|
721
|
+
* Decodes and narrows a signed token's base64url JSON payload, honoring its
|
|
711
722
|
* expiry — the shared decode step {@link verifyToken} applies after a
|
|
712
723
|
* signature match.
|
|
713
724
|
*
|
|
@@ -715,7 +726,7 @@ async function verifyToken(token, secret) {
|
|
|
715
726
|
* Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
|
|
716
727
|
* non-canonical base64url segment answers `undefined` rather than throwing),
|
|
717
728
|
* reads it as UTF-8 JSON, narrows it to a record with a string `value` without
|
|
718
|
-
* `as`, and rejects an expired `exp`.
|
|
729
|
+
* `as`, and rejects an expired `exp`. Total — any
|
|
719
730
|
* decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
|
|
720
731
|
* throws, and its `catch` answers `undefined` too.
|
|
721
732
|
*
|
|
@@ -737,13 +748,13 @@ function decodeTokenPayload(encoded) {
|
|
|
737
748
|
}
|
|
738
749
|
}
|
|
739
750
|
/**
|
|
740
|
-
* Normalizes a {@link TokenSecret} to a concrete list of
|
|
741
|
-
*
|
|
751
|
+
* Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
|
|
752
|
+
* behind both {@link signToken} and {@link verifyToken}.
|
|
742
753
|
*
|
|
743
754
|
* @remarks
|
|
744
755
|
* A single string becomes a one-element list; a rotation list is copied. Any
|
|
745
|
-
* blank/whitespace-only entry is
|
|
746
|
-
* emptiness test; each kept secret is stored
|
|
756
|
+
* blank/whitespace-only entry is dropped (`.trim()` is used only for that
|
|
757
|
+
* emptiness test; each kept secret is stored verbatim). The first kept
|
|
747
758
|
* element is the signing secret; all kept are accepted on verify.
|
|
748
759
|
*
|
|
749
760
|
* @param secret - The {@link TokenSecret} (a single string, or a rotation list)
|
|
@@ -765,10 +776,10 @@ function normalizeSecret(secret) {
|
|
|
765
776
|
* Splits on `,`; for each part takes the token before the first `;`
|
|
766
777
|
* (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
|
|
767
778
|
* quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
|
|
768
|
-
* back to `1`). A `;q=0` entry is
|
|
769
|
-
* honor). The result is sorted by `q`
|
|
779
|
+
* back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must
|
|
780
|
+
* honor). The result is sorted by `q` descending, a stable sort preserving
|
|
770
781
|
* the header's own order within a tie — a single pass with no backtracking,
|
|
771
|
-
* so parsing stays linear in the header length (ReDoS-safe).
|
|
782
|
+
* so parsing stays linear in the header length (ReDoS-safe). Total — an
|
|
772
783
|
* empty/malformed header yields `[]`/best-effort entries, never throws.
|
|
773
784
|
*
|
|
774
785
|
* @param header - The raw weighted header value
|
|
@@ -812,7 +823,7 @@ function parseAcceptHeader(header) {
|
|
|
812
823
|
* each offered coding.
|
|
813
824
|
*
|
|
814
825
|
* @remarks
|
|
815
|
-
* Prefers an
|
|
826
|
+
* Prefers an exact named match (including an explicit `;q=0` rejection);
|
|
816
827
|
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
817
828
|
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
818
829
|
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
@@ -834,7 +845,8 @@ function computeCodingQuality(entries, coding) {
|
|
|
834
845
|
}
|
|
835
846
|
/**
|
|
836
847
|
* Picks the highest-scoring content-coding the server offers against already
|
|
837
|
-
* parsed `Accept-Encoding` entries
|
|
848
|
+
* parsed `Accept-Encoding` entries — the shared selection leaf behind
|
|
849
|
+
* {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
|
|
838
850
|
*
|
|
839
851
|
* @remarks
|
|
840
852
|
* The single selection leaf behind both doors onto this axis —
|
|
@@ -842,9 +854,9 @@ function computeCodingQuality(entries, coding) {
|
|
|
842
854
|
* entity — so the scoring loop has one implementation. Scores each `available`
|
|
843
855
|
* coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
|
|
844
856
|
* keeps the earlier-offered coding on a client-side tie, which is what makes
|
|
845
|
-
* `available` the
|
|
857
|
+
* `available` the server's preference order. An empty `available` list, and a
|
|
846
858
|
* list the client rejects outright, both yield `undefined` (identity — no
|
|
847
|
-
* compression).
|
|
859
|
+
* compression). Total on hostile input.
|
|
848
860
|
*
|
|
849
861
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
850
862
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
@@ -877,7 +889,7 @@ function resolveCoding(entries, available) {
|
|
|
877
889
|
* Parses the header ({@link parseAcceptHeader}) and hands the entries to
|
|
878
890
|
* {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
|
|
879
891
|
* the two doors onto this axis cannot drift. Returns `undefined` when the
|
|
880
|
-
* client accepts none of `available` (identity — no compression).
|
|
892
|
+
* client accepts none of `available` (identity — no compression). Total on
|
|
881
893
|
* hostile input.
|
|
882
894
|
*
|
|
883
895
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
@@ -895,7 +907,7 @@ function negotiateEncoding(header, available) {
|
|
|
895
907
|
return resolveCoding(parseAcceptHeader(header), available);
|
|
896
908
|
}
|
|
897
909
|
/**
|
|
898
|
-
* Reports the rank
|
|
910
|
+
* Reports the rank and quality of one `candidate` media type against the parsed `Accept`
|
|
899
911
|
* entries — the generic media-type primitive the `Negotiator`'s `negotiate`
|
|
900
912
|
* uses to score each `available` candidate.
|
|
901
913
|
*
|
|
@@ -909,7 +921,7 @@ function negotiateEncoding(header, available) {
|
|
|
909
921
|
* rank tie the highest `q` wins.
|
|
910
922
|
*
|
|
911
923
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
912
|
-
* @param candidate - The candidate media type to score (
|
|
924
|
+
* @param candidate - The candidate media type to score (for example `'text/html'`)
|
|
913
925
|
* @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
|
|
914
926
|
*
|
|
915
927
|
* @example
|
|
@@ -952,7 +964,7 @@ function matchMediaType(entries, candidate) {
|
|
|
952
964
|
* is an explicit rejection).
|
|
953
965
|
*
|
|
954
966
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
955
|
-
* @param candidate - The candidate language tag to score (
|
|
967
|
+
* @param candidate - The candidate language tag to score (for example `'en-US'`)
|
|
956
968
|
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
957
969
|
*
|
|
958
970
|
* @example
|
|
@@ -986,8 +998,8 @@ function computeLanguageQuality(entries, candidate) {
|
|
|
986
998
|
* Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
|
|
987
999
|
* type, a `+json`/`+xml` structured suffix, or one of the explicit
|
|
988
1000
|
* {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
|
|
989
|
-
* binary (`image/png`, `application/zip`) is
|
|
990
|
-
* absent/empty type is not compressible.
|
|
1001
|
+
* binary (`image/png`, `application/zip`) is not compressible. An
|
|
1002
|
+
* absent/empty type is not compressible. Total.
|
|
991
1003
|
*
|
|
992
1004
|
* @param type - The response `Content-Type` header value (with or without parameters)
|
|
993
1005
|
* @returns True if the type is text-shaped and worth compressing; false otherwise
|
|
@@ -1007,13 +1019,13 @@ function isCompressibleType(type) {
|
|
|
1007
1019
|
return COMPRESSIBLE_TYPES.has(bare);
|
|
1008
1020
|
}
|
|
1009
1021
|
/**
|
|
1010
|
-
* Computes a
|
|
1022
|
+
* Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
|
|
1011
1023
|
*
|
|
1012
1024
|
* @remarks
|
|
1013
1025
|
* Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
|
|
1014
|
-
* digest as a
|
|
1015
|
-
* default, encoding-
|
|
1016
|
-
* re-encoding (gzip) and still matches on revalidation — or a
|
|
1026
|
+
* digest as a weak validator (`W/"<hash>"`) when `weak` is `true` — the
|
|
1027
|
+
* default, encoding-agnostic, so the tag survives a downstream content
|
|
1028
|
+
* re-encoding (gzip) and still matches on revalidation — or a strong one
|
|
1017
1029
|
* (`"<hash>"`, byte-identity) when `weak` is `false`.
|
|
1018
1030
|
*
|
|
1019
1031
|
* @param body - The full (uncompressed) response body to hash
|
|
@@ -1032,8 +1044,8 @@ async function computeBodyETag(body, weak = true) {
|
|
|
1032
1044
|
return weak ? `W/"${hex}"` : `"${hex}"`;
|
|
1033
1045
|
}
|
|
1034
1046
|
/**
|
|
1035
|
-
* Strips the
|
|
1036
|
-
* comparison body — the reduction {@link matchesETag} applies to
|
|
1047
|
+
* Strips the weak indicator (`W/`) from an entity-tag, returning its opaque
|
|
1048
|
+
* comparison body — the reduction {@link matchesETag} applies to each side
|
|
1037
1049
|
* before the RFC 7232 §2.3.2 weak comparison.
|
|
1038
1050
|
*
|
|
1039
1051
|
* @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
|
|
@@ -1050,14 +1062,14 @@ function unwrapETag(tag) {
|
|
|
1050
1062
|
}
|
|
1051
1063
|
/**
|
|
1052
1064
|
* Checks whether a request's `If-None-Match` header matches a resource's current
|
|
1053
|
-
* `ETag` — the RFC 7232 §2.3.2
|
|
1065
|
+
* `ETag` — the RFC 7232 §2.3.2 weak comparison.
|
|
1054
1066
|
*
|
|
1055
1067
|
* @remarks
|
|
1056
|
-
* `If-None-Match` is a
|
|
1057
|
-
* listed tag matches), or the `*` wildcard (matches
|
|
1068
|
+
* `If-None-Match` is a comma-separated list of entity-tags (matches if any
|
|
1069
|
+
* listed tag matches), or the `*` wildcard (matches any current
|
|
1058
1070
|
* representation — only a list of exactly `*` is the wildcard). Comparison is
|
|
1059
|
-
*
|
|
1060
|
-
* through {@link unwrapETag} before comparing the opaque body).
|
|
1071
|
+
* weak: `W/"abc"` and `"abc"` are equal (each side's weak prefix is stripped
|
|
1072
|
+
* through {@link unwrapETag} before comparing the opaque body). Total — a
|
|
1061
1073
|
* malformed/empty header matches nothing, never throws.
|
|
1062
1074
|
*
|
|
1063
1075
|
* @param header - The raw `If-None-Match` header value
|
|
@@ -1083,17 +1095,17 @@ function matchesETag(header, etag) {
|
|
|
1083
1095
|
}
|
|
1084
1096
|
/**
|
|
1085
1097
|
* Parses an HTTP `Range` request header against a known resource `size` —
|
|
1086
|
-
*
|
|
1098
|
+
* total, returning a {@link RangeSpec} or `undefined`.
|
|
1087
1099
|
*
|
|
1088
1100
|
* @remarks
|
|
1089
1101
|
* Handles the three single-range `bytes=` forms — closed (`start-end`), open
|
|
1090
1102
|
* (`start-`), and suffix (`-suffixLength`) — clamping the window to
|
|
1091
|
-
* `[0, size - 1]` (the HTTP
|
|
1103
|
+
* `[0, size - 1]` (the HTTP inclusive-end convention). Returns
|
|
1092
1104
|
* `{ satisfiable: true, start, end }` for an overlapping range,
|
|
1093
1105
|
* `{ satisfiable: false }` for a range wholly past the resource, and
|
|
1094
|
-
* `undefined` for the "serve the whole resource" case: an
|
|
1095
|
-
* non-`bytes` unit, a
|
|
1096
|
-
* supported), or any malformed/non-finite bound.
|
|
1106
|
+
* `undefined` for the "serve the whole resource" case: an absent header, a
|
|
1107
|
+
* non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
|
|
1108
|
+
* supported), or any malformed/non-finite bound. Never throws on a hostile
|
|
1097
1109
|
* header.
|
|
1098
1110
|
*
|
|
1099
1111
|
* @param header - The raw `Range` header value
|
|
@@ -1150,9 +1162,9 @@ function parseRange(header, size) {
|
|
|
1150
1162
|
* @remarks
|
|
1151
1163
|
* `'*'` and a single origin string pass straight through. An allow-list
|
|
1152
1164
|
* echoes the request's `Origin` only when it is present in the list, else
|
|
1153
|
-
* `undefined` (no header set).
|
|
1165
|
+
* `undefined` (no header set). Security: the literal `'null'` origin — sent
|
|
1154
1166
|
* by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
|
|
1155
|
-
*
|
|
1167
|
+
* never reflected even if `'null'` were listed, closing the hostile-context
|
|
1156
1168
|
* cross-origin-access hole.
|
|
1157
1169
|
*
|
|
1158
1170
|
* @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
|
|
@@ -1220,15 +1232,15 @@ function resolveSecurityHeader(value, fallback) {
|
|
|
1220
1232
|
return value ?? fallback;
|
|
1221
1233
|
}
|
|
1222
1234
|
/**
|
|
1223
|
-
* Checks whether a client-supplied `X-Request-ID` is
|
|
1224
|
-
* header
|
|
1235
|
+
* Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
|
|
1236
|
+
* header and `context.state`.
|
|
1225
1237
|
*
|
|
1226
1238
|
* @remarks
|
|
1227
|
-
* A request id is echoed
|
|
1239
|
+
* A request id is echoed raw into a response header and log lines, so an
|
|
1228
1240
|
* untrusted one is a header-injection + log-injection + DoS vector. This
|
|
1229
1241
|
* refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
|
|
1230
1242
|
* (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
|
|
1231
|
-
*
|
|
1243
|
+
* Total — never throws.
|
|
1232
1244
|
*
|
|
1233
1245
|
* @param value - The candidate incoming request id
|
|
1234
1246
|
* @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
|
|
@@ -1250,7 +1262,7 @@ function isValidRequestId(value) {
|
|
|
1250
1262
|
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
1251
1263
|
* is the identity) or any string that does not expand to exactly eight
|
|
1252
1264
|
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
1253
|
-
* first
|
|
1265
|
+
* first four (the `/64` prefix), normalizes each (lower-case, no leading
|
|
1254
1266
|
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
1255
1267
|
* first. Total — a malformed address returns `undefined`.
|
|
1256
1268
|
*
|
|
@@ -1293,11 +1305,11 @@ function computeIPv6Network(address) {
|
|
|
1293
1305
|
return `${prefix.join(":")}::/64`;
|
|
1294
1306
|
}
|
|
1295
1307
|
/**
|
|
1296
|
-
* Collapses a client IP into its rate-limit
|
|
1308
|
+
* Collapses a client IP into its rate-limit bucket key — an IPv6 address to
|
|
1297
1309
|
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
1298
1310
|
*
|
|
1299
1311
|
* @remarks
|
|
1300
|
-
* A residential/mobile IPv6 user is routinely handed a
|
|
1312
|
+
* A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
|
|
1301
1313
|
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
1302
1314
|
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
1303
1315
|
* {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
@@ -1319,7 +1331,7 @@ function computeClientKey(address) {
|
|
|
1319
1331
|
* Serializes one {@link SSEMessage} to the SSE wire.
|
|
1320
1332
|
*
|
|
1321
1333
|
* @remarks
|
|
1322
|
-
* Emits an `event:`/`id:`/`retry:` line for each present field, then
|
|
1334
|
+
* Emits an `event:`/`id:`/`retry:` line for each present field, then one
|
|
1323
1335
|
* `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
|
|
1324
1336
|
* (so a consuming parser's multi-`data` concat reproduces the original
|
|
1325
1337
|
* `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
|
|
@@ -1343,9 +1355,9 @@ function serializeEvent(message) {
|
|
|
1343
1355
|
return `${lines.join("\n")}\n\n`;
|
|
1344
1356
|
}
|
|
1345
1357
|
/**
|
|
1346
|
-
* Checks whether a key is a
|
|
1347
|
-
* or `prototype
|
|
1348
|
-
*
|
|
1358
|
+
* Checks whether a key is a prototype-pollution vector — `__proto__`,
|
|
1359
|
+
* `constructor`, or `prototype`, each of which can reach and mutate
|
|
1360
|
+
* `Object.prototype` when it is assigned onto a normal object.
|
|
1349
1361
|
*
|
|
1350
1362
|
* @param key - The candidate object key
|
|
1351
1363
|
* @returns True if `key` is one of the three prototype-pollution keys; false otherwise
|
|
@@ -1360,12 +1372,11 @@ function isDangerousKey(key) {
|
|
|
1360
1372
|
return key === "__proto__" || key === "constructor" || key === "prototype";
|
|
1361
1373
|
}
|
|
1362
1374
|
/**
|
|
1363
|
-
* Strips the prototype-pollution keys from a parsed value
|
|
1364
|
-
* recursively.
|
|
1375
|
+
* Strips the prototype-pollution keys from a parsed value in place, recursively.
|
|
1365
1376
|
*
|
|
1366
1377
|
* @remarks
|
|
1367
|
-
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an
|
|
1368
|
-
* enumerable `__proto__`
|
|
1378
|
+
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
|
|
1379
|
+
* enumerable `__proto__` data property — but that own key becomes a
|
|
1369
1380
|
* pollution gadget the moment a downstream deep-merge copies it onto a live
|
|
1370
1381
|
* object. This walks the value and `delete`s any own {@link isDangerousKey}
|
|
1371
1382
|
* key at every depth, recursing into nested objects + array elements.
|
|
@@ -1404,7 +1415,7 @@ function scrubPrototype(value) {
|
|
|
1404
1415
|
* @remarks
|
|
1405
1416
|
* Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
|
|
1406
1417
|
* throwing a {@link ContentTooLargeError} (413) the instant the running total
|
|
1407
|
-
* exceeds `limit` —
|
|
1418
|
+
* exceeds `limit` — before the rest of the stream is buffered — rather than
|
|
1408
1419
|
* collecting an unbounded body. A bodyless request (`request.body === null`)
|
|
1409
1420
|
* resolves an empty array. A non-positive `limit` means unbounded.
|
|
1410
1421
|
*
|
|
@@ -1447,11 +1458,11 @@ async function collectRequestBody(request, limit) {
|
|
|
1447
1458
|
* whether a request body needs transparent decompression.
|
|
1448
1459
|
*
|
|
1449
1460
|
* @remarks
|
|
1450
|
-
* Lower-cases + trims and returns the matching {@link Encoding}
|
|
1461
|
+
* Lower-cases + trims and returns the matching {@link Encoding} only for
|
|
1451
1462
|
* `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
|
|
1452
1463
|
* absent header, `identity`, an unknown value, or a
|
|
1453
1464
|
* comma-joined multi-coding all yield `undefined` (the body is read as-is).
|
|
1454
|
-
*
|
|
1465
|
+
* Total — never asserts the loose `string | null` header.
|
|
1455
1466
|
*
|
|
1456
1467
|
* @param header - The raw `Content-Encoding` header value
|
|
1457
1468
|
* @returns The single decompressible {@link Encoding}, or `undefined` when none applies
|
|
@@ -1469,12 +1480,12 @@ function parseEncoding(header) {
|
|
|
1469
1480
|
}
|
|
1470
1481
|
/**
|
|
1471
1482
|
* Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
|
|
1472
|
-
* transparently through `DecompressionStream`, capping the
|
|
1483
|
+
* transparently through `DecompressionStream`, capping the decompressed output —
|
|
1473
1484
|
* the zip-bomb defense.
|
|
1474
1485
|
*
|
|
1475
1486
|
* @remarks
|
|
1476
1487
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
1477
|
-
* `TransformStream` that
|
|
1488
|
+
* `TransformStream` that aborts the pipe the instant the running decompressed
|
|
1478
1489
|
* total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
|
|
1479
1490
|
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
1480
1491
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
@@ -1524,9 +1535,10 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1524
1535
|
return merged;
|
|
1525
1536
|
}
|
|
1526
1537
|
/**
|
|
1527
|
-
* Collects
|
|
1538
|
+
* Collects and decodes a `Request` body — the shared body-collection pipeline
|
|
1528
1539
|
* surfaced to middleware and handlers as the middleware context's cached
|
|
1529
|
-
* `body()`.
|
|
1540
|
+
* `body()`. An empty body and a malformed `application/json` body each decode to
|
|
1541
|
+
* `undefined`.
|
|
1530
1542
|
*
|
|
1531
1543
|
* @remarks
|
|
1532
1544
|
* Collects the wire body capped at `options.limit` bytes ({@link
|
|
@@ -1537,13 +1549,11 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1537
1549
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1538
1550
|
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1539
1551
|
* `parseJSON` and scrubbed of prototype-pollution keys ({@link
|
|
1540
|
-
* scrubPrototype}); any other type decodes as UTF-8 text
|
|
1541
|
-
* decodes to `undefined`.
|
|
1552
|
+
* scrubPrototype}); any other type decodes as UTF-8 text.
|
|
1542
1553
|
*
|
|
1543
|
-
* A malformed JSON body is total: it decodes
|
|
1544
|
-
*
|
|
1545
|
-
*
|
|
1546
|
-
* returned value tells them apart.
|
|
1554
|
+
* A malformed JSON body is total: it decodes rather than throwing, so a handler
|
|
1555
|
+
* that must reject one checks for `undefined` itself, and nothing in the returned
|
|
1556
|
+
* value tells an empty body from a malformed one.
|
|
1547
1557
|
*
|
|
1548
1558
|
* @param request - The `Request` to read the body from
|
|
1549
1559
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
@@ -1602,18 +1612,19 @@ async function probePort(port) {
|
|
|
1602
1612
|
return address.port;
|
|
1603
1613
|
}
|
|
1604
1614
|
/**
|
|
1605
|
-
* Finds a
|
|
1606
|
-
*
|
|
1615
|
+
* Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
|
|
1616
|
+
* port where one is given and on an ephemeral port otherwise, reads the bound
|
|
1617
|
+
* port, closes the server, and resolves that port.
|
|
1607
1618
|
*
|
|
1608
1619
|
* @remarks
|
|
1609
1620
|
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
1610
|
-
* and returns it. With a `preferred` port it tries
|
|
1611
|
-
* returns it when free; if already in use (`EADDRINUSE`) it
|
|
1621
|
+
* and returns it. With a `preferred` port it tries that port first and
|
|
1622
|
+
* returns it when free; if already in use (`EADDRINUSE`) it falls back to an
|
|
1612
1623
|
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
1613
1624
|
* port. It binds then immediately closes a probe server, so the returned
|
|
1614
1625
|
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
1615
1626
|
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
1616
|
-
* `preferred` port (
|
|
1627
|
+
* `preferred` port (for example, a permission fault). A listener whose address is not
|
|
1617
1628
|
* an {@link import('node:net').AddressInfo} — a pipe listener, which this
|
|
1618
1629
|
* package's options cannot request — rejects with a `TypeError` rather than
|
|
1619
1630
|
* reporting `0`, because `0` is this package's own request for an ephemeral
|
|
@@ -1644,13 +1655,13 @@ async function discoverPort(preferred) {
|
|
|
1644
1655
|
//#region src/server/Negotiator.ts
|
|
1645
1656
|
/**
|
|
1646
1657
|
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
1647
|
-
* reusable, cross-middleware
|
|
1658
|
+
* reusable, cross-middleware entity rather than a middleware. Implements exactly
|
|
1648
1659
|
* {@link NegotiatorInterface}.
|
|
1649
1660
|
*
|
|
1650
1661
|
* @remarks
|
|
1651
1662
|
* `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
|
|
1652
1663
|
* any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
|
|
1653
|
-
* sibling axes and
|
|
1664
|
+
* sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
|
|
1654
1665
|
* rest of the substrate uses — one parser, never two. `format` reads the
|
|
1655
1666
|
* request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
|
|
1656
1667
|
* the winner — or answers `406 Not Acceptable`.
|
|
@@ -1706,7 +1717,7 @@ var Negotiator = class {
|
|
|
1706
1717
|
* answering 406 when none matches.
|
|
1707
1718
|
*
|
|
1708
1719
|
* @remarks
|
|
1709
|
-
* Errors thrown by the negotiated handler propagate
|
|
1720
|
+
* Errors thrown by the negotiated handler propagate unmodified — the
|
|
1710
1721
|
* server boundary classifies them, never this negotiator.
|
|
1711
1722
|
*/
|
|
1712
1723
|
async format(request, context, handlers) {
|
|
@@ -1724,37 +1735,37 @@ var Negotiator = class {
|
|
|
1724
1735
|
/**
|
|
1725
1736
|
* Represents the HTTP server facade — an observable `node:http` lifecycle composing this
|
|
1726
1737
|
* module's own middleware onion around a consumed `@orkestrel/router`
|
|
1727
|
-
* dispatcher.
|
|
1738
|
+
* dispatcher. Implements exactly {@link ServerInterface}.
|
|
1728
1739
|
*
|
|
1729
1740
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1730
1741
|
*
|
|
1731
1742
|
* @remarks
|
|
1732
1743
|
* - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
|
|
1733
1744
|
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1734
|
-
* ServerOptions.port} (omitted/`0` port ⇒
|
|
1745
|
+
* ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
|
|
1735
1746
|
* bound address), exposes that {@link AddressInfo} through `address`, observes
|
|
1736
1747
|
* caller cancellation plus the configured `timeouts.start` deadline while the
|
|
1737
1748
|
* bind is pending, and transitions `idle → starting → listening`. A
|
|
1738
1749
|
* cancelled or expired bind closes its partial server and resets to `idle` for
|
|
1739
1750
|
* another start. `stop()` transitions
|
|
1740
1751
|
* to `stopping`: refuses new connections, fires a fresh-per-run stop signal
|
|
1741
|
-
* so in-flight handlers observe cancellation, drains in-flight requests
|
|
1752
|
+
* so in-flight handlers observe cancellation, drains in-flight requests and
|
|
1742
1753
|
* claimed upgraded sockets up to the `drain` deadline (event-driven, no
|
|
1743
1754
|
* busy-loop), then closes → `stopped`, forcing whatever the deadline caught
|
|
1744
1755
|
* still open. `destroy()` is the idempotent final teardown.
|
|
1745
1756
|
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1746
1757
|
* `close`); a `Request` is built through the router's `buildRequest`, its
|
|
1747
|
-
* `signal`
|
|
1758
|
+
* `signal` linked to this run's stop signal through `@orkestrel/abort`'s
|
|
1748
1759
|
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1749
|
-
* `buildRequest`'s own abort, armed by
|
|
1760
|
+
* `buildRequest`'s own abort, armed by request-side and response-side
|
|
1750
1761
|
* teardown, composes with the server's stop signal through `AbortSignal.any`,
|
|
1751
|
-
* so a handler awaiting `request.signal` observes
|
|
1762
|
+
* so a handler awaiting `request.signal` observes either); `context.state` is built through
|
|
1752
1763
|
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1753
1764
|
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1754
1765
|
* written back through `sendResponse`.
|
|
1755
|
-
* - **The built-in boundary** wraps the
|
|
1766
|
+
* - **The built-in boundary** wraps the whole per-request chain, including
|
|
1756
1767
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1757
|
-
* throw (
|
|
1768
|
+
* throw (for example, a malformed `Host` header) to a silent `400` with no
|
|
1758
1769
|
* `error` emit; everything after (`Request` reconstruction, connection
|
|
1759
1770
|
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1760
1771
|
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
@@ -1766,12 +1777,12 @@ var Negotiator = class {
|
|
|
1766
1777
|
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1767
1778
|
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1768
1779
|
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
1769
|
-
* A
|
|
1780
|
+
* A claimed socket joins `#upgraded` until it closes: the claimant still
|
|
1770
1781
|
* owns it, and the tracking exists because node detaches an upgraded socket
|
|
1771
1782
|
* from the set its own close calls walk, so nothing else can end it.
|
|
1772
1783
|
* - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1773
1784
|
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1774
|
-
* routes it to the `error`
|
|
1785
|
+
* routes it to the `error` option rather than to the domain `error` event.
|
|
1775
1786
|
*/
|
|
1776
1787
|
var Server = class {
|
|
1777
1788
|
#id;
|
|
@@ -2089,7 +2100,7 @@ var Server = class {
|
|
|
2089
2100
|
* @remarks
|
|
2090
2101
|
* Builds the `Response` at construction from
|
|
2091
2102
|
* {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
|
|
2092
|
-
* merged
|
|
2103
|
+
* merged over them, at `options.status` (default `200`). A caller repeating one
|
|
2093
2104
|
* of those keys therefore replaces the seam's value, in any casing. The
|
|
2094
2105
|
* instance owns the stream's
|
|
2095
2106
|
* controller, its text encoder, the closed flag, and the parked producer's
|
|
@@ -2101,7 +2112,7 @@ var Server = class {
|
|
|
2101
2112
|
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
2102
2113
|
* consumer pull restoring capacity, or on stream closure. `comment` writes a
|
|
2103
2114
|
* `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
|
|
2104
|
-
* stream. Every method is a
|
|
2115
|
+
* stream. Every method is a safe no-op once `closed` (ended by `end()`, or
|
|
2105
2116
|
* the consumer cancelled the stream), so a late write never throws.
|
|
2106
2117
|
*
|
|
2107
2118
|
* The readiness signal reflects only the process-local `ReadableStream`
|
|
@@ -2202,11 +2213,18 @@ var Stream = class {
|
|
|
2202
2213
|
*
|
|
2203
2214
|
* @example
|
|
2204
2215
|
* ```ts
|
|
2216
|
+
* import type { MiddlewareContext } from '@src/server'
|
|
2205
2217
|
* import { createNegotiator } from '@src/server'
|
|
2206
2218
|
*
|
|
2219
|
+
* declare const context: MiddlewareContext<Record<string, never>>
|
|
2220
|
+
*
|
|
2207
2221
|
* const negotiator = createNegotiator()
|
|
2208
|
-
* negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
|
|
2209
|
-
* // '
|
|
2222
|
+
* negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'
|
|
2223
|
+
* negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
|
|
2224
|
+
* negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'
|
|
2225
|
+
* await negotiator.format(new Request('http://x'), context, {
|
|
2226
|
+
* 'application/json': (_request, _context) => Response.json({ ok: true }),
|
|
2227
|
+
* })
|
|
2210
2228
|
* ```
|
|
2211
2229
|
*/
|
|
2212
2230
|
function createNegotiator() {
|
|
@@ -2220,20 +2238,34 @@ function createNegotiator() {
|
|
|
2220
2238
|
* @param options - {@link ServerOptions}
|
|
2221
2239
|
* @returns A {@link ServerInterface}, not yet started
|
|
2222
2240
|
*
|
|
2223
|
-
* @example
|
|
2241
|
+
* @example Quickstart: dispatcher, middleware, lifecycle
|
|
2224
2242
|
* ```ts
|
|
2225
|
-
* import {
|
|
2243
|
+
* import type { MiddlewareHandler } from '@orkestrel/server'
|
|
2244
|
+
* import { createServer } from '@orkestrel/server'
|
|
2226
2245
|
* import { createDispatcher } from '@orkestrel/router'
|
|
2227
2246
|
*
|
|
2228
|
-
*
|
|
2247
|
+
* interface State {
|
|
2248
|
+
* readonly requestId: string
|
|
2249
|
+
* readonly ip: string | undefined
|
|
2250
|
+
* }
|
|
2251
|
+
*
|
|
2252
|
+
* const dispatcher = createDispatcher<State>()
|
|
2229
2253
|
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
2230
2254
|
*
|
|
2231
|
-
* const
|
|
2255
|
+
* const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {
|
|
2256
|
+
* const response = await next()
|
|
2257
|
+
* response.headers.set('X-Request-ID', context.state.requestId)
|
|
2258
|
+
* return response
|
|
2259
|
+
* }
|
|
2260
|
+
*
|
|
2261
|
+
* const server = createServer<State>({
|
|
2232
2262
|
* dispatcher,
|
|
2233
|
-
* state: (connection) => ({ ip: connection.ip }),
|
|
2263
|
+
* state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
|
|
2234
2264
|
* })
|
|
2265
|
+
* server.use(logRequestId)
|
|
2235
2266
|
* const port = await server.start()
|
|
2236
2267
|
* await server.stop()
|
|
2268
|
+
* await server.destroy()
|
|
2237
2269
|
* ```
|
|
2238
2270
|
*/
|
|
2239
2271
|
function createServer(options) {
|