axiam-sdk 1.3.1 → 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 +9 -9
@@ -594,6 +594,7 @@ var SharedSession = class {
594
594
  this.expectedIssuer = options.expectedIssuer;
595
595
  this.expectedAudience = options.expectedAudience;
596
596
  this.presentsClientCertificate = options.clientCert !== void 0 && options.clientKey !== void 0;
597
+ registerTlsOptions(this, options);
597
598
  this.resolvedTenantId = options.tenantId;
598
599
  this.resolvedOrgId = options.orgId;
599
600
  this.refreshGuard = createRefreshGuard();
@@ -645,7 +646,7 @@ var SharedSession = class {
645
646
  }
646
647
  /**
647
648
  * Host-isolation guard (3A, defense in depth): returns `true` when `url`
648
- * targets a host other than this session's base origin — an absolute
649
+ * targets an origin (scheme, host and port) other than this session's base origin — an absolute
649
650
  * third-party URL, or a redirect that axios/the browser resolved off-origin.
650
651
  * The tenant identifier and CSRF token must never be attached to such a
651
652
  * request. A relative/host-less `url` (the normal case, merged against
@@ -659,7 +660,7 @@ var SharedSession = class {
659
660
  }
660
661
  try {
661
662
  const target = new URL(url, this.baseUrl);
662
- return target.host !== new URL(this.baseUrl).host;
663
+ return target.origin !== new URL(this.baseUrl).origin;
663
664
  } catch {
664
665
  return true;
665
666
  }
@@ -721,6 +722,19 @@ function resolveTenantHeaderValue(options) {
721
722
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
722
723
  );
723
724
  }
725
+ function agentTlsOptions(tls) {
726
+ if (tls === void 0) return {};
727
+ if (tls.ca === void 0) {
728
+ return { ...tls.cert !== void 0 ? { cert: tls.cert } : {}, ...tls.key !== void 0 ? { key: tls.key } : {} };
729
+ }
730
+ const tlsMod = loadNodeBuiltin("node:tls");
731
+ const secureContext = tlsMod.createSecureContext({
732
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
733
+ ...tls.key !== void 0 ? { key: tls.key } : {}
734
+ });
735
+ secureContext.context.addCACert(tls.ca);
736
+ return { secureContext };
737
+ }
724
738
  function loadNodeBuiltin(id) {
725
739
  const getBuiltinModule = process.getBuiltinModule;
726
740
  if (typeof getBuiltinModule === "function") {
@@ -737,6 +751,27 @@ function loadNodeBuiltin(id) {
737
751
  function loadNodeHttps() {
738
752
  return loadNodeBuiltin("node:https");
739
753
  }
754
+ var sessionTlsOptions = /* @__PURE__ */ new WeakMap();
755
+ function registerTlsOptions(session, options) {
756
+ if (options.customCa === void 0 && options.clientCert === void 0) return;
757
+ try {
758
+ const tls = resolveNodeTlsOptions(options);
759
+ if (tls !== void 0) sessionTlsOptions.set(session, tls);
760
+ } catch {
761
+ }
762
+ }
763
+ function nodeTlsOptionsOf(session, targetUrl) {
764
+ const tls = sessionTlsOptions.get(session);
765
+ if (tls === void 0 || targetUrl === void 0) return tls;
766
+ let sameOrigin = false;
767
+ try {
768
+ sameOrigin = new URL(targetUrl).origin === new URL(session.baseUrl).origin;
769
+ } catch {
770
+ sameOrigin = false;
771
+ }
772
+ if (sameOrigin) return tls;
773
+ return tls.ca !== void 0 ? { ca: tls.ca } : void 0;
774
+ }
740
775
  function tlsOptionsFrom(customCa, identity) {
741
776
  if (!customCa) {
742
777
  if (!identity) {
@@ -760,7 +795,7 @@ function buildPlainNodeAgents(tls) {
760
795
  const https = loadNodeHttps();
761
796
  return {
762
797
  httpAgent: new http.Agent(),
763
- httpsAgent: new https.Agent(tls ?? {})
798
+ httpsAgent: new https.Agent(agentTlsOptions(tls))
764
799
  };
765
800
  }
766
801
  function maybeBuildHttpsAgent(customCa, identity) {
@@ -772,7 +807,7 @@ function maybeBuildHttpsAgent(customCa, identity) {
772
807
  return void 0;
773
808
  }
774
809
  const https = loadNodeHttps();
775
- return new https.Agent(tls);
810
+ return new https.Agent(agentTlsOptions(tls));
776
811
  }
777
812
  function createSession(options) {
778
813
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -3828,7 +3863,7 @@ function normalizeSearch(term) {
3828
3863
  const trimmed = term?.trim();
3829
3864
  return trimmed ? trimmed : void 0;
3830
3865
  }
3831
- async function collectPages(start, fetch) {
3866
+ async function collectPages(start, fetch2) {
3832
3867
  let request = {
3833
3868
  offset: start.offset ?? 0,
3834
3869
  limit: start.limit,
@@ -3836,7 +3871,7 @@ async function collectPages(start, fetch) {
3836
3871
  };
3837
3872
  const out = [];
3838
3873
  for (; ; ) {
3839
- const page = await fetch(request);
3874
+ const page = await fetch2(request);
3840
3875
  out.push(...page.items);
3841
3876
  const next = page.offset + page.items.length;
3842
3877
  if (page.items.length === 0 || next >= page.total) return out;
@@ -8226,7 +8261,7 @@ function createJar() {
8226
8261
  function wrapAxios(instance, jar, tls) {
8227
8262
  const cookies = { jar };
8228
8263
  instance.defaults.httpAgent = new HttpCookieAgent({ cookies });
8229
- instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...tls ?? {} });
8264
+ instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...agentTlsOptions(tls) });
8230
8265
  return instance;
8231
8266
  }
8232
8267
  async function extractCookieValue(jar, url, name) {
@@ -8336,6 +8371,9 @@ function resolveClockSkewSec(clockSkewSec) {
8336
8371
  if (clockSkewSec === void 0) {
8337
8372
  return MAX_CLOCK_SKEW_SEC;
8338
8373
  }
8374
+ if (typeof clockSkewSec !== "number" || !Number.isFinite(clockSkewSec)) {
8375
+ throw new TypeError("clockSkewSec must be a finite number of seconds");
8376
+ }
8339
8377
  return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
8340
8378
  }
8341
8379
  function constantTimeEquals(a, b) {
@@ -8451,32 +8489,202 @@ function constantTimeEqual(a, b) {
8451
8489
  return diff === 0;
8452
8490
  }
8453
8491
  async function certificateThumbprintS256(der) {
8454
- const { createHash: createHash4 } = await import('crypto');
8455
- return createHash4("sha256").update(der).digest("base64url");
8492
+ const { createHash: createHash5 } = await import('crypto');
8493
+ return createHash5("sha256").update(der).digest("base64url");
8456
8494
  }
8457
8495
  var JWKS_PATH = "/oauth2/jwks";
8458
8496
  var COOLDOWN_DURATION_MS = 6e4;
8459
8497
  var TIMEOUT_DURATION_MS = 5e3;
8498
+ var JWKS_MAX_TTL_MS = 3e5;
8499
+ var JWKS_MAX_STALE_MS = 3e5;
8500
+ var JWKS_MAX_BODY_BYTES = 50 * 1024;
8501
+ async function readCappedJson(res, maxBytes) {
8502
+ const declared = res.headers.get("content-length");
8503
+ if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
8504
+ await res.body?.cancel().catch(() => void 0);
8505
+ throw new Error("JWKS response too large");
8506
+ }
8507
+ const reader = res.body?.getReader();
8508
+ if (reader === void 0) throw new Error("JWKS response has no body");
8509
+ const chunks = [];
8510
+ let total = 0;
8511
+ for (; ; ) {
8512
+ const { done, value } = await reader.read();
8513
+ if (done) break;
8514
+ total += value.byteLength;
8515
+ if (total > maxBytes) {
8516
+ await reader.cancel().catch(() => void 0);
8517
+ throw new Error("JWKS response too large");
8518
+ }
8519
+ chunks.push(value);
8520
+ }
8521
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
8522
+ }
8523
+ function ttlFromResponse(res) {
8524
+ const m = /(?:^|[\s,])max-age=(\d+)/i.exec(res.headers.get("cache-control") ?? "");
8525
+ if (m === null) return JWKS_MAX_TTL_MS;
8526
+ const ms = Number(m[1]) * 1e3;
8527
+ return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;
8528
+ }
8529
+ async function fetchWithTls(url, init, tls) {
8530
+ const https = (await import('https')).default;
8531
+ const { Readable } = await import('stream');
8532
+ const tlsMod = await import('tls');
8533
+ let secureContext;
8534
+ if (tls.ca !== void 0) {
8535
+ secureContext = tlsMod.createSecureContext({
8536
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8537
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8538
+ });
8539
+ secureContext.context.addCACert(tls.ca);
8540
+ }
8541
+ return new Promise((resolve, reject) => {
8542
+ let settled = false;
8543
+ const settle = (fn) => {
8544
+ if (settled) return;
8545
+ settled = true;
8546
+ fn();
8547
+ };
8548
+ const agent = new https.Agent(
8549
+ secureContext !== void 0 ? { secureContext } : {
8550
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8551
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8552
+ }
8553
+ );
8554
+ const fail2 = (message = "unexpected JWKS status") => {
8555
+ agent.destroy();
8556
+ settle(() => reject(new Error(message)));
8557
+ };
8558
+ const req = https.request(
8559
+ url,
8560
+ { method: "GET", headers: init.headers, signal: init.signal, agent },
8561
+ (res) => {
8562
+ try {
8563
+ const status = res.statusCode ?? 0;
8564
+ if (status !== 200 && status !== 304) {
8565
+ res.destroy();
8566
+ fail2();
8567
+ return;
8568
+ }
8569
+ const headers = new Headers();
8570
+ for (const [name, value] of Object.entries(res.headers)) {
8571
+ if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
8572
+ }
8573
+ if (status === 304) res.resume();
8574
+ const body = status === 304 ? null : Readable.toWeb(res);
8575
+ const response = new Response(body, { status, headers });
8576
+ res.on("close", () => agent.destroy());
8577
+ settle(() => resolve(response));
8578
+ } catch {
8579
+ res.destroy();
8580
+ fail2();
8581
+ }
8582
+ }
8583
+ );
8584
+ req.on("error", (err) => {
8585
+ agent.destroy();
8586
+ settle(() => reject(err));
8587
+ });
8588
+ req.on("close", () => {
8589
+ if (!settled) fail2("JWKS request closed before a response");
8590
+ });
8591
+ req.end();
8592
+ });
8593
+ }
8594
+ var JwksCache = class {
8595
+ constructor(jwksUri, jose, tls) {
8596
+ this.jwksUri = jwksUri;
8597
+ this.jose = jose;
8598
+ this.#tls = tls;
8599
+ }
8600
+ jwksUri;
8601
+ jose;
8602
+ #resolver;
8603
+ #etag;
8604
+ #anchorMs = 0;
8605
+ #ttlMs = JWKS_MAX_TTL_MS;
8606
+ #lastAttemptMs;
8607
+ #inflight;
8608
+ /** Held privately: it may carry the client key, and must not be an enumerable property. */
8609
+ #tls;
8610
+ /** The key resolver handed to `jwtVerify`. */
8611
+ getKey = async (...args) => {
8612
+ const usable = () => this.#resolver !== void 0 && Date.now() >= this.#anchorMs && Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS ? this.#resolver : void 0;
8613
+ const nowMs = Date.now();
8614
+ if (this.#resolver === void 0 || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {
8615
+ const refresh2 = this.#refreshIfAllowed();
8616
+ if (usable() === void 0) await refresh2;
8617
+ }
8618
+ const held = usable();
8619
+ if (held === void 0) {
8620
+ throw new this.jose.errors.JOSEError("the JSON Web Key Set is unavailable");
8621
+ }
8622
+ try {
8623
+ return await held(...args);
8624
+ } catch (err) {
8625
+ if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;
8626
+ await this.#refreshIfAllowed();
8627
+ const refreshed = usable();
8628
+ if (refreshed === void 0) throw err;
8629
+ return refreshed(...args);
8630
+ }
8631
+ };
8632
+ async #refreshIfAllowed() {
8633
+ if (this.#inflight !== void 0) return this.#inflight;
8634
+ const now = Date.now();
8635
+ const sinceLast = this.#lastAttemptMs === void 0 ? Infinity : now - this.#lastAttemptMs;
8636
+ if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return;
8637
+ this.#lastAttemptMs = now;
8638
+ this.#inflight = this.#fetch().catch(() => void 0).finally(() => {
8639
+ this.#inflight = void 0;
8640
+ });
8641
+ return this.#inflight;
8642
+ }
8643
+ async #fetch() {
8644
+ const conditional = this.#resolver !== void 0 && this.#etag !== void 0;
8645
+ const headers = { accept: "application/json", ...conditional ? { "if-none-match": this.#etag } : {} };
8646
+ const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);
8647
+ 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 });
8648
+ if (res.status === 304 && conditional) {
8649
+ await res.body?.cancel().catch(() => void 0);
8650
+ this.#anchorMs = Date.now();
8651
+ this.#ttlMs = ttlFromResponse(res);
8652
+ return;
8653
+ }
8654
+ if (res.status !== 200) {
8655
+ await res.body?.cancel().catch(() => void 0);
8656
+ throw new Error("unexpected JWKS status");
8657
+ }
8658
+ const doc = await readCappedJson(res, JWKS_MAX_BODY_BYTES);
8659
+ const isJwk = (k) => typeof k === "object" && k !== null && !Array.isArray(k) && typeof k.kty === "string";
8660
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {
8661
+ throw new Error("not a JWKS document with a key");
8662
+ }
8663
+ const usable = doc.keys.filter(isJwk);
8664
+ const resolver = this.jose.createLocalJWKSet({ keys: usable });
8665
+ this.#resolver = resolver;
8666
+ const etag = res.headers.get("etag");
8667
+ this.#etag = etag !== null && Buffer.byteLength(etag) <= 256 && !/[\x00-\x1f\x7f]/.test(etag) ? etag : void 0;
8668
+ this.#anchorMs = Date.now();
8669
+ this.#ttlMs = ttlFromResponse(res);
8670
+ }
8671
+ };
8460
8672
  var CLOCK_SKEW_LEEWAY_SEC = 60;
8461
- function createVerifier(baseUrl) {
8462
- return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
8673
+ function createVerifier(baseUrl, tlsOptions) {
8674
+ return createJwksVerifier(`${baseUrl}${JWKS_PATH}`, tlsOptions);
8463
8675
  }
8464
- function createJwksVerifier(jwksUri) {
8676
+ function createJwksVerifier(jwksUri, tlsOptions) {
8465
8677
  let jwksPromise = null;
8466
8678
  async function getJwks() {
8467
8679
  if (!jwksPromise) {
8468
- jwksPromise = import('jose').then(
8469
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
8470
- cooldownDuration: COOLDOWN_DURATION_MS,
8471
- timeoutDuration: TIMEOUT_DURATION_MS
8472
- })
8473
- );
8680
+ jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));
8474
8681
  }
8475
- return jwksPromise;
8682
+ return (await jwksPromise).getKey;
8476
8683
  }
8477
8684
  return {
8478
8685
  async verifyAccessToken(token, expectations, proofs = {}) {
8479
8686
  const { jwtVerify: jwtVerify2 } = await import('jose');
8687
+ assertAccessTokenHeader(token);
8480
8688
  const jwks = await getJwks();
8481
8689
  const { payload } = await jwtVerify2(token, jwks, {
8482
8690
  algorithms: ["EdDSA"],
@@ -8486,6 +8694,7 @@ function createJwksVerifier(jwksUri) {
8486
8694
  ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
8487
8695
  });
8488
8696
  assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
8697
+ assertNoPurposeClaim(payload);
8489
8698
  const claims = payload;
8490
8699
  verifyTokenBinding(claims, proofs);
8491
8700
  return claims;
@@ -8524,6 +8733,40 @@ function createJwksVerifier(jwksUri) {
8524
8733
  }
8525
8734
  };
8526
8735
  }
8736
+ function assertAccessTokenHeader(token) {
8737
+ let header;
8738
+ try {
8739
+ const segments = token.split(".");
8740
+ if (segments.length !== 3) {
8741
+ throw new Error("not three segments");
8742
+ }
8743
+ const parsed = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
8744
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8745
+ throw new Error("header is not an object");
8746
+ }
8747
+ header = parsed;
8748
+ } catch {
8749
+ throw new AuthError("access token is not a well-formed JWS");
8750
+ }
8751
+ if (typeof header.kid !== "string" || header.kid.length === 0) {
8752
+ throw new AuthError("access token carries no kid header (CONTRACT.md \xA710.1 rule 12)");
8753
+ }
8754
+ if (header.typ !== void 0 && !isAccessTokenTyp(header.typ)) {
8755
+ throw new AuthError("token typ is not at+jwt: not an access token (CONTRACT.md \xA710.1 rule 10)");
8756
+ }
8757
+ }
8758
+ function assertNoPurposeClaim(payload) {
8759
+ if (Object.prototype.hasOwnProperty.call(payload, "purpose")) {
8760
+ throw new AuthError("token carries a purpose claim: not an access token (CONTRACT.md \xA710.1 rule 11)");
8761
+ }
8762
+ }
8763
+ function isAccessTokenTyp(typ) {
8764
+ if (typeof typ !== "string") {
8765
+ return false;
8766
+ }
8767
+ const lower = typ.toLowerCase();
8768
+ return lower === "at+jwt" || lower === "application/at+jwt";
8769
+ }
8527
8770
  function assertTenantClaim(claim, expected) {
8528
8771
  if (typeof expected !== "string" || expected === "") {
8529
8772
  throw new AuthError(
@@ -8656,7 +8899,7 @@ function createNodeSession(options) {
8656
8899
  const tlsOptions = resolveNodeTlsOptions(options);
8657
8900
  wrapAxios(base.axios, jar, tlsOptions);
8658
8901
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
8659
- const jwksVerifier = createVerifier(options.baseUrl);
8902
+ const jwksVerifier = createVerifier(options.baseUrl, tlsOptions);
8660
8903
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar, tlsOptions);
8661
8904
  }
8662
8905
  function createNodeClient(options) {
@@ -9112,14 +9355,14 @@ var DiscoveryCache = class {
9112
9355
  if (pending) {
9113
9356
  return pending;
9114
9357
  }
9115
- const fetch = fetcher().then((document2) => {
9358
+ const fetch2 = fetcher().then((document2) => {
9116
9359
  this.#documents.set(originKey, { document: document2, expiresAt: Date.now() + this.#ttlMs });
9117
9360
  return document2;
9118
9361
  }).finally(() => {
9119
9362
  this.#inFlight.delete(originKey);
9120
9363
  });
9121
- this.#inFlight.set(originKey, fetch);
9122
- return fetch;
9364
+ this.#inFlight.set(originKey, fetch2);
9365
+ return fetch2;
9123
9366
  }
9124
9367
  };
9125
9368
  function normalizeOrigin(url) {
@@ -9133,6 +9376,9 @@ function normalizeOrigin(url) {
9133
9376
  function exposeSecret(value) {
9134
9377
  return typeof value === "string" ? value : value.expose();
9135
9378
  }
9379
+ function refreshFlightKey(refreshToken, resolvedTenantId) {
9380
+ return createHash("sha256").update(resolvedTenantId.toLowerCase()).update("\0").update(exposeSecret(refreshToken)).digest("hex");
9381
+ }
9136
9382
  function axiosStatus3(err) {
9137
9383
  if (err && typeof err === "object" && "response" in err) {
9138
9384
  return err.response?.status;
@@ -9378,9 +9624,20 @@ var OidcClient = class {
9378
9624
  /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */
9379
9625
  #adoptedCredential = null;
9380
9626
  #adoptionInterceptorInstalled = false;
9381
- /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */
9382
- #pendingRefresh = null;
9627
+ /**
9628
+ * In-flight `oidcRefresh` calls, one per refresh token (§9 rule 2: a burst is the callers of ONE
9629
+ * token). Keyed by {@link refreshFlightKey}, a SHA-256 digest, never the raw token. A key's slot is
9630
+ * removed once its flight has settled.
9631
+ */
9632
+ #pendingRefresh = /* @__PURE__ */ new Map();
9633
+ /** @internal Test hook: the number of occupied single-flight slots. */
9634
+ _pendingRefreshSlots() {
9635
+ return this.#pendingRefresh.size;
9636
+ }
9383
9637
  constructor(session, options) {
9638
+ if (options.clockSkewSec !== void 0) {
9639
+ resolveClockSkewSec(options.clockSkewSec);
9640
+ }
9384
9641
  this.#session = session;
9385
9642
  this.#options = options;
9386
9643
  this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);
@@ -9487,32 +9744,42 @@ var OidcClient = class {
9487
9744
  // -------------------------------------------------------------------------
9488
9745
  /**
9489
9746
  * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an
9490
- * {@link OidcTokenSet}, under the §9 single-flight refresh guard.
9747
+ * {@link OidcTokenSet}, single-flight per refresh token (§9).
9491
9748
  *
9492
9749
  * @remarks
9493
9750
  * This is a **distinct operation** from `AxiamClient.refresh()`, which drives
9494
9751
  * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The
9495
9752
  * two are never merged or aliased and neither falls back to the other
9496
- * (§12.1). They do share the session's §9 guard, so at most one refresh of
9497
- * either kind is ever in flight for a session.
9753
+ * (§12.1), and they do not share a lock: the single-flight here is keyed per
9754
+ * refresh token, so refreshes of different tokens run concurrently.
9498
9755
  *
9499
- * Concurrent `oidcRefresh` calls collapse into one HTTP request and all
9500
- * receive the same token set — §9 rule 2's result sharing.
9756
+ * Concurrent `oidcRefresh` calls presenting the SAME refresh token (and
9757
+ * tenant) collapse into one HTTP request and all receive the same token set
9758
+ * — §9 rule 2's result sharing. A different token gets its own request and
9759
+ * its own result.
9501
9760
  *
9502
9761
  * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;
9503
9762
  * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce
9504
9763
  * in a refresh-issued ID token.
9505
9764
  */
9506
9765
  oidcRefresh(params) {
9507
- const existing = this.#pendingRefresh;
9766
+ let tenantId;
9767
+ let key;
9768
+ try {
9769
+ tenantId = this.#resolveTenantId(params.tenantId).toLowerCase();
9770
+ key = refreshFlightKey(params.refreshToken, tenantId);
9771
+ } catch (err) {
9772
+ return Promise.reject(err);
9773
+ }
9774
+ const existing = this.#pendingRefresh.get(key);
9508
9775
  if (existing) {
9509
9776
  return existing;
9510
9777
  }
9511
- const pending = this.#refreshUnderGuard(params);
9512
- this.#pendingRefresh = pending;
9778
+ const pending = this.#refreshFlight({ ...params, tenantId });
9779
+ this.#pendingRefresh.set(key, pending);
9513
9780
  const clear = () => {
9514
- if (this.#pendingRefresh === pending) {
9515
- this.#pendingRefresh = null;
9781
+ if (this.#pendingRefresh.get(key) === pending) {
9782
+ this.#pendingRefresh.delete(key);
9516
9783
  }
9517
9784
  };
9518
9785
  pending.then(clear, clear);
@@ -10519,8 +10786,14 @@ var OidcClient = class {
10519
10786
  * Every check exists because skipping it has a name:
10520
10787
  *
10521
10788
  * 1. **Signature**, through the same §12.4 JWKS verifier the ID-token path
10522
- * uses — no second key-fetching path — with the same `kid`-required
10523
- * discipline.
10789
+ * uses — no second key-fetching path. The key is selected **by `kid`**
10790
+ * (contract 1.69): the server signs every logout token with the header
10791
+ * `{"alg":"EdDSA","typ":"logout+jwt","kid":"<kid>"}`. A token with no
10792
+ * `kid` is refused as `unknown_kid` (no single-key fallback, no trying
10793
+ * every key), and an unknown `kid` causes at most one JWKS re-fetch per
10794
+ * cooldown window and is then refused as `unknown_kid`. §10.1 rules 10
10795
+ * and 11 (`typ` `at+jwt`, no `purpose`) apply to the access-token path
10796
+ * only, not here.
10524
10797
  * 2. **`iss`/`aud`**: a token minted for another RP is not accepted here.
10525
10798
  * 3. **`events` carries the back-channel-logout key.** This is what
10526
10799
  * distinguishes a logout token from an ID token; skipping it means
@@ -10548,11 +10821,19 @@ var OidcClient = class {
10548
10821
  throw new AuthError(`logout token alg must be EdDSA, got ${String(header.alg)}`);
10549
10822
  }
10550
10823
  if (!header.kid) {
10551
- throw new AuthError("logout token carries no kid header");
10824
+ throw new AuthError("logout token carries no kid header (unknown_kid)", "unknown_kid");
10825
+ }
10826
+ let claims;
10827
+ try {
10828
+ claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
10829
+ token
10830
+ );
10831
+ } catch (err) {
10832
+ if (typeof err === "object" && err !== null && err.code === "ERR_JWKS_NO_MATCHING_KEY") {
10833
+ throw new AuthError("no JWKS key matches the logout token kid (unknown_kid)", "unknown_kid");
10834
+ }
10835
+ throw err;
10552
10836
  }
10553
- const claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
10554
- token
10555
- );
10556
10837
  if (claims.iss !== config.issuer) {
10557
10838
  throw new AuthError("logout token issuer does not match the discovery document");
10558
10839
  }
@@ -10597,17 +10878,13 @@ var OidcClient = class {
10597
10878
  // internals
10598
10879
  // -------------------------------------------------------------------------
10599
10880
  /**
10600
- * Run one `refresh_token` grant under the session's §9 single-flight guard.
10601
- *
10602
- * The guard's callback signature returns `void`, so the token set is
10603
- * published through a local variable. When the callback does NOT run, the
10604
- * guard was already busy with a *different* refresh (the §1 cookie-session
10605
- * path, which cannot produce an `OidcTokenSet`); rather than return a stale
10606
- * or wrong result we simply try again now that the other refresh has
10607
- * settled. Bounded, so a pathologically busy guard fails loudly instead of
10608
- * spinning.
10881
+ * One `oidcRefresh` wire call: the unit the per-token single-flight map shares. It deliberately holds
10882
+ * NO session-wide lock across the call (§9 rules 5 and 7, contract clarification): flights of
10883
+ * different refresh tokens run independently and concurrently, and the §1 cookie-session refresh
10884
+ * (the session's own `refreshGuard`) neither waits for nor fails them. The per-key map in
10885
+ * {@link OidcClient.oidcRefresh} is the guard; a refresh token namespace is not the session cookie's.
10609
10886
  */
10610
- async #refreshUnderGuard(params) {
10887
+ async #refreshFlight(params) {
10611
10888
  const configuration = params.configuration ?? await this.oidcDiscover();
10612
10889
  const form = new URLSearchParams();
10613
10890
  form.set("grant_type", "refresh_token");
@@ -10617,19 +10894,8 @@ var OidcClient = class {
10617
10894
  if (params.scope !== void 0) {
10618
10895
  form.set("scope", params.scope);
10619
10896
  }
10620
- for (let attempt = 0; attempt < 3; attempt += 1) {
10621
- let refreshed;
10622
- await this.#session.refreshGuard(async () => {
10623
- const wire = await this.#postToken(configuration, form, params.tenantId);
10624
- refreshed = await this.#toTokenSet(wire, configuration, void 0);
10625
- });
10626
- if (refreshed) {
10627
- return refreshed;
10628
- }
10629
- }
10630
- throw new AuthError(
10631
- "oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md \xA79); another refresh kept it busy."
10632
- );
10897
+ const wire = await this.#postToken(configuration, form, params.tenantId);
10898
+ return this.#toTokenSet(wire, configuration, void 0);
10633
10899
  }
10634
10900
  // -------------------------------------------------------------------------
10635
10901
  // §33 CIBA — client-initiated backchannel authentication (contract 1.58)
@@ -11024,7 +11290,7 @@ var OidcClient = class {
11024
11290
  if (existing) {
11025
11291
  return existing;
11026
11292
  }
11027
- const verifier = createJwksVerifier(jwksUri);
11293
+ const verifier = createJwksVerifier(jwksUri, nodeTlsOptionsOf(this.#session, jwksUri));
11028
11294
  this.#verifiers.set(jwksUri, verifier);
11029
11295
  return verifier;
11030
11296
  }
@@ -11253,17 +11519,26 @@ var HANDOFF_CODE_TTL_SECS = 60;
11253
11519
 
11254
11520
  // src/node/oidcState.ts
11255
11521
  var OIDC_STATE_TTL_MS = 6e5;
11522
+ var OIDC_STATE_MAX_ENTRIES = 1e4;
11256
11523
  var MemoryOidcStateStore = class {
11257
11524
  #entries = /* @__PURE__ */ new Map();
11258
11525
  #ttlMs;
11526
+ #maxEntries;
11259
11527
  /**
11260
11528
  * @param ttlMs entry lifetime in milliseconds. Defaults to
11261
11529
  * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
11262
11530
  * shorter TTL is honoured (useful in tests), a longer one is reduced,
11263
11531
  * because §12.3 rule 1 fixes 10 minutes as the maximum.
11532
+ * @param maxEntries the most entries held at once. Defaults to
11533
+ * {@link OIDC_STATE_MAX_ENTRIES}; at the bound, saving a new entry evicts
11534
+ * the oldest. Must be a positive integer.
11264
11535
  */
11265
- constructor(ttlMs = OIDC_STATE_TTL_MS) {
11536
+ constructor(ttlMs = OIDC_STATE_TTL_MS, maxEntries = OIDC_STATE_MAX_ENTRIES) {
11537
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
11538
+ throw new RangeError("MemoryOidcStateStore maxEntries must be a positive integer");
11539
+ }
11266
11540
  this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
11541
+ this.#maxEntries = maxEntries;
11267
11542
  }
11268
11543
  /** Number of unexpired entries currently held. Intended for tests and metrics. */
11269
11544
  get size() {
@@ -11273,6 +11548,12 @@ var MemoryOidcStateStore = class {
11273
11548
  /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
11274
11549
  async save(entry) {
11275
11550
  this.#sweep();
11551
+ this.#entries.delete(entry.state);
11552
+ while (this.#entries.size >= this.#maxEntries) {
11553
+ const oldest = this.#entries.keys().next();
11554
+ if (oldest.done) break;
11555
+ this.#entries.delete(oldest.value);
11556
+ }
11276
11557
  this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
11277
11558
  }
11278
11559
  /**
@@ -11914,6 +12195,6 @@ function parseJsonQuiet(data) {
11914
12195
  }
11915
12196
  }
11916
12197
 
11917
- export { ACCESS_COOKIE, ACCESS_TOKEN_TYPE, BACKCHANNEL_LOGOUT_EVENT, CIBA_GRANT_TYPE, CIBA_SLOW_DOWN_INCREMENT_SECS, CLOCK_SKEW_LEEWAY_SEC, CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, CSRF_COOKIE, CibaRequestSigner, DEFAULT_CIBA_INTERVAL_SECS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_INTERVAL_SECS, DEFAULT_WEBHOOK_TOLERANCE_SEC, DEVICE_CODE_GRANT_TYPE, DISCOVERY_PATH, DPOP_IAT_LEEWAY_SEC, HANDOFF_CODE_TTL_SECS, HANDOFF_QUERY_PARAM, ID_TOKEN_ALG, InMemoryJtiStore, JWKS_PATH, JWKS_REFETCH_INTERVAL_MS, JWT_TOKEN_TYPE, MAX_CLOCK_SKEW_SEC, MAX_ENTRIES2 as MAX_ENTRIES, MAX_LOGOUT_TOKEN_AGE_SECS, MIN_DISCOVERY_TTL_MS, MIN_POLL_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryOidcStateStore, MemoryReplayStore, NodeSession, OIDC_STATE_TTL_MS, OidcClient, PROTOCOL_OAUTH2, PROTOCOL_OIDC_CONNECT, PROTOCOL_SAML, PROVIDER_ID_TOKEN_GRANT_TYPE, PollSchedule, REFRESH_COOKIE, RevocationFeed, SIGNED_REQUEST_LIFETIME_SECS, SLOW_DOWN_INCREMENT_SECS, SSF_EVENT_TYPES, SSO_CALLBACK_PATH, SSO_HANDOFF_PATH, SSO_OAUTH2_CALLBACK_PATH, SSO_OAUTH2_START_PATH, SSO_PROVIDERS_PATH, SSO_START_PATH, Sensitive, SetRefusedError, SsfReceiver, TOKEN_EXCHANGE_GRANT_TYPE, TokenManager, UMA_CLAIM_TOKEN_FORMAT, UMA_PROTECTION_SCOPE, UMA_TICKET_GRANT_TYPE, WebhookVerifyError, accessTokenHash, assertTenantClaim, canonicalHtu, certificateThumbprintS256, computeCodeChallenge, createJar, createJwksVerifier, createNodeClient, createNodeSession, createOidcClient, createVerifier, extractCookieValue, generateCodeVerifier, isAccessDenied, isExpiredToken, jwkThumbprintS256, nativeNonce, normalizeOrigin, pushErrorCode, randomUrlSafeToken, setErrFromReason, umaChallengeHeader, umaParseChallenge, verifyCertificateBinding, verifyDpopProof, verifyTokenBinding, verifyWebhook, wrapAxios };
12198
+ export { ACCESS_COOKIE, ACCESS_TOKEN_TYPE, BACKCHANNEL_LOGOUT_EVENT, CIBA_GRANT_TYPE, CIBA_SLOW_DOWN_INCREMENT_SECS, CLOCK_SKEW_LEEWAY_SEC, CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, CSRF_COOKIE, CibaRequestSigner, DEFAULT_CIBA_INTERVAL_SECS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_INTERVAL_SECS, DEFAULT_WEBHOOK_TOLERANCE_SEC, DEVICE_CODE_GRANT_TYPE, DISCOVERY_PATH, DPOP_IAT_LEEWAY_SEC, HANDOFF_CODE_TTL_SECS, HANDOFF_QUERY_PARAM, ID_TOKEN_ALG, InMemoryJtiStore, JWKS_PATH, JWKS_REFETCH_INTERVAL_MS, JWT_TOKEN_TYPE, MAX_CLOCK_SKEW_SEC, MAX_ENTRIES2 as MAX_ENTRIES, MAX_LOGOUT_TOKEN_AGE_SECS, MIN_DISCOVERY_TTL_MS, MIN_POLL_INTERVAL_MS, MIN_REPLAY_WINDOW_MS, MemoryOidcStateStore, MemoryReplayStore, NodeSession, OIDC_STATE_MAX_ENTRIES, OIDC_STATE_TTL_MS, OidcClient, PROTOCOL_OAUTH2, PROTOCOL_OIDC_CONNECT, PROTOCOL_SAML, PROVIDER_ID_TOKEN_GRANT_TYPE, PollSchedule, REFRESH_COOKIE, RevocationFeed, SIGNED_REQUEST_LIFETIME_SECS, SLOW_DOWN_INCREMENT_SECS, SSF_EVENT_TYPES, SSO_CALLBACK_PATH, SSO_HANDOFF_PATH, SSO_OAUTH2_CALLBACK_PATH, SSO_OAUTH2_START_PATH, SSO_PROVIDERS_PATH, SSO_START_PATH, Sensitive, SetRefusedError, SsfReceiver, TOKEN_EXCHANGE_GRANT_TYPE, TokenManager, UMA_CLAIM_TOKEN_FORMAT, UMA_PROTECTION_SCOPE, UMA_TICKET_GRANT_TYPE, WebhookVerifyError, accessTokenHash, assertAccessTokenHeader, assertNoPurposeClaim, assertTenantClaim, canonicalHtu, certificateThumbprintS256, computeCodeChallenge, createJar, createJwksVerifier, createNodeClient, createNodeSession, createOidcClient, createVerifier, extractCookieValue, generateCodeVerifier, isAccessDenied, isAccessTokenTyp, isExpiredToken, jwkThumbprintS256, nativeNonce, normalizeOrigin, pushErrorCode, randomUrlSafeToken, setErrFromReason, umaChallengeHeader, umaParseChallenge, verifyCertificateBinding, verifyDpopProof, verifyTokenBinding, verifyWebhook, wrapAxios };
11918
12199
  //# sourceMappingURL=index.mjs.map
11919
12200
  //# sourceMappingURL=index.mjs.map