@orkestrel/server 0.0.28 → 0.0.30
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 +7 -4
- package/dist/src/server/index.cjs +748 -324
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +611 -213
- package/dist/src/server/index.d.ts +611 -213
- package/dist/src/server/index.js +738 -326
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -14
package/dist/src/server/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { INTRINSICS, attempt, holds, isError, isFiniteNumber, isFunction, isInstance, isInteger, isNumber, isObject, isRecord, isString, parseJSON } from "@orkestrel/contract";
|
|
1
|
+
import { INTRINSICS, attempt, holds, isArray, isCodedError, isError, isFiniteNumber, isFunction, isInstance, isInteger, isNumber, isObject, isPromise, isRecord, isSafeInteger, isString, parseJSON, refuseValue, settle } from "@orkestrel/contract";
|
|
2
2
|
import { addAbortListener, once } from "node:events";
|
|
3
3
|
import { createServer as createServer$1 } from "node:net";
|
|
4
4
|
import { decodeBase64URL, encodeBase64URL, encodeHex } from "@orkestrel/codec";
|
|
5
5
|
import { createServer as createServer$2 } from "node:http";
|
|
6
|
-
import { finished } from "node:stream/promises";
|
|
7
6
|
import { createAbort, linkSignal } from "@orkestrel/abort";
|
|
8
7
|
import { createTimeout, isTimeoutDuration } from "@orkestrel/timeout";
|
|
9
8
|
import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
|
|
10
9
|
import { Emitter } from "@orkestrel/emitter";
|
|
10
|
+
import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
|
|
11
11
|
// src/server/constants.ts
|
|
12
12
|
/**
|
|
13
13
|
* Names the default graceful-stop deadline `stop()` gives in-flight requests and
|
|
@@ -15,6 +15,17 @@ import { Emitter } from "@orkestrel/emitter";
|
|
|
15
15
|
*/
|
|
16
16
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
17
17
|
/**
|
|
18
|
+
* Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when
|
|
19
|
+
* `timeouts.request` is omitted.
|
|
20
|
+
*/
|
|
21
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
|
|
22
|
+
/**
|
|
23
|
+
* Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when
|
|
24
|
+
* `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the
|
|
25
|
+
* request timeout.
|
|
26
|
+
*/
|
|
27
|
+
var DEFAULT_HEADERS_TIMEOUT_MS = 6e4;
|
|
28
|
+
/**
|
|
18
29
|
* Names the `Symbol.for`-interned brand `HTTPError` carries,
|
|
19
30
|
* `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
|
|
20
31
|
* package copies. A consumer never sets it by hand.
|
|
@@ -40,7 +51,7 @@ var DEFAULT_BODY_LIMIT = 1048576;
|
|
|
40
51
|
* it transparently decompresses a `Content-Encoding` request body.
|
|
41
52
|
*
|
|
42
53
|
* @remarks
|
|
43
|
-
* A small compressed
|
|
54
|
+
* A small compressed body (under {@link DEFAULT_BODY_LIMIT} on the wire)
|
|
44
55
|
* can inflate by many orders of magnitude — a classic decompression bomb.
|
|
45
56
|
* Capping the decompressed byte count makes the pipe abort the moment the
|
|
46
57
|
* output would exceed this, before the full bomb is materialized, so the
|
|
@@ -74,7 +85,7 @@ var SSE_HEADERS = Object.freeze({
|
|
|
74
85
|
* to match, `^[A-Za-z0-9_-]{1,200}$`.
|
|
75
86
|
*
|
|
76
87
|
* @remarks
|
|
77
|
-
* An incoming id carrying CRLF,
|
|
88
|
+
* An incoming id carrying CRLF, log-injection input, a control character,
|
|
78
89
|
* or more characters than the pattern admits fails the match and is rejected —
|
|
79
90
|
* a fresh id is minted instead — so it never rides into a response header or
|
|
80
91
|
* `context.state`. Frozen so a consumer can read but never mutate the shared
|
|
@@ -82,6 +93,21 @@ var SSE_HEADERS = Object.freeze({
|
|
|
82
93
|
*/
|
|
83
94
|
var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
|
|
84
95
|
/**
|
|
96
|
+
* Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`.
|
|
97
|
+
*
|
|
98
|
+
* @remarks
|
|
99
|
+
* Mirrors the `first-pos`, `last-pos`, and `suffix-length` rules of RFC 9110
|
|
100
|
+
* § 14.1.1. A numeral `Number` reads but the grammar refuses — a hexadecimal,
|
|
101
|
+
* octal, or binary prefix, an exponent, a sign, or a decimal point — fails the
|
|
102
|
+
* match, as does a digit outside ASCII, which `Number` reads as `NaN`.
|
|
103
|
+
*/
|
|
104
|
+
var RANGE_BOUND_PATTERN = Object.freeze(/^[0-9]+$/);
|
|
105
|
+
/**
|
|
106
|
+
* Defines the line terminators of the SSE wire, `\r\n`, `\r`, and `\n`, which
|
|
107
|
+
* `serializeEvent` and `serializeComment` split text on.
|
|
108
|
+
*/
|
|
109
|
+
var SSE_LINE_PATTERN = Object.freeze(/\r\n|\r|\n/);
|
|
110
|
+
/**
|
|
85
111
|
* Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
|
|
86
112
|
* beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
|
|
87
113
|
* helper also applies.
|
|
@@ -132,10 +158,12 @@ var CONTENT_TOO_LARGE_ERROR_BRAND = Symbol.for("@orkestrel/server.ContentTooLarg
|
|
|
132
158
|
* @remarks
|
|
133
159
|
* Carries the HTTP `status` to send and an optional `context` record (the
|
|
134
160
|
* offending field / value). The server's built-in error boundary catches it
|
|
135
|
-
* and renders a response of `status` with the error's `message` as the body
|
|
136
|
-
* — so an `HTTPError`'s message is always
|
|
137
|
-
* deliberate signal), unlike a generic
|
|
138
|
-
* `expose` is set.
|
|
161
|
+
* and renders a response of `status` with the error's `message` as the body,
|
|
162
|
+
* and no body for 204, 205, and 304 — so an `HTTPError`'s message is always
|
|
163
|
+
* client-facing (it is the handler's deliberate signal), unlike a generic
|
|
164
|
+
* throw whose message is hidden unless `expose` is set. A `status` the
|
|
165
|
+
* `Response` constructor refuses, an integer below 200 or above 599 or a
|
|
166
|
+
* status that is not an integer, renders `500` instead. Subclass it (as {@link ContentTooLargeError} does) for
|
|
139
167
|
* specific statuses, or throw it directly. Narrow a caught value with
|
|
140
168
|
* {@link isHTTPError}. The machine-readable discriminator is `status`; there is
|
|
141
169
|
* no separate `code`.
|
|
@@ -237,15 +265,21 @@ function isContentTooLargeError(value) {
|
|
|
237
265
|
}
|
|
238
266
|
/**
|
|
239
267
|
* Represents the error this package raises when a caller programmed a call the
|
|
240
|
-
* entity refuses, carrying `'STATUS'` or `'
|
|
268
|
+
* entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code.
|
|
241
269
|
*
|
|
242
270
|
* @remarks
|
|
243
271
|
* Carries a machine-readable {@link ServerErrorCode} and an optional `context`
|
|
244
272
|
* record naming the offending facts. This is a programmer error, so it carries
|
|
245
273
|
* no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
|
|
246
|
-
* invoked the lifecycle method,
|
|
274
|
+
* invoked the lifecycle method, a `'NEXT'` refusal of a second `next` call or
|
|
275
|
+
* of a `next` call with an argument escapes its
|
|
247
276
|
* middleware into the request boundary, which reaches it as a generic 500 with
|
|
248
|
-
* the message hidden unless `expose` is set
|
|
277
|
+
* the message hidden unless `expose` is set, and an `'EVENT'` refusal is raised
|
|
278
|
+
* to the caller that serialized an SSE message, its `context.field` naming the
|
|
279
|
+
* refused field, and a `'SECRET'` refusal is raised to the caller that built a
|
|
280
|
+
* signer from a malformed secret, its `context` naming the refused positions,
|
|
281
|
+
* or the received type for a value that is not a string or a readable list, and holding
|
|
282
|
+
* no secret text. Throw an {@link HTTPError} for a
|
|
249
283
|
* client-facing fault instead. Narrow a caught value with
|
|
250
284
|
* {@link isServerError}.
|
|
251
285
|
*
|
|
@@ -304,7 +338,7 @@ function isServerError(value) {
|
|
|
304
338
|
if (INTRINSICS.describe(value, SERVER_ERROR_BRAND)?.value !== value) return false;
|
|
305
339
|
const code = INTRINSICS.reflect.read(value, "code");
|
|
306
340
|
const context = INTRINSICS.reflect.read(value, "context");
|
|
307
|
-
return (code === "STATUS" || code === "NEXT") && isString(INTRINSICS.reflect.read(value, "message")) && (context === void 0 || isObject(context) || isFunction(context));
|
|
341
|
+
return (code === "STATUS" || code === "NEXT" || code === "EVENT" || code === "SECRET") && isString(INTRINSICS.reflect.read(value, "message")) && (context === void 0 || isObject(context) || isFunction(context));
|
|
308
342
|
});
|
|
309
343
|
}
|
|
310
344
|
// src/server/validators.ts
|
|
@@ -335,19 +369,23 @@ function isAddressInfo(value) {
|
|
|
335
369
|
// src/server/helpers.ts
|
|
336
370
|
/**
|
|
337
371
|
* Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
|
|
338
|
-
* handler into one request handler — the
|
|
372
|
+
* handler into one request handler — the middleware seam.
|
|
339
373
|
*
|
|
340
374
|
* @remarks
|
|
341
375
|
* `middleware[0]` runs outermost: it is invoked first, and its call to `next`
|
|
342
376
|
* runs `middleware[1]`, and so on until the last middleware's `next` invokes
|
|
343
|
-
* `terminal`.
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
*
|
|
350
|
-
*
|
|
377
|
+
* `terminal`. Every layer and `terminal` receive the same `Request` and the same
|
|
378
|
+
* context object. A middleware's `next` is called with no argument, or not
|
|
379
|
+
* called at all (a short-circuit — the middleware's own returned `Response` is
|
|
380
|
+
* sent, and everything downstream never runs). A second call to the same
|
|
381
|
+
* `next` within one middleware invocation, or a call that passes an argument,
|
|
382
|
+
* rejects with a `ServerError` of code `'NEXT'` — each link runs the chain at
|
|
383
|
+
* most once, so a middleware cannot fork the request into two divergent
|
|
384
|
+
* downstream runs. Each `next` resolves the downstream response through
|
|
385
|
+
* {@link normalizeResponse}, so a layer can set headers on a redirect or a
|
|
386
|
+
* `fetch` result; each run keeps its own memo of checked responses, which ends
|
|
387
|
+
* with the run. `compose` copies `middleware` when called, so a layer added to
|
|
388
|
+
* the array later never runs in the returned handler.
|
|
351
389
|
*
|
|
352
390
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
353
391
|
* @param middleware - The ordered chain, outermost first
|
|
@@ -366,19 +404,27 @@ function isAddressInfo(value) {
|
|
|
366
404
|
* ```
|
|
367
405
|
*/
|
|
368
406
|
function compose(middleware, terminal) {
|
|
369
|
-
|
|
407
|
+
const layers = [...middleware];
|
|
408
|
+
return (request, context) => {
|
|
409
|
+
const known = /* @__PURE__ */ new Map();
|
|
410
|
+
return layers.reduceRight((next, layer) => wrapMiddleware(layer, next, known), terminal)(request, context);
|
|
411
|
+
};
|
|
370
412
|
}
|
|
371
413
|
/**
|
|
372
414
|
* Wraps one middleware layer around its downstream handler, enforcing the one-call
|
|
373
415
|
* `next` invariant.
|
|
374
416
|
*
|
|
375
417
|
* @remarks
|
|
376
|
-
* The returned handler enforces the one-call `next` invariant
|
|
377
|
-
*
|
|
418
|
+
* The returned handler enforces the one-call, no-argument `next` invariant: every
|
|
419
|
+
* call, refused or not, spends the layer's one call, so a call after a refused
|
|
420
|
+
* `next(request)` rejects too. It hands `next` the same request and context, and
|
|
421
|
+
* keeps the middleware's synchronous or asynchronous result.
|
|
378
422
|
*
|
|
379
423
|
* @typeParam TState - The consumer's opaque per-request state type
|
|
380
424
|
* @param layer - The middleware layer to invoke
|
|
381
425
|
* @param next - The downstream handler wrapped by `layer`
|
|
426
|
+
* @param known - The {@link normalizeResponse} memo of one composed run, shared by its
|
|
427
|
+
* layers; Default: a fresh `Map` per call of the returned handler
|
|
382
428
|
* @returns A handler with `layer` composed around `next`
|
|
383
429
|
*
|
|
384
430
|
* @example
|
|
@@ -389,18 +435,79 @@ function compose(middleware, terminal) {
|
|
|
389
435
|
* )
|
|
390
436
|
* ```
|
|
391
437
|
*/
|
|
392
|
-
function wrapMiddleware(layer, next) {
|
|
438
|
+
function wrapMiddleware(layer, next, known) {
|
|
393
439
|
return async (request, context) => {
|
|
440
|
+
const memo = known ?? /* @__PURE__ */ new Map();
|
|
394
441
|
const calls = [next].values();
|
|
395
|
-
return Promise.resolve(layer(request, context, (
|
|
442
|
+
return Promise.resolve(layer(request, context, (...args) => {
|
|
396
443
|
const invocation = calls.next();
|
|
397
444
|
if (invocation.done) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
|
|
398
|
-
|
|
399
|
-
return
|
|
445
|
+
if (args.length > 0) return Promise.reject(new ServerError("NEXT", "next() takes no argument; every layer reads one request"));
|
|
446
|
+
return invocation.value(request, context).then((response) => normalizeResponse(response, memo));
|
|
400
447
|
}));
|
|
401
448
|
};
|
|
402
449
|
}
|
|
403
450
|
/**
|
|
451
|
+
* Returns a response whose headers a middleware can set: a copy of `response` when its headers are
|
|
452
|
+
* immutable and its status lies from 200 through 599, and `response` itself otherwise.
|
|
453
|
+
*
|
|
454
|
+
* @remarks
|
|
455
|
+
* A `Response.redirect` result and a `fetch` result carry immutable headers, so `headers.set`
|
|
456
|
+
* throws on them. The copy keeps the body, the status, the status text, and every header; it
|
|
457
|
+
* drops the fields a constructed `Response` cannot carry, such as `url` and `redirected`. A
|
|
458
|
+
* response whose status lies outside 200 through 599, such as `Response.error()`, passes through
|
|
459
|
+
* unchanged. `known` maps each response already checked to its answer, and the copy to itself, so
|
|
460
|
+
* a response that crosses several layers of one composed run is checked once.
|
|
461
|
+
*
|
|
462
|
+
* @param response - The response a downstream handler resolved
|
|
463
|
+
* @param known - The memo of one composed run; Default: a fresh `Map`
|
|
464
|
+
* @returns `response` itself, or its mutable copy
|
|
465
|
+
*
|
|
466
|
+
* @example
|
|
467
|
+
* ```ts
|
|
468
|
+
* const response = normalizeResponse(Response.redirect('http://localhost/next', 302))
|
|
469
|
+
* response.headers.set('X-Request-ID', 'abc') // no throw
|
|
470
|
+
* ```
|
|
471
|
+
*/
|
|
472
|
+
function normalizeResponse(response, known = /* @__PURE__ */ new Map()) {
|
|
473
|
+
const remembered = known.get(response);
|
|
474
|
+
if (remembered !== void 0) return remembered;
|
|
475
|
+
const normal = response.status < 200 || response.status > 599 || supportsMutation(response.headers) ? response : new Response(response.body, {
|
|
476
|
+
status: response.status,
|
|
477
|
+
statusText: response.statusText,
|
|
478
|
+
headers: new Headers(response.headers)
|
|
479
|
+
});
|
|
480
|
+
known.set(response, normal);
|
|
481
|
+
if (normal !== response) known.set(normal, normal);
|
|
482
|
+
return normal;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Checks whether a `Headers` object accepts changes, leaving its entries as they were.
|
|
486
|
+
*
|
|
487
|
+
* @remarks
|
|
488
|
+
* Fetch refuses `delete` on immutable headers before it looks the name up, so deleting a name
|
|
489
|
+
* the headers lack answers the question and changes nothing. When the probe name is present, the
|
|
490
|
+
* check sets it to its own combined value instead.
|
|
491
|
+
*
|
|
492
|
+
* @param headers - The headers to check
|
|
493
|
+
* @returns True if `headers` accepts changes; false otherwise
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```ts
|
|
497
|
+
* supportsMutation(new Headers()) // true
|
|
498
|
+
* supportsMutation(Response.redirect('http://localhost/', 302).headers) // false
|
|
499
|
+
* ```
|
|
500
|
+
*/
|
|
501
|
+
function supportsMutation(headers) {
|
|
502
|
+
const name = "x-orkestrel-probe";
|
|
503
|
+
const value = headers.get(name);
|
|
504
|
+
return holds(() => {
|
|
505
|
+
if (value === null) headers.delete(name);
|
|
506
|
+
else headers.set(name, value);
|
|
507
|
+
return true;
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
404
511
|
* Parses a raw `Cookie:` request header into a `name → value` lookup.
|
|
405
512
|
*
|
|
406
513
|
* @remarks
|
|
@@ -413,8 +520,12 @@ function wrapMiddleware(layer, next) {
|
|
|
413
520
|
* name, is skipped; a later duplicate name wins. Total — an absent/empty/
|
|
414
521
|
* malformed header yields an empty record, never throws.
|
|
415
522
|
*
|
|
523
|
+
* The record has a null prototype, so a name that `Object.prototype` carries
|
|
524
|
+
* (`constructor`, `toString`, `__proto__`) reads as an ordinary cookie when
|
|
525
|
+
* present and as `undefined` when absent.
|
|
526
|
+
*
|
|
416
527
|
* @param header - The raw `Cookie` header value (possibly `undefined`)
|
|
417
|
-
* @returns A record of every parsed cookie, `name → decoded value`
|
|
528
|
+
* @returns A null-prototype record of every parsed cookie, `name → decoded value`
|
|
418
529
|
*
|
|
419
530
|
* @example
|
|
420
531
|
* ```ts
|
|
@@ -422,18 +533,16 @@ function wrapMiddleware(layer, next) {
|
|
|
422
533
|
* ```
|
|
423
534
|
*/
|
|
424
535
|
function parseCookies(header) {
|
|
425
|
-
const
|
|
426
|
-
if (header === void 0) return out;
|
|
427
|
-
const segments = header.split(";");
|
|
428
|
-
for (const [index, raw] of segments.entries()) {
|
|
536
|
+
const pairs = (header ?? "").split(";").flatMap((raw, index) => {
|
|
429
537
|
const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
|
|
430
538
|
const eq = segment.indexOf("=");
|
|
431
|
-
if (eq < 0)
|
|
539
|
+
if (eq < 0) return [];
|
|
432
540
|
const name = segment.slice(0, eq);
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
541
|
+
return isCookieName(name) ? [[name, decodeCookieValue(segment.slice(eq + 1).trim())]] : [];
|
|
542
|
+
});
|
|
543
|
+
const cookies = Object.fromEntries(pairs);
|
|
544
|
+
Object.setPrototypeOf(cookies, null);
|
|
545
|
+
return cookies;
|
|
437
546
|
}
|
|
438
547
|
/**
|
|
439
548
|
* Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
|
|
@@ -579,50 +688,52 @@ function resolveSecure(secure, encrypted) {
|
|
|
579
688
|
* appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
|
|
580
689
|
*
|
|
581
690
|
* @remarks
|
|
582
|
-
* The cookie value is `await signToken(value, {
|
|
691
|
+
* The cookie value is `await signToken(value, { signer })`
|
|
583
692
|
* (`<payload>.<signature>`), so a signed cookie is a stateless token in a
|
|
584
|
-
* cookie — the same
|
|
693
|
+
* cookie — the same key rotation and tamper rejection, no second HMAC
|
|
585
694
|
* scheme. Appends (never clobbers) through `Headers.append`, which accumulates
|
|
586
|
-
* repeated headers.
|
|
695
|
+
* repeated headers.
|
|
587
696
|
*
|
|
588
697
|
* @param headers - The response `Headers` to write into
|
|
589
698
|
* @param name - The cookie name
|
|
590
699
|
* @param value - The opaque value to sign into the cookie
|
|
591
|
-
* @param
|
|
700
|
+
* @param signer - The {@link SignerInterface} that signs (its first key signs)
|
|
592
701
|
* @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
|
|
593
702
|
*
|
|
594
703
|
* @example
|
|
595
704
|
* ```ts
|
|
596
705
|
* const headers = new Headers()
|
|
597
|
-
* await writeSignedCookie(headers, 'session', 'user-1', 'secret')
|
|
706
|
+
* await writeSignedCookie(headers, 'session', 'user-1', createSigner('secret'))
|
|
598
707
|
* ```
|
|
599
708
|
*/
|
|
600
|
-
async function writeSignedCookie(headers, name, value,
|
|
601
|
-
headers.append("set-cookie", serializeCookie(name, await signToken(value, {
|
|
709
|
+
async function writeSignedCookie(headers, name, value, signer, options) {
|
|
710
|
+
headers.append("set-cookie", serializeCookie(name, await signToken(value, { signer }), options));
|
|
602
711
|
}
|
|
603
712
|
/**
|
|
604
|
-
* Reads and verifies a signed cookie off a request
|
|
605
|
-
*
|
|
713
|
+
* Reads and verifies a signed cookie off a request, returning the embedded value
|
|
714
|
+
* or `undefined` (the inverse of {@link writeSignedCookie}).
|
|
606
715
|
*
|
|
607
716
|
* @remarks
|
|
608
717
|
* Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
|
|
609
|
-
* and verifies it with {@link verifyToken} against `
|
|
610
|
-
* accepts a cookie signed by any of its
|
|
611
|
-
*
|
|
718
|
+
* and verifies it with {@link verifyToken} against `signer` (a signer over a
|
|
719
|
+
* rotation list accepts a cookie signed by any of its keys). An absent cookie,
|
|
720
|
+
* a tampered value, and a wrong key each yield `undefined`, a name such as
|
|
721
|
+
* `constructor` included. It rejects only when `signer.verify` rejects, which
|
|
722
|
+
* the signer `createSigner` returns never does.
|
|
612
723
|
*
|
|
613
724
|
* @param request - The `Request` to read the `Cookie` header from
|
|
614
725
|
* @param name - The cookie name to read
|
|
615
|
-
* @param
|
|
726
|
+
* @param signer - The {@link SignerInterface} to verify against
|
|
616
727
|
* @returns The embedded value when the cookie is present + valid, else `undefined`
|
|
617
728
|
*
|
|
618
729
|
* @example
|
|
619
730
|
* ```ts
|
|
620
|
-
* const value = await readSignedCookie(request, 'session', 'secret')
|
|
731
|
+
* const value = await readSignedCookie(request, 'session', createSigner('secret'))
|
|
621
732
|
* ```
|
|
622
733
|
*/
|
|
623
|
-
async function readSignedCookie(request, name,
|
|
734
|
+
async function readSignedCookie(request, name, signer) {
|
|
624
735
|
const cookie = parseCookies(request.headers.get("cookie") ?? void 0)[name];
|
|
625
|
-
return cookie === void 0 ? void 0 : verifyToken(cookie,
|
|
736
|
+
return cookie === void 0 ? void 0 : verifyToken(cookie, signer);
|
|
626
737
|
}
|
|
627
738
|
/**
|
|
628
739
|
* Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
|
|
@@ -655,86 +766,55 @@ function clearCookie(headers, name, options) {
|
|
|
655
766
|
* The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
|
|
656
767
|
* absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
|
|
657
768
|
* the expiry is HMAC-COVERED — a client cannot extend it without invalidating
|
|
658
|
-
* the signature), signed by
|
|
659
|
-
* {@link
|
|
660
|
-
* Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
|
|
661
|
-
* misconfigured secret with no usable entry throws an {@link HTTPError}
|
|
662
|
-
* (`500`) — fail-closed, a programmer error. Verify with
|
|
663
|
-
* {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
769
|
+
* the signature), signed by `options.signer`, whose first key signs. Verify
|
|
770
|
+
* with {@link verifyToken}. Omitting `ttl` mints a token that never expires.
|
|
664
771
|
*
|
|
665
772
|
* @param value - The opaque value to embed (a session id, a deployment marker)
|
|
666
|
-
* @param options - The
|
|
773
|
+
* @param options - The `signer` and optional `ttl` (ms); see {@link TokenOptions}
|
|
667
774
|
* @returns The signed `<payload>.<signature>` token string
|
|
668
|
-
* @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
|
|
669
775
|
*
|
|
670
776
|
* @example
|
|
671
777
|
* ```ts
|
|
672
|
-
* const
|
|
673
|
-
*
|
|
778
|
+
* const signer = createSigner('shh')
|
|
779
|
+
* const token = await signToken('client', { signer, ttl: 60_000 })
|
|
780
|
+
* await verifyToken(token, signer) // 'client' (within 60s), else undefined
|
|
674
781
|
* ```
|
|
675
782
|
*/
|
|
676
783
|
async function signToken(value, options) {
|
|
677
|
-
const secret = normalizeSecret(options.secret)[0];
|
|
678
|
-
if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
|
|
679
784
|
const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
|
|
680
785
|
const encoded = encodeBase64URL(new TextEncoder().encode(JSON.stringify({
|
|
681
786
|
value,
|
|
682
787
|
exp
|
|
683
788
|
})));
|
|
684
|
-
|
|
685
|
-
name: "HMAC",
|
|
686
|
-
hash: "SHA-256"
|
|
687
|
-
}, false, ["sign"]);
|
|
688
|
-
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
|
|
689
|
-
return `${encoded}.${encodeBase64URL(new Uint8Array(signature))}`;
|
|
789
|
+
return `${encoded}.${await options.signer.sign(encoded)}`;
|
|
690
790
|
}
|
|
691
791
|
/**
|
|
692
|
-
* Verifies a stateless token and returns its embedded value
|
|
792
|
+
* Verifies a stateless token and returns its embedded value, or `undefined` for a
|
|
793
|
+
* malformed, tampered, or expired token.
|
|
693
794
|
*
|
|
694
795
|
* @remarks
|
|
695
796
|
* The inverse of {@link signToken}: splits the token on its last `.` (so a
|
|
696
|
-
* value containing dots survives),
|
|
697
|
-
*
|
|
698
|
-
*
|
|
699
|
-
*
|
|
700
|
-
* `
|
|
701
|
-
*
|
|
702
|
-
* rotation path). It then decodes + narrows the payload (`isRecord` +
|
|
703
|
-
* `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
|
|
704
|
-
* token. Any failure — a malformed token, a bad signature,
|
|
705
|
-
* a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
|
|
706
|
-
* yields `undefined` rather than throwing.
|
|
797
|
+
* value containing dots survives), checks the signature with `signer.verify`
|
|
798
|
+
* (a signer over a rotation list accepts any of its keys), then decodes and
|
|
799
|
+
* narrows the payload with {@link decodeTokenPayload}, which refuses an
|
|
800
|
+
* elapsed expiry. It rejects only when `signer.verify` rejects, which the
|
|
801
|
+
* signer `createSigner` returns never does, so a consumer signer's outage
|
|
802
|
+
* surfaces as an error rather than as an invalid token.
|
|
707
803
|
*
|
|
708
804
|
* @param token - The candidate token string (from a request header/cookie)
|
|
709
|
-
* @param
|
|
805
|
+
* @param signer - The {@link SignerInterface} to verify against
|
|
710
806
|
* @returns The embedded value when the token is valid + unexpired, else `undefined`
|
|
711
807
|
*
|
|
712
808
|
* @example
|
|
713
809
|
* ```ts
|
|
714
|
-
* await verifyToken('bad.token', 'shh') // undefined
|
|
810
|
+
* await verifyToken('bad.token', createSigner('shh')) // undefined
|
|
715
811
|
* ```
|
|
716
812
|
*/
|
|
717
|
-
async function verifyToken(token,
|
|
718
|
-
const secrets = normalizeSecret(secret);
|
|
719
|
-
if (secrets.length === 0) return void 0;
|
|
813
|
+
async function verifyToken(token, signer) {
|
|
720
814
|
const dot = token.lastIndexOf(".");
|
|
721
815
|
if (dot < 0) return void 0;
|
|
722
816
|
const encoded = token.slice(0, dot);
|
|
723
|
-
|
|
724
|
-
if (signature === void 0) return void 0;
|
|
725
|
-
const data = new TextEncoder().encode(encoded);
|
|
726
|
-
try {
|
|
727
|
-
for (const candidate of secrets) {
|
|
728
|
-
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
|
|
729
|
-
name: "HMAC",
|
|
730
|
-
hash: "SHA-256"
|
|
731
|
-
}, false, ["verify"]);
|
|
732
|
-
if (await crypto.subtle.verify("HMAC", key, signature, data)) return decodeTokenPayload(encoded);
|
|
733
|
-
}
|
|
734
|
-
return;
|
|
735
|
-
} catch {
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
817
|
+
return await signer.verify(encoded, token.slice(dot + 1)) ? decodeTokenPayload(encoded) : void 0;
|
|
738
818
|
}
|
|
739
819
|
/**
|
|
740
820
|
* Decodes and narrows a signed token's base64url JSON payload, honoring its
|
|
@@ -762,25 +842,38 @@ function decodeTokenPayload(encoded) {
|
|
|
762
842
|
return payload.value;
|
|
763
843
|
}
|
|
764
844
|
/**
|
|
765
|
-
* Normalizes a {@link TokenSecret} to
|
|
766
|
-
*
|
|
845
|
+
* Normalizes a {@link TokenSecret} to its `[current, ...older]` list — the list a
|
|
846
|
+
* signer creates its keys from — refusing a malformed secret.
|
|
767
847
|
*
|
|
768
848
|
* @remarks
|
|
769
|
-
* A single string becomes a one-element list; a rotation list is copied
|
|
770
|
-
*
|
|
771
|
-
*
|
|
772
|
-
*
|
|
849
|
+
* A single string becomes a one-element list; a rotation list is copied once
|
|
850
|
+
* and its copy validated, each secret kept verbatim. A blank entry is refused,
|
|
851
|
+
* never dropped, because dropping a blank current secret would make an older
|
|
852
|
+
* key sign. The refusal names the blank or non-string positions in `context`
|
|
853
|
+
* and carries no secret text.
|
|
773
854
|
*
|
|
774
855
|
* @param secret - The {@link TokenSecret} (a single string, or a rotation list)
|
|
775
|
-
* @returns The
|
|
856
|
+
* @returns The secrets, current first
|
|
857
|
+
* @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of
|
|
858
|
+
* strings, when the list is empty, or when any entry is blank
|
|
776
859
|
*
|
|
777
860
|
* @example
|
|
778
861
|
* ```ts
|
|
779
|
-
* normalizeSecret(['new', '
|
|
862
|
+
* normalizeSecret(['new', 'old']) // ['new', 'old']
|
|
863
|
+
* normalizeSecret(['new', ' ']) // throws ServerError 'SECRET', context { entries: [1], count: 2 }
|
|
780
864
|
* ```
|
|
781
865
|
*/
|
|
782
866
|
function normalizeSecret(secret) {
|
|
783
|
-
|
|
867
|
+
const copied = attempt(() => isString(secret) ? [secret] : isArray(secret) ? Array.from(secret) : void 0);
|
|
868
|
+
const entries = copied.success ? copied.value : void 0;
|
|
869
|
+
if (entries === void 0) throw new ServerError("SECRET", "the signing secret is not a string or a list of strings: pass a non-blank string or a non-empty list of non-blank strings", { received: typeof secret });
|
|
870
|
+
const blank = entries.flatMap((entry, index) => isString(entry) && entry.trim().length > 0 ? [] : [index]);
|
|
871
|
+
const [current, ...older] = entries;
|
|
872
|
+
if (!isString(current) || blank.length > 0 || !older.every(isString)) throw new ServerError("SECRET", entries.length === 0 ? "the signing secret is an empty list: pass a non-blank string or a non-empty list of non-blank strings" : `the signing secret has blank or non-string entries at ${blank.join(", ")}: pass a non-blank string or a non-empty list of non-blank strings`, {
|
|
873
|
+
entries: blank,
|
|
874
|
+
count: entries.length
|
|
875
|
+
});
|
|
876
|
+
return [current, ...older];
|
|
784
877
|
}
|
|
785
878
|
/**
|
|
786
879
|
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
@@ -865,7 +958,7 @@ function computeCodingQuality(entries, coding) {
|
|
|
865
958
|
* keeps the earlier-offered coding on a client-side tie, which is what makes
|
|
866
959
|
* `available` the server's preference order. An empty `available` list, and a
|
|
867
960
|
* list the client rejects outright, both yield `undefined` (identity — no
|
|
868
|
-
* compression). Total on
|
|
961
|
+
* compression). Total on malformed input.
|
|
869
962
|
*
|
|
870
963
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
871
964
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
@@ -896,7 +989,7 @@ function resolveCoding(entries, available) {
|
|
|
896
989
|
* {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
|
|
897
990
|
* the two doors onto this axis cannot drift. Returns `undefined` when the
|
|
898
991
|
* client accepts none of `available` (identity — no compression). Total on
|
|
899
|
-
*
|
|
992
|
+
* malformed input.
|
|
900
993
|
*
|
|
901
994
|
* @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
|
|
902
995
|
* @param header - The raw `Accept-Encoding` header value
|
|
@@ -924,7 +1017,8 @@ function negotiateEncoding(header, available) {
|
|
|
924
1017
|
* `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
|
|
925
1018
|
* (less specific) coverage, so a later more-specific match can still allow
|
|
926
1019
|
* it. Among multiple matching entries, the lowest `rank` wins, and among a
|
|
927
|
-
* rank tie the highest `q` wins.
|
|
1020
|
+
* rank tie the highest `q` wins. The candidate matches case-insensitively, as
|
|
1021
|
+
* the entries do.
|
|
928
1022
|
*
|
|
929
1023
|
* @param entries - The parsed {@link AcceptEntry} list
|
|
930
1024
|
* @param candidate - The candidate media type to score (for example `'text/html'`)
|
|
@@ -954,10 +1048,11 @@ function matchMediaType(entries, candidate) {
|
|
|
954
1048
|
* ```
|
|
955
1049
|
*/
|
|
956
1050
|
function* iterateMediaMatches(entries, candidate) {
|
|
957
|
-
const
|
|
958
|
-
const
|
|
1051
|
+
const media = candidate.toLowerCase();
|
|
1052
|
+
const slash = media.indexOf("/");
|
|
1053
|
+
const type = slash === -1 ? media : media.slice(0, slash);
|
|
959
1054
|
for (const entry of entries) {
|
|
960
|
-
const rank = entry.value ===
|
|
1055
|
+
const rank = entry.value === media ? 0 : entry.value === `${type}/*` ? 1 : entry.value === "*/*" ? 2 : void 0;
|
|
961
1056
|
if (rank === void 0) continue;
|
|
962
1057
|
if (entry.q === 0) {
|
|
963
1058
|
if (rank === 0) {
|
|
@@ -1136,15 +1231,28 @@ function matchesETag(header, etag) {
|
|
|
1136
1231
|
* total, returning a {@link RangeSpec} or `undefined`.
|
|
1137
1232
|
*
|
|
1138
1233
|
* @remarks
|
|
1139
|
-
*
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
*
|
|
1143
|
-
*
|
|
1144
|
-
*
|
|
1145
|
-
*
|
|
1146
|
-
*
|
|
1147
|
-
*
|
|
1234
|
+
* Reads the field value by RFC 9110 § 14.1:
|
|
1235
|
+
* `range-unit "=" OWS range-set`, where the unit matches `bytes`
|
|
1236
|
+
* case-insensitively and `range-set` is `1#range-spec` under the § 5.6.1 list
|
|
1237
|
+
* rule, so empty list elements are skipped. OWS is a space or a tab, and it
|
|
1238
|
+
* stands only around the field value, after `=`, and around a `,`; a range
|
|
1239
|
+
* holds none. A range is an `int-range` (`first-pos "-" [ last-pos ]`) or a
|
|
1240
|
+
* `suffix-range` (`"-" suffix-length`), each bound `1*DIGIT` ({@link
|
|
1241
|
+
* import('./constants.js').RANGE_BOUND_PATTERN}). A bound of any length is
|
|
1242
|
+
* compared with {@link compareDigits}, so none is misread through `Number`.
|
|
1243
|
+
* OWS is stripped with {@link stripOWS}, so the read is linear in the header's
|
|
1244
|
+
* length.
|
|
1245
|
+
*
|
|
1246
|
+
* Returns `{ satisfiable: true, start, end }` with the window clamped to
|
|
1247
|
+
* `[0, size - 1]` (the HTTP inclusive-end convention), and
|
|
1248
|
+
* `{ satisfiable: false }` when the range does not overlap the resource: a
|
|
1249
|
+
* `first-pos` at or past `size`, or a zero `suffix-length`.
|
|
1250
|
+
* Returns `undefined`, the § 14.2 "ignore the field and serve the whole
|
|
1251
|
+
* resource" answer, for an absent header, another unit, text outside the
|
|
1252
|
+
* grammar, a `last-pos` below its `first-pos`, more than one range (not
|
|
1253
|
+
* supported), a non-zero `suffix-length` on an empty resource (satisfiable by
|
|
1254
|
+
* § 14.1.2, but it selects no window to serve), and a `size` that is not a
|
|
1255
|
+
* non-negative safe integer. Never throws on a malformed header.
|
|
1148
1256
|
*
|
|
1149
1257
|
* @param header - The raw `Range` header value
|
|
1150
1258
|
* @param size - The resource's total byte length
|
|
@@ -1153,48 +1261,95 @@ function matchesETag(header, etag) {
|
|
|
1153
1261
|
* @example
|
|
1154
1262
|
* ```ts
|
|
1155
1263
|
* parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
|
|
1264
|
+
* parseRange('Bytes=-100,', 1000) // { satisfiable: true, start: 900, end: 999 }
|
|
1156
1265
|
* parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
|
|
1266
|
+
* parseRange('bytes=0x10-', 1000) // undefined — not a decimal bound
|
|
1267
|
+
* parseRange('bytes=5 - 9', 1000) // undefined — no OWS inside a range
|
|
1157
1268
|
* ```
|
|
1158
1269
|
*/
|
|
1159
1270
|
function parseRange(header, size) {
|
|
1160
|
-
if (header === void 0) return void 0;
|
|
1161
|
-
const
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
const spec =
|
|
1166
|
-
if (spec.
|
|
1271
|
+
if (header === void 0 || !isSafeInteger(size) || size < 0) return void 0;
|
|
1272
|
+
const field = stripOWS(header);
|
|
1273
|
+
const equals = field.indexOf("=");
|
|
1274
|
+
if (equals < 0 || field.slice(0, equals).toLowerCase() !== "bytes") return void 0;
|
|
1275
|
+
const specs = field.slice(equals + 1).split(",").map((item) => stripOWS(item)).filter((spec) => spec !== "");
|
|
1276
|
+
const spec = specs[0];
|
|
1277
|
+
if (spec === void 0 || specs.length > 1) return void 0;
|
|
1167
1278
|
const dash = spec.indexOf("-");
|
|
1168
1279
|
if (dash < 0) return void 0;
|
|
1169
|
-
const
|
|
1170
|
-
const
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
if (
|
|
1174
|
-
if (
|
|
1280
|
+
const first = spec.slice(0, dash);
|
|
1281
|
+
const last = spec.slice(dash + 1);
|
|
1282
|
+
const extent = String(size);
|
|
1283
|
+
if (first === "") {
|
|
1284
|
+
if (!RANGE_BOUND_PATTERN.test(last)) return void 0;
|
|
1285
|
+
if (compareDigits(last, "0") === 0) return { satisfiable: false };
|
|
1286
|
+
if (size === 0) return void 0;
|
|
1175
1287
|
return {
|
|
1176
1288
|
satisfiable: true,
|
|
1177
|
-
start:
|
|
1289
|
+
start: compareDigits(last, extent) < 0 ? size - Number(last) : 0,
|
|
1178
1290
|
end: size - 1
|
|
1179
1291
|
};
|
|
1180
1292
|
}
|
|
1181
|
-
|
|
1182
|
-
if (
|
|
1183
|
-
if (
|
|
1184
|
-
if (
|
|
1185
|
-
|
|
1186
|
-
start,
|
|
1187
|
-
end: size - 1
|
|
1188
|
-
};
|
|
1189
|
-
const end = Number(endText);
|
|
1190
|
-
if (!isInteger(end) || end < start) return void 0;
|
|
1293
|
+
if (!RANGE_BOUND_PATTERN.test(first)) return void 0;
|
|
1294
|
+
if (last !== "" && !RANGE_BOUND_PATTERN.test(last)) return void 0;
|
|
1295
|
+
if (last !== "" && compareDigits(last, first) < 0) return void 0;
|
|
1296
|
+
if (compareDigits(first, extent) >= 0) return { satisfiable: false };
|
|
1297
|
+
const end = last === "" || compareDigits(last, extent) >= 0 ? size - 1 : Number(last);
|
|
1191
1298
|
return {
|
|
1192
1299
|
satisfiable: true,
|
|
1193
|
-
start,
|
|
1194
|
-
end
|
|
1300
|
+
start: Number(first),
|
|
1301
|
+
end
|
|
1195
1302
|
};
|
|
1196
1303
|
}
|
|
1197
1304
|
/**
|
|
1305
|
+
* Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other
|
|
1306
|
+
* character — from both ends of a text, in time linear in its length.
|
|
1307
|
+
*
|
|
1308
|
+
* @remarks
|
|
1309
|
+
* Reads the leading run with one anchored match and the trailing run with one
|
|
1310
|
+
* scan from the end, so a long run of spaces followed by another character
|
|
1311
|
+
* costs one pass, where a search for a trailing run restarts at every space.
|
|
1312
|
+
* A Unicode space such as U+00A0 stays, unlike `trim`.
|
|
1313
|
+
*
|
|
1314
|
+
* @param text - The text to strip
|
|
1315
|
+
* @returns `text` without its leading and trailing spaces and tabs
|
|
1316
|
+
*
|
|
1317
|
+
* @example
|
|
1318
|
+
* ```ts
|
|
1319
|
+
* stripOWS(' \tbytes=0-1 ') // 'bytes=0-1'
|
|
1320
|
+
* ```
|
|
1321
|
+
*/
|
|
1322
|
+
function stripOWS(text) {
|
|
1323
|
+
const start = /^[ \t]*/.exec(text)?.[0].length ?? 0;
|
|
1324
|
+
const end = text.split("").findLastIndex((char) => char !== " " && char !== " ") + 1;
|
|
1325
|
+
return end <= start ? "" : text.slice(start, end);
|
|
1326
|
+
}
|
|
1327
|
+
/**
|
|
1328
|
+
* Compares two `1*DIGIT` strings by their decimal value, at any length.
|
|
1329
|
+
*
|
|
1330
|
+
* @remarks
|
|
1331
|
+
* Drops leading zeros, then compares the digit counts and, at an equal count,
|
|
1332
|
+
* the digits in order, so a bound longer than any safe integer compares
|
|
1333
|
+
* exactly and never passes through `Number`. Both arguments must be
|
|
1334
|
+
* `1*DIGIT`; the answer for any other text is unspecified.
|
|
1335
|
+
*
|
|
1336
|
+
* @param left - The first digit string
|
|
1337
|
+
* @param right - The second digit string
|
|
1338
|
+
* @returns `-1` if `left` is less, `1` if it is greater, `0` if the two are equal
|
|
1339
|
+
*
|
|
1340
|
+
* @example
|
|
1341
|
+
* ```ts
|
|
1342
|
+
* compareDigits('9', '10') // -1
|
|
1343
|
+
* compareDigits('007', '7') // 0
|
|
1344
|
+
* ```
|
|
1345
|
+
*/
|
|
1346
|
+
function compareDigits(left, right) {
|
|
1347
|
+
const a = left.replace(/^0+/, "");
|
|
1348
|
+
const b = right.replace(/^0+/, "");
|
|
1349
|
+
if (a.length !== b.length) return a.length < b.length ? -1 : 1;
|
|
1350
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1198
1353
|
* Resolves the `Access-Control-Allow-Origin` value for a request.
|
|
1199
1354
|
*
|
|
1200
1355
|
* @remarks
|
|
@@ -1202,7 +1357,7 @@ function parseRange(header, size) {
|
|
|
1202
1357
|
* echoes the request's `Origin` only when it is present in the list, else
|
|
1203
1358
|
* `undefined` (no header set). Security: the literal `'null'` origin — sent
|
|
1204
1359
|
* by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
|
|
1205
|
-
* never reflected even if `'null'` were listed, closing the
|
|
1360
|
+
* never reflected even if `'null'` were listed, closing the opaque-origin
|
|
1206
1361
|
* cross-origin-access hole.
|
|
1207
1362
|
*
|
|
1208
1363
|
* @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
|
|
@@ -1368,12 +1523,19 @@ function computeClientKey(address) {
|
|
|
1368
1523
|
* @remarks
|
|
1369
1524
|
* Emits an `event:`/`id:`/`retry:` line for each present field, then one
|
|
1370
1525
|
* `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
|
|
1371
|
-
* (so a consuming parser's multi-`data` concat reproduces
|
|
1372
|
-
*
|
|
1373
|
-
* a `data:` line), then the terminating blank line.
|
|
1526
|
+
* (so a consuming parser's multi-`data` concat reproduces `data` with each
|
|
1527
|
+
* line break read as `\n`, and no raw `\r` or `\n` can ever ride onto the wire
|
|
1528
|
+
* inside a `data:` line), then the terminating blank line.
|
|
1529
|
+
*
|
|
1530
|
+
* It refuses a field the wire cannot carry rather than emit a second field or
|
|
1531
|
+
* a second event: an `event` with a line break, an `id` with a line break or
|
|
1532
|
+
* a NUL (which a conforming parser drops), and a `retry` that is not a
|
|
1533
|
+
* non-negative safe integer.
|
|
1374
1534
|
*
|
|
1375
1535
|
* @param message - The event to serialize
|
|
1376
1536
|
* @returns The SSE wire text for the event (terminated by a blank line)
|
|
1537
|
+
* @throws {ServerError} Thrown when a field is refused, with code `'EVENT'`
|
|
1538
|
+
* and `context.field` naming the field
|
|
1377
1539
|
*
|
|
1378
1540
|
* @example
|
|
1379
1541
|
* ```ts
|
|
@@ -1382,12 +1544,32 @@ function computeClientKey(address) {
|
|
|
1382
1544
|
* ```
|
|
1383
1545
|
*/
|
|
1384
1546
|
function serializeEvent(message) {
|
|
1385
|
-
const
|
|
1386
|
-
if (
|
|
1387
|
-
if (
|
|
1388
|
-
if (
|
|
1389
|
-
|
|
1390
|
-
|
|
1547
|
+
const { event, id, retry } = message;
|
|
1548
|
+
if (event !== void 0 && /[\r\n]/.test(event)) throw new ServerError("EVENT", "an SSE event type must be one line", { field: "event" });
|
|
1549
|
+
if (id !== void 0 && /[\r\n\0]/.test(id)) throw new ServerError("EVENT", "an SSE id must be one line with no NUL", { field: "id" });
|
|
1550
|
+
if (retry !== void 0 && !(isSafeInteger(retry) && retry >= 0)) throw new ServerError("EVENT", "an SSE retry must be a non-negative safe integer", { field: "retry" });
|
|
1551
|
+
return `${[
|
|
1552
|
+
...event === void 0 ? [] : [`event: ${event}`],
|
|
1553
|
+
...id === void 0 ? [] : [`id: ${id}`],
|
|
1554
|
+
...retry === void 0 ? [] : [`retry: ${retry}`],
|
|
1555
|
+
...message.data.split(SSE_LINE_PATTERN).map((segment) => `data: ${segment}`)
|
|
1556
|
+
].join("\n")}\n\n`;
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Serializes a comment to the SSE wire, one `: ` line per line of `text`.
|
|
1560
|
+
*
|
|
1561
|
+
* @remarks
|
|
1562
|
+
* Splits `text` on `\r\n`, `\r`, and `\n`, so no line of the comment can
|
|
1563
|
+
* reach a parser as a field and no comment can dispatch an event.
|
|
1564
|
+
*
|
|
1565
|
+
* @example
|
|
1566
|
+
* ```ts
|
|
1567
|
+
* serializeComment('keep-alive') // ': keep-alive\n\n'
|
|
1568
|
+
* serializeComment('a\nb') // ': a\n: b\n\n'
|
|
1569
|
+
* ```
|
|
1570
|
+
*/
|
|
1571
|
+
function serializeComment(text) {
|
|
1572
|
+
return `${text.split(SSE_LINE_PATTERN).map((line) => `: ${line}`).join("\n")}\n\n`;
|
|
1391
1573
|
}
|
|
1392
1574
|
/**
|
|
1393
1575
|
* Checks whether a key is a prototype-pollution vector — `__proto__`,
|
|
@@ -1407,17 +1589,21 @@ function isDangerousKey(key) {
|
|
|
1407
1589
|
return key === "__proto__" || key === "constructor" || key === "prototype";
|
|
1408
1590
|
}
|
|
1409
1591
|
/**
|
|
1410
|
-
* Strips the prototype-pollution keys from a parsed value in place,
|
|
1592
|
+
* Strips the prototype-pollution keys from a parsed value in place, at every depth.
|
|
1411
1593
|
*
|
|
1412
1594
|
* @remarks
|
|
1413
1595
|
* `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
|
|
1414
1596
|
* enumerable `__proto__` data property — but that own key becomes a
|
|
1415
1597
|
* pollution gadget the moment a downstream deep-merge copies it onto a live
|
|
1416
1598
|
* object. This walks the value and `delete`s any own {@link isDangerousKey}
|
|
1417
|
-
* key at every depth,
|
|
1599
|
+
* key at every depth, into nested records and array elements.
|
|
1418
1600
|
* Primitives/`null` pass through untouched. Total — never throws. Mutates the
|
|
1419
1601
|
* freshly-parsed value (which nothing else holds yet).
|
|
1420
1602
|
*
|
|
1603
|
+
* The walk keeps a worklist rather than the call stack, so a value nested as
|
|
1604
|
+
* deep as the body limit admits costs no stack depth, and it reads a node
|
|
1605
|
+
* reached twice once, so a self-referencing value terminates.
|
|
1606
|
+
*
|
|
1421
1607
|
* @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
|
|
1422
1608
|
* @returns The same `value`, with every dangerous key removed at every depth
|
|
1423
1609
|
*
|
|
@@ -1428,19 +1614,21 @@ function isDangerousKey(key) {
|
|
|
1428
1614
|
* ```
|
|
1429
1615
|
*/
|
|
1430
1616
|
function scrubPrototype(value) {
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1617
|
+
const nodes = /* @__PURE__ */ new Set([value]);
|
|
1618
|
+
for (const node of nodes) {
|
|
1619
|
+
if (isArray(node)) {
|
|
1620
|
+
for (const member of node) if (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member);
|
|
1621
|
+
continue;
|
|
1622
|
+
}
|
|
1623
|
+
if (!isRecord(node)) continue;
|
|
1624
|
+
for (const key of Object.keys(node)) {
|
|
1437
1625
|
if (isDangerousKey(key)) {
|
|
1438
|
-
Reflect.deleteProperty(
|
|
1626
|
+
Reflect.deleteProperty(node, key);
|
|
1439
1627
|
continue;
|
|
1440
1628
|
}
|
|
1441
|
-
|
|
1629
|
+
const member = node[key];
|
|
1630
|
+
if (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member);
|
|
1442
1631
|
}
|
|
1443
|
-
return value;
|
|
1444
1632
|
}
|
|
1445
1633
|
return value;
|
|
1446
1634
|
}
|
|
@@ -1452,7 +1640,9 @@ function scrubPrototype(value) {
|
|
|
1452
1640
|
* throwing a {@link ContentTooLargeError} (413) the instant the running total
|
|
1453
1641
|
* exceeds `limit` — before the rest of the stream is buffered — rather than
|
|
1454
1642
|
* collecting an unbounded body. A bodyless request (`request.body === null`)
|
|
1455
|
-
* resolves an empty array. A non-positive `limit` means unbounded.
|
|
1643
|
+
* resolves an empty array. A non-positive `limit` means unbounded. When
|
|
1644
|
+
* `request.signal` aborts before the call or while a read waits, the body is
|
|
1645
|
+
* cancelled with the signal's reason and the promise rejects with that reason.
|
|
1456
1646
|
*
|
|
1457
1647
|
* @param request - The `Request` to drain
|
|
1458
1648
|
* @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
|
|
@@ -1465,21 +1655,29 @@ function scrubPrototype(value) {
|
|
|
1465
1655
|
* ```
|
|
1466
1656
|
*/
|
|
1467
1657
|
async function collectRequestBody(request, limit) {
|
|
1658
|
+
const signal = request.signal;
|
|
1659
|
+
signal.throwIfAborted();
|
|
1468
1660
|
if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
|
|
1469
1661
|
const reader = request.body.getReader();
|
|
1470
1662
|
const chunks = [];
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1663
|
+
const relay = addAbortListener(signal, () => reader.cancel(signal.reason).catch(() => void 0));
|
|
1664
|
+
try {
|
|
1665
|
+
for (;;) {
|
|
1666
|
+
const { done, value } = await reader.read();
|
|
1667
|
+
signal.throwIfAborted();
|
|
1668
|
+
if (done) break;
|
|
1669
|
+
const total = (chunks.at(-1)?.total ?? 0) + value.byteLength;
|
|
1670
|
+
if (limit > 0 && total > limit) {
|
|
1671
|
+
await reader.cancel();
|
|
1672
|
+
throw new ContentTooLargeError(limit);
|
|
1673
|
+
}
|
|
1674
|
+
chunks.push({
|
|
1675
|
+
bytes: value,
|
|
1676
|
+
total
|
|
1677
|
+
});
|
|
1478
1678
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
total
|
|
1482
|
-
});
|
|
1679
|
+
} finally {
|
|
1680
|
+
relay[Symbol.dispose]();
|
|
1483
1681
|
}
|
|
1484
1682
|
const merged = new Uint8Array(chunks.at(-1)?.total ?? 0);
|
|
1485
1683
|
chunks.reduce((offset, chunk) => {
|
|
@@ -1522,7 +1720,7 @@ function parseEncoding(header) {
|
|
|
1522
1720
|
* @remarks
|
|
1523
1721
|
* Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
|
|
1524
1722
|
* `TransformStream` that aborts the pipe the instant the running decompressed
|
|
1525
|
-
* total exceeds `cap` — fail-before-materialize,
|
|
1723
|
+
* total exceeds `cap` — fail-before-materialize, because `DecompressionStream`
|
|
1526
1724
|
* has no `maxOutputLength` knob. A cap breach surfaces
|
|
1527
1725
|
* as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
|
|
1528
1726
|
* compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
|
|
@@ -1583,8 +1781,11 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1583
1781
|
* `options.decompression`, default {@link
|
|
1584
1782
|
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
|
|
1585
1783
|
* content type: `application/json` is parsed by using `@orkestrel/contract`'s
|
|
1586
|
-
* `parseJSON`
|
|
1587
|
-
*
|
|
1784
|
+
* `parseJSON`, `application/x-www-form-urlencoded` is read through
|
|
1785
|
+
* `URLSearchParams` into a record whose repeated field keeps its last value,
|
|
1786
|
+
* and both are scrubbed of prototype-pollution keys ({@link scrubPrototype});
|
|
1787
|
+
* any other type decodes as UTF-8 text. The media type matches
|
|
1788
|
+
* case-insensitively and ignores its parameters.
|
|
1588
1789
|
*
|
|
1589
1790
|
* A malformed JSON body is total: it decodes rather than throwing, so a handler
|
|
1590
1791
|
* that must reject one checks for `undefined` itself, and nothing in the returned
|
|
@@ -1592,8 +1793,9 @@ async function decompressRequestBody(bytes, encoding, cap) {
|
|
|
1592
1793
|
*
|
|
1593
1794
|
* @param request - The `Request` to read the body from
|
|
1594
1795
|
* @param options - The {@link BodyOptions} `limit` + `decompression` caps
|
|
1595
|
-
* @returns The parsed JSON value, the raw text, or
|
|
1596
|
-
* body, and for an `application/json` body whose
|
|
1796
|
+
* @returns The parsed JSON value, the decoded form record, the raw text, or
|
|
1797
|
+
* `undefined` — for an empty body, and for an `application/json` body whose
|
|
1798
|
+
* text is not valid JSON
|
|
1597
1799
|
* @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
|
|
1598
1800
|
* @throws {HTTPError} When the compressed body is corrupt (400)
|
|
1599
1801
|
*
|
|
@@ -1614,6 +1816,7 @@ async function readBody(request, options) {
|
|
|
1614
1816
|
const bareType = contentType === null ? "" : (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase();
|
|
1615
1817
|
const text = new TextDecoder().decode(bytes);
|
|
1616
1818
|
if (bareType === "application/json") return scrubPrototype(parseJSON(text));
|
|
1819
|
+
if (bareType === "application/x-www-form-urlencoded") return scrubPrototype(Object.fromEntries(new URLSearchParams(text)));
|
|
1617
1820
|
return text;
|
|
1618
1821
|
}
|
|
1619
1822
|
/**
|
|
@@ -1679,12 +1882,55 @@ async function probePort(port) {
|
|
|
1679
1882
|
*/
|
|
1680
1883
|
async function discoverPort(preferred) {
|
|
1681
1884
|
if (preferred === void 0) return probePort(0);
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1885
|
+
const probed = await settle(() => probePort(preferred));
|
|
1886
|
+
if (probed.success) return probed.value;
|
|
1887
|
+
if (isCodedError(probed.error) && probed.error.code === "EADDRINUSE") return probePort(0);
|
|
1888
|
+
throw probed.error;
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the
|
|
1892
|
+
* `Response` constructor admits keeps that status, and every other value renders a 500 whose
|
|
1893
|
+
* message stays hidden unless `expose` is `true`.
|
|
1894
|
+
*
|
|
1895
|
+
* @remarks
|
|
1896
|
+
* The renderer is total: it returns a `Response` for every value and never throws.
|
|
1897
|
+
* - An `HTTPError` whose status the `Response` constructor admits renders that status with its
|
|
1898
|
+
* message as the body, and with no body for a null body status (204, 205, and 304).
|
|
1899
|
+
* - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status
|
|
1900
|
+
* no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a
|
|
1901
|
+
* status that is not an integer). Its body is `Internal Server Error`, or the error's own message
|
|
1902
|
+
* when `expose` is `true` and the value is an `Error`.
|
|
1903
|
+
* - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status
|
|
1904
|
+
* differs from its `status`. The server's boundary reports those values with their
|
|
1905
|
+
* `RequestLine`, except a throw after the peer disconnected, which is no fault and reports
|
|
1906
|
+
* nothing.
|
|
1907
|
+
*
|
|
1908
|
+
* @param error - The thrown value
|
|
1909
|
+
* @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it
|
|
1910
|
+
* carries `Internal Server Error`
|
|
1911
|
+
* @returns The response to send
|
|
1912
|
+
*
|
|
1913
|
+
* @example
|
|
1914
|
+
* ```ts
|
|
1915
|
+
* import { buildErrorResponse, HTTPError } from '@src/server'
|
|
1916
|
+
*
|
|
1917
|
+
* buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404
|
|
1918
|
+
* buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500
|
|
1919
|
+
* buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'
|
|
1920
|
+
* ```
|
|
1921
|
+
*/
|
|
1922
|
+
function buildErrorResponse(error, expose) {
|
|
1923
|
+
if (isHTTPError(error)) {
|
|
1924
|
+
const rendered = attempt(() => {
|
|
1925
|
+
const status = error.status;
|
|
1926
|
+
const full = attempt(() => new Response(error.message, { status }));
|
|
1927
|
+
const response = full.success ? full.value : new Response(null, { status });
|
|
1928
|
+
return response.status === status ? response : void 0;
|
|
1929
|
+
});
|
|
1930
|
+
if (rendered.success && rendered.value !== void 0) return rendered.value;
|
|
1687
1931
|
}
|
|
1932
|
+
const message = attempt(() => expose && isError(error) ? error.message : void 0);
|
|
1933
|
+
return new Response(message.success && isString(message.value) ? message.value : "Internal Server Error", { status: 500 });
|
|
1688
1934
|
}
|
|
1689
1935
|
// src/server/Negotiator.ts
|
|
1690
1936
|
/**
|
|
@@ -1696,9 +1942,10 @@ async function discoverPort(preferred) {
|
|
|
1696
1942
|
* `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
|
|
1697
1943
|
* any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
|
|
1698
1944
|
* sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
|
|
1699
|
-
* rest of the substrate uses — one parser, never two.
|
|
1700
|
-
* request `Accept`, negotiates a
|
|
1701
|
-
* the winner — or answers
|
|
1945
|
+
* rest of the substrate uses — one parser, never two. A media type matches
|
|
1946
|
+
* case-insensitively. `format` reads the request `Accept`, negotiates a
|
|
1947
|
+
* {@link FormatHandlerMap}'s keys, and invokes the winner — or answers
|
|
1948
|
+
* `406 Not Acceptable` — and sets `Vary: Accept` on either answer.
|
|
1702
1949
|
*
|
|
1703
1950
|
* @example
|
|
1704
1951
|
* ```ts
|
|
@@ -1745,16 +1992,26 @@ var Negotiator = class {
|
|
|
1745
1992
|
*
|
|
1746
1993
|
* @remarks
|
|
1747
1994
|
* Errors thrown by the negotiated handler propagate unmodified — the
|
|
1748
|
-
* server boundary classifies them, never this negotiator.
|
|
1995
|
+
* server boundary classifies them, never this negotiator. The answer is a
|
|
1996
|
+
* copy of the handler's response carrying `Vary: Accept`.
|
|
1749
1997
|
*/
|
|
1750
1998
|
async format(request, context, handlers) {
|
|
1751
1999
|
const keys = Object.keys(handlers);
|
|
1752
2000
|
const header = request.headers.get("accept");
|
|
1753
2001
|
const type = header === null ? keys[0] : this.negotiate(header, keys);
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
2002
|
+
const handler = type === void 0 ? void 0 : handlers[type];
|
|
2003
|
+
if (handler === void 0) return new Response("Not Acceptable", {
|
|
2004
|
+
status: 406,
|
|
2005
|
+
headers: { Vary: "Accept" }
|
|
2006
|
+
});
|
|
2007
|
+
const response = await handler(request, context);
|
|
2008
|
+
const headers = new Headers(response.headers);
|
|
2009
|
+
headers.set("Vary", mergeVary(headers.get("vary") ?? void 0, "Accept"));
|
|
2010
|
+
return new Response(response.body, {
|
|
2011
|
+
status: response.status,
|
|
2012
|
+
statusText: response.statusText,
|
|
2013
|
+
headers
|
|
2014
|
+
});
|
|
1758
2015
|
}
|
|
1759
2016
|
};
|
|
1760
2017
|
// src/server/ServerBinding.ts
|
|
@@ -1803,9 +2060,9 @@ var ServerBinding = class {
|
|
|
1803
2060
|
* bind is pending, and transitions `idle → starting → listening`. A
|
|
1804
2061
|
* cancelled or expired bind closes its partial server and resets to `idle` for
|
|
1805
2062
|
* another start. `stop()` transitions
|
|
1806
|
-
* to `stopping`:
|
|
2063
|
+
* to `stopping`: aborts the signal of every in-flight request so handlers
|
|
1807
2064
|
* observe cancellation (a request that arrives during the drain is served
|
|
1808
|
-
* with
|
|
2065
|
+
* with its signal already aborted), drains in-flight requests and
|
|
1809
2066
|
* claimed upgraded sockets up to the `drain` deadline (event-driven, no
|
|
1810
2067
|
* busy-loop), then closes → `stopped`. After a clean drain the close
|
|
1811
2068
|
* destroys every connection that carries no open request exchange, and a
|
|
@@ -1817,27 +2074,35 @@ var ServerBinding = class {
|
|
|
1817
2074
|
* counted before the close. After an expired drain the close destroys every
|
|
1818
2075
|
* socket. A `stop()` call made while a stop runs returns that stop's
|
|
1819
2076
|
* promise. `destroy()` is the idempotent final teardown.
|
|
1820
|
-
* - **Per request.**
|
|
1821
|
-
*
|
|
1822
|
-
* `
|
|
1823
|
-
*
|
|
1824
|
-
*
|
|
1825
|
-
*
|
|
1826
|
-
*
|
|
1827
|
-
*
|
|
1828
|
-
*
|
|
1829
|
-
*
|
|
2077
|
+
* - **Per request.** The exchange's own `AbortController` joins the
|
|
2078
|
+
* in-flight registry until the response's `close`; the one
|
|
2079
|
+
* `Request` of the exchange is built through the router's `buildRequest`
|
|
2080
|
+
* with that controller's signal, so `request.signal` aborts on a peer
|
|
2081
|
+
* disconnect, on `context.abort(reason)`, or on `stop()`, and no request
|
|
2082
|
+
* signal links to a signal that outlives the exchange; `context.state` is
|
|
2083
|
+
* built through {@link ServerOptions.state} from the connection facts, which
|
|
2084
|
+
* `context.connection` carries as the same object; the composed middleware
|
|
2085
|
+
* onion runs, terminating in `dispatcher.handle`; the result is written
|
|
2086
|
+
* back through `sendResponse`.
|
|
1830
2087
|
* - **The built-in boundary** wraps the whole per-request chain, including
|
|
1831
2088
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1832
2089
|
* throw (for example, a malformed `Host` header) to a silent `400` with no
|
|
1833
|
-
* `error` emit; everything after (
|
|
2090
|
+
* `error` emit; everything after (connection
|
|
1834
2091
|
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1835
|
-
* behind the outer boundary
|
|
1836
|
-
*
|
|
1837
|
-
*
|
|
1838
|
-
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
2092
|
+
* behind the outer boundary, which renders a throw through
|
|
2093
|
+
* `buildErrorResponse`: an `HTTPError` whose status `Response` admits
|
|
2094
|
+
* keeps that status, with no body for 204, 205, and 304, and every other
|
|
2095
|
+
* throw renders `500` (message hidden unless `expose`). Each fault, every
|
|
2096
|
+
* throw except an `HTTPError` whose status the response carries and a
|
|
2097
|
+
* throw after a peer disconnect the server read first (the peer's FIN or a
|
|
2098
|
+
* reset), reaches `error` and `report` with its
|
|
2099
|
+
* `RequestLine`; a fault on the inner phase's `400` path carries none,
|
|
2100
|
+
* because no `Request` exists there. A `report` that throws or rejects is
|
|
2101
|
+
* contained, except a rejected native promise whose species constructor
|
|
2102
|
+
* cannot build a promise, which reaches `unhandledRejection` (see
|
|
2103
|
+
* `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,
|
|
2104
|
+
* and a terminal catch over the whole exchange, the `400` path included,
|
|
2105
|
+
* holds a throw from any step.
|
|
1841
2106
|
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1842
2107
|
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1843
2108
|
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
@@ -1855,6 +2120,7 @@ var Server = class {
|
|
|
1855
2120
|
#middleware;
|
|
1856
2121
|
#upgradeHandlers = [];
|
|
1857
2122
|
#upgraded = /* @__PURE__ */ new Set();
|
|
2123
|
+
#requests = /* @__PURE__ */ new Set();
|
|
1858
2124
|
#exchanges = /* @__PURE__ */ new Map();
|
|
1859
2125
|
#emitter;
|
|
1860
2126
|
#host;
|
|
@@ -1863,28 +2129,84 @@ var Server = class {
|
|
|
1863
2129
|
#limit;
|
|
1864
2130
|
#expose;
|
|
1865
2131
|
#report;
|
|
1866
|
-
#
|
|
2132
|
+
#startup;
|
|
2133
|
+
#options;
|
|
1867
2134
|
#sockets;
|
|
1868
2135
|
#http;
|
|
1869
|
-
#abort = createAbort();
|
|
1870
2136
|
#wakeup = createAbort();
|
|
1871
2137
|
#status = "idle";
|
|
1872
2138
|
#port;
|
|
1873
|
-
#pending = 0;
|
|
1874
2139
|
#stopping;
|
|
1875
2140
|
constructor(options) {
|
|
1876
|
-
|
|
1877
|
-
|
|
2141
|
+
refuseValue(options.state, isFunction, "Server", {
|
|
2142
|
+
path: ["options", "state"],
|
|
2143
|
+
limit: "a function",
|
|
2144
|
+
code: "placement"
|
|
2145
|
+
});
|
|
2146
|
+
if (options.report !== void 0) refuseValue(options.report, isFunction, "Server", {
|
|
2147
|
+
path: ["options", "report"],
|
|
2148
|
+
limit: "a function",
|
|
2149
|
+
code: "placement"
|
|
2150
|
+
});
|
|
1878
2151
|
const drain = options.drain ?? 1e4;
|
|
1879
|
-
|
|
2152
|
+
refuseValue(drain, isTimeoutDuration, "Server", {
|
|
2153
|
+
path: ["options", "drain"],
|
|
2154
|
+
limit: "an integer from 0 through 2_147_483_647",
|
|
2155
|
+
code: "range"
|
|
2156
|
+
});
|
|
1880
2157
|
const limit = options.limit ?? 1048576;
|
|
1881
|
-
|
|
2158
|
+
refuseValue(limit, (value) => isFiniteNumber(value) && value >= 0, "Server", {
|
|
2159
|
+
path: ["options", "limit"],
|
|
2160
|
+
limit: "a non-negative finite number",
|
|
2161
|
+
code: "range"
|
|
2162
|
+
});
|
|
1882
2163
|
const timeouts = options.timeouts ?? {};
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
2164
|
+
for (const [name, value] of Object.entries(timeouts)) {
|
|
2165
|
+
if (value === void 0) continue;
|
|
2166
|
+
if (name === "keepalive") refuseValue(value, (candidate) => isTimeoutDuration(candidate) && isTimeoutDuration(candidate + 1e3), "Server", {
|
|
2167
|
+
path: [
|
|
2168
|
+
"options",
|
|
2169
|
+
"timeouts",
|
|
2170
|
+
name
|
|
2171
|
+
],
|
|
2172
|
+
limit: "an integer from 0 through 2_147_482_647",
|
|
2173
|
+
code: "range"
|
|
2174
|
+
});
|
|
2175
|
+
else refuseValue(value, isTimeoutDuration, "Server", {
|
|
2176
|
+
path: [
|
|
2177
|
+
"options",
|
|
2178
|
+
"timeouts",
|
|
2179
|
+
name
|
|
2180
|
+
],
|
|
2181
|
+
limit: "an integer from 0 through 2_147_483_647",
|
|
2182
|
+
code: "range"
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
const request = timeouts.request ?? 3e5;
|
|
2186
|
+
const headers = timeouts.headers ?? Math.min(6e4, request);
|
|
2187
|
+
refuseValue(headers, (value) => !(request > 0 && Number(value) > request), "Server", {
|
|
2188
|
+
path: [
|
|
2189
|
+
"options",
|
|
2190
|
+
"timeouts",
|
|
2191
|
+
"headers"
|
|
2192
|
+
],
|
|
2193
|
+
limit: "no greater than options.timeouts.request (300_000 when omitted) while it is positive",
|
|
2194
|
+
code: "range"
|
|
2195
|
+
});
|
|
2196
|
+
const checked = [headers, request].filter((ms) => ms > 0);
|
|
1886
2197
|
const sockets = options.sockets ?? {};
|
|
1887
|
-
for (const [name, value] of Object.entries(sockets))
|
|
2198
|
+
for (const [name, value] of Object.entries(sockets)) {
|
|
2199
|
+
if (value === void 0) continue;
|
|
2200
|
+
refuseValue(value, (candidate) => isInteger(candidate) && candidate >= 0, "Server", {
|
|
2201
|
+
path: [
|
|
2202
|
+
"options",
|
|
2203
|
+
"sockets",
|
|
2204
|
+
name
|
|
2205
|
+
],
|
|
2206
|
+
limit: "a non-negative integer",
|
|
2207
|
+
code: "range"
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
1888
2210
|
this.#id = crypto.randomUUID();
|
|
1889
2211
|
this.#dispatcher = options.dispatcher;
|
|
1890
2212
|
this.#state = options.state;
|
|
@@ -1895,7 +2217,13 @@ var Server = class {
|
|
|
1895
2217
|
this.#limit = limit;
|
|
1896
2218
|
this.#expose = options.expose ?? false;
|
|
1897
2219
|
this.#report = options.report;
|
|
1898
|
-
this.#
|
|
2220
|
+
this.#startup = timeouts.start;
|
|
2221
|
+
this.#options = {
|
|
2222
|
+
headersTimeout: headers,
|
|
2223
|
+
requestTimeout: request,
|
|
2224
|
+
...timeouts.keepalive === void 0 ? {} : { keepAliveTimeout: timeouts.keepalive },
|
|
2225
|
+
...checked.length === 0 ? {} : { connectionsCheckingInterval: Math.ceil(Math.min(...checked) / 2) }
|
|
2226
|
+
};
|
|
1899
2227
|
this.#sockets = sockets;
|
|
1900
2228
|
this.#emitter = new Emitter({
|
|
1901
2229
|
...options.on === void 0 ? {} : { on: options.on },
|
|
@@ -1931,11 +2259,7 @@ var Server = class {
|
|
|
1931
2259
|
start(signal) {
|
|
1932
2260
|
if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
|
|
1933
2261
|
this.#status = "starting";
|
|
1934
|
-
this.#
|
|
1935
|
-
const server = createServer$2((request, response) => this.#handle(request, response));
|
|
1936
|
-
if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
|
|
1937
|
-
if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
|
|
1938
|
-
if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
|
|
2262
|
+
const server = createServer$2(this.#options, (request, response) => this.#handle(request, response));
|
|
1939
2263
|
if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
|
|
1940
2264
|
if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
|
|
1941
2265
|
if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
|
|
@@ -1958,7 +2282,7 @@ var Server = class {
|
|
|
1958
2282
|
this.#emitter.destroy();
|
|
1959
2283
|
return;
|
|
1960
2284
|
}
|
|
1961
|
-
|
|
2285
|
+
for (const exchange of this.#requests) exchange.abort();
|
|
1962
2286
|
const server = this.#http;
|
|
1963
2287
|
if (server !== void 0) await this.#close(server, true);
|
|
1964
2288
|
this.#http = void 0;
|
|
@@ -1970,12 +2294,12 @@ var Server = class {
|
|
|
1970
2294
|
this.#status = "stopping";
|
|
1971
2295
|
this.#emitter.emit("stop");
|
|
1972
2296
|
const server = this.#http;
|
|
1973
|
-
this.#
|
|
2297
|
+
for (const exchange of this.#requests) exchange.abort();
|
|
1974
2298
|
const deadline = createTimeout({ ms: this.#drain });
|
|
1975
2299
|
deadline.start();
|
|
1976
2300
|
try {
|
|
1977
2301
|
await this.#drainPending(deadline.signal);
|
|
1978
|
-
const pending = this.#
|
|
2302
|
+
const pending = this.#requests.size;
|
|
1979
2303
|
const upgraded = this.#upgraded.size;
|
|
1980
2304
|
this.#emitter.emit("drain", pending, upgraded);
|
|
1981
2305
|
if (server !== void 0) {
|
|
@@ -1998,79 +2322,104 @@ var Server = class {
|
|
|
1998
2322
|
message.socket.destroy();
|
|
1999
2323
|
return;
|
|
2000
2324
|
}
|
|
2001
|
-
const
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
this.#
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2325
|
+
const exchange = new AbortController();
|
|
2326
|
+
const disconnect = new AbortController();
|
|
2327
|
+
const release = this.#register(exchange);
|
|
2328
|
+
if (this.#status === "stopping") exchange.abort();
|
|
2329
|
+
const socket = message.socket;
|
|
2330
|
+
response.once("close", () => this.#latch(socket, response, disconnect, release));
|
|
2331
|
+
this.#trackExchange(message, response, () => {
|
|
2332
|
+
this.#latch(socket, response, disconnect, release);
|
|
2333
|
+
exchange.abort();
|
|
2334
|
+
});
|
|
2335
|
+
this.#accept(message, response, exchange, disconnect.signal);
|
|
2336
|
+
}
|
|
2337
|
+
#latch(socket, response, disconnect, release) {
|
|
2338
|
+
const failure = socket.errored;
|
|
2339
|
+
const reset = failure !== null && "code" in failure && failure.code === "ECONNRESET";
|
|
2340
|
+
if (!response.writableEnded && response.errored === null && (socket.readableEnded || reset)) disconnect.abort();
|
|
2341
|
+
release();
|
|
2342
|
+
}
|
|
2343
|
+
async #accept(message, response, exchange, disconnect) {
|
|
2344
|
+
try {
|
|
2345
|
+
const created = attempt(() => buildRequest(message, {
|
|
2346
|
+
response,
|
|
2347
|
+
signal: exchange.signal
|
|
2348
|
+
}));
|
|
2349
|
+
if (created.success) await this.#serve(created.value, message, response, exchange, disconnect);
|
|
2350
|
+
else await this.#respond(buildErrorResponse(new HTTPError(400, "invalid request"), false), response);
|
|
2351
|
+
} catch (error) {
|
|
2352
|
+
response.destroy();
|
|
2353
|
+
this.#fault(error, void 0);
|
|
2012
2354
|
}
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
const
|
|
2355
|
+
}
|
|
2356
|
+
async #serve(request, message, response, exchange, disconnect) {
|
|
2357
|
+
const line = {
|
|
2358
|
+
method: request.method,
|
|
2359
|
+
url: new URL(request.url)
|
|
2360
|
+
};
|
|
2016
2361
|
const start = performance.now();
|
|
2017
2362
|
try {
|
|
2018
|
-
|
|
2019
|
-
const
|
|
2020
|
-
this.#emitter.emit("
|
|
2363
|
+
this.#emitter.emit("request", line.method, line.url.pathname);
|
|
2364
|
+
const result = await this.#run(request, line, message, exchange, disconnect);
|
|
2365
|
+
if (await this.#respond(result, response, line, disconnect) && !disconnect.aborted) this.#emitter.emit("response", {
|
|
2366
|
+
method: line.method,
|
|
2367
|
+
pathname: line.url.pathname,
|
|
2368
|
+
status: result.status,
|
|
2369
|
+
ms: Math.round(performance.now() - start)
|
|
2370
|
+
});
|
|
2371
|
+
} catch (error) {
|
|
2372
|
+
response.destroy();
|
|
2373
|
+
this.#fault(error, line);
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
async #run(request, line, message, exchange, disconnect) {
|
|
2377
|
+
try {
|
|
2021
2378
|
const ip = message.socket.remoteAddress;
|
|
2022
2379
|
const connection = {
|
|
2023
2380
|
...ip === void 0 ? {} : { ip },
|
|
2024
2381
|
encrypted: isEncryptedSocket(message.socket)
|
|
2025
2382
|
};
|
|
2026
2383
|
const context = {
|
|
2027
|
-
url,
|
|
2028
|
-
method,
|
|
2384
|
+
url: line.url,
|
|
2385
|
+
method: line.method,
|
|
2029
2386
|
state: this.#state(connection),
|
|
2030
|
-
|
|
2387
|
+
connection,
|
|
2388
|
+
body: this.#createBody(request),
|
|
2389
|
+
abort: exchange.abort.bind(exchange)
|
|
2031
2390
|
};
|
|
2032
2391
|
const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
pathname: url.pathname,
|
|
2037
|
-
status: result.status,
|
|
2038
|
-
ms: Math.round(performance.now() - start)
|
|
2039
|
-
});
|
|
2392
|
+
const status = result.status;
|
|
2393
|
+
if (isInteger(status) && status >= 200 && status <= 599) return result;
|
|
2394
|
+
throw new HTTPError(status, `a handler returned status ${String(status)}`);
|
|
2040
2395
|
} catch (error) {
|
|
2041
|
-
|
|
2042
|
-
if (!isHTTPError(error)) {
|
|
2043
|
-
this.#emitter.emit("error", error, {
|
|
2044
|
-
method,
|
|
2045
|
-
url
|
|
2046
|
-
});
|
|
2047
|
-
if (this.#report !== void 0) try {
|
|
2048
|
-
this.#report(error, {
|
|
2049
|
-
method,
|
|
2050
|
-
url
|
|
2051
|
-
});
|
|
2052
|
-
} catch {}
|
|
2053
|
-
}
|
|
2054
|
-
await this.#respond(mapped, response);
|
|
2055
|
-
this.#emitter.emit("response", {
|
|
2056
|
-
method,
|
|
2057
|
-
pathname: url.pathname,
|
|
2058
|
-
status: mapped.status,
|
|
2059
|
-
ms: Math.round(performance.now() - start)
|
|
2060
|
-
});
|
|
2396
|
+
return this.#boundary(error, line, disconnect.aborted);
|
|
2061
2397
|
}
|
|
2062
2398
|
}
|
|
2063
|
-
async #respond(result, response) {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
} catch {
|
|
2399
|
+
async #respond(result, response, line, disconnect) {
|
|
2400
|
+
const sent = await settle(() => sendResponse(result, response));
|
|
2401
|
+
if (!sent.success) {
|
|
2067
2402
|
response.destroy();
|
|
2403
|
+
if (disconnect?.aborted !== true) this.#fault(sent.error, line);
|
|
2404
|
+
return false;
|
|
2068
2405
|
}
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
const
|
|
2073
|
-
|
|
2406
|
+
return response.writableFinished;
|
|
2407
|
+
}
|
|
2408
|
+
#boundary(error, line, disconnected) {
|
|
2409
|
+
const rendered = buildErrorResponse(error, this.#expose);
|
|
2410
|
+
const carried = attempt(() => isHTTPError(error) && error.status === rendered.status);
|
|
2411
|
+
if (!disconnected && !(carried.success && carried.value)) this.#fault(error, line);
|
|
2412
|
+
return rendered;
|
|
2413
|
+
}
|
|
2414
|
+
#fault(error, line) {
|
|
2415
|
+
if (line === void 0) this.#emitter.emit("error", error);
|
|
2416
|
+
else this.#emitter.emit("error", error, line);
|
|
2417
|
+
const report = this.#report;
|
|
2418
|
+
if (report === void 0) return;
|
|
2419
|
+
const reported = attempt(() => report(error, line));
|
|
2420
|
+
if (!reported.success) return;
|
|
2421
|
+
const value = reported.value;
|
|
2422
|
+
attempt(() => isPromise(value) ? Promise.prototype.then.call(value, void 0, () => void 0) : Promise.resolve(value).catch(() => void 0));
|
|
2074
2423
|
}
|
|
2075
2424
|
#onUpgrade(request, socket, head) {
|
|
2076
2425
|
if (this.#closed) {
|
|
@@ -2090,7 +2439,7 @@ var Server = class {
|
|
|
2090
2439
|
this.#emitter.emit("upgrade", request, handled);
|
|
2091
2440
|
}
|
|
2092
2441
|
async #listen(server, signal) {
|
|
2093
|
-
const deadline = this.#
|
|
2442
|
+
const deadline = this.#startup === void 0 ? void 0 : createTimeout({ ms: this.#startup });
|
|
2094
2443
|
const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
|
|
2095
2444
|
const binding = createAbort();
|
|
2096
2445
|
const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
|
|
@@ -2141,7 +2490,7 @@ var Server = class {
|
|
|
2141
2490
|
return new Promise((resolve) => {
|
|
2142
2491
|
server.close(() => resolve());
|
|
2143
2492
|
if (force) this.#cut(server);
|
|
2144
|
-
else for (const [socket, open] of this.#exchanges) if (open === 0) socket.destroy();
|
|
2493
|
+
else for (const [socket, open] of this.#exchanges) if (open.size === 0) socket.destroy();
|
|
2145
2494
|
});
|
|
2146
2495
|
}
|
|
2147
2496
|
#cut(server) {
|
|
@@ -2149,25 +2498,27 @@ var Server = class {
|
|
|
2149
2498
|
for (const socket of this.#upgraded) socket.destroy();
|
|
2150
2499
|
}
|
|
2151
2500
|
#trackConnection(socket) {
|
|
2152
|
-
|
|
2153
|
-
|
|
2501
|
+
const open = /* @__PURE__ */ new Map();
|
|
2502
|
+
this.#exchanges.set(socket, open);
|
|
2503
|
+
socket.once("close", () => {
|
|
2504
|
+
for (const [response, release] of open) if (response.socket === null) release();
|
|
2505
|
+
this.#exchanges.delete(socket);
|
|
2506
|
+
});
|
|
2154
2507
|
}
|
|
2155
|
-
async #trackExchange(message, response) {
|
|
2508
|
+
async #trackExchange(message, response, release) {
|
|
2156
2509
|
const socket = message.socket;
|
|
2157
2510
|
const open = this.#exchanges.get(socket);
|
|
2158
2511
|
if (open === void 0) return;
|
|
2159
|
-
|
|
2160
|
-
await Promise.
|
|
2161
|
-
|
|
2162
|
-
if (
|
|
2163
|
-
this.#exchanges.set(socket, left - 1);
|
|
2164
|
-
if (left === 1 && this.#closed) socket.destroy();
|
|
2512
|
+
open.set(response, release);
|
|
2513
|
+
await Promise.all([new Promise((resolve) => message.once("close", resolve)), new Promise((resolve) => response.once("close", resolve))]);
|
|
2514
|
+
open.delete(response);
|
|
2515
|
+
if (open.size === 0 && this.#exchanges.get(socket) === open && this.#closed) socket.destroy();
|
|
2165
2516
|
}
|
|
2166
2517
|
get #closed() {
|
|
2167
2518
|
return this.#status === "stopping" && this.#http?.listening === false;
|
|
2168
2519
|
}
|
|
2169
2520
|
get #inflight() {
|
|
2170
|
-
return this.#
|
|
2521
|
+
return this.#requests.size + this.#upgraded.size;
|
|
2171
2522
|
}
|
|
2172
2523
|
#enter() {
|
|
2173
2524
|
if (this.#inflight === 0) this.#wakeup = createAbort();
|
|
@@ -2175,14 +2526,11 @@ var Server = class {
|
|
|
2175
2526
|
#settle() {
|
|
2176
2527
|
if (this.#inflight === 0) this.#wakeup.abort();
|
|
2177
2528
|
}
|
|
2178
|
-
#
|
|
2529
|
+
#register(exchange) {
|
|
2179
2530
|
this.#enter();
|
|
2180
|
-
this.#
|
|
2181
|
-
const completions = [void 0].values();
|
|
2531
|
+
this.#requests.add(exchange);
|
|
2182
2532
|
return () => {
|
|
2183
|
-
if (
|
|
2184
|
-
this.#pending -= 1;
|
|
2185
|
-
this.#settle();
|
|
2533
|
+
if (this.#requests.delete(exchange)) this.#settle();
|
|
2186
2534
|
};
|
|
2187
2535
|
}
|
|
2188
2536
|
#trackSocket(socket) {
|
|
@@ -2199,6 +2547,42 @@ var Server = class {
|
|
|
2199
2547
|
await once(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
|
|
2200
2548
|
}
|
|
2201
2549
|
};
|
|
2550
|
+
// src/server/Signer.ts
|
|
2551
|
+
/**
|
|
2552
|
+
* Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at
|
|
2553
|
+
* construction and reuses it on every call. Implements exactly {@link SignerInterface}.
|
|
2554
|
+
*
|
|
2555
|
+
* @remarks
|
|
2556
|
+
* The constructor normalizes the secret through {@link normalizeSecret}, so it
|
|
2557
|
+
* throws a {@link ServerError} of code `'SECRET'` for a secret that is not a
|
|
2558
|
+
* string or a list of strings, an empty list, or a list holding a blank entry.
|
|
2559
|
+
* `verify` compares signature bytes only through `timingSafeEqual`, after a
|
|
2560
|
+
* length check.
|
|
2561
|
+
*
|
|
2562
|
+
* @example
|
|
2563
|
+
* ```ts
|
|
2564
|
+
* import { Signer } from '@orkestrel/server'
|
|
2565
|
+
*
|
|
2566
|
+
* const signer = new Signer(['current-secret', 'previous-secret'])
|
|
2567
|
+
* await signer.verify('payload', await signer.sign('payload')) // true
|
|
2568
|
+
* ```
|
|
2569
|
+
*/
|
|
2570
|
+
var Signer = class {
|
|
2571
|
+
#keys;
|
|
2572
|
+
constructor(secret) {
|
|
2573
|
+
const [current, ...older] = normalizeSecret(secret);
|
|
2574
|
+
this.#keys = [createSecretKey(current, "utf8"), ...older.map((entry) => createSecretKey(entry, "utf8"))];
|
|
2575
|
+
}
|
|
2576
|
+
async sign(message) {
|
|
2577
|
+
const [key] = this.#keys;
|
|
2578
|
+
return encodeBase64URL(createHmac("sha256", key).update(message, "utf8").digest());
|
|
2579
|
+
}
|
|
2580
|
+
async verify(message, signature) {
|
|
2581
|
+
const bytes = decodeBase64URL(signature);
|
|
2582
|
+
if (bytes === void 0 || bytes.byteLength !== 32) return false;
|
|
2583
|
+
return this.#keys.some((key) => timingSafeEqual(createHmac("sha256", key).update(message, "utf8").digest(), bytes));
|
|
2584
|
+
}
|
|
2585
|
+
};
|
|
2202
2586
|
// src/server/Stream.ts
|
|
2203
2587
|
/**
|
|
2204
2588
|
* Represents the Server-Sent-Events handle over an open, fetch-standard streaming
|
|
@@ -2214,13 +2598,18 @@ var Server = class {
|
|
|
2214
2598
|
* wakeup, so the whole handle is one entity rather than a closure over four
|
|
2215
2599
|
* bindings.
|
|
2216
2600
|
*
|
|
2601
|
+
* The stream opens with one comment line ({@link serializeComment}), so the
|
|
2602
|
+
* response pump has a first chunk and the headers leave before any event.
|
|
2217
2603
|
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
2218
|
-
* returns whether the controller still has positive desired size
|
|
2604
|
+
* returns whether the controller still has positive desired size; on an open
|
|
2605
|
+
* stream it throws the `ServerError` `serializeEvent` raises for a refused
|
|
2606
|
+
* field and enqueues nothing. A producer
|
|
2219
2607
|
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
2220
2608
|
* consumer pull restoring capacity, or on stream closure. `comment` writes a
|
|
2221
|
-
* `: text` keep-alive line a conforming SSE parser
|
|
2222
|
-
* stream. Every method is a safe no-op
|
|
2223
|
-
* the consumer cancelled the stream), so a late write
|
|
2609
|
+
* `: text` keep-alive line per line of its text, which a conforming SSE parser
|
|
2610
|
+
* ignores; `end` closes the stream. Every method is a safe no-op while `closed`
|
|
2611
|
+
* (ended by `end()`, or the consumer cancelled the stream), so a late write
|
|
2612
|
+
* never throws.
|
|
2224
2613
|
*
|
|
2225
2614
|
* The readiness signal reflects only the process-local `ReadableStream`
|
|
2226
2615
|
* queue — it is not proof that a remote peer consumed bytes. When the response
|
|
@@ -2229,8 +2618,9 @@ var Server = class {
|
|
|
2229
2618
|
* its buffering. Ignoring the return value preserves an unconditional-enqueue
|
|
2230
2619
|
* producer. The default stream strategy counts chunks rather than their byte
|
|
2231
2620
|
* length, so a byte-bounded producer must also cap each message. Return
|
|
2232
|
-
* `response` before awaiting a `false` write
|
|
2233
|
-
* until it receives the response
|
|
2621
|
+
* `response` before awaiting a `false` write or `drain()`, because the consumer
|
|
2622
|
+
* cannot pull until it receives the response, and the opening comment fills
|
|
2623
|
+
* the queue, so a `drain()` before any write also waits on that pull.
|
|
2234
2624
|
*
|
|
2235
2625
|
* @example
|
|
2236
2626
|
* ```ts
|
|
@@ -2276,7 +2666,7 @@ var Stream = class {
|
|
|
2276
2666
|
return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
|
|
2277
2667
|
}
|
|
2278
2668
|
comment(text) {
|
|
2279
|
-
this.#enqueue(
|
|
2669
|
+
this.#enqueue(serializeComment(text));
|
|
2280
2670
|
}
|
|
2281
2671
|
drain() {
|
|
2282
2672
|
const desired = this.#controller?.desiredSize;
|
|
@@ -2292,6 +2682,7 @@ var Stream = class {
|
|
|
2292
2682
|
}
|
|
2293
2683
|
#attach(controller) {
|
|
2294
2684
|
this.#controller = controller;
|
|
2685
|
+
controller.enqueue(this.#encoder.encode(serializeComment("")));
|
|
2295
2686
|
}
|
|
2296
2687
|
#pull(controller) {
|
|
2297
2688
|
if (controller.desiredSize === null || controller.desiredSize <= 0) return;
|
|
@@ -2378,6 +2769,27 @@ function createServer(options) {
|
|
|
2378
2769
|
return new Server(options);
|
|
2379
2770
|
}
|
|
2380
2771
|
/**
|
|
2772
|
+
* Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each
|
|
2773
|
+
* created at this call.
|
|
2774
|
+
*
|
|
2775
|
+
* @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}
|
|
2776
|
+
* @returns A {@link SignerInterface} whose first key signs and whose every key verifies
|
|
2777
|
+
* @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,
|
|
2778
|
+
* when the list is empty, or when any entry is blank
|
|
2779
|
+
*
|
|
2780
|
+
* @example
|
|
2781
|
+
* ```ts
|
|
2782
|
+
* import { createSigner, signToken, verifyToken } from '@orkestrel/server'
|
|
2783
|
+
*
|
|
2784
|
+
* const signer = createSigner(['current-secret', 'previous-secret'])
|
|
2785
|
+
* const token = await signToken('session-7f3a', { signer, ttl: 60_000 })
|
|
2786
|
+
* await verifyToken(token, signer) // 'session-7f3a'
|
|
2787
|
+
* ```
|
|
2788
|
+
*/
|
|
2789
|
+
function createSigner(secret) {
|
|
2790
|
+
return new Signer(secret);
|
|
2791
|
+
}
|
|
2792
|
+
/**
|
|
2381
2793
|
* Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose
|
|
2382
2794
|
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
2383
2795
|
*
|
|
@@ -2400,6 +2812,6 @@ function createServer(options) {
|
|
|
2400
2812
|
function createStream(options) {
|
|
2401
2813
|
return new Stream(options);
|
|
2402
2814
|
}
|
|
2403
|
-
export { COMPRESSIBLE_TYPES, CONTENT_TOO_LARGE_ERROR_BRAND, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SERVER_ERROR_BRAND, SSE_HEADERS, Server, ServerBinding, ServerError, Stream, clearCookie, collectRequestBody, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isContentTooLargeError, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, iterateMediaMatches, iterateRequestBody, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
|
|
2815
|
+
export { COMPRESSIBLE_TYPES, CONTENT_TOO_LARGE_ERROR_BRAND, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, DEFAULT_HEADERS_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, HTTPError, HTTP_ERROR_BRAND, Negotiator, RANGE_BOUND_PATTERN, REQUEST_ID_PATTERN, SERVER_ERROR_BRAND, SSE_HEADERS, SSE_LINE_PATTERN, Server, ServerBinding, ServerError, Signer, Stream, buildErrorResponse, clearCookie, collectRequestBody, compareDigits, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createSigner, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isContentTooLargeError, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, iterateMediaMatches, iterateRequestBody, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeResponse, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeComment, serializeCookie, serializeEvent, signToken, stripOWS, supportsMutation, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
|
|
2404
2816
|
|
|
2405
2817
|
//# sourceMappingURL=index.js.map
|