axiam-sdk 1.3.0 → 1.4.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.
Files changed (58) hide show
  1. package/README.md +130 -14
  2. package/dist/amqp/index.d.cts +384 -17
  3. package/dist/amqp/index.d.ts +384 -17
  4. package/dist/amqp/index.js +639 -66
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +631 -67
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
  9. package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
  10. package/dist/browser/index.d.cts +1 -1
  11. package/dist/browser/index.d.ts +1 -1
  12. package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
  13. package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
  14. package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
  15. package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
  16. package/dist/grpc/index.d.cts +5 -5
  17. package/dist/grpc/index.d.ts +5 -5
  18. package/dist/grpc/index.js +249 -18
  19. package/dist/grpc/index.js.map +1 -1
  20. package/dist/grpc/index.mjs +249 -18
  21. package/dist/grpc/index.mjs.map +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +29 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +29 -3
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
  29. package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
  30. package/dist/middleware/index.d.cts +220 -43
  31. package/dist/middleware/index.d.ts +220 -43
  32. package/dist/middleware/index.js +587 -149
  33. package/dist/middleware/index.js.map +1 -1
  34. package/dist/middleware/index.mjs +579 -150
  35. package/dist/middleware/index.mjs.map +1 -1
  36. package/dist/nestjs/index.d.cts +18 -4
  37. package/dist/nestjs/index.d.ts +18 -4
  38. package/dist/nestjs/index.js +20 -1
  39. package/dist/nestjs/index.js.map +1 -1
  40. package/dist/nestjs/index.mjs +19 -2
  41. package/dist/nestjs/index.mjs.map +1 -1
  42. package/dist/node/index.d.cts +5 -5
  43. package/dist/node/index.d.ts +5 -5
  44. package/dist/node/index.js +351 -66
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/index.mjs +348 -67
  47. package/dist/node/index.mjs.map +1 -1
  48. package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
  49. package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
  50. package/dist/rest/index.d.cts +3 -3
  51. package/dist/rest/index.d.ts +3 -3
  52. package/dist/rest/index.js +29 -3
  53. package/dist/rest/index.js.map +1 -1
  54. package/dist/rest/index.mjs +29 -3
  55. package/dist/rest/index.mjs.map +1 -1
  56. package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
  57. package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
  58. package/package.json +10 -10
