@orkestrel/server 0.0.16 → 0.0.17

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.
@@ -348,26 +348,6 @@ export declare function createNegotiator(): NegotiatorInterface;
348
348
  */
349
349
  export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
350
350
 
351
- /**
352
- * Decode a base64url string back into its bytes — the inverse of
353
- * {@link encodeBase64Url}.
354
- *
355
- * @remarks
356
- * Restores the standard base64 alphabet + padding before decoding with
357
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
358
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
359
- *
360
- * @param value - The base64url string to decode
361
- * @returns The decoded bytes
362
- * @throws {DOMException} When `value` is not valid base64url
363
- *
364
- * @example
365
- * ```ts
366
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
367
- * ```
368
- */
369
- export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
370
-
371
351
  /**
372
352
  * Decode a cookie value with `decodeURIComponent`, falling back to the raw
373
353
  * text when the value is not valid percent-encoding.
@@ -389,9 +369,12 @@ export declare function decodeCookieValue(raw: string): string;
389
369
  * signature match.
390
370
  *
391
371
  * @remarks
392
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
393
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
394
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
372
+ * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
373
+ * non-canonical base64url segment answers `undefined` rather than throwing),
374
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value`
375
+ * (AGENTS §14 — never `as`), and rejects an expired `exp`. TOTAL — any
376
+ * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
377
+ * throws, and its `catch` answers `undefined` too.
395
378
  *
396
379
  * @param encoded - The base64url-encoded payload segment (before the last `.`)
397
380
  * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
@@ -485,20 +468,6 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
485
468
  */
486
469
  export declare function discoverPort(preferred?: number): Promise<number>;
487
470
 
488
- /**
489
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
490
- * {@link verifyToken} use, and the signature encoding for the HMAC.
491
- *
492
- * @param bytes - The bytes to encode
493
- * @returns The base64url string (no padding)
494
- *
495
- * @example
496
- * ```ts
497
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
498
- * ```
499
- */
500
- export declare function encodeBase64Url(bytes: Uint8Array): string;
501
-
502
471
  /**
503
472
  * A content-coding the substrate compresses / decompresses with — the
504
473
  * `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
@@ -1966,8 +1935,10 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
1966
1935
  *
1967
1936
  * @remarks
1968
1937
  * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
1969
- * value containing dots survives), and checks the payload's HMAC-SHA256
1970
- * signature against EACH {@link TokenSecret} candidate via
1938
+ * value containing dots survives), decodes the signature with
1939
+ * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
1940
+ * base64url is refused there, before any key import — and checks the payload's
1941
+ * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate via
1971
1942
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
1972
1943
  * retired, §3 of the proposal), accepting the token on the first match (the
1973
1944
  * rotation path). It then decodes + narrows the payload (`isRecord` +
@@ -348,26 +348,6 @@ export declare function createNegotiator(): NegotiatorInterface;
348
348
  */
349
349
  export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
350
350
 
351
- /**
352
- * Decode a base64url string back into its bytes — the inverse of
353
- * {@link encodeBase64Url}.
354
- *
355
- * @remarks
356
- * Restores the standard base64 alphabet + padding before decoding with
357
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
358
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
359
- *
360
- * @param value - The base64url string to decode
361
- * @returns The decoded bytes
362
- * @throws {DOMException} When `value` is not valid base64url
363
- *
364
- * @example
365
- * ```ts
366
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
367
- * ```
368
- */
369
- export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
370
-
371
351
  /**
372
352
  * Decode a cookie value with `decodeURIComponent`, falling back to the raw
373
353
  * text when the value is not valid percent-encoding.
@@ -389,9 +369,12 @@ export declare function decodeCookieValue(raw: string): string;
389
369
  * signature match.
390
370
  *
391
371
  * @remarks
392
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
393
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
394
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
372
+ * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
373
+ * non-canonical base64url segment answers `undefined` rather than throwing),
374
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value`
375
+ * (AGENTS §14 — never `as`), and rejects an expired `exp`. TOTAL — any
376
+ * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
377
+ * throws, and its `catch` answers `undefined` too.
395
378
  *
396
379
  * @param encoded - The base64url-encoded payload segment (before the last `.`)
397
380
  * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
@@ -485,20 +468,6 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
485
468
  */
486
469
  export declare function discoverPort(preferred?: number): Promise<number>;
487
470
 
