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