@orkestrel/server 0.0.17 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -11
- package/dist/src/server/index.cjs +595 -441
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +778 -531
- package/dist/src/server/index.d.ts +778 -531
- package/dist/src/server/index.js +587 -435
- package/dist/src/server/index.js.map +1 -1
- package/package.json +18 -20
package/dist/src/server/index.js
CHANGED
|
@@ -1,58 +1,66 @@
|
|
|
1
1
|
import { isFiniteNumber, isFunction, isInteger, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
|
|
2
2
|
import { addAbortListener, once } from "node:events";
|
|
3
3
|
import { createServer as createServer$1 } from "node:net";
|
|
4
|
-
import { decodeBase64URL, encodeBase64URL } from "@orkestrel/codec";
|
|
4
|
+
import { decodeBase64URL, encodeBase64URL, encodeHex } from "@orkestrel/codec";
|
|
5
5
|
import { createServer as createServer$2 } from "node:http";
|
|
6
6
|
import { createAbort, linkSignal } from "@orkestrel/abort";
|
|
7
7
|
import { createTimeout } from "@orkestrel/timeout";
|
|
8
8
|
import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
|
|
9
9
|
import { Emitter } from "@orkestrel/emitter";
|
|
10
10
|
//#region src/server/constants.ts
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Names the default graceful-stop deadline `stop()` gives in-flight requests and
|
|
13
|
+
* claimed upgraded sockets, `10_000` ms.
|
|
14
|
+
*/
|
|
12
15
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
13
16
|
/**
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* `instanceof` alone fails because the two copies' `HTTPError` constructors
|
|
18
|
-
* 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.
|
|
19
20
|
*
|
|
20
21
|
* @remarks
|
|
21
|
-
*
|
|
22
|
-
*
|
|
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
|
|
23
27
|
* instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
|
|
24
28
|
* unequal symbol per copy and defeat the whole point of a cross-copy brand.
|
|
25
29
|
*/
|
|
26
30
|
var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
|
|
27
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* Names the default maximum request body size `readBody` accepts before a 413,
|
|
33
|
+
* `1_048_576` bytes.
|
|
34
|
+
*/
|
|
28
35
|
var DEFAULT_BODY_LIMIT = 1048576;
|
|
29
36
|
/**
|
|
30
|
-
*
|
|
31
|
-
* the body pipeline's byte-counting `TransformStream` enforces when
|
|
32
|
-
* 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.
|
|
33
40
|
*
|
|
34
41
|
* @remarks
|
|
35
42
|
* A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
|
|
36
43
|
* can inflate by many orders of magnitude — a classic decompression bomb.
|
|
37
|
-
* Capping the decompressed byte count makes the pipe
|
|
38
|
-
* 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
|
|
39
46
|
* inflation can never exhaust memory. Defaults to `16 MiB` — a generous
|
|
40
47
|
* ceiling for a legitimate compressed JSON / form body, far below an OOM. A
|
|
41
|
-
* consumer raises it
|
|
48
|
+
* consumer raises it through {@link import('./types.js').BodyOptions}
|
|
42
49
|
* `decompression` for a workload that genuinely ships larger decompressed
|
|
43
50
|
* bodies.
|
|
44
51
|
*/
|
|
45
52
|
var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
|
|
46
53
|
/**
|
|
47
|
-
*
|
|
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.
|
|
48
56
|
*
|
|
49
57
|
* @remarks
|
|
50
58
|
* `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
|
|
51
59
|
* keeps a proxy from caching the stream; `keep-alive` holds the connection
|
|
52
60
|
* open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
|
|
53
61
|
* events flush promptly rather than batching. Frozen so a consumer can read
|
|
54
|
-
* but never mutate the shared default;
|
|
55
|
-
* {@link import('./types.js').StreamOptions.headers}
|
|
62
|
+
* but never mutate the shared default; the merged keys are
|
|
63
|
+
* {@link import('./types.js').StreamOptions.headers}.
|
|
56
64
|
*/
|
|
57
65
|
var SSE_HEADERS = Object.freeze({
|
|
58
66
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
@@ -61,27 +69,31 @@ var SSE_HEADERS = Object.freeze({
|
|
|
61
69
|
"X-Accel-Buffering": "no"
|
|
62
70
|
});
|
|
63
71
|
/**
|
|
64
|
-
*
|
|
65
|
-
* to match
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
72
|
+
* Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
|
|
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.
|
|
70
81
|
*/
|
|
71
82
|
var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
|
|
72
83
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
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.
|
|
76
87
|
*
|
|
77
88
|
* @remarks
|
|
78
89
|
* The text-shaped application types worth compressing (JSON / JavaScript /
|
|
79
|
-
* XML / SVG / WASM / a few document formats) —
|
|
90
|
+
* XML / SVG / WASM / a few document formats) — never already-compressed
|
|
80
91
|
* binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
|
|
81
|
-
* `woff2`), which gzip/deflate would only bloat.
|
|
82
|
-
*
|
|
92
|
+
* `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
|
|
93
|
+
* withholds `add` / `delete` / `clear` from the shared default, so a consumer
|
|
94
|
+
* reads it without reaching a mutator.
|
|
83
95
|
*/
|
|
84
|
-
var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
|
|
96
|
+
var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
|
|
85
97
|
"application/json",
|
|
86
98
|
"application/javascript",
|
|
87
99
|
"application/xml",
|
|
@@ -94,13 +106,13 @@ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
|
|
|
94
106
|
"application/wasm",
|
|
95
107
|
"image/svg+xml",
|
|
96
108
|
"application/pdf"
|
|
97
|
-
]);
|
|
109
|
+
]));
|
|
98
110
|
/**
|
|
99
|
-
*
|
|
100
|
-
*
|
|
111
|
+
* Lists the default {@link Encoding} content-codings the substrate offers, in
|
|
112
|
+
* preference order — `gzip` then `deflate`.
|
|
101
113
|
*
|
|
102
114
|
* @remarks
|
|
103
|
-
* `identity` (no compression) is always implicitly acceptable and is
|
|
115
|
+
* `identity` (no compression) is always implicitly acceptable and is not
|
|
104
116
|
* listed here — it is the fall-through when a client accepts none of these.
|
|
105
117
|
* Brotli is omitted per the core's `CompressionStream`-only decision (see
|
|
106
118
|
* {@link Encoding}). Frozen so a consumer can read but never mutate the
|
|
@@ -110,18 +122,19 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
|
|
|
110
122
|
//#endregion
|
|
111
123
|
//#region src/server/errors.ts
|
|
112
124
|
/**
|
|
113
|
-
*
|
|
125
|
+
* Represents an error a handler (or middleware) throws to produce an HTTP response of a
|
|
114
126
|
* specific status.
|
|
115
127
|
*
|
|
116
128
|
* @remarks
|
|
117
129
|
* Carries the HTTP `status` to send and an optional `context` record (the
|
|
118
130
|
* offending field / value). The server's built-in error boundary catches it
|
|
119
131
|
* and renders a response of `status` with the error's `message` as the body
|
|
120
|
-
* — so an `HTTPError`'s message is
|
|
132
|
+
* — so an `HTTPError`'s message is always client-facing (it is the handler's
|
|
121
133
|
* deliberate signal), unlike a generic throw whose message is hidden unless
|
|
122
134
|
* `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
|
|
123
135
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
124
|
-
* {@link isHTTPError}.
|
|
136
|
+
* {@link isHTTPError}. The machine-readable discriminator is `status`; there is
|
|
137
|
+
* no separate `code`.
|
|
125
138
|
*
|
|
126
139
|
* @example
|
|
127
140
|
* ```ts
|
|
@@ -146,7 +159,7 @@ var HTTPError = class extends Error {
|
|
|
146
159
|
}
|
|
147
160
|
};
|
|
148
161
|
/**
|
|
149
|
-
*
|
|
162
|
+
* Represents the {@link HTTPError} thrown when a request body exceeds the body
|
|
150
163
|
* pipeline's size limit — a `413 Content Too Large`.
|
|
151
164
|
*
|
|
152
165
|
* @remarks
|
|
@@ -173,21 +186,22 @@ var ContentTooLargeError = class extends HTTPError {
|
|
|
173
186
|
}
|
|
174
187
|
};
|
|
175
188
|
/**
|
|
176
|
-
*
|
|
177
|
-
*
|
|
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.
|
|
178
192
|
*
|
|
179
193
|
* @param value - The value to test (typically a `catch` binding)
|
|
180
|
-
* @returns
|
|
194
|
+
* @returns True if `value` is an {@link HTTPError}; false otherwise
|
|
181
195
|
*
|
|
182
196
|
* @remarks
|
|
183
197
|
* Tries `instanceof` first, then falls back to a total structural check for
|
|
184
|
-
* an instance built by a
|
|
198
|
+
* an instance built by a different copy of this package (the dual-package
|
|
185
199
|
* hazard — version skew, a linked workspace duplicate) whose `HTTPError`
|
|
186
200
|
* constructor is a distinct object from this copy's: the value must carry
|
|
187
|
-
* the cross-copy brand (interned
|
|
188
|
-
* same key)
|
|
201
|
+
* the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
|
|
202
|
+
* same key) and expose the exact fields the server's error boundary reads off
|
|
189
203
|
* a recognized `HTTPError` — a numeric `status` and a string `message`. A
|
|
190
|
-
* plain object that merely carries a `status`
|
|
204
|
+
* plain object that merely carries a `status` without the brand is rejected.
|
|
191
205
|
*
|
|
192
206
|
* @example
|
|
193
207
|
* ```ts
|
|
@@ -207,21 +221,112 @@ function isHTTPError(value) {
|
|
|
207
221
|
if (!("status" in value) || !("message" in value)) return false;
|
|
208
222
|
return isNumber(value.status) && isString(value.message);
|
|
209
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Represents the error this package raises when a caller programmed a call the
|
|
226
|
+
* entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
|
|
227
|
+
*
|
|
228
|
+
* @remarks
|
|
229
|
+
* Carries a machine-readable {@link ServerErrorCode} and an optional `context`
|
|
230
|
+
* record naming the offending facts. This is a programmer error, so it carries
|
|
231
|
+
* no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
|
|
232
|
+
* invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
|
|
233
|
+
* middleware into the request boundary, which reaches it as a generic 500 with
|
|
234
|
+
* the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
|
|
235
|
+
* client-facing fault instead. Narrow a caught value with
|
|
236
|
+
* {@link isServerError}.
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* import { ServerError } from '@src/server'
|
|
241
|
+
*
|
|
242
|
+
* const error = new ServerError('STATUS', "server cannot start from 'listening'", {
|
|
243
|
+
* status: 'listening',
|
|
244
|
+
* })
|
|
245
|
+
* error.code // 'STATUS'
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
var ServerError = class extends Error {
|
|
249
|
+
code;
|
|
250
|
+
context;
|
|
251
|
+
constructor(code, message, context) {
|
|
252
|
+
super(message);
|
|
253
|
+
this.name = "ServerError";
|
|
254
|
+
this.code = code;
|
|
255
|
+
if (context !== void 0) this.context = context;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
|
|
260
|
+
* of a call the caller programmed.
|
|
261
|
+
*
|
|
262
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
263
|
+
* @returns True if `value` is a {@link ServerError}; false otherwise
|
|
264
|
+
*
|
|
265
|
+
* @remarks
|
|
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
|
|
268
|
+
* hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
|
|
269
|
+
* consumer here.
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* ```ts
|
|
273
|
+
* import { createServer, isServerError } from '@src/server'
|
|
274
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
275
|
+
*
|
|
276
|
+
* const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
|
|
277
|
+
* await server.start()
|
|
278
|
+
* try {
|
|
279
|
+
* await server.start()
|
|
280
|
+
* } catch (error) {
|
|
281
|
+
* if (isServerError(error)) console.log(error.code) // 'STATUS'
|
|
282
|
+
* }
|
|
283
|
+
* await server.stop()
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
function isServerError(value) {
|
|
287
|
+
return value instanceof ServerError;
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region src/server/validators.ts
|
|
291
|
+
/**
|
|
292
|
+
* Checks whether a `node:net` `server.address()` return is the structured
|
|
293
|
+
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
294
|
+
* or `null` — the total, never-throwing narrow `discoverPort`
|
|
295
|
+
* and the `Server`'s own port resolution read the bound port through.
|
|
296
|
+
*
|
|
297
|
+
* @remarks
|
|
298
|
+
* Checks the `address`, `family`, and `port` members `node:net` declares as
|
|
299
|
+
* `string`, `string`, and `number`.
|
|
300
|
+
*
|
|
301
|
+
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
302
|
+
* @returns True if `value` is an `AddressInfo`; false otherwise
|
|
303
|
+
*
|
|
304
|
+
* @example
|
|
305
|
+
* ```ts
|
|
306
|
+
* import { isAddressInfo } from '@src/server'
|
|
307
|
+
*
|
|
308
|
+
* isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
|
|
309
|
+
* isAddressInfo(null) // false
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
312
|
+
function isAddressInfo(value) {
|
|
313
|
+
return isRecord(value) && isString(value.address) && isString(value.family) && isNumber(value.port);
|
|
314
|
+
}
|
|
210
315
|
//#endregion
|
|
211
316
|
//#region src/server/helpers.ts
|
|
212
317
|
/**
|
|
213
|
-
*
|
|
214
|
-
* handler into one request handler — the frozen middleware seam
|
|
318
|
+
* Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
|
|
319
|
+
* handler into one request handler — the frozen middleware seam.
|
|
215
320
|
*
|
|
216
321
|
* @remarks
|
|
217
|
-
* `middleware[0]` runs
|
|
218
|
-
* 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
|
|
219
324
|
* `terminal`. Each middleware's `next` may be called with a substituted
|
|
220
325
|
* `Request` (the downstream chain then sees that request instead of the
|
|
221
326
|
* original), called with no argument (the original request continues
|
|
222
|
-
* downstream), or
|
|
327
|
+
* downstream), or not called at all (a short-circuit — the middleware's own
|
|
223
328
|
* returned `Response` is sent, and everything downstream never runs). A
|
|
224
|
-
*
|
|
329
|
+
* second call to the same `next` within one middleware invocation rejects —
|
|
225
330
|
* each link runs the chain at most once, so a middleware cannot fork the
|
|
226
331
|
* request into two divergent downstream runs.
|
|
227
332
|
*
|
|
@@ -245,7 +350,8 @@ function compose(middleware, terminal) {
|
|
|
245
350
|
return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
|
|
246
351
|
}
|
|
247
352
|
/**
|
|
248
|
-
*
|
|
353
|
+
* Wraps one middleware layer around its downstream handler, enforcing the one-call
|
|
354
|
+
* `next` invariant.
|
|
249
355
|
*
|
|
250
356
|
* @remarks
|
|
251
357
|
* The returned handler enforces the one-call `next` invariant while preserving
|
|
@@ -268,24 +374,24 @@ function wrapMiddleware(layer, next) {
|
|
|
268
374
|
return async (request, context) => {
|
|
269
375
|
let called = false;
|
|
270
376
|
return Promise.resolve(layer(request, context, (nextRequest) => {
|
|
271
|
-
if (called) return Promise.reject(
|
|
377
|
+
if (called) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
|
|
272
378
|
called = true;
|
|
273
379
|
return next(nextRequest ?? request, context);
|
|
274
380
|
}));
|
|
275
381
|
};
|
|
276
382
|
}
|
|
277
383
|
/**
|
|
278
|
-
*
|
|
384
|
+
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
279
385
|
*
|
|
280
386
|
* @remarks
|
|
281
|
-
* Splits on `;`; the
|
|
387
|
+
* Splits on `;`; the first segment keeps any leading whitespace (a genuine
|
|
282
388
|
* cookie-pair separator never precedes it), while every later segment has its
|
|
283
389
|
* inter-pair separator (ASCII space/tab) stripped before parsing — so a
|
|
284
|
-
* whitespace-
|
|
390
|
+
* whitespace-padded name (`' __Host-x=evil'`) is rejected by
|
|
285
391
|
* {@link isCookieName} rather than silently reconciling into a
|
|
286
392
|
* prefix-protected `__Host-` name. A pair without `=`, or with an invalid
|
|
287
|
-
* name, is skipped; a later duplicate name wins.
|
|
288
|
-
* malformed header yields an empty record, never throws
|
|
393
|
+
* name, is skipped; a later duplicate name wins. Total — an absent/empty/
|
|
394
|
+
* malformed header yields an empty record, never throws.
|
|
289
395
|
*
|
|
290
396
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
291
397
|
* @returns A record of every parsed cookie, `name → decoded value`
|
|
@@ -311,8 +417,8 @@ function parseCookies(header) {
|
|
|
311
417
|
return out;
|
|
312
418
|
}
|
|
313
419
|
/**
|
|
314
|
-
*
|
|
315
|
-
* 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.
|
|
316
422
|
*
|
|
317
423
|
* @remarks
|
|
318
424
|
* A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
|
|
@@ -321,7 +427,7 @@ function parseCookies(header) {
|
|
|
321
427
|
* `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
|
|
322
428
|
*
|
|
323
429
|
* @param value - The candidate cookie name
|
|
324
|
-
* @returns
|
|
430
|
+
* @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
|
|
325
431
|
*
|
|
326
432
|
* @example
|
|
327
433
|
* ```ts
|
|
@@ -333,7 +439,7 @@ function isCookieName(value) {
|
|
|
333
439
|
return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
|
|
334
440
|
}
|
|
335
441
|
/**
|
|
336
|
-
*
|
|
442
|
+
* Decodes a cookie value with `decodeURIComponent`, falling back to the raw
|
|
337
443
|
* text when the value is not valid percent-encoding.
|
|
338
444
|
*
|
|
339
445
|
* @param raw - The raw (trimmed) cookie value
|
|
@@ -353,9 +459,9 @@ function decodeCookieValue(raw) {
|
|
|
353
459
|
}
|
|
354
460
|
}
|
|
355
461
|
/**
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
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.
|
|
359
465
|
*
|
|
360
466
|
* @remarks
|
|
361
467
|
* Rejects a value carrying a `;` (splits attributes), a `,` (can split a
|
|
@@ -364,7 +470,7 @@ function decodeCookieValue(raw) {
|
|
|
364
470
|
* directive. Total — never throws (a bad value returns `false`).
|
|
365
471
|
*
|
|
366
472
|
* @param value - The candidate attribute value (a `Domain` or `Path`)
|
|
367
|
-
* @returns
|
|
473
|
+
* @returns True if `value` carries no separator / whitespace / control char; false otherwise
|
|
368
474
|
*
|
|
369
475
|
* @example
|
|
370
476
|
* ```ts
|
|
@@ -381,18 +487,17 @@ function isCookieAttribute(value) {
|
|
|
381
487
|
return true;
|
|
382
488
|
}
|
|
383
489
|
/**
|
|
384
|
-
*
|
|
490
|
+
* Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
|
|
385
491
|
*
|
|
386
492
|
* @remarks
|
|
387
493
|
* URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
|
|
388
494
|
* appends the present {@link CookieOptions} attributes in canonical order:
|
|
389
495
|
* `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
|
|
390
|
-
* (default
|
|
391
|
-
* with {@link isCookieAttribute} and
|
|
392
|
-
* injection attempt (a programmer misconfiguration
|
|
393
|
-
* silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
|
|
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
|
|
394
499
|
* the `secure` option (the spec requires it); an un-resolved `undefined`
|
|
395
|
-
* `secure` here falls to
|
|
500
|
+
* `secure` here falls to off — request-aware callers resolve it first through
|
|
396
501
|
* {@link resolveSecure}.
|
|
397
502
|
*
|
|
398
503
|
* @param name - The cookie name
|
|
@@ -423,7 +528,7 @@ function serializeCookie(name, value, options) {
|
|
|
423
528
|
return parts.join("; ");
|
|
424
529
|
}
|
|
425
530
|
/**
|
|
426
|
-
*
|
|
531
|
+
* Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
|
|
427
532
|
* `secure` setting and whether the request arrived over TLS.
|
|
428
533
|
*
|
|
429
534
|
* @remarks
|
|
@@ -433,7 +538,10 @@ function serializeCookie(name, value, options) {
|
|
|
433
538
|
* gets `Secure` automatically while local-dev HTTP still works.
|
|
434
539
|
*
|
|
435
540
|
* @param secure - The {@link CookieOptions} `secure` setting
|
|
436
|
-
* @param encrypted - The connection's TLS flag
|
|
541
|
+
* @param encrypted - The connection's TLS flag
|
|
542
|
+
* ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
|
|
543
|
+
* `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
|
|
544
|
+
* no `Secure` attribute.
|
|
437
545
|
* @returns The concrete `Secure` flag to emit
|
|
438
546
|
*
|
|
439
547
|
* @example
|
|
@@ -448,39 +556,15 @@ function resolveSecure(secure, encrypted) {
|
|
|
448
556
|
return encrypted;
|
|
449
557
|
}
|
|
450
558
|
/**
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
* @remarks
|
|
455
|
-
* `Headers.append` already accumulates repeated headers (unlike node's
|
|
456
|
-
* `setHeader`), so this is a thin, self-documenting wrapper naming the
|
|
457
|
-
* cookie-append intent — the primitive {@link writeSignedCookie} /
|
|
458
|
-
* {@link clearCookie} use.
|
|
459
|
-
*
|
|
460
|
-
* @param headers - The response `Headers` to write into
|
|
461
|
-
* @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
|
|
462
|
-
*
|
|
463
|
-
* @example
|
|
464
|
-
* ```ts
|
|
465
|
-
* const headers = new Headers()
|
|
466
|
-
* appendCookie(headers, serializeCookie('a', '1'))
|
|
467
|
-
* appendCookie(headers, serializeCookie('b', '2'))
|
|
468
|
-
* headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
|
|
469
|
-
* ```
|
|
470
|
-
*/
|
|
471
|
-
function appendCookie(headers, cookie) {
|
|
472
|
-
headers.append("set-cookie", cookie);
|
|
473
|
-
}
|
|
474
|
-
/**
|
|
475
|
-
* Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
|
|
476
|
-
* it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
559
|
+
* Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
|
|
560
|
+
* appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
477
561
|
*
|
|
478
562
|
* @remarks
|
|
479
563
|
* The cookie value is `await signToken(value, { secret })`
|
|
480
564
|
* (`<payload>.<signature>`), so a signed cookie is a stateless token in a
|
|
481
565
|
* cookie — the same secret rotation and tamper rejection, no second HMAC
|
|
482
|
-
* scheme. Appends (never clobbers)
|
|
483
|
-
*
|
|
566
|
+
* scheme. Appends (never clobbers) through `Headers.append`, which accumulates
|
|
567
|
+
* repeated headers. Async — WebCrypto signing is asynchronous.
|
|
484
568
|
*
|
|
485
569
|
* @param headers - The response `Headers` to write into
|
|
486
570
|
* @param name - The cookie name
|
|
@@ -495,16 +579,16 @@ function appendCookie(headers, cookie) {
|
|
|
495
579
|
* ```
|
|
496
580
|
*/
|
|
497
581
|
async function writeSignedCookie(headers, name, value, secret, options) {
|
|
498
|
-
|
|
582
|
+
headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
|
|
499
583
|
}
|
|
500
584
|
/**
|
|
501
|
-
*
|
|
585
|
+
* Reads and verifies a signed cookie off a request — total, returning the
|
|
502
586
|
* embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
503
587
|
*
|
|
504
588
|
* @remarks
|
|
505
589
|
* Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
|
|
506
590
|
* and verifies it with {@link verifyToken} against `secret` (a rotation list
|
|
507
|
-
* accepts a cookie signed by any of its secrets).
|
|
591
|
+
* accepts a cookie signed by any of its secrets). Any failure — an absent
|
|
508
592
|
* cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
|
|
509
593
|
*
|
|
510
594
|
* @param request - The `Request` to read the `Cookie` header from
|
|
@@ -522,12 +606,12 @@ async function readSignedCookie(request, name, secret) {
|
|
|
522
606
|
return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
|
|
523
607
|
}
|
|
524
608
|
/**
|
|
525
|
-
*
|
|
609
|
+
* Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
|
|
526
610
|
*
|
|
527
611
|
* @remarks
|
|
528
612
|
* Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
|
|
529
613
|
* same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
|
|
530
|
-
* a cookie when those
|
|
614
|
+
* a cookie when those match the one it set).
|
|
531
615
|
*
|
|
532
616
|
* @param headers - The response `Headers` to write into
|
|
533
617
|
* @param name - The cookie name to clear
|
|
@@ -540,23 +624,23 @@ async function readSignedCookie(request, name, secret) {
|
|
|
540
624
|
* ```
|
|
541
625
|
*/
|
|
542
626
|
function clearCookie(headers, name, options) {
|
|
543
|
-
|
|
627
|
+
headers.append("set-cookie", serializeCookie(name, "", {
|
|
544
628
|
...options,
|
|
545
629
|
maxAge: 0
|
|
546
630
|
}));
|
|
547
631
|
}
|
|
548
632
|
/**
|
|
549
|
-
*
|
|
633
|
+
* Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
|
|
550
634
|
*
|
|
551
635
|
* @remarks
|
|
552
636
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
553
637
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
554
638
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
555
|
-
* the signature), signed
|
|
639
|
+
* the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
|
|
556
640
|
* {@link TokenSecret} (the current secret, or the head of a rotation list).
|
|
557
|
-
* Blank/whitespace-only secrets are
|
|
558
|
-
* misconfigured secret with no usable entry
|
|
559
|
-
* (`500`) — fail-closed, a programmer error
|
|
641
|
+
* Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
|
|
642
|
+
* misconfigured secret with no usable entry throws an {@link HTTPError}
|
|
643
|
+
* (`500`) — fail-closed, a programmer error. Verify with
|
|
560
644
|
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
561
645
|
*
|
|
562
646
|
* @param value - The opaque value to embed (a session id, a deployment marker)
|
|
@@ -586,19 +670,19 @@ async function signToken(value, options) {
|
|
|
586
670
|
return `${encoded}.${encodeBase64URL(new Uint8Array(signature))}`;
|
|
587
671
|
}
|
|
588
672
|
/**
|
|
589
|
-
*
|
|
673
|
+
* Verifies a stateless token and returns its embedded value — total, never throws.
|
|
590
674
|
*
|
|
591
675
|
* @remarks
|
|
592
|
-
* The inverse of {@link signToken}: splits the token on its
|
|
676
|
+
* The inverse of {@link signToken}: splits the token on its last `.` (so a
|
|
593
677
|
* value containing dots survives), decodes the signature with
|
|
594
678
|
* `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
|
|
595
679
|
* base64url is refused there, before any key import — and checks the payload's
|
|
596
|
-
* HMAC-SHA256 signature against
|
|
680
|
+
* HMAC-SHA256 signature against each {@link TokenSecret} candidate through
|
|
597
681
|
* `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
|
|
598
|
-
* retired
|
|
682
|
+
* retired), accepting the token on the first match (the
|
|
599
683
|
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
600
|
-
* `typeof`, never `as`
|
|
601
|
-
*
|
|
684
|
+
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
685
|
+
* token. Any failure — a malformed token, a bad signature,
|
|
602
686
|
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
603
687
|
* yields `undefined` rather than throwing.
|
|
604
688
|
*
|
|
@@ -634,15 +718,15 @@ async function verifyToken(token, secret) {
|
|
|
634
718
|
}
|
|
635
719
|
}
|
|
636
720
|
/**
|
|
637
|
-
*
|
|
721
|
+
* Decodes and narrows a signed token's base64url JSON payload, honoring its
|
|
638
722
|
* expiry — the shared decode step {@link verifyToken} applies after a
|
|
639
723
|
* signature match.
|
|
640
724
|
*
|
|
641
725
|
* @remarks
|
|
642
726
|
* Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
|
|
643
727
|
* non-canonical base64url segment answers `undefined` rather than throwing),
|
|
644
|
-
* reads it as UTF-8 JSON, narrows it to a record with a string `value`
|
|
645
|
-
*
|
|
728
|
+
* reads it as UTF-8 JSON, narrows it to a record with a string `value` without
|
|
729
|
+
* `as`, and rejects an expired `exp`. Total — any
|
|
646
730
|
* decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
|
|
647
731
|
* throws, and its `catch` answers `undefined` too.
|
|
648
732
|
*
|
|
@@ -664,13 +748,13 @@ function decodeTokenPayload(encoded) {
|
|
|
664
748
|
}
|
|
665
749
|
}
|
|
666
750
|
/**
|
|
667
|
-
*
|
|
668
|
-
*
|
|
751
|
+
* Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
|
|
752
|
+
* behind both {@link signToken} and {@link verifyToken}.
|
|
669
753
|
*
|
|
670
754
|
* @remarks
|
|
671
755
|
* A single string becomes a one-element list; a rotation list is copied. Any
|
|
672
|
-
* blank/whitespace-only entry is
|
|
673
|
-
* 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
|
|
674
758
|
* element is the signing secret; all kept are accepted on verify.
|
|
675
759
|
*
|
|
676
760
|
* @param secret - The {@link TokenSecret} (a single string, or a rotation list)
|
|
@@ -685,17 +769,17 @@ function normalizeSecret(secret) {
|
|
|
685
769
|
return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
|
|
686
770
|
}
|
|
687
771
|
/**
|
|
688
|
-
*
|
|
772
|
+
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
689
773
|
* into its q-sorted entries.
|
|
690
774
|
*
|
|
691
775
|
* @remarks
|
|
692
776
|
* Splits on `,`; for each part takes the token before the first `;`
|
|
693
777
|
* (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
|
|
694
778
|
* quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
|
|
695
|
-
* back to `1`). A `;q=0` entry is
|
|
696
|
-
* 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
|
|
697
781
|
* the header's own order within a tie — a single pass with no backtracking,
|
|
698
|
-
* so parsing stays linear in the header length (ReDoS-safe).
|
|
782
|
+
* so parsing stays linear in the header length (ReDoS-safe). Total — an
|
|
699
783
|
* empty/malformed header yields `[]`/best-effort entries, never throws.
|
|
700
784
|
*
|
|
701
785
|
* @param header - The raw weighted header value
|
|
@@ -734,12 +818,12 @@ function parseAcceptHeader(header) {
|
|
|
734
818
|
})).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
|
|
735
819
|
}
|
|
736
820
|
/**
|
|
737
|
-
*
|
|
738
|
-
* `Accept-Encoding` entries —
|
|
739
|
-
*
|
|
821
|
+
* Computes the client's quality (q) for one content-coding from the parsed
|
|
822
|
+
* `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
|
|
823
|
+
* each offered coding.
|
|
740
824
|
*
|
|
741
825
|
* @remarks
|
|
742
|
-
* Prefers an
|
|
826
|
+
* Prefers an exact named match (including an explicit `;q=0` rejection);
|
|
743
827
|
* failing that, a bare `*` wildcard's q applies. A coding that is neither
|
|
744
828
|
* named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
|
|
745
829
|
* over a `*` (a specific rejection beats the wildcard), so it scores `0`.
|
|
@@ -750,43 +834,46 @@ function parseAcceptHeader(header) {
|
|
|
750
834
|
*
|
|
751
835
|
* @example
|
|
752
836
|
* ```ts
|
|
753
|
-
*
|
|
754
|
-
*
|
|
837
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
|
|
838
|
+
* computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
|
|
755
839
|
* ```
|
|
756
840
|
*/
|
|
757
|
-
function
|
|
841
|
+
function computeCodingQuality(entries, coding) {
|
|
758
842
|
const named = entries.find((entry) => entry.value === coding);
|
|
759
843
|
if (named !== void 0) return named.q;
|
|
760
844
|
return entries.find((entry) => entry.value === "*")?.q ?? 0;
|
|
761
845
|
}
|
|
762
846
|
/**
|
|
763
|
-
*
|
|
764
|
-
*
|
|
847
|
+
* Picks the highest-scoring content-coding the server offers against already
|
|
848
|
+
* parsed `Accept-Encoding` entries — the shared selection leaf behind
|
|
849
|
+
* {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
|
|
765
850
|
*
|
|
766
851
|
* @remarks
|
|
767
|
-
*
|
|
768
|
-
*
|
|
769
|
-
*
|
|
770
|
-
*
|
|
771
|
-
*
|
|
852
|
+
* The single selection leaf behind both doors onto this axis —
|
|
853
|
+
* {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
|
|
854
|
+
* entity — so the scoring loop has one implementation. Scores each `available`
|
|
855
|
+
* coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
|
|
856
|
+
* keeps the earlier-offered coding on a client-side tie, which is what makes
|
|
857
|
+
* `available` the server's preference order. An empty `available` list, and a
|
|
858
|
+
* list the client rejects outright, both yield `undefined` (identity — no
|
|
859
|
+
* compression). Total on hostile input.
|
|
772
860
|
*
|
|
773
861
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
774
|
-
* @param
|
|
862
|
+
* @param entries - The parsed {@link AcceptEntry} list
|
|
775
863
|
* @param available - The codings the server offers, in preference (tie-break) order
|
|
776
|
-
* @returns The
|
|
864
|
+
* @returns The winning coding, or `undefined` when none of `available` is acceptable
|
|
777
865
|
*
|
|
778
866
|
* @example
|
|
779
867
|
* ```ts
|
|
780
|
-
*
|
|
868
|
+
* resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
|
|
869
|
+
* resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
|
|
781
870
|
* ```
|
|
782
871
|
*/
|
|
783
|
-
function
|
|
784
|
-
if (available.length === 0) return void 0;
|
|
785
|
-
const entries = parseAcceptHeader(header);
|
|
872
|
+
function resolveCoding(entries, available) {
|
|
786
873
|
let best;
|
|
787
874
|
let bestQuality = 0;
|
|
788
875
|
for (const coding of available) {
|
|
789
|
-
const quality =
|
|
876
|
+
const quality = computeCodingQuality(entries, coding);
|
|
790
877
|
if (quality > bestQuality) {
|
|
791
878
|
best = coding;
|
|
792
879
|
bestQuality = quality;
|
|
@@ -795,7 +882,32 @@ function negotiateEncoding(header, available) {
|
|
|
795
882
|
return best;
|
|
796
883
|
}
|
|
797
884
|
/**
|
|
798
|
-
*
|
|
885
|
+
* Selects the best content-coding for a raw `Accept-Encoding` header from the
|
|
886
|
+
* codings the server offers.
|
|
887
|
+
*
|
|
888
|
+
* @remarks
|
|
889
|
+
* Parses the header ({@link parseAcceptHeader}) and hands the entries to
|
|
890
|
+
* {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
|
|
891
|
+
* the two doors onto this axis cannot drift. Returns `undefined` when the
|
|
892
|
+
* client accepts none of `available` (identity — no compression). Total on
|
|
893
|
+
* hostile input.
|
|
894
|
+
*
|
|
895
|
+
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
896
|
+
* @param header - The raw `Accept-Encoding` header value
|
|
897
|
+
* @param available - The codings the server offers, in preference (tie-break) order
|
|
898
|
+
* @returns The negotiated coding, or `undefined` when none of `available` is acceptable
|
|
899
|
+
*
|
|
900
|
+
* @example
|
|
901
|
+
* ```ts
|
|
902
|
+
* negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
|
|
903
|
+
* ```
|
|
904
|
+
*/
|
|
905
|
+
function negotiateEncoding(header, available) {
|
|
906
|
+
if (available.length === 0) return void 0;
|
|
907
|
+
return resolveCoding(parseAcceptHeader(header), available);
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Reports the rank and quality of one `candidate` media type against the parsed `Accept`
|
|
799
911
|
* entries — the generic media-type primitive the `Negotiator`'s `negotiate`
|
|
800
912
|
* uses to score each `available` candidate.
|
|
801
913
|
*
|
|
@@ -809,8 +921,8 @@ function negotiateEncoding(header, available) {
|
|
|
809
921
|
* rank tie the highest `q` wins.
|
|
810
922
|
*
|
|
811
923
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
812
|
-
* @param candidate - The candidate media type to score (
|
|
813
|
-
* @returns The
|
|
924
|
+
* @param candidate - The candidate media type to score (for example `'text/html'`)
|
|
925
|
+
* @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
|
|
814
926
|
*
|
|
815
927
|
* @example
|
|
816
928
|
* ```ts
|
|
@@ -842,8 +954,9 @@ function matchMediaType(entries, candidate) {
|
|
|
842
954
|
return best;
|
|
843
955
|
}
|
|
844
956
|
/**
|
|
845
|
-
*
|
|
846
|
-
* `Accept-Language` entries —
|
|
957
|
+
* Computes the client's quality for one `candidate` language from the parsed
|
|
958
|
+
* `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
|
|
959
|
+
* axis runs over each offered tag.
|
|
847
960
|
*
|
|
848
961
|
* @remarks
|
|
849
962
|
* Prefers an exact match, then a primary-tag prefix match (`en` accepts
|
|
@@ -851,17 +964,17 @@ function matchMediaType(entries, candidate) {
|
|
|
851
964
|
* is an explicit rejection).
|
|
852
965
|
*
|
|
853
966
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
854
|
-
* @param candidate - The candidate language tag to score (
|
|
967
|
+
* @param candidate - The candidate language tag to score (for example `'en-US'`)
|
|
855
968
|
* @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
|
|
856
969
|
*
|
|
857
970
|
* @example
|
|
858
971
|
* ```ts
|
|
859
|
-
*
|
|
860
|
-
*
|
|
861
|
-
*
|
|
972
|
+
* computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
|
|
973
|
+
* computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
|
|
974
|
+
* computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
|
|
862
975
|
* ```
|
|
863
976
|
*/
|
|
864
|
-
function
|
|
977
|
+
function computeLanguageQuality(entries, candidate) {
|
|
865
978
|
const lower = candidate.toLowerCase();
|
|
866
979
|
const primary = lower.split("-")[0];
|
|
867
980
|
let named;
|
|
@@ -879,17 +992,17 @@ function languageQuality(entries, candidate) {
|
|
|
879
992
|
return wildcard ?? 0;
|
|
880
993
|
}
|
|
881
994
|
/**
|
|
882
|
-
*
|
|
995
|
+
* Checks whether a `Content-Type` is worth compressing.
|
|
883
996
|
*
|
|
884
997
|
* @remarks
|
|
885
998
|
* Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
|
|
886
999
|
* type, a `+json`/`+xml` structured suffix, or one of the explicit
|
|
887
1000
|
* {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
|
|
888
|
-
* binary (`image/png`, `application/zip`) is
|
|
889
|
-
* absent/empty type is not compressible.
|
|
1001
|
+
* binary (`image/png`, `application/zip`) is not compressible. An
|
|
1002
|
+
* absent/empty type is not compressible. Total.
|
|
890
1003
|
*
|
|
891
1004
|
* @param type - The response `Content-Type` header value (with or without parameters)
|
|
892
|
-
* @returns
|
|
1005
|
+
* @returns True if the type is text-shaped and worth compressing; false otherwise
|
|
893
1006
|
*
|
|
894
1007
|
* @example
|
|
895
1008
|
* ```ts
|
|
@@ -906,17 +1019,18 @@ function isCompressibleType(type) {
|
|
|
906
1019
|
return COMPRESSIBLE_TYPES.has(bare);
|
|
907
1020
|
}
|
|
908
1021
|
/**
|
|
909
|
-
*
|
|
1022
|
+
* Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
|
|
910
1023
|
*
|
|
911
1024
|
* @remarks
|
|
912
1025
|
* Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
|
|
913
|
-
* digest as a
|
|
914
|
-
* default, encoding-
|
|
915
|
-
* 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
|
|
916
1029
|
* (`"<hash>"`, byte-identity) when `weak` is `false`.
|
|
917
1030
|
*
|
|
918
1031
|
* @param body - The full (uncompressed) response body to hash
|
|
919
|
-
* @param weak - `true`
|
|
1032
|
+
* @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
|
|
1033
|
+
* `false`, returns a strong `"…"` one.
|
|
920
1034
|
* @returns The `ETag` header value
|
|
921
1035
|
*
|
|
922
1036
|
* @example
|
|
@@ -926,12 +1040,12 @@ function isCompressibleType(type) {
|
|
|
926
1040
|
*/
|
|
927
1041
|
async function computeBodyETag(body, weak = true) {
|
|
928
1042
|
const digest = await crypto.subtle.digest("SHA-256", body);
|
|
929
|
-
const hex =
|
|
1043
|
+
const hex = encodeHex(new Uint8Array(digest));
|
|
930
1044
|
return weak ? `W/"${hex}"` : `"${hex}"`;
|
|
931
1045
|
}
|
|
932
1046
|
/**
|
|
933
|
-
*
|
|
934
|
-
* 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
|
|
935
1049
|
* before the RFC 7232 §2.3.2 weak comparison.
|
|
936
1050
|
*
|
|
937
1051
|
* @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
|
|
@@ -947,20 +1061,20 @@ function unwrapETag(tag) {
|
|
|
947
1061
|
return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
|
|
948
1062
|
}
|
|
949
1063
|
/**
|
|
950
|
-
*
|
|
951
|
-
* `ETag` — the RFC 7232 §2.3.2
|
|
1064
|
+
* Checks whether a request's `If-None-Match` header matches a resource's current
|
|
1065
|
+
* `ETag` — the RFC 7232 §2.3.2 weak comparison.
|
|
952
1066
|
*
|
|
953
1067
|
* @remarks
|
|
954
|
-
* `If-None-Match` is a
|
|
955
|
-
* 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
|
|
956
1070
|
* representation — only a list of exactly `*` is the wildcard). Comparison is
|
|
957
|
-
*
|
|
958
|
-
*
|
|
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
|
|
959
1073
|
* malformed/empty header matches nothing, never throws.
|
|
960
1074
|
*
|
|
961
1075
|
* @param header - The raw `If-None-Match` header value
|
|
962
1076
|
* @param etag - The resource's current `ETag`
|
|
963
|
-
* @returns
|
|
1077
|
+
* @returns True if the conditional matches (the caller answers `304`); false otherwise
|
|
964
1078
|
*
|
|
965
1079
|
* @example
|
|
966
1080
|
* ```ts
|
|
@@ -980,18 +1094,18 @@ function matchesETag(header, etag) {
|
|
|
980
1094
|
return false;
|
|
981
1095
|
}
|
|
982
1096
|
/**
|
|
983
|
-
*
|
|
984
|
-
*
|
|
1097
|
+
* Parses an HTTP `Range` request header against a known resource `size` —
|
|
1098
|
+
* total, returning a {@link RangeSpec} or `undefined`.
|
|
985
1099
|
*
|
|
986
1100
|
* @remarks
|
|
987
1101
|
* Handles the three single-range `bytes=` forms — closed (`start-end`), open
|
|
988
1102
|
* (`start-`), and suffix (`-suffixLength`) — clamping the window to
|
|
989
|
-
* `[0, size - 1]` (the HTTP
|
|
1103
|
+
* `[0, size - 1]` (the HTTP inclusive-end convention). Returns
|
|
990
1104
|
* `{ satisfiable: true, start, end }` for an overlapping range,
|
|
991
1105
|
* `{ satisfiable: false }` for a range wholly past the resource, and
|
|
992
|
-
* `undefined` for the "serve the whole resource" case: an
|
|
993
|
-
* non-`bytes` unit, a
|
|
994
|
-
* 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
|
|
995
1109
|
* header.
|
|
996
1110
|
*
|
|
997
1111
|
* @param header - The raw `Range` header value
|
|
@@ -1043,14 +1157,14 @@ function parseRange(header, size) {
|
|
|
1043
1157
|
};
|
|
1044
1158
|
}
|
|
1045
1159
|
/**
|
|
1046
|
-
*
|
|
1160
|
+
* Resolves the `Access-Control-Allow-Origin` value for a request.
|
|
1047
1161
|
*
|
|
1048
1162
|
* @remarks
|
|
1049
1163
|
* `'*'` and a single origin string pass straight through. An allow-list
|
|
1050
1164
|
* echoes the request's `Origin` only when it is present in the list, else
|
|
1051
|
-
* `undefined` (no header set).
|
|
1165
|
+
* `undefined` (no header set). Security: the literal `'null'` origin — sent
|
|
1052
1166
|
* by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
|
|
1053
|
-
*
|
|
1167
|
+
* never reflected even if `'null'` were listed, closing the hostile-context
|
|
1054
1168
|
* cross-origin-access hole.
|
|
1055
1169
|
*
|
|
1056
1170
|
* @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
|
|
@@ -1070,7 +1184,7 @@ function resolveOrigin(origin, requestOrigin) {
|
|
|
1070
1184
|
return origin.includes(requestOrigin) ? requestOrigin : void 0;
|
|
1071
1185
|
}
|
|
1072
1186
|
/**
|
|
1073
|
-
*
|
|
1187
|
+
* Merges a `Vary` value into an existing `Vary` header without duplication.
|
|
1074
1188
|
*
|
|
1075
1189
|
* @remarks
|
|
1076
1190
|
* Splits `existing` on `,`, trims each member, and appends `value` only when
|
|
@@ -1094,11 +1208,11 @@ function mergeVary(existing, value) {
|
|
|
1094
1208
|
return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
|
|
1095
1209
|
}
|
|
1096
1210
|
/**
|
|
1097
|
-
*
|
|
1211
|
+
* Resolves one opt-out, value-bearing security header.
|
|
1098
1212
|
*
|
|
1099
1213
|
* @remarks
|
|
1100
1214
|
* The shared "a `string` value, or `false` to omit, or a default when unset"
|
|
1101
|
-
* resolution (
|
|
1215
|
+
* resolution (a value-or-off union, not a behavioral toggle):
|
|
1102
1216
|
* `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
|
|
1103
1217
|
* override, `undefined` (unset) ⇒ `fallback` (the secure default).
|
|
1104
1218
|
*
|
|
@@ -1118,18 +1232,18 @@ function resolveSecurityHeader(value, fallback) {
|
|
|
1118
1232
|
return value ?? fallback;
|
|
1119
1233
|
}
|
|
1120
1234
|
/**
|
|
1121
|
-
*
|
|
1122
|
-
* header
|
|
1235
|
+
* Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
|
|
1236
|
+
* header and `context.state`.
|
|
1123
1237
|
*
|
|
1124
1238
|
* @remarks
|
|
1125
|
-
* A request id is echoed
|
|
1239
|
+
* A request id is echoed raw into a response header and log lines, so an
|
|
1126
1240
|
* untrusted one is a header-injection + log-injection + DoS vector. This
|
|
1127
1241
|
* refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
|
|
1128
1242
|
* (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
|
|
1129
|
-
*
|
|
1243
|
+
* Total — never throws.
|
|
1130
1244
|
*
|
|
1131
1245
|
* @param value - The candidate incoming request id
|
|
1132
|
-
* @returns
|
|
1246
|
+
* @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
|
|
1133
1247
|
*
|
|
1134
1248
|
* @example
|
|
1135
1249
|
* ```ts
|
|
@@ -1141,14 +1255,14 @@ function isValidRequestId(value) {
|
|
|
1141
1255
|
return REQUEST_ID_PATTERN.test(value);
|
|
1142
1256
|
}
|
|
1143
1257
|
/**
|
|
1144
|
-
*
|
|
1258
|
+
* Computes the `/64` network of a full IPv6 address, or `undefined` when the
|
|
1145
1259
|
* input is not a plain IPv6 address to collapse.
|
|
1146
1260
|
*
|
|
1147
1261
|
* @remarks
|
|
1148
1262
|
* Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
|
|
1149
1263
|
* is the identity) or any string that does not expand to exactly eight
|
|
1150
1264
|
* hextets. Expands a single `::` into the missing zero hextets, takes the
|
|
1151
|
-
* first
|
|
1265
|
+
* first four (the `/64` prefix), normalizes each (lower-case, no leading
|
|
1152
1266
|
* zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
|
|
1153
1267
|
* first. Total — a malformed address returns `undefined`.
|
|
1154
1268
|
*
|
|
@@ -1157,11 +1271,11 @@ function isValidRequestId(value) {
|
|
|
1157
1271
|
*
|
|
1158
1272
|
* @example
|
|
1159
1273
|
* ```ts
|
|
1160
|
-
*
|
|
1161
|
-
*
|
|
1274
|
+
* computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
|
|
1275
|
+
* computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
|
|
1162
1276
|
* ```
|
|
1163
1277
|
*/
|
|
1164
|
-
function
|
|
1278
|
+
function computeIPv6Network(address) {
|
|
1165
1279
|
if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
|
|
1166
1280
|
const percent = address.indexOf("%");
|
|
1167
1281
|
const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
|
|
@@ -1191,33 +1305,33 @@ function ipv6Network(address) {
|
|
|
1191
1305
|
return `${prefix.join(":")}::/64`;
|
|
1192
1306
|
}
|
|
1193
1307
|
/**
|
|
1194
|
-
*
|
|
1308
|
+
* Collapses a client IP into its rate-limit bucket key — an IPv6 address to
|
|
1195
1309
|
* its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
|
|
1196
1310
|
*
|
|
1197
1311
|
* @remarks
|
|
1198
|
-
* A residential/mobile IPv6 user is routinely handed a
|
|
1312
|
+
* A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
|
|
1199
1313
|
* per-`/128` rate limit is trivially bypassed by rotating host bits — the
|
|
1200
1314
|
* real identity is the `/64` network. Delegates the IPv6 collapse to
|
|
1201
|
-
* {@link
|
|
1315
|
+
* {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
|
|
1202
1316
|
* a malformed string) is kept unchanged.
|
|
1203
1317
|
*
|
|
1204
|
-
* @param address - The raw connection peer address ({@link import('./types.js').
|
|
1318
|
+
* @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
|
|
1205
1319
|
* @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
|
|
1206
1320
|
*
|
|
1207
1321
|
* @example
|
|
1208
1322
|
* ```ts
|
|
1209
|
-
*
|
|
1210
|
-
*
|
|
1323
|
+
* computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
|
|
1324
|
+
* computeClientKey('192.0.2.1') // '192.0.2.1'
|
|
1211
1325
|
* ```
|
|
1212
1326
|
*/
|
|
1213
|
-
function
|
|
1214
|
-
return
|
|
1327
|
+
function computeClientKey(address) {
|
|
1328
|
+
return computeIPv6Network(address) ?? address;
|
|
1215
1329
|
}
|
|
1216
1330
|
/**
|
|
1217
|
-
*
|
|
1331
|
+
* Serializes one {@link SSEMessage} to the SSE wire.
|
|
1218
1332
|
*
|
|
1219
1333
|
* @remarks
|
|
1220
|
-
* Emits an `event:`/`id:`/`retry:` line for each present field, then
|
|
1334
|
+
* Emits an `event:`/`id:`/`retry:` line for each present field, then one
|
|
1221
1335
|
* `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
|
|
1222
1336
|
* (so a consuming parser's multi-`data` concat reproduces the original
|
|
1223
1337
|
* `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
|
|
@@ -1241,129 +1355,12 @@ function serializeEvent(message) {
|
|
|
1241
1355
|
return `${lines.join("\n")}\n\n`;
|
|
1242
1356
|
}
|
|
1243
1357
|
/**
|
|
1244
|
-
*
|
|
1245
|
-
*
|
|
1246
|
-
*
|
|
1247
|
-
* @param encoder - The encoder used for the stream's byte representation
|
|
1248
|
-
* @param closed - Whether the stream has already ended or been cancelled
|
|
1249
|
-
* @param text - The text to encode and enqueue
|
|
1250
|
-
* @returns Nothing
|
|
1251
|
-
*
|
|
1252
|
-
* @example
|
|
1253
|
-
* ```ts
|
|
1254
|
-
* const body = new ReadableStream<Uint8Array>({
|
|
1255
|
-
* start(controller) {
|
|
1256
|
-
* enqueueStreamText(controller, new TextEncoder(), false, 'hello')
|
|
1257
|
-
* },
|
|
1258
|
-
* })
|
|
1259
|
-
* ```
|
|
1260
|
-
*/
|
|
1261
|
-
function enqueueStreamText(controller, encoder, closed, text) {
|
|
1262
|
-
if (closed || controller === void 0) return;
|
|
1263
|
-
controller.enqueue(encoder.encode(text));
|
|
1264
|
-
}
|
|
1265
|
-
/**
|
|
1266
|
-
* Open a generic Server-Sent-Events stream — a fetch-standard `Response`
|
|
1267
|
-
* whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
|
|
1268
|
-
*
|
|
1269
|
-
* @remarks
|
|
1270
|
-
* Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
|
|
1271
|
-
* merged under any `options.headers` (a seam-owned key is never overridden),
|
|
1272
|
-
* at `options.status` (default `200`). The returned {@link StreamInterface}'s
|
|
1273
|
-
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
1274
|
-
* returns whether the controller still has positive desired size. A producer
|
|
1275
|
-
* receiving `false` can await `drain()`; its event-driven promise resolves on
|
|
1276
|
-
* the next consumer pull that restores capacity, or on stream closure.
|
|
1277
|
-
* `comment` writes a `: text` keep-alive line a conforming parser ignores;
|
|
1278
|
-
* `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
|
|
1279
|
-
* by `end()`, or the consumer cancelled the stream), so a late write never
|
|
1280
|
-
* throws.
|
|
1281
|
-
*
|
|
1282
|
-
* This readiness reflects only the process-local `ReadableStream` queue — it
|
|
1283
|
-
* is not proof that a remote peer consumed bytes. When the response pump
|
|
1284
|
-
* honors its socket sink's drain state, socket pressure stops body pulls and
|
|
1285
|
-
* therefore keeps this queue full, allowing a cooperative producer to bound
|
|
1286
|
-
* buffering. Ignoring the return value preserves the prior unconditional-
|
|
1287
|
-
* enqueue behavior. The default stream strategy counts chunks rather than
|
|
1288
|
-
* their byte length, so a byte-bounded producer must also cap each message.
|
|
1289
|
-
* Return `response` before awaiting a `false` write, because the consumer
|
|
1290
|
-
* cannot pull until it receives the response.
|
|
1291
|
-
*
|
|
1292
|
-
* @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
|
|
1293
|
-
* @returns The {@link StreamInterface} handle
|
|
1294
|
-
*
|
|
1295
|
-
* @example
|
|
1296
|
-
* ```ts
|
|
1297
|
-
* const stream = openStream()
|
|
1298
|
-
* void Promise.resolve().then(async () => {
|
|
1299
|
-
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
1300
|
-
* stream.end()
|
|
1301
|
-
* })
|
|
1302
|
-
* // return stream.response from the route handler
|
|
1303
|
-
* ```
|
|
1304
|
-
*/
|
|
1305
|
-
function openStream(options) {
|
|
1306
|
-
const encoder = new TextEncoder();
|
|
1307
|
-
let closed = false;
|
|
1308
|
-
let controller;
|
|
1309
|
-
let wakeup;
|
|
1310
|
-
const body = new ReadableStream({
|
|
1311
|
-
start(streamController) {
|
|
1312
|
-
controller = streamController;
|
|
1313
|
-
},
|
|
1314
|
-
pull(streamController) {
|
|
1315
|
-
if (streamController.desiredSize === null || streamController.desiredSize <= 0) return;
|
|
1316
|
-
wakeup?.resolve();
|
|
1317
|
-
wakeup = void 0;
|
|
1318
|
-
},
|
|
1319
|
-
cancel() {
|
|
1320
|
-
closed = true;
|
|
1321
|
-
wakeup?.resolve();
|
|
1322
|
-
wakeup = void 0;
|
|
1323
|
-
}
|
|
1324
|
-
});
|
|
1325
|
-
const headers = new Headers({
|
|
1326
|
-
...SSE_HEADERS,
|
|
1327
|
-
...options?.headers
|
|
1328
|
-
});
|
|
1329
|
-
return {
|
|
1330
|
-
response: new Response(body, {
|
|
1331
|
-
status: options?.status ?? 200,
|
|
1332
|
-
headers
|
|
1333
|
-
}),
|
|
1334
|
-
get closed() {
|
|
1335
|
-
return closed;
|
|
1336
|
-
},
|
|
1337
|
-
write(message) {
|
|
1338
|
-
if (closed || controller === void 0) return false;
|
|
1339
|
-
enqueueStreamText(controller, encoder, closed, serializeEvent(message));
|
|
1340
|
-
return controller.desiredSize !== null && controller.desiredSize > 0;
|
|
1341
|
-
},
|
|
1342
|
-
comment(text) {
|
|
1343
|
-
enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
|
|
1344
|
-
},
|
|
1345
|
-
drain() {
|
|
1346
|
-
const desired = controller?.desiredSize;
|
|
1347
|
-
if (closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
|
|
1348
|
-
wakeup ??= Promise.withResolvers();
|
|
1349
|
-
return wakeup.promise;
|
|
1350
|
-
},
|
|
1351
|
-
end() {
|
|
1352
|
-
if (closed) return;
|
|
1353
|
-
closed = true;
|
|
1354
|
-
controller?.close();
|
|
1355
|
-
wakeup?.resolve();
|
|
1356
|
-
wakeup = void 0;
|
|
1357
|
-
}
|
|
1358
|
-
};
|
|
1359
|
-
}
|
|
1360
|
-
/**
|
|
1361
|
-
* Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
|
|
1362
|
-
* or `prototype` — the three keys that, assigned onto a normal object, can
|
|
1363
|
-
* reach and mutate `Object.prototype`.
|
|
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.
|
|
1364
1361
|
*
|
|
1365
1362
|
* @param key - The candidate object key
|
|
1366
|
-
* @returns
|
|
1363
|
+
* @returns True if `key` is one of the three prototype-pollution keys; false otherwise
|
|
1367
1364
|
*
|
|
1368
1365
|
* @example
|
|
1369
1366
|
* ```ts
|
|
@@ -1375,12 +1372,11 @@ function isDangerousKey(key) {
|
|
|
1375
1372
|
return key === "__proto__" || key === "constructor" || key === "prototype";
|
|
1376
1373
|
}
|
|
1377
1374
|
/**
|
|
1378
|
-
*
|
|
1379
|
-
* PLACE.
|
|
1375
|
+
* Strips the prototype-pollution keys from a parsed value in place, recursively.
|
|
1380
1376
|
*
|
|
1381
1377
|
* @remarks
|
|
1382
|
-
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an
|
|
1383
|
-
* 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
|
|
1384
1380
|
* pollution gadget the moment a downstream deep-merge copies it onto a live
|
|
1385
1381
|
* object. This walks the value and `delete`s any own {@link isDangerousKey}
|
|
1386
1382
|
* key at every depth, recursing into nested objects + array elements.
|
|
@@ -1398,7 +1394,7 @@ function isDangerousKey(key) {
|
|
|
1398
1394
|
*/
|
|
1399
1395
|
function scrubPrototype(value) {
|
|
1400
1396
|
if (Array.isArray(value)) {
|
|
1401
|
-
for (const
|
|
1397
|
+
for (const member of value) scrubPrototype(member);
|
|
1402
1398
|
return value;
|
|
1403
1399
|
}
|
|
1404
1400
|
if (isRecord(value)) {
|
|
@@ -1414,12 +1410,12 @@ function scrubPrototype(value) {
|
|
|
1414
1410
|
return value;
|
|
1415
1411
|
}
|
|
1416
1412
|
/**
|
|
1417
|
-
*
|
|
1413
|
+
* Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
|
|
1418
1414
|
*
|
|
1419
1415
|
* @remarks
|
|
1420
1416
|
* Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
|
|
1421
1417
|
* throwing a {@link ContentTooLargeError} (413) the instant the running total
|
|
1422
|
-
* exceeds `limit` —
|
|
1418
|
+
* exceeds `limit` — before the rest of the stream is buffered — rather than
|
|
1423
1419
|
* collecting an unbounded body. A bodyless request (`request.body === null`)
|
|
1424
1420
|
* resolves an empty array. A non-positive `limit` means unbounded.
|
|
1425
1421
|
*
|
|
@@ -1457,41 +1453,41 @@ async function collectRequestBody(request, limit) {
|
|
|
1457
1453
|
return merged;
|
|
1458
1454
|
}
|
|
1459
1455
|
/**
|
|
1460
|
-
*
|
|
1461
|
-
* {@link Encoding} — the boundary
|
|
1456
|
+
* Parses a raw `Content-Encoding` header value into a decompressible
|
|
1457
|
+
* {@link Encoding} — the boundary {@link readBody} coerces through to decide
|
|
1462
1458
|
* whether a request body needs transparent decompression.
|
|
1463
1459
|
*
|
|
1464
1460
|
* @remarks
|
|
1465
|
-
* Lower-cases + trims and returns the matching {@link Encoding}
|
|
1466
|
-
* `gzip` / `deflate` (the two `DecompressionStream`-supported codings
|
|
1467
|
-
*
|
|
1461
|
+
* Lower-cases + trims and returns the matching {@link Encoding} only for
|
|
1462
|
+
* `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
|
|
1463
|
+
* absent header, `identity`, an unknown value, or a
|
|
1468
1464
|
* comma-joined multi-coding all yield `undefined` (the body is read as-is).
|
|
1469
|
-
*
|
|
1465
|
+
* Total — never asserts the loose `string | null` header.
|
|
1470
1466
|
*
|
|
1471
1467
|
* @param header - The raw `Content-Encoding` header value
|
|
1472
1468
|
* @returns The single decompressible {@link Encoding}, or `undefined` when none applies
|
|
1473
1469
|
*
|
|
1474
1470
|
* @example
|
|
1475
1471
|
* ```ts
|
|
1476
|
-
*
|
|
1477
|
-
*
|
|
1472
|
+
* parseEncoding('gzip') // 'gzip'
|
|
1473
|
+
* parseEncoding('br') // undefined — unsupported by DecompressionStream
|
|
1478
1474
|
* ```
|
|
1479
1475
|
*/
|
|
1480
|
-
function
|
|
1476
|
+
function parseEncoding(header) {
|
|
1481
1477
|
if (!isString(header)) return void 0;
|
|
1482
1478
|
const value = header.trim().toLowerCase();
|
|
1483
1479
|
return value === "gzip" || value === "deflate" ? value : void 0;
|
|
1484
1480
|
}
|
|
1485
1481
|
/**
|
|
1486
|
-
*
|
|
1487
|
-
*
|
|
1482
|
+
* Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
|
|
1483
|
+
* transparently through `DecompressionStream`, capping the decompressed output —
|
|
1488
1484
|
* the zip-bomb defense.
|
|
1489
1485
|
*
|
|
1490
1486
|
* @remarks
|
|
1491
1487
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
1492
|
-
* `TransformStream` that
|
|
1488
|
+
* `TransformStream` that aborts the pipe the instant the running decompressed
|
|
1493
1489
|
* total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
|
|
1494
|
-
* has no `maxOutputLength` knob
|
|
1490
|
+
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
1495
1491
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
1496
1492
|
* compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
|
|
1497
1493
|
* (never conflated with the cap). A non-positive `cap` means uncapped.
|
|
@@ -1539,9 +1535,10 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1539
1535
|
return merged;
|
|
1540
1536
|
}
|
|
1541
1537
|
/**
|
|
1542
|
-
*
|
|
1538
|
+
* Collects and decodes a `Request` body — the shared body-collection pipeline
|
|
1543
1539
|
* surfaced to middleware and handlers as the middleware context's cached
|
|
1544
|
-
* `body()`.
|
|
1540
|
+
* `body()`. An empty body and a malformed `application/json` body each decode to
|
|
1541
|
+
* `undefined`.
|
|
1545
1542
|
*
|
|
1546
1543
|
* @remarks
|
|
1547
1544
|
* Collects the wire body capped at `options.limit` bytes ({@link
|
|
@@ -1550,14 +1547,18 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1550
1547
|
* through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
|
|
1551
1548
|
* `options.decompression`, default {@link
|
|
1552
1549
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1553
|
-
* content type: `application/json` is parsed
|
|
1550
|
+
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1554
1551
|
* `parseJSON` and scrubbed of prototype-pollution keys ({@link
|
|
1555
|
-
* scrubPrototype}); any other type decodes as UTF-8 text
|
|
1556
|
-
*
|
|
1552
|
+
* scrubPrototype}); any other type decodes as UTF-8 text.
|
|
1553
|
+
*
|
|
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.
|
|
1557
1557
|
*
|
|
1558
1558
|
* @param request - The `Request` to read the body from
|
|
1559
1559
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
1560
|
-
* @returns The parsed JSON value, the raw text, or `undefined` for an empty
|
|
1560
|
+
* @returns The parsed JSON value, the raw text, or `undefined` — for an empty
|
|
1561
|
+
* body, and for an `application/json` body whose text is not valid JSON
|
|
1561
1562
|
* @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
|
|
1562
1563
|
* @throws {HTTPError} When the compressed body is corrupt (400)
|
|
1563
1564
|
*
|
|
@@ -1570,7 +1571,7 @@ async function readBody(request, options) {
|
|
|
1570
1571
|
const limit = options?.limit ?? 1048576;
|
|
1571
1572
|
const decompression = options?.decompression ?? 16777216;
|
|
1572
1573
|
const wire = await collectRequestBody(request, limit);
|
|
1573
|
-
const encoding =
|
|
1574
|
+
const encoding = parseEncoding(request.headers.get("content-encoding"));
|
|
1574
1575
|
const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
|
|
1575
1576
|
if (bytes.length === 0) return void 0;
|
|
1576
1577
|
const contentType = request.headers.get("content-type");
|
|
@@ -1581,30 +1582,17 @@ async function readBody(request, options) {
|
|
|
1581
1582
|
return text;
|
|
1582
1583
|
}
|
|
1583
1584
|
/**
|
|
1584
|
-
*
|
|
1585
|
-
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
1586
|
-
* or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
|
|
1587
|
-
* and the `Server`'s own port resolution read the bound port through.
|
|
1588
|
-
*
|
|
1589
|
-
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
1590
|
-
* @returns `true` when `value` is an `AddressInfo` with a numeric `port`
|
|
1591
|
-
*
|
|
1592
|
-
* @example
|
|
1593
|
-
* ```ts
|
|
1594
|
-
* import { isAddressInfo } from '@src/server'
|
|
1585
|
+
* Binds and closes a throwaway TCP server to resolve one available port.
|
|
1595
1586
|
*
|
|
1596
|
-
*
|
|
1597
|
-
*
|
|
1598
|
-
*
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
return isRecord(value) && isNumber(value.port);
|
|
1602
|
-
}
|
|
1603
|
-
/**
|
|
1604
|
-
* Bind and close a throwaway TCP server to resolve one available port.
|
|
1587
|
+
* @remarks
|
|
1588
|
+
* The probe always closes, including on the rejection path. A listener whose
|
|
1589
|
+
* address is not an {@link import('node:net').AddressInfo} — a pipe listener,
|
|
1590
|
+
* which a numeric `port` cannot request — has no port to report, so this
|
|
1591
|
+
* rejects rather than substituting a number.
|
|
1605
1592
|
*
|
|
1606
1593
|
* @param port - The requested port, with `0` selecting an ephemeral port
|
|
1607
1594
|
* @returns The bound port after the probe server has closed
|
|
1595
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
1608
1596
|
*
|
|
1609
1597
|
* @example
|
|
1610
1598
|
* ```ts
|
|
@@ -1617,29 +1605,35 @@ async function probePort(port) {
|
|
|
1617
1605
|
probe.listen(port);
|
|
1618
1606
|
await listening;
|
|
1619
1607
|
const address = probe.address();
|
|
1620
|
-
const resolved = isAddressInfo(address) ? address.port : 0;
|
|
1621
1608
|
const closed = once(probe, "close");
|
|
1622
1609
|
probe.close();
|
|
1623
1610
|
await closed;
|
|
1624
|
-
|
|
1611
|
+
if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
|
|
1612
|
+
return address.port;
|
|
1625
1613
|
}
|
|
1626
1614
|
/**
|
|
1627
|
-
*
|
|
1628
|
-
*
|
|
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.
|
|
1629
1618
|
*
|
|
1630
1619
|
* @remarks
|
|
1631
1620
|
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
1632
|
-
* and returns it. With a `preferred` port it tries
|
|
1633
|
-
* 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
|
|
1634
1623
|
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
1635
1624
|
* port. It binds then immediately closes a probe server, so the returned
|
|
1636
1625
|
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
1637
1626
|
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
1638
|
-
* `preferred` port (
|
|
1627
|
+
* `preferred` port (for example, a permission fault). A listener whose address is not
|
|
1628
|
+
* an {@link import('node:net').AddressInfo} — a pipe listener, which this
|
|
1629
|
+
* package's options cannot request — rejects with a `TypeError` rather than
|
|
1630
|
+
* reporting `0`, because `0` is this package's own request for an ephemeral
|
|
1631
|
+
* port and never means an unknown one.
|
|
1639
1632
|
*
|
|
1640
1633
|
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
1641
1634
|
* fall back to an ephemeral port
|
|
1642
1635
|
* @returns A free TCP port number
|
|
1636
|
+
* @throws {TypeError} When the bound listener's address carries no numeric port
|
|
1643
1637
|
*
|
|
1644
1638
|
* @example
|
|
1645
1639
|
* ```ts
|
|
@@ -1660,14 +1654,14 @@ async function discoverPort(preferred) {
|
|
|
1660
1654
|
//#endregion
|
|
1661
1655
|
//#region src/server/Negotiator.ts
|
|
1662
1656
|
/**
|
|
1663
|
-
*
|
|
1664
|
-
* reusable, cross-middleware
|
|
1657
|
+
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
1658
|
+
* reusable, cross-middleware entity rather than a middleware. Implements exactly
|
|
1665
1659
|
* {@link NegotiatorInterface}.
|
|
1666
1660
|
*
|
|
1667
1661
|
* @remarks
|
|
1668
1662
|
* `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
|
|
1669
1663
|
* any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
|
|
1670
|
-
* sibling axes and
|
|
1664
|
+
* sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
|
|
1671
1665
|
* rest of the substrate uses — one parser, never two. `format` reads the
|
|
1672
1666
|
* request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
|
|
1673
1667
|
* the winner — or answers `406 Not Acceptable`.
|
|
@@ -1700,7 +1694,8 @@ var Negotiator = class {
|
|
|
1700
1694
|
return best;
|
|
1701
1695
|
}
|
|
1702
1696
|
encoding(header, available) {
|
|
1703
|
-
|
|
1697
|
+
if (available.length === 0) return void 0;
|
|
1698
|
+
return resolveCoding(parseAcceptHeader(header), available);
|
|
1704
1699
|
}
|
|
1705
1700
|
language(header, available) {
|
|
1706
1701
|
if (available.length === 0) return void 0;
|
|
@@ -1709,7 +1704,7 @@ var Negotiator = class {
|
|
|
1709
1704
|
let best;
|
|
1710
1705
|
let bestQuality = 0;
|
|
1711
1706
|
for (const candidate of available) {
|
|
1712
|
-
const quality =
|
|
1707
|
+
const quality = computeLanguageQuality(entries, candidate);
|
|
1713
1708
|
if (quality > bestQuality) {
|
|
1714
1709
|
best = candidate;
|
|
1715
1710
|
bestQuality = quality;
|
|
@@ -1718,8 +1713,11 @@ var Negotiator = class {
|
|
|
1718
1713
|
return best;
|
|
1719
1714
|
}
|
|
1720
1715
|
/**
|
|
1716
|
+
* Dispatches the request to the handler its `Accept` header negotiates,
|
|
1717
|
+
* answering 406 when none matches.
|
|
1718
|
+
*
|
|
1721
1719
|
* @remarks
|
|
1722
|
-
* Errors thrown by the negotiated handler propagate
|
|
1720
|
+
* Errors thrown by the negotiated handler propagate unmodified — the
|
|
1723
1721
|
* server boundary classifies them, never this negotiator.
|
|
1724
1722
|
*/
|
|
1725
1723
|
async format(request, context, handlers) {
|
|
@@ -1735,39 +1733,39 @@ var Negotiator = class {
|
|
|
1735
1733
|
//#endregion
|
|
1736
1734
|
//#region src/server/Server.ts
|
|
1737
1735
|
/**
|
|
1738
|
-
*
|
|
1736
|
+
* Represents the HTTP server facade — an observable `node:http` lifecycle composing this
|
|
1739
1737
|
* module's own middleware onion around a consumed `@orkestrel/router`
|
|
1740
|
-
* dispatcher.
|
|
1738
|
+
* dispatcher. Implements exactly {@link ServerInterface}.
|
|
1741
1739
|
*
|
|
1742
1740
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
1743
1741
|
*
|
|
1744
1742
|
* @remarks
|
|
1745
|
-
* - **Lifecycle
|
|
1743
|
+
* - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
|
|
1746
1744
|
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1747
|
-
* ServerOptions.port} (omitted/`0` port ⇒
|
|
1745
|
+
* ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
|
|
1748
1746
|
* bound address), exposes that {@link AddressInfo} through `address`, observes
|
|
1749
1747
|
* caller cancellation plus the configured `timeouts.start` deadline while the
|
|
1750
1748
|
* bind is pending, and transitions `idle → starting → listening`. A
|
|
1751
1749
|
* cancelled or expired bind closes its partial server and resets to `idle` for
|
|
1752
1750
|
* another start. `stop()` transitions
|
|
1753
1751
|
* to `stopping`: refuses new connections, fires a fresh-per-run stop signal
|
|
1754
|
-
* so in-flight handlers observe cancellation, drains in-flight requests
|
|
1752
|
+
* so in-flight handlers observe cancellation, drains in-flight requests and
|
|
1755
1753
|
* claimed upgraded sockets up to the `drain` deadline (event-driven, no
|
|
1756
1754
|
* busy-loop), then closes → `stopped`, forcing whatever the deadline caught
|
|
1757
1755
|
* still open. `destroy()` is the idempotent final teardown.
|
|
1758
1756
|
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1759
|
-
* `close`); a `Request` is built
|
|
1760
|
-
* `signal`
|
|
1757
|
+
* `close`); a `Request` is built through the router's `buildRequest`, its
|
|
1758
|
+
* `signal` linked to this run's stop signal through `@orkestrel/abort`'s
|
|
1761
1759
|
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1762
|
-
* `buildRequest`'s own abort, armed by
|
|
1763
|
-
* teardown, composes with the server's stop signal
|
|
1764
|
-
* so a handler awaiting `request.signal` observes
|
|
1760
|
+
* `buildRequest`'s own abort, armed by request-side and response-side
|
|
1761
|
+
* teardown, composes with the server's stop signal through `AbortSignal.any`,
|
|
1762
|
+
* so a handler awaiting `request.signal` observes either); `context.state` is built through
|
|
1765
1763
|
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1766
1764
|
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1767
|
-
* written back
|
|
1768
|
-
* - **The built-in boundary** wraps the
|
|
1765
|
+
* written back through `sendResponse`.
|
|
1766
|
+
* - **The built-in boundary** wraps the whole per-request chain, including
|
|
1769
1767
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1770
|
-
* throw (
|
|
1768
|
+
* throw (for example, a malformed `Host` header) to a silent `400` with no
|
|
1771
1769
|
* `error` emit; everything after (`Request` reconstruction, connection
|
|
1772
1770
|
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1773
1771
|
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
@@ -1779,15 +1777,15 @@ var Negotiator = class {
|
|
|
1779
1777
|
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1780
1778
|
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1781
1779
|
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
1782
|
-
* A
|
|
1780
|
+
* A claimed socket joins `#upgraded` until it closes: the claimant still
|
|
1783
1781
|
* owns it, and the tracking exists because node detaches an upgraded socket
|
|
1784
1782
|
* from the set its own close calls walk, so nothing else can end it.
|
|
1785
|
-
* - **Observable
|
|
1783
|
+
* - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1786
1784
|
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1787
|
-
* routes it to the `error`
|
|
1785
|
+
* routes it to the `error` option rather than to the domain `error` event.
|
|
1788
1786
|
*/
|
|
1789
1787
|
var Server = class {
|
|
1790
|
-
id
|
|
1788
|
+
#id;
|
|
1791
1789
|
#dispatcher;
|
|
1792
1790
|
#state;
|
|
1793
1791
|
#middleware;
|
|
@@ -1820,6 +1818,7 @@ var Server = class {
|
|
|
1820
1818
|
if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
|
|
1821
1819
|
const sockets = options.sockets ?? {};
|
|
1822
1820
|
for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!isInteger(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
|
|
1821
|
+
this.#id = crypto.randomUUID();
|
|
1823
1822
|
this.#dispatcher = options.dispatcher;
|
|
1824
1823
|
this.#state = options.state;
|
|
1825
1824
|
this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
|
|
@@ -1836,8 +1835,8 @@ var Server = class {
|
|
|
1836
1835
|
...options.error === void 0 ? {} : { error: options.error }
|
|
1837
1836
|
});
|
|
1838
1837
|
}
|
|
1839
|
-
get
|
|
1840
|
-
return this.#
|
|
1838
|
+
get id() {
|
|
1839
|
+
return this.#id;
|
|
1841
1840
|
}
|
|
1842
1841
|
get status() {
|
|
1843
1842
|
return this.#status;
|
|
@@ -1863,7 +1862,7 @@ var Server = class {
|
|
|
1863
1862
|
this.#upgradeHandlers.push(handler);
|
|
1864
1863
|
}
|
|
1865
1864
|
start(signal) {
|
|
1866
|
-
if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(
|
|
1865
|
+
if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
|
|
1867
1866
|
this.#status = "starting";
|
|
1868
1867
|
this.#abort = createAbort();
|
|
1869
1868
|
const server = createServer$2((request, response) => this.#handle(request, response));
|
|
@@ -1997,17 +1996,13 @@ var Server = class {
|
|
|
1997
1996
|
else socket.destroy();
|
|
1998
1997
|
this.#emitter.emit("upgrade", request, handled);
|
|
1999
1998
|
}
|
|
2000
|
-
#resolvePort(server) {
|
|
2001
|
-
const address = server.address();
|
|
2002
|
-
if (isAddressInfo(address)) return address.port;
|
|
2003
|
-
return 0;
|
|
2004
|
-
}
|
|
2005
1999
|
async #listen(server, signal) {
|
|
2006
2000
|
const deadline = this.#timeouts.start === void 0 ? void 0 : createTimeout({ ms: this.#timeouts.start });
|
|
2007
2001
|
const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
|
|
2008
2002
|
const binding = createAbort();
|
|
2009
2003
|
const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
|
|
2010
2004
|
let listening;
|
|
2005
|
+
let port;
|
|
2011
2006
|
try {
|
|
2012
2007
|
signal?.throwIfAborted();
|
|
2013
2008
|
deadline?.start();
|
|
@@ -2021,6 +2016,9 @@ var Server = class {
|
|
|
2021
2016
|
signal: binding.signal
|
|
2022
2017
|
});
|
|
2023
2018
|
await listening;
|
|
2019
|
+
const address = server.address();
|
|
2020
|
+
if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
|
|
2021
|
+
port = address.port;
|
|
2024
2022
|
} catch (error) {
|
|
2025
2023
|
const expired = deadline?.expired === true;
|
|
2026
2024
|
const cancelled = startup?.aborted === true;
|
|
@@ -2038,7 +2036,6 @@ var Server = class {
|
|
|
2038
2036
|
relay?.[Symbol.dispose]();
|
|
2039
2037
|
deadline?.clear();
|
|
2040
2038
|
}
|
|
2041
|
-
const port = this.#resolvePort(server);
|
|
2042
2039
|
this.#port = port;
|
|
2043
2040
|
this.#status = "listening";
|
|
2044
2041
|
this.#emitter.emit("start", port);
|
|
@@ -2060,6 +2057,9 @@ var Server = class {
|
|
|
2060
2057
|
} else server.closeIdleConnections();
|
|
2061
2058
|
});
|
|
2062
2059
|
}
|
|
2060
|
+
get #inflight() {
|
|
2061
|
+
return this.#pending + this.#upgraded.size;
|
|
2062
|
+
}
|
|
2063
2063
|
#enter() {
|
|
2064
2064
|
if (this.#inflight === 0) this.#wakeup = createAbort();
|
|
2065
2065
|
}
|
|
@@ -2092,57 +2092,209 @@ var Server = class {
|
|
|
2092
2092
|
}
|
|
2093
2093
|
};
|
|
2094
2094
|
//#endregion
|
|
2095
|
-
//#region src/server/
|
|
2095
|
+
//#region src/server/Stream.ts
|
|
2096
2096
|
/**
|
|
2097
|
-
*
|
|
2098
|
-
*
|
|
2097
|
+
* Represents the Server-Sent-Events handle over an open, fetch-standard streaming
|
|
2098
|
+
* `Response`. Implements exactly {@link StreamInterface}.
|
|
2099
2099
|
*
|
|
2100
2100
|
* @remarks
|
|
2101
|
-
*
|
|
2102
|
-
*
|
|
2101
|
+
* Builds the `Response` at construction from
|
|
2102
|
+
* {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
|
|
2103
|
+
* merged over them, at `options.status` (default `200`). A caller repeating one
|
|
2104
|
+
* of those keys therefore replaces the seam's value, in any casing. The
|
|
2105
|
+
* instance owns the stream's
|
|
2106
|
+
* controller, its text encoder, the closed flag, and the parked producer's
|
|
2107
|
+
* wakeup, so the whole handle is one entity rather than a closure over four
|
|
2108
|
+
* bindings.
|
|
2109
|
+
*
|
|
2110
|
+
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
2111
|
+
* returns whether the controller still has positive desired size. A producer
|
|
2112
|
+
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
2113
|
+
* consumer pull restoring capacity, or on stream closure. `comment` writes a
|
|
2114
|
+
* `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
|
|
2115
|
+
* stream. Every method is a safe no-op once `closed` (ended by `end()`, or
|
|
2116
|
+
* the consumer cancelled the stream), so a late write never throws.
|
|
2117
|
+
*
|
|
2118
|
+
* The readiness signal reflects only the process-local `ReadableStream`
|
|
2119
|
+
* queue — it is not proof that a remote peer consumed bytes. When the response
|
|
2120
|
+
* pump honors its socket sink's drain state, socket pressure stops body pulls
|
|
2121
|
+
* and therefore keeps this queue full, letting a cooperative producer bound
|
|
2122
|
+
* its buffering. Ignoring the return value preserves an unconditional-enqueue
|
|
2123
|
+
* producer. The default stream strategy counts chunks rather than their byte
|
|
2124
|
+
* length, so a byte-bounded producer must also cap each message. Return
|
|
2125
|
+
* `response` before awaiting a `false` write, because the consumer cannot pull
|
|
2126
|
+
* until it receives the response.
|
|
2127
|
+
*
|
|
2128
|
+
* @example
|
|
2129
|
+
* ```ts
|
|
2130
|
+
* import { Stream } from '@src/server'
|
|
2131
|
+
*
|
|
2132
|
+
* const stream = new Stream()
|
|
2133
|
+
* void Promise.resolve().then(async () => {
|
|
2134
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
2135
|
+
* stream.comment('keep-alive')
|
|
2136
|
+
* stream.end()
|
|
2137
|
+
* })
|
|
2138
|
+
* // return stream.response from the route handler
|
|
2139
|
+
* ```
|
|
2140
|
+
*/
|
|
2141
|
+
var Stream = class {
|
|
2142
|
+
#encoder = new TextEncoder();
|
|
2143
|
+
#response;
|
|
2144
|
+
#controller;
|
|
2145
|
+
#closed = false;
|
|
2146
|
+
#wakeup;
|
|
2147
|
+
constructor(options) {
|
|
2148
|
+
const body = new ReadableStream({
|
|
2149
|
+
start: this.#attach.bind(this),
|
|
2150
|
+
pull: this.#pull.bind(this),
|
|
2151
|
+
cancel: this.#cancel.bind(this)
|
|
2152
|
+
});
|
|
2153
|
+
const headers = new Headers(SSE_HEADERS);
|
|
2154
|
+
for (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value);
|
|
2155
|
+
this.#response = new Response(body, {
|
|
2156
|
+
status: options?.status ?? 200,
|
|
2157
|
+
headers
|
|
2158
|
+
});
|
|
2159
|
+
}
|
|
2160
|
+
get response() {
|
|
2161
|
+
return this.#response;
|
|
2162
|
+
}
|
|
2163
|
+
get closed() {
|
|
2164
|
+
return this.#closed;
|
|
2165
|
+
}
|
|
2166
|
+
write(message) {
|
|
2167
|
+
if (this.#closed || this.#controller === void 0) return false;
|
|
2168
|
+
this.#enqueue(serializeEvent(message));
|
|
2169
|
+
return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
|
|
2170
|
+
}
|
|
2171
|
+
comment(text) {
|
|
2172
|
+
this.#enqueue(`: ${text}\n\n`);
|
|
2173
|
+
}
|
|
2174
|
+
drain() {
|
|
2175
|
+
const desired = this.#controller?.desiredSize;
|
|
2176
|
+
if (this.#closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
|
|
2177
|
+
this.#wakeup ??= Promise.withResolvers();
|
|
2178
|
+
return this.#wakeup.promise;
|
|
2179
|
+
}
|
|
2180
|
+
end() {
|
|
2181
|
+
if (this.#closed) return;
|
|
2182
|
+
this.#closed = true;
|
|
2183
|
+
this.#controller?.close();
|
|
2184
|
+
this.#settle();
|
|
2185
|
+
}
|
|
2186
|
+
#attach(controller) {
|
|
2187
|
+
this.#controller = controller;
|
|
2188
|
+
}
|
|
2189
|
+
#pull(controller) {
|
|
2190
|
+
if (controller.desiredSize === null || controller.desiredSize <= 0) return;
|
|
2191
|
+
this.#settle();
|
|
2192
|
+
}
|
|
2193
|
+
#cancel() {
|
|
2194
|
+
this.#closed = true;
|
|
2195
|
+
this.#settle();
|
|
2196
|
+
}
|
|
2197
|
+
#enqueue(text) {
|
|
2198
|
+
if (this.#closed || this.#controller === void 0) return;
|
|
2199
|
+
this.#controller.enqueue(this.#encoder.encode(text));
|
|
2200
|
+
}
|
|
2201
|
+
#settle() {
|
|
2202
|
+
this.#wakeup?.resolve();
|
|
2203
|
+
this.#wakeup = void 0;
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
//#endregion
|
|
2207
|
+
//#region src/server/factories.ts
|
|
2208
|
+
/**
|
|
2209
|
+
* Creates a {@link NegotiatorInterface} — the reusable content-negotiation
|
|
2210
|
+
* machine over the weighted `Accept` family.
|
|
2103
2211
|
*
|
|
2104
2212
|
* @returns A {@link NegotiatorInterface}
|
|
2105
2213
|
*
|
|
2106
2214
|
* @example
|
|
2107
2215
|
* ```ts
|
|
2216
|
+
* import type { MiddlewareContext } from '@src/server'
|
|
2108
2217
|
* import { createNegotiator } from '@src/server'
|
|
2109
2218
|
*
|
|
2219
|
+
* declare const context: MiddlewareContext<Record<string, never>>
|
|
2220
|
+
*
|
|
2110
2221
|
* const negotiator = createNegotiator()
|
|
2111
|
-
* negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
|
|
2112
|
-
* // '
|
|
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
|
+
* })
|
|
2113
2228
|
* ```
|
|
2114
2229
|
*/
|
|
2115
2230
|
function createNegotiator() {
|
|
2116
2231
|
return new Negotiator();
|
|
2117
2232
|
}
|
|
2118
2233
|
/**
|
|
2119
|
-
*
|
|
2234
|
+
* Creates a {@link ServerInterface} — the node face's HTTP server facade over
|
|
2120
2235
|
* a consumed `@orkestrel/router` dispatcher.
|
|
2121
2236
|
*
|
|
2122
2237
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
2123
2238
|
* @param options - {@link ServerOptions}
|
|
2124
2239
|
* @returns A {@link ServerInterface}, not yet started
|
|
2125
2240
|
*
|
|
2126
|
-
* @example
|
|
2241
|
+
* @example Quickstart: dispatcher, middleware, lifecycle
|
|
2127
2242
|
* ```ts
|
|
2128
|
-
* import {
|
|
2243
|
+
* import type { MiddlewareHandler } from '@orkestrel/server'
|
|
2244
|
+
* import { createServer } from '@orkestrel/server'
|
|
2129
2245
|
* import { createDispatcher } from '@orkestrel/router'
|
|
2130
2246
|
*
|
|
2131
|
-
*
|
|
2247
|
+
* interface State {
|
|
2248
|
+
* readonly requestId: string
|
|
2249
|
+
* readonly ip: string | undefined
|
|
2250
|
+
* }
|
|
2251
|
+
*
|
|
2252
|
+
* const dispatcher = createDispatcher<State>()
|
|
2132
2253
|
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
2133
2254
|
*
|
|
2134
|
-
* 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>({
|
|
2135
2262
|
* dispatcher,
|
|
2136
|
-
* state: (connection) => ({ ip: connection.ip }),
|
|
2263
|
+
* state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
|
|
2137
2264
|
* })
|
|
2265
|
+
* server.use(logRequestId)
|
|
2138
2266
|
* const port = await server.start()
|
|
2139
2267
|
* await server.stop()
|
|
2268
|
+
* await server.destroy()
|
|
2140
2269
|
* ```
|
|
2141
2270
|
*/
|
|
2142
2271
|
function createServer(options) {
|
|
2143
2272
|
return new Server(options);
|
|
2144
2273
|
}
|
|
2274
|
+
/**
|
|
2275
|
+
* Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
|
|
2276
|
+
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
2277
|
+
*
|
|
2278
|
+
* @param options - {@link StreamOptions}
|
|
2279
|
+
* @returns A {@link StreamInterface} whose stream is open
|
|
2280
|
+
*
|
|
2281
|
+
* @example
|
|
2282
|
+
* ```ts
|
|
2283
|
+
* import { createStream } from '@src/server'
|
|
2284
|
+
*
|
|
2285
|
+
* const stream = createStream()
|
|
2286
|
+
* void Promise.resolve().then(async () => {
|
|
2287
|
+
* if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
|
|
2288
|
+
* stream.comment('keep-alive')
|
|
2289
|
+
* stream.end()
|
|
2290
|
+
* })
|
|
2291
|
+
* // return stream.response from the route handler
|
|
2292
|
+
* ```
|
|
2293
|
+
*/
|
|
2294
|
+
function createStream(options) {
|
|
2295
|
+
return new Stream(options);
|
|
2296
|
+
}
|
|
2145
2297
|
//#endregion
|
|
2146
|
-
export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server,
|
|
2298
|
+
export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, ServerError, Stream, clearCookie, collectRequestBody, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
|
|
2147
2299
|
|
|
2148
2300
|
//# sourceMappingURL=index.js.map
|