@theokit/gateway 0.26.0 → 0.27.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.27.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e3bf8c9: Add `jwksKeySet`, `decodeJwt` and `verifyRs256Jwt`: a JWKS key-set cache (max-age, shared in-flight read, unknown-kid refetch floor, stale-while-revalidate) and RS256 JWT signature verification for adapters whose platform signs requests with a JWT.
8
+
9
+ ### Patch Changes
10
+
11
+ - 8585427: README status lines say "0.x, pre-1.0" instead of a hard-coded version.
12
+
3
13
  ## 0.26.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Multi-platform messaging gateway for `@theokit/sdk`. Transport-agnostic primitives — adapters live in separate peer-dep packages.
4
4
 
5
- > **Status: 0.1.0 — pre-release.** Breaking changes allowed within the `0.x` line per semver.
5
+ > **Status: 0.x, pre-1.0.** Breaking changes allowed within the `0.x` line per semver.
6
6
 
7
7
  ## Install
8
8
 
@@ -684,6 +684,21 @@ assuming this one's.
684
684
  Adapters whose transport is a long-lived connection rather than a webhook own that transport and do
685
685
  not go through this seam.
686
686
 
687
+ ## Verifying a JWT-signed request
688
+
689
+ Platforms that sign requests with an RS256 JWT can share one key-set cache and verifier:
690
+
691
+ ```ts
692
+ import { jwksKeySet, verifyRs256Jwt } from "@theokit/gateway";
693
+
694
+ const keys = jwksKeySet({ url: "https://www.googleapis.com/oauth2/v3/certs" });
695
+ const result = await verifyRs256Jwt(bearerToken, keys);
696
+ if (!result.ok) throw new Error(result.reason);
697
+ // result.payload is signature-verified; check issuer, audience and expiry yourself.
698
+ ```
699
+
700
+ The cache honours `Cache-Control: max-age`, shares one in-flight read, refetches for an unknown `kid` at most once per `unknownKidRefetchFloorMs` (default 60 s) and, by default, serves a stale key while one refresh runs (`staleWhileRevalidate`). `reason` is `malformed`, `unsupported_alg` (only `RS256` is accepted), `unknown_kid`, `keys_unavailable` or `bad_signature`. `decodeJwt` splits a token without verifying it.
701
+
687
702
  ## Design principles
688
703
 
689
704
  - **Compose, don't reimplement.** The gateway never owns session persistence (SDK does), never owns scheduling (Cron does), never owns prompt resolution (SystemPromptResolver does).
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var sdk = require('@theokit/sdk');
4
3
  var crypto = require('crypto');
4
+ var sdk = require('@theokit/sdk');
5
5
  var fs = require('fs');
6
6
  var path = require('path');
7
7
  var promises = require('fs/promises');
@@ -630,6 +630,125 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
630
630
  }
631
631
  }
632
632
  };