@@ -600,6 +600,7 @@ var SharedSession = class {
600
600
  this.expectedIssuer = options.expectedIssuer;
601
601
  this.expectedAudience = options.expectedAudience;
602
602
  this.presentsClientCertificate = options.clientCert !== void 0 && options.clientKey !== void 0;
603
+ registerTlsOptions(this, options);
603
604
  this.resolvedTenantId = options.tenantId;
604
605
  this.resolvedOrgId = options.orgId;
605
606
  this.refreshGuard = createRefreshGuard();
@@ -651,7 +652,7 @@ var SharedSession = class {
651
652
  }
652
653
  /**
653
654
  * Host-isolation guard (3A, defense in depth): returns `true` when `url`
654
- * targets a host other than this session's base origin — an absolute
655
+ * targets an origin (scheme, host and port) other than this session's base origin — an absolute
655
656
  * third-party URL, or a redirect that axios/the browser resolved off-origin.
656
657
  * The tenant identifier and CSRF token must never be attached to such a
657
658
  * request. A relative/host-less `url` (the normal case, merged against
@@ -665,7 +666,7 @@ var SharedSession = class {
665
666
  }
666
667
  try {
667
668
  const target = new URL(url, this.baseUrl);
668
- return target.host !== new URL(this.baseUrl).host;
669
+ return target.origin !== new URL(this.baseUrl).origin;
669
670
  } catch {
670
671
  return true;
671
672
  }
@@ -727,6 +728,19 @@ function resolveTenantHeaderValue(options) {
727
728
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
728
729
  );
729
730
  }
731
+ function agentTlsOptions(tls) {
732
+ if (tls === void 0) return {};
733
+ if (tls.ca === void 0) {
734
+ return { ...tls.cert !== void 0 ? { cert: tls.cert } : {}, ...tls.key !== void 0 ? { key: tls.key } : {} };
735
+ }
736
+ const tlsMod = loadNodeBuiltin("node:tls");
737
+ const secureContext = tlsMod.createSecureContext({
738
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
739
+ ...tls.key !== void 0 ? { key: tls.key } : {}
740
+ });
741
+ secureContext.context.addCACert(tls.ca);
742
+ return { secureContext };
743
+ }
730
744
  function loadNodeBuiltin(id) {
731
745
  const getBuiltinModule = process.getBuiltinModule;
732
746
  if (typeof getBuiltinModule === "function") {
@@ -743,6 +757,27 @@ function loadNodeBuiltin(id) {
743
757
  function loadNodeHttps() {
744
758
  return loadNodeBuiltin("node:https");
745
759
  }
760
+ var sessionTlsOptions = /* @__PURE__ */ new WeakMap();
761
+ function registerTlsOptions(session, options) {
762
+ if (options.customCa === void 0 && options.clientCert === void 0) return;
763
+ try {
764
+ const tls = resolveNodeTlsOptions(options);
765
+ if (tls !== void 0) sessionTlsOptions.set(session, tls);
766
+ } catch {
767
+ }
768
+ }
769
+ function nodeTlsOptionsOf(session, targetUrl) {
770
+ const tls = sessionTlsOptions.get(session);
771
+ if (tls === void 0 || targetUrl === void 0) return tls;
772
+ let sameOrigin = false;
773
+ try {
774
+ sameOrigin = new URL(targetUrl).origin === new URL(session.baseUrl).origin;
775
+ } catch {
776
+ sameOrigin = false;
777
+ }
778
+ if (sameOrigin) return tls;
779
+ return tls.ca !== void 0 ? { ca: tls.ca } : void 0;
780
+ }
746
781
  function tlsOptionsFrom(customCa, identity) {
747
782
  if (!customCa) {
748
783
  if (!identity) {
@@ -766,7 +801,7 @@ function buildPlainNodeAgents(tls) {
766
801
  const https = loadNodeHttps();
767
802
  return {
768
803
  httpAgent: new http.Agent(),
769
- httpsAgent: new https.Agent(tls ?? {})
804
+ httpsAgent: new https.Agent(agentTlsOptions(tls))
770
805
  };
771
806
  }
772
807
  function maybeBuildHttpsAgent(customCa, identity) {
@@ -778,7 +813,7 @@ function maybeBuildHttpsAgent(customCa, identity) {
778
813
  return void 0;
779
814
  }
780
815
  const https = loadNodeHttps();
781
- return new https.Agent(tls);
816
+ return new https.Agent(agentTlsOptions(tls));
782
817
  }
783
818
  function createSession(options) {
784
819
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -3834,7 +3869,7 @@ function normalizeSearch(term) {
3834
3869
  const trimmed = term?.trim();
3835
3870
  return trimmed ? trimmed : void 0;
3836
3871
  }
3837
- async function collectPages(start, fetch) {
3872
+ async function collectPages(start, fetch2) {
3838
3873
  let request = {
3839
3874
  offset: start.offset ?? 0,
3840
3875
  limit: start.limit,
@@ -3842,7 +3877,7 @@ async function collectPages(start, fetch) {
3842
3877
  };
3843
3878
  const out = [];
3844
3879
  for (; ; ) {
3845
- const page = await fetch(request);
3880
+ const page = await fetch2(request);
3846
3881
  out.push(...page.items);
3847
3882
  const next = page.offset + page.items.length;
3848
3883
  if (page.items.length === 0 || next >= page.total) return out;
@@ -8232,7 +8267,7 @@ function createJar() {
8232
8267
  function wrapAxios(instance, jar, tls) {
8233
8268
  const cookies = { jar };
8234
8269
  instance.defaults.httpAgent = new http.HttpCookieAgent({ cookies });
8235
- instance.defaults.httpsAgent = new http.HttpsCookieAgent({ cookies, ...tls ?? {} });
8270
+ instance.defaults.httpsAgent = new http.HttpsCookieAgent({ cookies, ...agentTlsOptions(tls) });
8236
8271
  return instance;
8237
8272
  }
8238
8273
  async function extractCookieValue(jar, url, name) {
@@ -8342,6 +8377,9 @@ function resolveClockSkewSec(clockSkewSec) {
8342
8377
  if (clockSkewSec === void 0) {
8343
8378
  return MAX_CLOCK_SKEW_SEC;
8344
8379
  }
8380
+ if (typeof clockSkewSec !== "number" || !Number.isFinite(clockSkewSec)) {
8381
+ throw new TypeError("clockSkewSec must be a finite number of seconds");
8382
+ }
8345
8383
  return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
8346
8384
  }
8347
8385
  function constantTimeEquals(a, b) {
@@ -8457,32 +8495,202 @@ function constantTimeEqual(a, b) {
8457
8495
  return diff === 0;
8458
8496
  }
8459
8497
  async function certificateThumbprintS256(der) {
8460
- const { createHash: createHash4 } = await import('crypto');
8461
- return createHash4("sha256").update(der).digest("base64url");
8498
+ const { createHash: createHash5 } = await import('crypto');
8499
+ return createHash5("sha256").update(der).digest("base64url");
8462
8500
  }
8463
8501
  var JWKS_PATH = "/oauth2/jwks";
8464
8502
  var COOLDOWN_DURATION_MS = 6e4;
8465
8503
  var TIMEOUT_DURATION_MS = 5e3;
8504
+ var JWKS_MAX_TTL_MS = 3e5;
8505
+ var JWKS_MAX_STALE_MS = 3e5;
8506
+ var JWKS_MAX_BODY_BYTES = 50 * 1024;
8507
+ async function readCappedJson(res, maxBytes) {
8508
+ const declared = res.headers.get("content-length");
8509
+ if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
8510
+ await res.body?.cancel().catch(() => void 0);
8511
+ throw new Error("JWKS response too large");
8512
+ }
8513
+ const reader = res.body?.getReader();
8514
+ if (reader === void 0) throw new Error("JWKS response has no body");
8515
+ const chunks = [];
8516
+ let total = 0;
8517
+ for (; ; ) {
8518
+ const { done, value } = await reader.read();
8519
+ if (done) break;
8520
+ total += value.byteLength;
8521
+ if (total > maxBytes) {
8522
+ await reader.cancel().catch(() => void 0);
8523
+ throw new Error("JWKS response too large");
8524
+ }
8525
+ chunks.push(value);
8526
+ }
8527
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
8528
+ }
8529
+ function ttlFromResponse(res) {
8530
+ const m = /(?:^|[\s,])max-age=(\d+)/i.exec(res.headers.get("cache-control") ?? "");
8531
+ if (m === null) return JWKS_MAX_TTL_MS;
8532
+ const ms = Number(m[1]) * 1e3;
8533
+ return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;
8534
+ }
8535
+ async function fetchWithTls(url, init, tls) {
8536
+ const https = (await import('https')).default;
8537
+ const { Readable } = await import('stream');
8538
+ const tlsMod = await import('tls');
8539
+ let secureContext;
8540
+ if (tls.ca !== void 0) {
8541
+ secureContext = tlsMod.createSecureContext({
8542
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8543
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8544
+ });
8545
+ secureContext.context.addCACert(tls.ca);
8546
+ }
8547
+ return new Promise((resolve, reject) => {
8548
+ let settled = false;
8549
+ const settle = (fn) => {
8550
+ if (settled) return;
8551
+ settled = true;
8552
+ fn();
8553
+ };
8554
+ const agent = new https.Agent(
8555
+ secureContext !== void 0 ? { secureContext } : {
8556
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8557
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8558
+ }
8559
+ );
8560
+ const fail2 = (message = "unexpected JWKS status") => {
8561
+ agent.destroy();
8562
+ settle(() => reject(new Error(message)));
8563
+ };
8564
+ const req = https.request(
8565
+ url,
8566
+ { method: "GET", headers: init.headers, signal: init.signal, agent },
8567
+ (res) => {
8568
+ try {
8569
+ const status = res.statusCode ?? 0;
8570
+ if (status !== 200 && status !== 304) {
8571
+ res.destroy();
8572
+ fail2();
8573
+ return;
8574
+ }
8575
+ const headers = new Headers();
8576
+ for (const [name, value] of Object.entries(res.headers)) {
8577
+ if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
8578
+ }
8579
+ if (status === 304) res.resume();
8580
+ const body = status === 304 ? null : Readable.toWeb(res);
8581
+ const response = new Response(body, { status, headers });
8582
+ res.on("close", () => agent.destroy());
8583
+ settle(() => resolve(response));
8584
+ } catch {
8585
+ res.destroy();
8586
+ fail2();
8587
+ }
8588
+ }
8589
+ );
8590
+ req.on("error", (err) => {
8591
+ agent.destroy();
8592
+ settle(() => reject(err));
8593
+ });
8594
+ req.on("close", () => {
8595
+ if (!settled) fail2("JWKS request closed before a response");
8596
+ });
8597
+ req.end();
8598
+ });
8599
+ }
8600
+ var JwksCache = class {
8601
+ constructor(jwksUri, jose, tls) {
8602
+ this.jwksUri = jwksUri;
8603
+ this.jose = jose;
8604
+ this.#tls = tls;
8605
+ }
8606
+ jwksUri;
8607
+ jose;
8608
+ #resolver;
8609
+ #etag;
8610
+ #anchorMs = 0;
8611
+ #ttlMs = JWKS_MAX_TTL_MS;
8612
+ #lastAttemptMs;
8613
+ #inflight;
8614
+ /** Held privately: it may carry the client key, and must not be an enumerable property. */
8615
+ #tls;
8616
+ /** The key resolver handed to `jwtVerify`. */
8617
+ getKey = async (...args) => {
8618
+ const usable = () => this.#resolver !== void 0 && Date.now() >= this.#anchorMs && Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS ? this.#resolver : void 0;
8619
+ const nowMs = Date.now();
8620
+ if (this.#resolver === void 0 || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {
8621
+ const refresh2 = this.#refreshIfAllowed();
8622
+ if (usable() === void 0) await refresh2;
8623
+ }
8624
+ const held = usable();
8625
+ if (held === void 0) {
8626
+ throw new this.jose.errors.JOSEError("the JSON Web Key Set is unavailable");
8627
+ }
8628
+ try {
8629
+ return await held(...args);
8630
+ } catch (err) {
8631
+ if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;
8632
+ await this.#refreshIfAllowed();
8633
+ const refreshed = usable();
8634
+ if (refreshed === void 0) throw err;
8635
+ return refreshed(...args);
8636
+ }
8637
+ };
8638
+ async #refreshIfAllowed() {
8639
+ if (this.#inflight !== void 0) return this.#inflight;
8640
+ const now = Date.now();
8641
+ const sinceLast = this.#lastAttemptMs === void 0 ? Infinity : now - this.#lastAttemptMs;
8642
+ if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return;
8643
+ this.#lastAttemptMs = now;
8644
+ this.#inflight = this.#fetch().catch(() => void 0).finally(() => {
8645
+ this.#inflight = void 0;
8646
+ });
8647
+ return this.#inflight;
8648
+ }
8649
+ async #fetch() {
8650
+ const conditional = this.#resolver !== void 0 && this.#etag !== void 0;
8651
+ const headers = { accept: "application/json", ...conditional ? { "if-none-match": this.#etag } : {} };
8652
+ const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);
8653
+ const res = this.#tls !== void 0 && new URL(this.jwksUri).protocol === "https:" ? await fetchWithTls(this.jwksUri, { headers, signal }, this.#tls) : await fetch(this.jwksUri, { redirect: "manual", signal, headers });
8654
+ if (res.status === 304 && conditional) {
8655
+ await res.body?.cancel().catch(() => void 0);
8656
+ this.#anchorMs = Date.now();
8657
+ this.#ttlMs = ttlFromResponse(res);
8658
+ return;
8659
+ }
8660
+ if (res.status !== 200) {
8661
+ await res.body?.cancel().catch(() => void 0);
8662
+ throw new Error("unexpected JWKS status");
8663
+ }
8664
+ const doc = await readCappedJson(res, JWKS_MAX_BODY_BYTES);
8665
+ const isJwk = (k) => typeof k === "object" && k !== null && !Array.isArray(k) && typeof k.kty === "string";
8666
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {
8667
+ throw new Error("not a JWKS document with a key");
8668
+ }
8669
+ const usable = doc.keys.filter(isJwk);
8670
+ const resolver = this.jose.createLocalJWKSet({ keys: usable });
8671
+ this.#resolver = resolver;
8672
+ const etag = res.headers.get("etag");
8673
+ this.#etag = etag !== null && Buffer.byteLength(etag) <= 256 && !/[\x00-\x1f\x7f]/.test(etag) ? etag : void 0;
8674
+ this.#anchorMs = Date.now();
8675
+ this.#ttlMs = ttlFromResponse(res);
8676
+ }
8677
+ };
8466
8678
  var CLOCK_SKEW_LEEWAY_SEC = 60;
8467
- function createVerifier(baseUrl) {
8468
- return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
8679
+ function createVerifier(baseUrl, tlsOptions) {
8680
+ return createJwksVerifier(`${baseUrl}${JWKS_PATH}`, tlsOptions);
8469
8681
  }
8470
- function createJwksVerifier(jwksUri) {
8682
+ function createJwksVerifier(jwksUri, tlsOptions) {
8471
8683
  let jwksPromise = null;
8472
8684
  async function getJwks() {
8473
8685
  if (!jwksPromise) {
8474
- jwksPromise = import('jose').then(
8475
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
8476
- cooldownDuration: COOLDOWN_DURATION_MS,
8477
- timeoutDuration: TIMEOUT_DURATION_MS
8478
- })
8479
- );
8686
+ jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));
8480
8687
  }
8481
- return jwksPromise;
8688
+ return (await jwksPromise).getKey;
8482
8689
  }
8483
8690
  return {
8484
8691
  async verifyAccessToken(token, expectations, proofs = {}) {
8485
8692
  const { jwtVerify: jwtVerify2 } = await import('jose');
8693
+ assertAccessTokenHeader(token);
8486
8694
  const jwks = await getJwks();
8487
8695
  const { payload } = await jwtVerify2(token, jwks, {
8488
8696
  algorithms: ["EdDSA"],
@@ -8492,6 +8700,7 @@ function createJwksVerifier(jwksUri) {
8492
8700
  ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
8493
8701
  });
8494
8702
  assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
8703
+ assertNoPurposeClaim(payload);
8495
8704
  const claims = payload;
8496
8705
  verifyTokenBinding(claims, proofs);
8497
8706
  return claims;
@@ -8530,6 +8739,40 @@ function createJwksVerifier(jwksUri) {
8530
8739
  }
8531
8740
  };
8532
8741
  }
8742
+ function assertAccessTokenHeader(token) {
8743
+ let header;
8744
+ try {
8745
+ const segments = token.split(".");
8746
+ if (segments.length !== 3) {
8747
+ throw new Error("not three segments");
8748
+ }
8749
+ const parsed = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
8750
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8751
+ throw new Error("header is not an object");
8752
+ }
8753
+ header = parsed;
8754
+ } catch {
8755
+ throw new AuthError("access token is not a well-formed JWS");
8756
+ }
8757
+ if (typeof header.kid !== "string" || header.kid.length === 0) {
8758
+ throw new AuthError("access token carries no kid header (CONTRACT.md \xA710.1 rule 12)");
8759
+ }
8760
+ if (header.typ !== void 0 && !isAccessTokenTyp(header.typ)) {
8761
+ throw new AuthError("token typ is not at+jwt: not an access token (CONTRACT.md \xA710.1 rule 10)");
8762
+ }
8763
+ }
8764
+ function assertNoPurposeClaim(payload) {
8765
+ if (Object.prototype.hasOwnProperty.call(payload, "purpose")) {
8766
+ throw new AuthError("token carries a purpose claim: not an access token (CONTRACT.md \xA710.1 rule 11)");
8767
+ }
8768
+ }
8769
+ function isAccessTokenTyp(typ) {
8770
+ if (typeof typ !== "string") {
8771
+ return false;
8772
+ }
8773
+ const lower = typ.toLowerCase();
8774
+ return lower === "at+jwt" || lower === "application/at+jwt";
8775
+ }
8533
8776
  function assertTenantClaim(claim, expected) {
8534
8777
  if (typeof expected !== "string" || expected === "") {
8535
8778
  throw new AuthError(
@@ -8662,7 +8905,7 @@ function createNodeSession(options) {
8662
8905
  const tlsOptions = resolveNodeTlsOptions(options);
8663
8906
  wrapAxios(base.axios, jar, tlsOptions);
8664
8907
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
8665
- const jwksVerifier = createVerifier(options.baseUrl);
8908
+ const jwksVerifier = createVerifier(options.baseUrl, tlsOptions);
8666
8909
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar, tlsOptions);
8667
8910
  }
8668
8911
  function createNodeClient(options) {
@@ -9118,14 +9361,14 @@ var DiscoveryCache = class {
9118
9361
  if (pending) {
9119
9362
  return pending;
9120
9363
  }
9121
- const fetch = fetcher().then((document2) => {
9364
+ const fetch2 = fetcher().then((document2) => {
9122
9365
  this.#documents.set(originKey, { document: document2, expiresAt: Date.now() + this.#ttlMs });
9123
9366
  return document2;
9124
9367
  }).finally(() => {
9125
9368
  this.#inFlight.delete(originKey);
9126
9369
  });
9127
- this.#inFlight.set(originKey, fetch);
9128
- return fetch;
9370
+ this.#inFlight.set(originKey, fetch2);
9371
+ return fetch2;
9129
9372
  }
9130
9373
  };
9131
9374
  function normalizeOrigin(url) {
@@ -9139,6 +9382,9 @@ function normalizeOrigin(url) {
9139
9382
  function exposeSecret(value) {
9140
9383
  return typeof value === "string" ? value : value.expose();
9141
9384
  }
9385
+ function refreshFlightKey(refreshToken, resolvedTenantId) {
9386
+ return crypto.createHash("sha256").update(resolvedTenantId.toLowerCase()).update("\0").update(exposeSecret(refreshToken)).digest("hex");
9387
+ }
9142
9388
  function axiosStatus3(err) {
9143
9389
  if (err && typeof err === "object" && "response" in err) {
9144
9390
  return err.response?.status;
@@ -9384,9 +9630,20 @@ var OidcClient = class {
9384
9630
  /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */
9385
9631
  #adoptedCredential = null;
9386
9632
  #adoptionInterceptorInstalled = false;
9387
- /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */
9388
- #pendingRefresh = null;
9633
+ /**
9634
+ * In-flight `oidcRefresh` calls, one per refresh token (§9 rule 2: a burst is the callers of ONE
9635
+ * token). Keyed by {@link refreshFlightKey}, a SHA-256 digest, never the raw token. A key's slot is
9636
+ * removed once its flight has settled.
9637
+ */
9638
+ #pendingRefresh = /* @__PURE__ */ new Map();
9639
+ /** @internal Test hook: the number of occupied single-flight slots. */
9640
+ _pendingRefreshSlots() {
9641
+ return this.#pendingRefresh.size;
9642
+ }
9389
9643
  constructor(session, options) {
9644
+ if (options.clockSkewSec !== void 0) {
9645
+ resolveClockSkewSec(options.clockSkewSec);
9646
+ }
9390
9647
  this.#session = session;
9391
9648
  this.#options = options;
9392
9649
  this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);
@@ -9493,32 +9750,42 @@ var OidcClient = class {
9493
9750
  // -------------------------------------------------------------------------
9494
9751
  /**
9495
9752
  * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an
9496
- * {@link OidcTokenSet}, under the §9 single-flight refresh guard.
9753
+ * {@link OidcTokenSet}, single-flight per refresh token (§9).
9497
9754
  *
9498
9755
  * @remarks
9499
9756
  * This is a **distinct operation** from `AxiamClient.refresh()`, which drives
9500
9757
  * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The
9501
9758
  * two are never merged or aliased and neither falls back to the other
9502
- * (§12.1). They do share the session's §9 guard, so at most one refresh of
9503
- * either kind is ever in flight for a session.
9759
+ * (§12.1), and they do not share a lock: the single-flight here is keyed per
9760
+ * refresh token, so refreshes of different tokens run concurrently.
9504
9761
  *
9505
- * Concurrent `oidcRefresh` calls collapse into one HTTP request and all
9506
- * receive the same token set — §9 rule 2's result sharing.
9762
+ * Concurrent `oidcRefresh` calls presenting the SAME refresh token (and
9763
+ * tenant) collapse into one HTTP request and all receive the same token set
9764
+ * — §9 rule 2's result sharing. A different token gets its own request and
9765
+ * its own result.
9507
9766
  *
9508
9767
  * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;
9509
9768
  * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce
9510
9769
  * in a refresh-issued ID token.
9511
9770
  */
9512
9771
  oidcRefresh(params) {
9513
- const existing = this.#pendingRefresh;
9772
+ let tenantId;
9773
+ let key;
9774
+ try {
9775
+ tenantId = this.#resolveTenantId(params.tenantId).toLowerCase();
9776
+ key = refreshFlightKey(params.refreshToken, tenantId);
9777
+ } catch (err) {
9778
+ return Promise.reject(err);
9779
+ }
9780
+ const existing = this.#pendingRefresh.get(key);
9514
9781
  if (existing) {
9515
9782
  return existing;
9516
9783
  }
9517
- const pending = this.#refreshUnderGuard(params);
9518
- this.#pendingRefresh = pending;
9784
+ const pending = this.#refreshFlight({ ...params, tenantId });
9785
+ this.#pendingRefresh.set(key, pending);
9519
9786
  const clear = () => {
9520
- if (this.#pendingRefresh === pending) {
9521
- this.#pendingRefresh = null;
9787
+ if (this.#pendingRefresh.get(key) === pending) {
9788
+ this.#pendingRefresh.delete(key);
9522
9789
  }
9523
9790
  };
9524
9791
  pending.then(clear, clear);
@@ -10525,8 +10792,14 @@ var OidcClient = class {
10525
10792
  * Every check exists because skipping it has a name:
10526
10793
  *
10527
10794
  * 1. **Signature**, through the same §12.4 JWKS verifier the ID-token path
10528
- * uses — no second key-fetching path — with the same `kid`-required
10529
- * discipline.
10795
+ * uses — no second key-fetching path. The key is selected **by `kid`**
10796
+ * (contract 1.69): the server signs every logout token with the header
10797
+ * `{"alg":"EdDSA","typ":"logout+jwt","kid":"<kid>"}`. A token with no
10798
+ * `kid` is refused as `unknown_kid` (no single-key fallback, no trying
10799
+ * every key), and an unknown `kid` causes at most one JWKS re-fetch per
10800
+ * cooldown window and is then refused as `unknown_kid`. §10.1 rules 10
10801
+ * and 11 (`typ` `at+jwt`, no `purpose`) apply to the access-token path
10802
+ * only, not here.
10530
10803
  * 2. **`iss`/`aud`**: a token minted for another RP is not accepted here.
10531
10804
  * 3. **`events` carries the back-channel-logout key.** This is what
10532
10805
  * distinguishes a logout token from an ID token; skipping it means
@@ -10554,11 +10827,19 @@ var OidcClient = class {
10554
10827
  throw new AuthError(`logout token alg must be EdDSA, got ${String(header.alg)}`);
10555
10828
  }
10556
10829
  if (!header.kid) {
10557
- throw new AuthError("logout token carries no kid header");
10830
+ throw new AuthError("logout token carries no kid header (unknown_kid)", "unknown_kid");
10831
+ }
10832
+ let claims;
10833
+ try {
10834
+ claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
10835
+ token
10836
+ );
10837
+ } catch (err) {
10838
+ if (typeof err === "object" && err !== null && err.code === "ERR_JWKS_NO_MATCHING_KEY") {
10839
+ throw new AuthError("no JWKS key matches the logout token kid (unknown_kid)", "unknown_kid");
10840
+ }
10841
+ throw err;
10558
10842
  }
10559
- const claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
10560
- token
10561
- );
10562
10843
  if (claims.iss !== config.issuer) {
10563
10844
  throw new AuthError("logout token issuer does not match the discovery document");
10564
10845
  }
@@ -10603,17 +10884,13 @@ var OidcClient = class {
10603
10884
  // internals
10604
10885
  // -------------------------------------------------------------------------
10605
10886
  /**
10606
- * Run one `refresh_token` grant under the session's §9 single-flight guard.
10607
- *
10608
- * The guard's callback signature returns `void`, so the token set is
10609
- * published through a local variable. When the callback does NOT run, the
10610
- * guard was already busy with a *different* refresh (the §1 cookie-session
10611
- * path, which cannot produce an `OidcTokenSet`); rather than return a stale
10612
- * or wrong result we simply try again now that the other refresh has
10613
- * settled. Bounded, so a pathologically busy guard fails loudly instead of
10614
- * spinning.
10887
+ * One `oidcRefresh` wire call: the unit the per-token single-flight map shares. It deliberately holds
10888
+ * NO session-wide lock across the call (§9 rules 5 and 7, contract clarification): flights of
10889
+ * different refresh tokens run independently and concurrently, and the §1 cookie-session refresh
10890
+ * (the session's own `refreshGuard`) neither waits for nor fails them. The per-key map in
10891
+ * {@link OidcClient.oidcRefresh} is the guard; a refresh token namespace is not the session cookie's.
10615
10892
  */
10616
- async #refreshUnderGuard(params) {
10893
+ async #refreshFlight(params) {
10617
10894
  const configuration = params.configuration ?? await this.oidcDiscover();
10618
10895
  const form = new URLSearchParams();
10619
10896
  form.set("grant_type", "refresh_token");
@@ -10623,19 +10900,8 @@ var OidcClient = class {
10623
10900
  if (params.scope !== void 0) {
10624
10901
  form.set("scope", params.scope);
10625
10902
  }
10626
- for (let attempt = 0; attempt < 3; attempt += 1) {
10627
- let refreshed;
10628
- await this.#session.refreshGuard(async () => {
10629
- const wire = await this.#postToken(configuration, form, params.tenantId);
10630
- refreshed = await this.#toTokenSet(wire, configuration, void 0);
10631
- });
10632
- if (refreshed) {
10633
- return refreshed;
10634
- }
10635
- }
10636
- throw new AuthError(
10637
- "oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md \xA79); another refresh kept it busy."
10638
- );
10903
+ const wire = await this.#postToken(configuration, form, params.tenantId);
10904
+ return this.#toTokenSet(wire, configuration, void 0);
10639
10905
  }
10640
10906
  // -------------------------------------------------------------------------
10641
10907
  // §33 CIBA — client-initiated backchannel authentication (contract 1.58)
@@ -11030,7 +11296,7 @@ var OidcClient = class {
11030
11296
  if (existing) {
11031
11297
  return existing;
11032
11298
  }
11033
- const verifier = createJwksVerifier(jwksUri);
11299
+ const verifier = createJwksVerifier(jwksUri, nodeTlsOptionsOf(this.#session, jwksUri));
11034
11300
  this.#verifiers.set(jwksUri, verifier);
11035
11301
  return verifier;
11036
11302
  }
@@ -11259,17 +11525,26 @@ var HANDOFF_CODE_TTL_SECS = 60;
11259
11525
 
11260
11526
  // src/node/oidcState.ts
11261
11527
  var OIDC_STATE_TTL_MS = 6e5;
11528
+ var OIDC_STATE_MAX_ENTRIES = 1e4;
11262
11529
  var MemoryOidcStateStore = class {
11263
11530
  #entries = /* @__PURE__ */ new Map();
11264
11531
  #ttlMs;
11532
+ #maxEntries;
11265
11533
  /**
11266
11534
  * @param ttlMs entry lifetime in milliseconds. Defaults to
11267
11535
  * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
11268
11536
  * shorter TTL is honoured (useful in tests), a longer one is reduced,
11269
11537
  * because §12.3 rule 1 fixes 10 minutes as the maximum.
11538
+ * @param maxEntries the most entries held at once. Defaults to
11539
+ * {@link OIDC_STATE_MAX_ENTRIES}; at the bound, saving a new entry evicts
11540
+ * the oldest. Must be a positive integer.
11270
11541
  */
11271
- constructor(ttlMs = OIDC_STATE_TTL_MS) {
11542
+ constructor(ttlMs = OIDC_STATE_TTL_MS, maxEntries = OIDC_STATE_MAX_ENTRIES) {
11543
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
11544
+ throw new RangeError("MemoryOidcStateStore maxEntries must be a positive integer");
11545
+ }
11272
11546
  this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
11547
+ this.#maxEntries = maxEntries;
11273
11548
  }
11274
11549
  /** Number of unexpired entries currently held. Intended for tests and metrics. */
11275
11550
  get size() {
@@ -11279,6 +11554,12 @@ var MemoryOidcStateStore = class {
11279
11554
  /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
11280
11555
  async save(entry) {
11281
11556
  this.#sweep();
11557
+ this.#entries.delete(entry.state);
11558
+ while (this.#entries.size >= this.#maxEntries) {
11559
+ const oldest = this.#entries.keys().next();
11560
+ if (oldest.done) break;
11561
+ this.#entries.delete(oldest.value);
11562
+ }
11282
11563
  this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
11283
11564
  }
11284
11565
  /**
@@ -11953,6 +12234,7 @@ exports.MIN_REPLAY_WINDOW_MS = MIN_REPLAY_WINDOW_MS;
11953
12234
  exports.MemoryOidcStateStore = MemoryOidcStateStore;
11954
12235
  exports.MemoryReplayStore = MemoryReplayStore;
11955
12236
  exports.NodeSession = NodeSession;
12237
+ exports.OIDC_STATE_MAX_ENTRIES = OIDC_STATE_MAX_ENTRIES;
11956
12238
  exports.OIDC_STATE_TTL_MS = OIDC_STATE_TTL_MS;
11957
12239
  exports.OidcClient = OidcClient;
11958
12240
  exports.PROTOCOL_OAUTH2 = PROTOCOL_OAUTH2;
@@ -11981,6 +12263,8 @@ exports.UMA_PROTECTION_SCOPE = UMA_PROTECTION_SCOPE;
11981
12263
  exports.UMA_TICKET_GRANT_TYPE = UMA_TICKET_GRANT_TYPE;
11982
12264
  exports.WebhookVerifyError = WebhookVerifyError;
11983
12265
  exports.accessTokenHash = accessTokenHash;
12266
+ exports.assertAccessTokenHeader = assertAccessTokenHeader;
12267
+ exports.assertNoPurposeClaim = assertNoPurposeClaim;
11984
12268
  exports.assertTenantClaim = assertTenantClaim;
11985
12269
  exports.canonicalHtu = canonicalHtu;
11986
12270
  exports.certificateThumbprintS256 = certificateThumbprintS256;
@@ -11994,6 +12278,7 @@ exports.createVerifier = createVerifier;
11994
12278
  exports.extractCookieValue = extractCookieValue;
11995
12279
  exports.generateCodeVerifier = generateCodeVerifier;
11996
12280
  exports.isAccessDenied = isAccessDenied;
12281
+ exports.isAccessTokenTyp = isAccessTokenTyp;
11997
12282
  exports.isExpiredToken = isExpiredToken;
11998
12283
  exports.jwkThumbprintS256 = jwkThumbprintS256;
11999
12284
  exports.nativeNonce = nativeNonce;