@orkestrel/server 0.0.27 → 0.0.29
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 +687 -312
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +610 -212
- package/dist/src/server/index.d.ts +610 -212
- package/dist/src/server/index.js +677 -314
- 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, isError, isFiniteNumber, isFunction, isInstance, isInteger, isNumber, isObject, isPromise, 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
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 || !Number.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 && !(Number.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
|
/**
|
|
@@ -1686,6 +1889,51 @@ async function discoverPort(preferred) {
|
|
|
1686
1889
|
throw error;
|
|
1687
1890
|
}
|
|
1688
1891
|
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the
|
|
1894
|
+
* `Response` constructor admits keeps that status, and every other value renders a 500 whose
|
|
1895
|
+
* message stays hidden unless `expose` is `true`.
|
|
1896
|
+
*
|
|
1897
|
+
* @remarks
|
|
1898
|
+
* The renderer is total: it returns a `Response` for every value and never throws.
|
|
1899
|
+
* - An `HTTPError` whose status the `Response` constructor admits renders that status with its
|
|
1900
|
+
* message as the body, and with no body for a null body status (204, 205, and 304).
|
|
1901
|
+
* - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status
|
|
1902
|
+
* no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a
|
|
1903
|
+
* status that is not an integer). Its body is `Internal Server Error`, or the error's own message
|
|
1904
|
+
* when `expose` is `true` and the value is an `Error`.
|
|
1905
|
+
* - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status
|
|
1906
|
+
* differs from its `status`. The server's boundary reports those values with their
|
|
1907
|
+
* `RequestLine`, except a throw after the peer disconnected, which is no fault and reports
|
|
1908
|
+
* nothing.
|
|
1909
|
+
*
|
|
1910
|
+
* @param error - The thrown value
|
|
1911
|
+
* @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it
|
|
1912
|
+
* carries `Internal Server Error`
|
|
1913
|
+
* @returns The response to send
|
|
1914
|
+
*
|
|
1915
|
+
* @example
|
|
1916
|
+
* ```ts
|
|
1917
|
+
* import { buildErrorResponse, HTTPError } from '@src/server'
|
|
1918
|
+
*
|
|
1919
|
+
* buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404
|
|
1920
|
+
* buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500
|
|
1921
|
+
* buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'
|
|
1922
|
+
* ```
|
|
1923
|
+
*/
|
|
1924
|
+
function buildErrorResponse(error, expose) {
|
|
1925
|
+
if (isHTTPError(error)) {
|
|
1926
|
+
const rendered = attempt(() => {
|
|
1927
|
+
const status = error.status;
|
|
1928
|
+
const full = attempt(() => new Response(error.message, { status }));
|
|
1929
|
+
const response = full.success ? full.value : new Response(null, { status });
|
|
1930
|
+
return response.status === status ? response : void 0;
|
|
1931
|
+
});
|
|
1932
|
+
if (rendered.success && rendered.value !== void 0) return rendered.value;
|
|
1933
|
+
}
|
|
1934
|
+
const message = attempt(() => expose && isError(error) ? error.message : void 0);
|
|
1935
|
+
return new Response(message.success && isString(message.value) ? message.value : "Internal Server Error", { status: 500 });
|
|
1936
|
+
}
|
|
1689
1937
|
// src/server/Negotiator.ts
|
|
1690
1938
|
/**
|
|
1691
1939
|
* Represents the content-negotiation machine over the weighted `Accept` family — a
|
|
@@ -1696,9 +1944,10 @@ async function discoverPort(preferred) {
|
|
|
1696
1944
|
* `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
|
|
1697
1945
|
* any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
|
|
1698
1946
|
* 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
|
|
1947
|
+
* rest of the substrate uses — one parser, never two. A media type matches
|
|
1948
|
+
* case-insensitively. `format` reads the request `Accept`, negotiates a
|
|
1949
|
+
* {@link FormatHandlerMap}'s keys, and invokes the winner — or answers
|
|
1950
|
+
* `406 Not Acceptable` — and sets `Vary: Accept` on either answer.
|
|
1702
1951
|
*
|
|
1703
1952
|
* @example
|
|
1704
1953
|
* ```ts
|
|
@@ -1745,16 +1994,26 @@ var Negotiator = class {
|
|
|
1745
1994
|
*
|
|
1746
1995
|
* @remarks
|
|
1747
1996
|
* Errors thrown by the negotiated handler propagate unmodified — the
|
|
1748
|
-
* server boundary classifies them, never this negotiator.
|
|
1997
|
+
* server boundary classifies them, never this negotiator. The answer is a
|
|
1998
|
+
* copy of the handler's response carrying `Vary: Accept`.
|
|
1749
1999
|
*/
|
|
1750
2000
|
async format(request, context, handlers) {
|
|
1751
2001
|
const keys = Object.keys(handlers);
|
|
1752
2002
|
const header = request.headers.get("accept");
|
|
1753
2003
|
const type = header === null ? keys[0] : this.negotiate(header, keys);
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
2004
|
+
const handler = type === void 0 ? void 0 : handlers[type];
|
|
2005
|
+
if (handler === void 0) return new Response("Not Acceptable", {
|
|
2006
|
+
status: 406,
|
|
2007
|
+
headers: { Vary: "Accept" }
|
|
2008
|
+
});
|
|
2009
|
+
const response = await handler(request, context);
|
|
2010
|
+
const headers = new Headers(response.headers);
|
|
2011
|
+
headers.set("Vary", mergeVary(headers.get("vary") ?? void 0, "Accept"));
|
|
2012
|
+
return new Response(response.body, {
|
|
2013
|
+
status: response.status,
|
|
2014
|
+
statusText: response.statusText,
|
|
2015
|
+
headers
|
|
2016
|
+
});
|
|
1758
2017
|
}
|
|
1759
2018
|
};
|
|
1760
2019
|
// src/server/ServerBinding.ts
|
|
@@ -1803,9 +2062,9 @@ var ServerBinding = class {
|
|
|
1803
2062
|
* bind is pending, and transitions `idle → starting → listening`. A
|
|
1804
2063
|
* cancelled or expired bind closes its partial server and resets to `idle` for
|
|
1805
2064
|
* another start. `stop()` transitions
|
|
1806
|
-
* to `stopping`:
|
|
2065
|
+
* to `stopping`: aborts the signal of every in-flight request so handlers
|
|
1807
2066
|
* observe cancellation (a request that arrives during the drain is served
|
|
1808
|
-
* with
|
|
2067
|
+
* with its signal already aborted), drains in-flight requests and
|
|
1809
2068
|
* claimed upgraded sockets up to the `drain` deadline (event-driven, no
|
|
1810
2069
|
* busy-loop), then closes → `stopped`. After a clean drain the close
|
|
1811
2070
|
* destroys every connection that carries no open request exchange, and a
|
|
@@ -1817,27 +2076,35 @@ var ServerBinding = class {
|
|
|
1817
2076
|
* counted before the close. After an expired drain the close destroys every
|
|
1818
2077
|
* socket. A `stop()` call made while a stop runs returns that stop's
|
|
1819
2078
|
* promise. `destroy()` is the idempotent final teardown.
|
|
1820
|
-
* - **Per request.**
|
|
1821
|
-
*
|
|
1822
|
-
* `
|
|
1823
|
-
*
|
|
1824
|
-
*
|
|
1825
|
-
*
|
|
1826
|
-
*
|
|
1827
|
-
*
|
|
1828
|
-
*
|
|
1829
|
-
*
|
|
2079
|
+
* - **Per request.** The exchange's own `AbortController` joins the
|
|
2080
|
+
* in-flight registry until the response's `close`; the one
|
|
2081
|
+
* `Request` of the exchange is built through the router's `buildRequest`
|
|
2082
|
+
* with that controller's signal, so `request.signal` aborts on a peer
|
|
2083
|
+
* disconnect, on `context.abort(reason)`, or on `stop()`, and no request
|
|
2084
|
+
* signal links to a signal that outlives the exchange; `context.state` is
|
|
2085
|
+
* built through {@link ServerOptions.state} from the connection facts, which
|
|
2086
|
+
* `context.connection` carries as the same object; the composed middleware
|
|
2087
|
+
* onion runs, terminating in `dispatcher.handle`; the result is written
|
|
2088
|
+
* back through `sendResponse`.
|
|
1830
2089
|
* - **The built-in boundary** wraps the whole per-request chain, including
|
|
1831
2090
|
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1832
2091
|
* throw (for example, a malformed `Host` header) to a silent `400` with no
|
|
1833
|
-
* `error` emit; everything after (
|
|
2092
|
+
* `error` emit; everything after (connection
|
|
1834
2093
|
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1835
|
-
* behind the outer boundary
|
|
1836
|
-
*
|
|
1837
|
-
*
|
|
1838
|
-
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
2094
|
+
* behind the outer boundary, which renders a throw through
|
|
2095
|
+
* `buildErrorResponse`: an `HTTPError` whose status `Response` admits
|
|
2096
|
+
* keeps that status, with no body for 204, 205, and 304, and every other
|
|
2097
|
+
* throw renders `500` (message hidden unless `expose`). Each fault, every
|
|
2098
|
+
* throw except an `HTTPError` whose status the response carries and a
|
|
2099
|
+
* throw after a peer disconnect the server read first (the peer's FIN or a
|
|
2100
|
+
* reset), reaches `error` and `report` with its
|
|
2101
|
+
* `RequestLine`; a fault on the inner phase's `400` path carries none,
|
|
2102
|
+
* because no `Request` exists there. A `report` that throws or rejects is
|
|
2103
|
+
* contained, except a rejected native promise whose species constructor
|
|
2104
|
+
* cannot build a promise, which reaches `unhandledRejection` (see
|
|
2105
|
+
* `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,
|
|
2106
|
+
* and a terminal catch over the whole exchange, the `400` path included,
|
|
2107
|
+
* holds a throw from any step.
|
|
1841
2108
|
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1842
2109
|
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1843
2110
|
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
@@ -1855,6 +2122,7 @@ var Server = class {
|
|
|
1855
2122
|
#middleware;
|
|
1856
2123
|
#upgradeHandlers = [];
|
|
1857
2124
|
#upgraded = /* @__PURE__ */ new Set();
|
|
2125
|
+
#requests = /* @__PURE__ */ new Set();
|
|
1858
2126
|
#exchanges = /* @__PURE__ */ new Map();
|
|
1859
2127
|
#emitter;
|
|
1860
2128
|
#host;
|
|
@@ -1863,14 +2131,13 @@ var Server = class {
|
|
|
1863
2131
|
#limit;
|
|
1864
2132
|
#expose;
|
|
1865
2133
|
#report;
|
|
1866
|
-
#
|
|
2134
|
+
#startup;
|
|
2135
|
+
#options;
|
|
1867
2136
|
#sockets;
|
|
1868
2137
|
#http;
|
|
1869
|
-
#abort = createAbort();
|
|
1870
2138
|
#wakeup = createAbort();
|
|
1871
2139
|
#status = "idle";
|
|
1872
2140
|
#port;
|
|
1873
|
-
#pending = 0;
|
|
1874
2141
|
#stopping;
|
|
1875
2142
|
constructor(options) {
|
|
1876
2143
|
if (!isFunction(options.state)) throw new TypeError("ServerOptions.state must be a function");
|
|
@@ -1880,9 +2147,14 @@ var Server = class {
|
|
|
1880
2147
|
const limit = options.limit ?? 1048576;
|
|
1881
2148
|
if (!isFiniteNumber(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
|
|
1882
2149
|
const timeouts = options.timeouts ?? {};
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
2150
|
+
for (const [name, value] of Object.entries(timeouts)) {
|
|
2151
|
+
const keepalive = name === "keepalive";
|
|
2152
|
+
if (value !== void 0 && !(isTimeoutDuration(value) && (!keepalive || isTimeoutDuration(value + 1e3)))) throw new TypeError(`ServerOptions.timeouts.${name} must be an integer from 0 through ${keepalive ? "2_147_482_647" : "2_147_483_647"}`);
|
|
2153
|
+
}
|
|
2154
|
+
const request = timeouts.request ?? 3e5;
|
|
2155
|
+
const headers = timeouts.headers ?? Math.min(6e4, request);
|
|
2156
|
+
if (request > 0 && headers > request) throw new TypeError("ServerOptions.timeouts.headers must not exceed ServerOptions.timeouts.request (300_000 when omitted) while timeouts.request is positive");
|
|
2157
|
+
const checked = [headers, request].filter((ms) => ms > 0);
|
|
1886
2158
|
const sockets = options.sockets ?? {};
|
|
1887
2159
|
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`);
|
|
1888
2160
|
this.#id = crypto.randomUUID();
|
|
@@ -1895,7 +2167,13 @@ var Server = class {
|
|
|
1895
2167
|
this.#limit = limit;
|
|
1896
2168
|
this.#expose = options.expose ?? false;
|
|
1897
2169
|
this.#report = options.report;
|
|
1898
|
-
this.#
|
|
2170
|
+
this.#startup = timeouts.start;
|
|
2171
|
+
this.#options = {
|
|
2172
|
+
headersTimeout: headers,
|
|
2173
|
+
requestTimeout: request,
|
|
2174
|
+
...timeouts.keepalive === void 0 ? {} : { keepAliveTimeout: timeouts.keepalive },
|
|
2175
|
+
...checked.length === 0 ? {} : { connectionsCheckingInterval: Math.ceil(Math.min(...checked) / 2) }
|
|
2176
|
+
};
|
|
1899
2177
|
this.#sockets = sockets;
|
|
1900
2178
|
this.#emitter = new Emitter({
|
|
1901
2179
|
...options.on === void 0 ? {} : { on: options.on },
|
|
@@ -1931,11 +2209,7 @@ var Server = class {
|
|
|
1931
2209
|
start(signal) {
|
|
1932
2210
|
if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
|
|
1933
2211
|
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;
|
|
2212
|
+
const server = createServer$2(this.#options, (request, response) => this.#handle(request, response));
|
|
1939
2213
|
if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
|
|
1940
2214
|
if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
|
|
1941
2215
|
if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
|
|
@@ -1958,7 +2232,7 @@ var Server = class {
|
|
|
1958
2232
|
this.#emitter.destroy();
|
|
1959
2233
|
return;
|
|
1960
2234
|
}
|
|
1961
|
-
|
|
2235
|
+
for (const exchange of this.#requests) exchange.abort();
|
|
1962
2236
|
const server = this.#http;
|
|
1963
2237
|
if (server !== void 0) await this.#close(server, true);
|
|
1964
2238
|
this.#http = void 0;
|
|
@@ -1970,12 +2244,12 @@ var Server = class {
|
|
|
1970
2244
|
this.#status = "stopping";
|
|
1971
2245
|
this.#emitter.emit("stop");
|
|
1972
2246
|
const server = this.#http;
|
|
1973
|
-
this.#
|
|
2247
|
+
for (const exchange of this.#requests) exchange.abort();
|
|
1974
2248
|
const deadline = createTimeout({ ms: this.#drain });
|
|
1975
2249
|
deadline.start();
|
|
1976
2250
|
try {
|
|
1977
2251
|
await this.#drainPending(deadline.signal);
|
|
1978
|
-
const pending = this.#
|
|
2252
|
+
const pending = this.#requests.size;
|
|
1979
2253
|
const upgraded = this.#upgraded.size;
|
|
1980
2254
|
this.#emitter.emit("drain", pending, upgraded);
|
|
1981
2255
|
if (server !== void 0) {
|
|
@@ -1998,79 +2272,105 @@ var Server = class {
|
|
|
1998
2272
|
message.socket.destroy();
|
|
1999
2273
|
return;
|
|
2000
2274
|
}
|
|
2001
|
-
const
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
this.#
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2275
|
+
const exchange = new AbortController();
|
|
2276
|
+
const disconnect = new AbortController();
|
|
2277
|
+
const release = this.#register(exchange);
|
|
2278
|
+
if (this.#status === "stopping") exchange.abort();
|
|
2279
|
+
const socket = message.socket;
|
|
2280
|
+
response.once("close", () => this.#latch(socket, response, disconnect, release));
|
|
2281
|
+
this.#trackExchange(message, response, () => {
|
|
2282
|
+
this.#latch(socket, response, disconnect, release);
|
|
2283
|
+
exchange.abort();
|
|
2284
|
+
});
|
|
2285
|
+
this.#accept(message, response, exchange, disconnect.signal);
|
|
2286
|
+
}
|
|
2287
|
+
#latch(socket, response, disconnect, release) {
|
|
2288
|
+
const failure = socket.errored;
|
|
2289
|
+
const reset = failure !== null && "code" in failure && failure.code === "ECONNRESET";
|
|
2290
|
+
if (!response.writableEnded && response.errored === null && (socket.readableEnded || reset)) disconnect.abort();
|
|
2291
|
+
release();
|
|
2292
|
+
}
|
|
2293
|
+
async #accept(message, response, exchange, disconnect) {
|
|
2294
|
+
try {
|
|
2295
|
+
const created = attempt(() => buildRequest(message, {
|
|
2296
|
+
response,
|
|
2297
|
+
signal: exchange.signal
|
|
2298
|
+
}));
|
|
2299
|
+
if (created.success) await this.#serve(created.value, message, response, exchange, disconnect);
|
|
2300
|
+
else await this.#respond(buildErrorResponse(new HTTPError(400, "invalid request"), false), response);
|
|
2301
|
+
} catch (error) {
|
|
2302
|
+
response.destroy();
|
|
2303
|
+
this.#fault(error, void 0);
|
|
2012
2304
|
}
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
const
|
|
2305
|
+
}
|
|
2306
|
+
async #serve(request, message, response, exchange, disconnect) {
|
|
2307
|
+
const line = {
|
|
2308
|
+
method: request.method,
|
|
2309
|
+
url: new URL(request.url)
|
|
2310
|
+
};
|
|
2016
2311
|
const start = performance.now();
|
|
2017
2312
|
try {
|
|
2018
|
-
|
|
2019
|
-
const
|
|
2020
|
-
this.#emitter.emit("
|
|
2313
|
+
this.#emitter.emit("request", line.method, line.url.pathname);
|
|
2314
|
+
const result = await this.#run(request, line, message, exchange, disconnect);
|
|
2315
|
+
if (await this.#respond(result, response, line, disconnect) && !disconnect.aborted) this.#emitter.emit("response", {
|
|
2316
|
+
method: line.method,
|
|
2317
|
+
pathname: line.url.pathname,
|
|
2318
|
+
status: result.status,
|
|
2319
|
+
ms: Math.round(performance.now() - start)
|
|
2320
|
+
});
|
|
2321
|
+
} catch (error) {
|
|
2322
|
+
response.destroy();
|
|
2323
|
+
this.#fault(error, line);
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
async #run(request, line, message, exchange, disconnect) {
|
|
2327
|
+
try {
|
|
2021
2328
|
const ip = message.socket.remoteAddress;
|
|
2022
2329
|
const connection = {
|
|
2023
2330
|
...ip === void 0 ? {} : { ip },
|
|
2024
2331
|
encrypted: isEncryptedSocket(message.socket)
|
|
2025
2332
|
};
|
|
2026
2333
|
const context = {
|
|
2027
|
-
url,
|
|
2028
|
-
method,
|
|
2334
|
+
url: line.url,
|
|
2335
|
+
method: line.method,
|
|
2029
2336
|
state: this.#state(connection),
|
|
2030
|
-
|
|
2337
|
+
connection,
|
|
2338
|
+
body: this.#createBody(request),
|
|
2339
|
+
abort: exchange.abort.bind(exchange)
|
|
2031
2340
|
};
|
|
2032
2341
|
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
|
-
});
|
|
2342
|
+
const status = result.status;
|
|
2343
|
+
if (isInteger(status) && status >= 200 && status <= 599) return result;
|
|
2344
|
+
throw new HTTPError(status, `a handler returned status ${String(status)}`);
|
|
2040
2345
|
} 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
|
-
});
|
|
2346
|
+
return this.#boundary(error, line, disconnect.aborted);
|
|
2061
2347
|
}
|
|
2062
2348
|
}
|
|
2063
|
-
async #respond(result, response) {
|
|
2349
|
+
async #respond(result, response, line, disconnect) {
|
|
2064
2350
|
try {
|
|
2065
2351
|
await sendResponse(result, response);
|
|
2066
|
-
} catch {
|
|
2352
|
+
} catch (error) {
|
|
2067
2353
|
response.destroy();
|
|
2354
|
+
if (disconnect?.aborted !== true) this.#fault(error, line);
|
|
2355
|
+
return false;
|
|
2068
2356
|
}
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
const
|
|
2073
|
-
|
|
2357
|
+
return response.writableFinished;
|
|
2358
|
+
}
|
|
2359
|
+
#boundary(error, line, disconnected) {
|
|
2360
|
+
const rendered = buildErrorResponse(error, this.#expose);
|
|
2361
|
+
const carried = attempt(() => isHTTPError(error) && error.status === rendered.status);
|
|
2362
|
+
if (!disconnected && !(carried.success && carried.value)) this.#fault(error, line);
|
|
2363
|
+
return rendered;
|
|
2364
|
+
}
|
|
2365
|
+
#fault(error, line) {
|
|
2366
|
+
if (line === void 0) this.#emitter.emit("error", error);
|
|
2367
|
+
else this.#emitter.emit("error", error, line);
|
|
2368
|
+
const report = this.#report;
|
|
2369
|
+
if (report === void 0) return;
|
|
2370
|
+
const reported = attempt(() => report(error, line));
|
|
2371
|
+
if (!reported.success) return;
|
|
2372
|
+
const value = reported.value;
|
|
2373
|
+
attempt(() => isPromise(value) ? Promise.prototype.then.call(value, void 0, () => void 0) : Promise.resolve(value).catch(() => void 0));
|
|
2074
2374
|
}
|
|
2075
2375
|
#onUpgrade(request, socket, head) {
|
|
2076
2376
|
if (this.#closed) {
|
|
@@ -2090,7 +2390,7 @@ var Server = class {
|
|
|
2090
2390
|
this.#emitter.emit("upgrade", request, handled);
|
|
2091
2391
|
}
|
|
2092
2392
|
async #listen(server, signal) {
|
|
2093
|
-
const deadline = this.#
|
|
2393
|
+
const deadline = this.#startup === void 0 ? void 0 : createTimeout({ ms: this.#startup });
|
|
2094
2394
|
const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
|
|
2095
2395
|
const binding = createAbort();
|
|
2096
2396
|
const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
|
|
@@ -2141,7 +2441,7 @@ var Server = class {
|
|
|
2141
2441
|
return new Promise((resolve) => {
|
|
2142
2442
|
server.close(() => resolve());
|
|
2143
2443
|
if (force) this.#cut(server);
|
|
2144
|
-
else for (const [socket, open] of this.#exchanges) if (open === 0) socket.destroy();
|
|
2444
|
+
else for (const [socket, open] of this.#exchanges) if (open.size === 0) socket.destroy();
|
|
2145
2445
|
});
|
|
2146
2446
|
}
|
|
2147
2447
|
#cut(server) {
|
|
@@ -2149,25 +2449,27 @@ var Server = class {
|
|
|
2149
2449
|
for (const socket of this.#upgraded) socket.destroy();
|
|
2150
2450
|
}
|
|
2151
2451
|
#trackConnection(socket) {
|
|
2152
|
-
|
|
2153
|
-
|
|
2452
|
+
const open = /* @__PURE__ */ new Map();
|
|
2453
|
+
this.#exchanges.set(socket, open);
|
|
2454
|
+
socket.once("close", () => {
|
|
2455
|
+
for (const [response, settle] of open) if (response.socket === null) settle();
|
|
2456
|
+
this.#exchanges.delete(socket);
|
|
2457
|
+
});
|
|
2154
2458
|
}
|
|
2155
|
-
async #trackExchange(message, response) {
|
|
2459
|
+
async #trackExchange(message, response, settle) {
|
|
2156
2460
|
const socket = message.socket;
|
|
2157
2461
|
const open = this.#exchanges.get(socket);
|
|
2158
2462
|
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();
|
|
2463
|
+
open.set(response, settle);
|
|
2464
|
+
await Promise.all([new Promise((resolve) => message.once("close", resolve)), new Promise((resolve) => response.once("close", resolve))]);
|
|
2465
|
+
open.delete(response);
|
|
2466
|
+
if (open.size === 0 && this.#exchanges.get(socket) === open && this.#closed) socket.destroy();
|
|
2165
2467
|
}
|
|
2166
2468
|
get #closed() {
|
|
2167
2469
|
return this.#status === "stopping" && this.#http?.listening === false;
|
|
2168
2470
|
}
|
|
2169
2471
|
get #inflight() {
|
|
2170
|
-
return this.#
|
|
2472
|
+
return this.#requests.size + this.#upgraded.size;
|
|
2171
2473
|
}
|
|
2172
2474
|
#enter() {
|
|
2173
2475
|
if (this.#inflight === 0) this.#wakeup = createAbort();
|
|
@@ -2175,14 +2477,11 @@ var Server = class {
|
|
|
2175
2477
|
#settle() {
|
|
2176
2478
|
if (this.#inflight === 0) this.#wakeup.abort();
|
|
2177
2479
|
}
|
|
2178
|
-
#
|
|
2480
|
+
#register(exchange) {
|
|
2179
2481
|
this.#enter();
|
|
2180
|
-
this.#
|
|
2181
|
-
const completions = [void 0].values();
|
|
2482
|
+
this.#requests.add(exchange);
|
|
2182
2483
|
return () => {
|
|
2183
|
-
if (
|
|
2184
|
-
this.#pending -= 1;
|
|
2185
|
-
this.#settle();
|
|
2484
|
+
if (this.#requests.delete(exchange)) this.#settle();
|
|
2186
2485
|
};
|
|
2187
2486
|
}
|
|
2188
2487
|
#trackSocket(socket) {
|
|
@@ -2199,6 +2498,42 @@ var Server = class {
|
|
|
2199
2498
|
await once(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
|
|
2200
2499
|
}
|
|
2201
2500
|
};
|
|
2501
|
+
// src/server/Signer.ts
|
|
2502
|
+
/**
|
|
2503
|
+
* Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at
|
|
2504
|
+
* construction and reuses it on every call. Implements exactly {@link SignerInterface}.
|
|
2505
|
+
*
|
|
2506
|
+
* @remarks
|
|
2507
|
+
* The constructor normalizes the secret through {@link normalizeSecret}, so it
|
|
2508
|
+
* throws a {@link ServerError} of code `'SECRET'` for a secret that is not a
|
|
2509
|
+
* string or a list of strings, an empty list, or a list holding a blank entry.
|
|
2510
|
+
* `verify` compares signature bytes only through `timingSafeEqual`, after a
|
|
2511
|
+
* length check.
|
|
2512
|
+
*
|
|
2513
|
+
* @example
|
|
2514
|
+
* ```ts
|
|
2515
|
+
* import { Signer } from '@orkestrel/server'
|
|
2516
|
+
*
|
|
2517
|
+
* const signer = new Signer(['current-secret', 'previous-secret'])
|
|
2518
|
+
* await signer.verify('payload', await signer.sign('payload')) // true
|
|
2519
|
+
* ```
|
|
2520
|
+
*/
|
|
2521
|
+
var Signer = class {
|
|
2522
|
+
#keys;
|
|
2523
|
+
constructor(secret) {
|
|
2524
|
+
const [current, ...older] = normalizeSecret(secret);
|
|
2525
|
+
this.#keys = [createSecretKey(current, "utf8"), ...older.map((entry) => createSecretKey(entry, "utf8"))];
|
|
2526
|
+
}
|
|
2527
|
+
async sign(message) {
|
|
2528
|
+
const [key] = this.#keys;
|
|
2529
|
+
return encodeBase64URL(createHmac("sha256", key).update(message, "utf8").digest());
|
|
2530
|
+
}
|
|
2531
|
+
async verify(message, signature) {
|
|
2532
|
+
const bytes = decodeBase64URL(signature);
|
|
2533
|
+
if (bytes === void 0 || bytes.byteLength !== 32) return false;
|
|
2534
|
+
return this.#keys.some((key) => timingSafeEqual(createHmac("sha256", key).update(message, "utf8").digest(), bytes));
|
|
2535
|
+
}
|
|
2536
|
+
};
|
|
2202
2537
|
// src/server/Stream.ts
|
|
2203
2538
|
/**
|
|
2204
2539
|
* Represents the Server-Sent-Events handle over an open, fetch-standard streaming
|
|
@@ -2214,13 +2549,18 @@ var Server = class {
|
|
|
2214
2549
|
* wakeup, so the whole handle is one entity rather than a closure over four
|
|
2215
2550
|
* bindings.
|
|
2216
2551
|
*
|
|
2552
|
+
* The stream opens with one comment line ({@link serializeComment}), so the
|
|
2553
|
+
* response pump has a first chunk and the headers leave before any event.
|
|
2217
2554
|
* `write` serializes one message ({@link serializeEvent}), enqueues it, and
|
|
2218
|
-
* returns whether the controller still has positive desired size
|
|
2555
|
+
* returns whether the controller still has positive desired size; on an open
|
|
2556
|
+
* stream it throws the `ServerError` `serializeEvent` raises for a refused
|
|
2557
|
+
* field and enqueues nothing. A producer
|
|
2219
2558
|
* receiving `false` awaits `drain()`; that promise resolves on the next
|
|
2220
2559
|
* 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
|
|
2560
|
+
* `: text` keep-alive line per line of its text, which a conforming SSE parser
|
|
2561
|
+
* ignores; `end` closes the stream. Every method is a safe no-op while `closed`
|
|
2562
|
+
* (ended by `end()`, or the consumer cancelled the stream), so a late write
|
|
2563
|
+
* never throws.
|
|
2224
2564
|
*
|
|
2225
2565
|
* The readiness signal reflects only the process-local `ReadableStream`
|
|
2226
2566
|
* queue — it is not proof that a remote peer consumed bytes. When the response
|
|
@@ -2229,8 +2569,9 @@ var Server = class {
|
|
|
2229
2569
|
* its buffering. Ignoring the return value preserves an unconditional-enqueue
|
|
2230
2570
|
* producer. The default stream strategy counts chunks rather than their byte
|
|
2231
2571
|
* 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
|
|
2572
|
+
* `response` before awaiting a `false` write or `drain()`, because the consumer
|
|
2573
|
+
* cannot pull until it receives the response, and the opening comment fills
|
|
2574
|
+
* the queue, so a `drain()` before any write also waits on that pull.
|
|
2234
2575
|
*
|
|
2235
2576
|
* @example
|
|
2236
2577
|
* ```ts
|
|
@@ -2276,7 +2617,7 @@ var Stream = class {
|
|
|
2276
2617
|
return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
|
|
2277
2618
|
}
|
|
2278
2619
|
comment(text) {
|
|
2279
|
-
this.#enqueue(
|
|
2620
|
+
this.#enqueue(serializeComment(text));
|
|
2280
2621
|
}
|
|
2281
2622
|
drain() {
|
|
2282
2623
|
const desired = this.#controller?.desiredSize;
|
|
@@ -2292,6 +2633,7 @@ var Stream = class {
|
|
|
2292
2633
|
}
|
|
2293
2634
|
#attach(controller) {
|
|
2294
2635
|
this.#controller = controller;
|
|
2636
|
+
controller.enqueue(this.#encoder.encode(serializeComment("")));
|
|
2295
2637
|
}
|
|
2296
2638
|
#pull(controller) {
|
|
2297
2639
|
if (controller.desiredSize === null || controller.desiredSize <= 0) return;
|
|
@@ -2378,6 +2720,27 @@ function createServer(options) {
|
|
|
2378
2720
|
return new Server(options);
|
|
2379
2721
|
}
|
|
2380
2722
|
/**
|
|
2723
|
+
* Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each
|
|
2724
|
+
* created at this call.
|
|
2725
|
+
*
|
|
2726
|
+
* @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}
|
|
2727
|
+
* @returns A {@link SignerInterface} whose first key signs and whose every key verifies
|
|
2728
|
+
* @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,
|
|
2729
|
+
* when the list is empty, or when any entry is blank
|
|
2730
|
+
*
|
|
2731
|
+
* @example
|
|
2732
|
+
* ```ts
|
|
2733
|
+
* import { createSigner, signToken, verifyToken } from '@orkestrel/server'
|
|
2734
|
+
*
|
|
2735
|
+
* const signer = createSigner(['current-secret', 'previous-secret'])
|
|
2736
|
+
* const token = await signToken('session-7f3a', { signer, ttl: 60_000 })
|
|
2737
|
+
* await verifyToken(token, signer) // 'session-7f3a'
|
|
2738
|
+
* ```
|
|
2739
|
+
*/
|
|
2740
|
+
function createSigner(secret) {
|
|
2741
|
+
return new Signer(secret);
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2381
2744
|
* Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose
|
|
2382
2745
|
* `response` is a fetch-standard streaming `Response` a route returns.
|
|
2383
2746
|
*
|
|
@@ -2400,6 +2763,6 @@ function createServer(options) {
|
|
|
2400
2763
|
function createStream(options) {
|
|
2401
2764
|
return new Stream(options);
|
|
2402
2765
|
}
|
|
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 };
|
|
2766
|
+
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
2767
|
|
|
2405
2768
|
//# sourceMappingURL=index.js.map
|