488
- /**
489
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
490
- * {@link verifyToken} use, and the signature encoding for the HMAC.
491
- *
492
- * @param bytes - The bytes to encode
493
- * @returns The base64url string (no padding)
494
- *
495
- * @example
496
- * ```ts
497
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
498
- * ```
499
- */
500
- export declare function encodeBase64Url(bytes: Uint8Array): string;
501
-
502
471
  /**
503
472
  * A content-coding the substrate compresses / decompresses with — the
504
473
  * `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
@@ -1966,8 +1935,10 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
1966
1935
  *
1967
1936
  * @remarks
1968
1937
  * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
1969
- * value containing dots survives), and checks the payload's HMAC-SHA256
1970
- * signature against EACH {@link TokenSecret} candidate via
1938
+ * value containing dots survives), decodes the signature with
1939
+ * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
1940
+ * base64url is refused there, before any key import — and checks the payload's
1941
+ * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate via
1971
1942
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
1972
1943
  * retired, §3 of the proposal), accepting the token on the first match (the
1973
1944
  * rotation path). It then decodes + narrows the payload (`isRecord` +
@@ -1,6 +1,7 @@
1
1
  import { isFiniteNumber, isFunction, isInteger, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
2
  import { addAbortListener, once } from "node:events";
3
3
  import { createServer as createServer$1 } from "node:net";
4
+ import { decodeBase64URL, encodeBase64URL } from "@orkestrel/codec";
4
5
  import { createServer as createServer$2 } from "node:http";
5
6
  import { createAbort, linkSignal } from "@orkestrel/abort";
6
7
  import { createTimeout } from "@orkestrel/timeout";
@@ -545,49 +546,6 @@ function clearCookie(headers, name, options) {
545
546
  }));
546
547
  }
547
548
  /**
548
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
549
- * {@link verifyToken} use, and the signature encoding for the HMAC.
550
- *
551
- * @param bytes - The bytes to encode
552
- * @returns The base64url string (no padding)
553
- *
554
- * @example
555
- * ```ts
556
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
557
- * ```
558
- */
559
- function encodeBase64Url(bytes) {
560
- let binary = "";
561
- for (const byte of bytes) binary += String.fromCharCode(byte);
562
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
563
- }
564
- /**
565
- * Decode a base64url string back into its bytes — the inverse of
566
- * {@link encodeBase64Url}.
567
- *
568
- * @remarks
569
- * Restores the standard base64 alphabet + padding before decoding with
570
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
571
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
572
- *
573
- * @param value - The base64url string to decode
574
- * @returns The decoded bytes
575
- * @throws {DOMException} When `value` is not valid base64url
576
- *
577
- * @example
578
- * ```ts
579
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
580
- * ```
581
- */
582
- function decodeBase64Url(value) {
583
- const restored = value.replace(/-/g, "+").replace(/_/g, "/");
584
- const padding = restored.length % 4 === 0 ? "" : "=".repeat(4 - restored.length % 4);
585
- const binary = atob(restored + padding);
586
- const bytes = new Uint8Array(binary.length);
587
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
588
- return bytes;
589
- }
590
- /**
591
549
  * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
592
550
  *
593
551
  * @remarks
@@ -616,7 +574,7 @@ async function signToken(value, options) {
616
574
  const secret = normalizeSecret(options.secret)[0];
617
575
  if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
618
576
  const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
619
- const encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({
577
+ const encoded = encodeBase64URL(new TextEncoder().encode(JSON.stringify({
620
578
  value,
621
579
  exp
622
580
  })));
@@ -625,15 +583,17 @@ async function signToken(value, options) {
625
583
  hash: "SHA-256"
626
584
  }, false, ["sign"]);
627
585
  const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
628
- return `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`;
586
+ return `${encoded}.${encodeBase64URL(new Uint8Array(signature))}`;
629
587
  }
630
588
  /**
631
589
  * Verify a stateless token and return its embedded value — TOTAL, never throws.
632
590
  *
633
591
  * @remarks
634
592
  * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
635
- * value containing dots survives), and checks the payload's HMAC-SHA256
636
- * signature against EACH {@link TokenSecret} candidate via
593
+ * value containing dots survives), decodes the signature with
594
+ * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
595
+ * base64url is refused there, before any key import — and checks the payload's
596
+ * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate via
637
597
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
638
598
  * retired, §3 of the proposal), accepting the token on the first match (the
639
599
  * rotation path). It then decodes + narrows the payload (`isRecord` +
@@ -657,10 +617,10 @@ async function verifyToken(token, secret) {
657
617
  const dot = token.lastIndexOf(".");
658
618
  if (dot < 0) return void 0;
659
619
  const encoded = token.slice(0, dot);
660
- const signatureText = token.slice(dot + 1);
620
+ const signature = decodeBase64URL(token.slice(dot + 1));
621
+ if (signature === void 0) return void 0;
622
+ const data = new TextEncoder().encode(encoded);
661
623
  try {
662
- const signature = decodeBase64Url(signatureText);
663
- const data = new TextEncoder().encode(encoded);
664
624
  for (const candidate of secrets) {
665
625
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
666
626
  name: "HMAC",
@@ -679,17 +639,21 @@ async function verifyToken(token, secret) {
679
639
  * signature match.
680
640
  *
681
641
  * @remarks
682
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
683
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
684
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
642
+ * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
643
+ * non-canonical base64url segment answers `undefined` rather than throwing),
644
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value`
645
+ * (AGENTS §14 — never `as`), and rejects an expired `exp`. TOTAL — any
646
+ * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
647
+ * throws, and its `catch` answers `undefined` too.
685
648
  *
686
649
  * @param encoded - The base64url-encoded payload segment (before the last `.`)
687
650
  * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
688
651
  */
689
652
  function decodeTokenPayload(encoded) {
653
+ const bytes = decodeBase64URL(encoded);
654
+ if (bytes === void 0) return void 0;
690
655
  try {
691
- const text = new TextDecoder().decode(decodeBase64Url(encoded));
692
- const payload = JSON.parse(text);
656
+ const payload = JSON.parse(new TextDecoder().decode(bytes));
693
657
  if (!isRecord(payload)) return void 0;
694
658
  if (typeof payload.value !== "string") return void 0;
695
659
  if (payload.exp !== void 0 && typeof payload.exp !== "number") return void 0;
@@ -2179,6 +2143,6 @@ function createServer(options) {
2179
2143
  return new Server(options);
2180
2144
  }
2181
2145
  //#endregion
2182
- export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, createServer, decodeBase64Url, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, encodeBase64Url, enqueueStreamText, ipv6Network, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, probePort, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2146
+ export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, createServer, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, enqueueStreamText, ipv6Network, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, probePort, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2183
2147
 
2184
2148
  //# sourceMappingURL=index.js.map