633
+ var DEFAULT_REFETCH_FLOOR_MS = 6e4;
634
+ var READ_TIMEOUT_MS = 1e4;
635
+ function jwksKeySet(options) {
636
+ const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
637
+ const now = options.now ?? Date.now;
638
+ const floor = options.unknownKidRefetchFloorMs ?? DEFAULT_REFETCH_FLOOR_MS;
639
+ const swr = options.staleWhileRevalidate ?? true;
640
+ let held;
641
+ let lastReadStartedAt = Number.NEGATIVE_INFINITY;
642
+ let reading;
643
+ let lastFailure = "no read has completed";
644
+ async function fetchKeys() {
645
+ const response = await doFetch(options.url, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
646
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
647
+ const keys = parseKeys(await response.json());
648
+ return { keys, freshUntil: now() + maxAgeMs(response.headers.get("cache-control")) };
649
+ }
650
+ function read() {
651
+ if (reading) return reading;
652
+ lastReadStartedAt = now();
653
+ const current = fetchKeys().then(
654
+ (next) => {
655
+ held = next;
656
+ reading = void 0;
657
+ return void 0;
658
+ },
659
+ (error) => {
660
+ lastFailure = error instanceof Error ? error.message : String(error);
661
+ reading = void 0;
662
+ return lastFailure;
663
+ }
664
+ );
665
+ reading = current;
666
+ return current;
667
+ }
668
+ const mayRead = () => !reading && now() - lastReadStartedAt >= floor;
669
+ function answer(kid) {
670
+ const key = held?.keys.get(kid);
671
+ if (key) return key;
672
+ return held ? "unlisted" : { unavailable: lastFailure };
673
+ }
674
+ async function refreshListed(kid) {
675
+ const refresh = reading ?? (mayRead() ? read() : void 0);
676
+ if (refresh && !swr) await refresh;
677
+ return answer(kid);
678
+ }
679
+ async function refreshUnknown(kid) {
680
+ const refresh = reading ?? (mayRead() ? read() : void 0);
681
+ const failure = refresh ? await refresh : void 0;
682
+ if (failure && !held?.keys.has(kid)) return { unavailable: failure };
683
+ return answer(kid);
684
+ }
685
+ return {
686
+ async lookup(kid) {
687
+ const listed = held?.keys.get(kid);
688
+ if (!held || !listed) return refreshUnknown(kid);
689
+ if (now() < held.freshUntil) return listed;
690
+ return refreshListed(kid);
691
+ }
692
+ };
693
+ }
694
+ function parseKey(jwk) {
695
+ if (typeof jwk !== "object" || jwk === null) return void 0;
696
+ const { kid, kty, use } = jwk;
697
+ if (typeof kid !== "string" || kty !== "RSA" || use !== void 0 && use !== "sig") {
698
+ return void 0;
699
+ }
700
+ try {
701
+ return [kid, crypto.createPublicKey({ key: jwk, format: "jwk" })];
702
+ } catch {
703
+ return void 0;
704
+ }
705
+ }
706
+ function parseKeys(body) {
707
+ const list = body?.keys;
708
+ if (!Array.isArray(list)) throw new Error("the key set has no `keys` array");
709
+ const entries = list.map(parseKey).filter((e) => e !== void 0);
710
+ return new Map(entries);
711
+ }
712
+ function maxAgeMs(cacheControl) {
713
+ const match = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl ?? "");
714
+ return match?.[1] ? Number(match[1]) * 1e3 : 0;
715
+ }
716
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
717
+ function decodeJwt(token) {
718
+ const parts = token.split(".");
719
+ if (parts.length !== 3) return void 0;
720
+ const [h, p, s] = parts;
721
+ if (![h, p, s].every((part) => BASE64URL.test(part))) return void 0;
722
+ const header = jsonObject(h);
723
+ const payload = jsonObject(p);
724
+ if (!header || !payload) return void 0;
725
+ return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, "base64url") };
726
+ }
727
+ function jsonObject(segment) {
728
+ try {
729
+ const value = JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
730
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
731
+ } catch {
732
+ return void 0;
733
+ }
734
+ }
735
+ async function verifyRs256Jwt(token, keys) {
736
+ const jwt = decodeJwt(token);
737
+ if (!jwt) return { ok: false, reason: "malformed" };
738
+ if (jwt.header.alg !== "RS256") return { ok: false, reason: "unsupported_alg" };
739
+ const kid = jwt.header.kid;
740
+ if (typeof kid !== "string" || kid === "") return { ok: false, reason: "malformed" };
741
+ const found = await keys.lookup(kid);
742
+ if (found === "unlisted") return { ok: false, reason: "unknown_kid" };
743
+ if ("unavailable" in found) return { ok: false, reason: "keys_unavailable" };
744
+ let valid = false;
745
+ try {
746
+ valid = crypto.verify("RSA-SHA256", Buffer.from(jwt.signingInput), found, jwt.signature);
747
+ } catch {
748
+ valid = false;
749
+ }
750
+ return valid ? { ok: true, header: jwt.header, payload: jwt.payload } : { ok: false, reason: "bad_signature" };
751
+ }
633
752
 
634
753
  // src/errors/config-error.ts
635
754
  var GatewayConfigurationError = class extends Error {
@@ -2613,9 +2732,11 @@ exports.createFileCredentialStore = createFileCredentialStore;
2613
2732
  exports.createFilePairingStore = createFilePairingStore;
2614
2733
  exports.createTokenCache = createTokenCache;
2615
2734
  exports.createWebhookHandler = createWebhookHandler;
2735
+ exports.decodeJwt = decodeJwt;
2616
2736
  exports.defaultStrategy = defaultStrategy;
2617
2737
  exports.helpText = helpText;
2618
2738
  exports.isAuthenticatedSender = isAuthenticatedSender;
2739
+ exports.jwksKeySet = jwksKeySet;
2619
2740
  exports.listenerLifecycle = listenerLifecycle;
2620
2741
  exports.loadPeer = loadPeer;
2621
2742
  exports.maskSecrets = maskSecrets;
@@ -2632,6 +2753,7 @@ exports.senderKey = senderKey;
2632
2753
  exports.splitKeepingRows = splitKeepingRows;
2633
2754
  exports.statusForDeliver = statusForDeliver;
2634
2755
  exports.toDialect = toDialect;
2756
+ exports.verifyRs256Jwt = verifyRs256Jwt;
2635
2757
  exports.withMediaUnderstanding = withMediaUnderstanding;
2636
2758
  //# sourceMappingURL=index.cjs.map
2637
2759
  //# sourceMappingURL=index.cjs.map