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
@@ -299,8 +299,17 @@ function umaChallengeHeaderValue(realm, asUri, ticket) {
299
299
  return `UMA realm="${realm}", as_uri="${asUri}", ticket="${ticket}"`;
300
300
  }
301
301
  function hasAnyRole(identityRoles, roles) {
302
+ if (!Array.isArray(identityRoles)) {
303
+ return false;
304
+ }
302
305
  return roles.some((role) => identityRoles.includes(role));
303
306
  }
307
+ function hasAnyScope(identityScopes, scopes) {
308
+ if (!Array.isArray(identityScopes)) {
309
+ return false;
310
+ }
311
+ return scopes.some((scope) => identityScopes.includes(scope));
312
+ }
304
313
  function parseCookieHeader(header) {
305
314
  const cookies = {};
306
315
  if (!header) {
@@ -677,6 +686,75 @@ function isFastify(app) {
677
686
  return typeof app.addHook === "function";
678
687
  }
679
688
 
689
+ // src/node/oidcState.ts
690
+ var OIDC_STATE_TTL_MS = 6e5;
691
+ var OIDC_STATE_MAX_ENTRIES = 1e4;
692
+ var MemoryOidcStateStore = class {
693
+ #entries = /* @__PURE__ */ new Map();
694
+ #ttlMs;
695
+ #maxEntries;
696
+ /**
697
+ * @param ttlMs entry lifetime in milliseconds. Defaults to
698
+ * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
699
+ * shorter TTL is honoured (useful in tests), a longer one is reduced,
700
+ * because §12.3 rule 1 fixes 10 minutes as the maximum.
701
+ * @param maxEntries the most entries held at once. Defaults to
702
+ * {@link OIDC_STATE_MAX_ENTRIES}; at the bound, saving a new entry evicts
703
+ * the oldest. Must be a positive integer.
704
+ */
705
+ constructor(ttlMs = OIDC_STATE_TTL_MS, maxEntries = OIDC_STATE_MAX_ENTRIES) {
706
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
707
+ throw new RangeError("MemoryOidcStateStore maxEntries must be a positive integer");
708
+ }
709
+ this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
710
+ this.#maxEntries = maxEntries;
711
+ }
712
+ /** Number of unexpired entries currently held. Intended for tests and metrics. */
713
+ get size() {
714
+ this.#sweep();
715
+ return this.#entries.size;
716
+ }
717
+ /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
718
+ async save(entry) {
719
+ this.#sweep();
720
+ this.#entries.delete(entry.state);
721
+ while (this.#entries.size >= this.#maxEntries) {
722
+ const oldest = this.#entries.keys().next();
723
+ if (oldest.done) break;
724
+ this.#entries.delete(oldest.value);
725
+ }
726
+ this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
727
+ }
728
+ /**
729
+ * Atomically return and delete the entry for `state`. Deletion happens
730
+ * before the expiry check, so even an expired hit is removed rather than
731
+ * left to accumulate — and a second call can never return the same entry
732
+ * twice regardless of timing (JavaScript's single-threaded event loop makes
733
+ * this get-then-delete pair genuinely atomic; a store backed by real
734
+ * concurrency must use an atomic primitive such as Redis `GETDEL`).
735
+ */
736
+ async consume(state) {
737
+ const held = this.#entries.get(state);
738
+ if (!held) {
739
+ return void 0;
740
+ }
741
+ this.#entries.delete(state);
742
+ if (held.expiresAt <= Date.now()) {
743
+ return void 0;
744
+ }
745
+ return held.entry;
746
+ }
747
+ /** Drop every expired entry. Lazy housekeeping — no background timer. */
748
+ #sweep() {
749
+ const now = Date.now();
750
+ for (const [state, held] of this.#entries) {
751
+ if (held.expiresAt <= now) {
752
+ this.#entries.delete(state);
753
+ }
754
+ }
755
+ }
756
+ };
757
+
680
758
  // src/middleware/oidcLoginCore.ts
681
759
  function authenticationFailedBody(message) {
682
760
  return { error: "authentication_failed", message };
@@ -687,6 +765,75 @@ function invalidRequestBody2(message) {
687
765
  function unavailableBody(message) {
688
766
  return { error: "oidc_unavailable", message };
689
767
  }
768
+ var OIDC_BINDING_COOKIE_NAME = "__Host-axiam_oidc_bind";
769
+ var OIDC_BINDING_COOKIE_NAME_LOOPBACK = "axiam_oidc_bind";
770
+ var UNIFORM_STATE_FAILURE = "unknown, expired, or already-used login state";
771
+ var LOOPBACK_HOSTS2 = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
772
+ function isPlainHttpLoopback(redirectUri) {
773
+ try {
774
+ const url = new URL(redirectUri);
775
+ return url.protocol === "http:" && LOOPBACK_HOSTS2.has(url.hostname);
776
+ } catch {
777
+ return false;
778
+ }
779
+ }
780
+ function oidcBindingCookieName(redirectUri) {
781
+ return isPlainHttpLoopback(redirectUri) ? OIDC_BINDING_COOKIE_NAME_LOOPBACK : OIDC_BINDING_COOKIE_NAME;
782
+ }
783
+ function bindingCookieAttributes(redirectUri) {
784
+ return isPlainHttpLoopback(redirectUri) ? "Path=/; HttpOnly; SameSite=Lax" : "Path=/; HttpOnly; Secure; SameSite=Lax";
785
+ }
786
+ var BINDING_COOKIE_MAX_AGE_SEC = Math.floor(OIDC_STATE_TTL_MS / 1e3);
787
+ function setBindingCookie(redirectUri, value) {
788
+ return `${oidcBindingCookieName(redirectUri)}=${value}; ${bindingCookieAttributes(redirectUri)}; Max-Age=${BINDING_COOKIE_MAX_AGE_SEC}`;
789
+ }
790
+ function oidcBindingClearCookie(redirectUri) {
791
+ return `${oidcBindingCookieName(redirectUri)}=; ${bindingCookieAttributes(redirectUri)}; Max-Age=0`;
792
+ }
793
+ function encodeRedirectLocation(destination) {
794
+ return destination.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD").replace(/[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]+|%(?![0-9A-Fa-f]{2})/g, encodeURI);
795
+ }
796
+ function bindingDigest(value) {
797
+ return crypto.createHash("sha256").update(value, "ascii").digest("hex");
798
+ }
799
+ function bindingMatches(entry, presented) {
800
+ const stored = entry.bindingDigest;
801
+ if (typeof presented !== "string" || presented.length === 0 || typeof stored !== "string") {
802
+ return false;
803
+ }
804
+ const expected = Buffer.from(bindingDigest(presented), "utf8");
805
+ const actual = Buffer.from(stored, "utf8");
806
+ if (expected.length !== actual.length) {
807
+ return false;
808
+ }
809
+ return crypto.timingSafeEqual(expected, actual);
810
+ }
811
+ function isSafeReturnTo(value) {
812
+ if (value.length === 0 || value[0] !== "/") {
813
+ return false;
814
+ }
815
+ if (value.startsWith("//") || value.startsWith("/\\")) {
816
+ return false;
817
+ }
818
+ return !/[\\\u0000-\u001f\u007f]/.test(value);
819
+ }
820
+ function acceptedReturnTo(value, allowReturnTo) {
821
+ if (typeof value !== "string") {
822
+ return void 0;
823
+ }
824
+ if (isSafeReturnTo(value)) {
825
+ return value;
826
+ }
827
+ if (allowReturnTo !== void 0) {
828
+ try {
829
+ if (allowReturnTo(value) === true) {
830
+ return value;
831
+ }
832
+ } catch {
833
+ }
834
+ }
835
+ return void 0;
836
+ }
690
837
  async function beginOidcLogin(options, returnTo) {
691
838
  try {
692
839
  const configuration = await options.client.oidcDiscover();
@@ -695,14 +842,20 @@ async function beginOidcLogin(options, returnTo) {
695
842
  redirectUri: options.redirectUri,
696
843
  ...options.scope !== void 0 ? { scope: options.scope } : {}
697
844
  });
845
+ const safeReturnTo = acceptedReturnTo(returnTo, options.allowReturnTo);
846
+ if (returnTo !== void 0 && safeReturnTo === void 0) {
847
+ options.logger?.debug("axiam_sdk.oidc", "dropped a returnTo that is not a same-origin relative path");
848
+ }
849
+ const binding = crypto.randomBytes(32).toString("base64url");
698
850
  await options.store.save({
699
851
  state: request.state,
700
852
  nonce: request.nonce,
701
853
  codeVerifier: request.codeVerifier,
702
854
  redirectUri: options.redirectUri,
703
- ...returnTo !== void 0 ? { returnTo } : {}
855
+ ...safeReturnTo !== void 0 ? { returnTo: safeReturnTo } : {},
856
+ bindingDigest: bindingDigest(binding)
704
857
  });
705
- return { kind: "redirect", url: request.url };
858
+ return { kind: "redirect", url: request.url, setCookie: setBindingCookie(options.redirectUri, binding) };
706
859
  } catch (err) {
707
860
  options.logger?.debug("axiam_sdk.oidc", "oidc login could not be started", {
708
861
  reason: err instanceof Error ? err.message : "unknown"
@@ -710,7 +863,8 @@ async function beginOidcLogin(options, returnTo) {
710
863
  return { kind: "error", status: 503, body: unavailableBody("could not start the OIDC login flow") };
711
864
  }
712
865
  }
713
- async function completeOidcLogin(options, query) {
866
+ async function completeOidcLogin(options, query, context = {}) {
867
+ const setCookie = oidcBindingClearCookie(options.redirectUri);
714
868
  if (query.error) {
715
869
  options.logger?.debug("axiam_sdk.oidc", "idp returned an authorization error", { error: query.error });
716
870
  return {
@@ -718,24 +872,26 @@ async function completeOidcLogin(options, query) {
718
872
  status: 401,
719
873
  body: authenticationFailedBody(
720
874
  query.error_description ? `${query.error}: ${query.error_description}` : query.error
721
- )
875
+ ),
876
+ setCookie
722
877
  };
723
878
  }
724
879
  if (!query.state || !query.code) {
725
880
  return {
726
881
  kind: "error",
727
882
  status: 400,
728
- body: invalidRequestBody2("callback is missing the state or code query parameter")
883
+ body: invalidRequestBody2("callback is missing the state or code query parameter"),
884
+ setCookie
729
885
  };
730
886
  }
731
887
  const entry = await options.store.consume(query.state);
732
888
  if (!entry) {
733
889
  options.logger?.debug("axiam_sdk.oidc", "no stored login state for the callback state");
734
- return {
735
- kind: "error",
736
- status: 401,
737
- body: authenticationFailedBody("unknown, expired, or already-used login state")
738
- };
890
+ return { kind: "error", status: 401, body: authenticationFailedBody(UNIFORM_STATE_FAILURE), setCookie };
891
+ }
892
+ if (!bindingMatches(entry, context.bindingCookie)) {
893
+ options.logger?.debug("axiam_sdk.oidc", "login state is not bound to this browser");
894
+ return { kind: "error", status: 401, body: authenticationFailedBody(UNIFORM_STATE_FAILURE), setCookie };
739
895
  }
740
896
  let tokens;
741
897
  try {
@@ -748,16 +904,21 @@ async function completeOidcLogin(options, query) {
748
904
  } catch (err) {
749
905
  if (err instanceof NetworkError) {
750
906
  options.logger?.debug("axiam_sdk.oidc", "token exchange transport failure");
751
- return { kind: "error", status: 503, body: unavailableBody("the AXIAM token endpoint is unreachable") };
907
+ return {
908
+ kind: "error",
909
+ status: 503,
910
+ body: unavailableBody("the AXIAM token endpoint is unreachable"),
911
+ setCookie
912
+ };
752
913
  }
753
914
  const reason = err instanceof AuthError ? err.message : "token exchange failed";
754
915
  options.logger?.debug("axiam_sdk.oidc", "token exchange failed", { reason });
755
- return { kind: "error", status: 401, body: authenticationFailedBody(reason) };
916
+ return { kind: "error", status: 401, body: authenticationFailedBody(reason), setCookie };
756
917
  }
757
- await options.onSuccess?.(tokens, entry);
758
- const destination = options.successRedirect ?? entry.returnTo;
918
+ await options.onSuccess?.(tokens, entry, context.request);
919
+ const destination = options.successRedirect ?? acceptedReturnTo(entry.returnTo, options.allowReturnTo);
759
920
  if (destination) {
760
- return { kind: "redirect", url: destination };
921
+ return { kind: "redirect", url: destination, setCookie };
761
922
  }
762
923
  return {
763
924
  kind: "json",
@@ -765,7 +926,8 @@ async function completeOidcLogin(options, query) {
765
926
  authenticated: true,
766
927
  ...typeof tokens.idClaims?.sub === "string" ? { sub: tokens.idClaims.sub } : {},
767
928
  expiresIn: tokens.expiresIn
768
- }
929
+ },
930
+ setCookie
769
931
  };
770
932
  }
771
933
  var MAX_CLOCK_SKEW_SEC = 60;
@@ -776,6 +938,9 @@ function resolveClockSkewSec(clockSkewSec) {
776
938
  if (clockSkewSec === void 0) {
777
939
  return MAX_CLOCK_SKEW_SEC;
778
940
  }
941
+ if (typeof clockSkewSec !== "number" || !Number.isFinite(clockSkewSec)) {
942
+ throw new TypeError("clockSkewSec must be a finite number of seconds");
943
+ }
779
944
  return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
780
945
  }
781
946
  function constantTimeEquals(a, b) {
@@ -891,28 +1056,198 @@ function constantTimeEqual(a, b) {
891
1056
  return diff === 0;
892
1057
  }
893
1058
  async function certificateThumbprintS256(der) {
894
- const { createHash: createHash3 } = await import('crypto');
895
- return createHash3("sha256").update(der).digest("base64url");
1059
+ const { createHash: createHash5 } = await import('crypto');
1060
+ return createHash5("sha256").update(der).digest("base64url");
896
1061
  }
897
1062
  var COOLDOWN_DURATION_MS = 6e4;
898
1063
  var TIMEOUT_DURATION_MS = 5e3;
1064
+ var JWKS_MAX_TTL_MS = 3e5;
1065
+ var JWKS_MAX_STALE_MS = 3e5;
1066
+ var JWKS_MAX_BODY_BYTES = 50 * 1024;
1067
+ async function readCappedJson(res, maxBytes) {
1068
+ const declared = res.headers.get("content-length");
1069
+ if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
1070
+ await res.body?.cancel().catch(() => void 0);
1071
+ throw new Error("JWKS response too large");
1072
+ }
1073
+ const reader = res.body?.getReader();
1074
+ if (reader === void 0) throw new Error("JWKS response has no body");
1075
+ const chunks = [];
1076
+ let total = 0;
1077
+ for (; ; ) {
1078
+ const { done, value } = await reader.read();
1079
+ if (done) break;
1080
+ total += value.byteLength;
1081
+ if (total > maxBytes) {
1082
+ await reader.cancel().catch(() => void 0);
1083
+ throw new Error("JWKS response too large");
1084
+ }
1085
+ chunks.push(value);
1086
+ }
1087
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
1088
+ }
1089
+ function ttlFromResponse(res) {
1090
+ const m = /(?:^|[\s,])max-age=(\d+)/i.exec(res.headers.get("cache-control") ?? "");
1091
+ if (m === null) return JWKS_MAX_TTL_MS;
1092
+ const ms = Number(m[1]) * 1e3;
1093
+ return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;
1094
+ }
1095
+ async function fetchWithTls(url, init, tls) {
1096
+ const https = (await import('https')).default;
1097
+ const { Readable } = await import('stream');
1098
+ const tlsMod = await import('tls');
1099
+ let secureContext;
1100
+ if (tls.ca !== void 0) {
1101
+ secureContext = tlsMod.createSecureContext({
1102
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
1103
+ ...tls.key !== void 0 ? { key: tls.key } : {}
1104
+ });
1105
+ secureContext.context.addCACert(tls.ca);
1106
+ }
1107
+ return new Promise((resolve, reject) => {
1108
+ let settled = false;
1109
+ const settle = (fn) => {
1110
+ if (settled) return;
1111
+ settled = true;
1112
+ fn();
1113
+ };
1114
+ const agent = new https.Agent(
1115
+ secureContext !== void 0 ? { secureContext } : {
1116
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
1117
+ ...tls.key !== void 0 ? { key: tls.key } : {}
1118
+ }
1119
+ );
1120
+ const fail = (message = "unexpected JWKS status") => {
1121
+ agent.destroy();
1122
+ settle(() => reject(new Error(message)));
1123
+ };
1124
+ const req = https.request(
1125
+ url,
1126
+ { method: "GET", headers: init.headers, signal: init.signal, agent },
1127
+ (res) => {
1128
+ try {
1129
+ const status = res.statusCode ?? 0;
1130
+ if (status !== 200 && status !== 304) {
1131
+ res.destroy();
1132
+ fail();
1133
+ return;
1134
+ }
1135
+ const headers = new Headers();
1136
+ for (const [name, value] of Object.entries(res.headers)) {
1137
+ if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1138
+ }
1139
+ if (status === 304) res.resume();
1140
+ const body = status === 304 ? null : Readable.toWeb(res);
1141
+ const response = new Response(body, { status, headers });
1142
+ res.on("close", () => agent.destroy());
1143
+ settle(() => resolve(response));
1144
+ } catch {
1145
+ res.destroy();
1146
+ fail();
1147
+ }
1148
+ }
1149
+ );
1150
+ req.on("error", (err) => {
1151
+ agent.destroy();
1152
+ settle(() => reject(err));
1153
+ });
1154
+ req.on("close", () => {
1155
+ if (!settled) fail("JWKS request closed before a response");
1156
+ });
1157
+ req.end();
1158
+ });
1159
+ }
1160
+ var JwksCache = class {
1161
+ constructor(jwksUri, jose, tls) {
1162
+ this.jwksUri = jwksUri;
1163
+ this.jose = jose;
1164
+ this.#tls = tls;
1165
+ }
1166
+ jwksUri;
1167
+ jose;
1168
+ #resolver;
1169
+ #etag;
1170
+ #anchorMs = 0;
1171
+ #ttlMs = JWKS_MAX_TTL_MS;
1172
+ #lastAttemptMs;
1173
+ #inflight;
1174
+ /** Held privately: it may carry the client key, and must not be an enumerable property. */
1175
+ #tls;
1176
+ /** The key resolver handed to `jwtVerify`. */
1177
+ getKey = async (...args) => {
1178
+ const usable = () => this.#resolver !== void 0 && Date.now() >= this.#anchorMs && Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS ? this.#resolver : void 0;
1179
+ const nowMs = Date.now();
1180
+ if (this.#resolver === void 0 || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {
1181
+ const refresh = this.#refreshIfAllowed();
1182
+ if (usable() === void 0) await refresh;
1183
+ }
1184
+ const held = usable();
1185
+ if (held === void 0) {
1186
+ throw new this.jose.errors.JOSEError("the JSON Web Key Set is unavailable");
1187
+ }
1188
+ try {
1189
+ return await held(...args);
1190
+ } catch (err) {
1191
+ if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;
1192
+ await this.#refreshIfAllowed();
1193
+ const refreshed = usable();
1194
+ if (refreshed === void 0) throw err;
1195
+ return refreshed(...args);
1196
+ }
1197
+ };
1198
+ async #refreshIfAllowed() {
1199
+ if (this.#inflight !== void 0) return this.#inflight;
1200
+ const now = Date.now();
1201
+ const sinceLast = this.#lastAttemptMs === void 0 ? Infinity : now - this.#lastAttemptMs;
1202
+ if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return;
1203
+ this.#lastAttemptMs = now;
1204
+ this.#inflight = this.#fetch().catch(() => void 0).finally(() => {
1205
+ this.#inflight = void 0;
1206
+ });
1207
+ return this.#inflight;
1208
+ }
1209
+ async #fetch() {
1210
+ const conditional = this.#resolver !== void 0 && this.#etag !== void 0;
1211
+ const headers = { accept: "application/json", ...conditional ? { "if-none-match": this.#etag } : {} };
1212
+ const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);
1213
+ 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 });
1214
+ if (res.status === 304 && conditional) {
1215
+ await res.body?.cancel().catch(() => void 0);
1216
+ this.#anchorMs = Date.now();
1217
+ this.#ttlMs = ttlFromResponse(res);
1218
+ return;
1219
+ }
1220
+ if (res.status !== 200) {
1221
+ await res.body?.cancel().catch(() => void 0);
1222
+ throw new Error("unexpected JWKS status");
1223
+ }
1224
+ const doc = await readCappedJson(res, JWKS_MAX_BODY_BYTES);
1225
+ const isJwk = (k) => typeof k === "object" && k !== null && !Array.isArray(k) && typeof k.kty === "string";
1226
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {
1227
+ throw new Error("not a JWKS document with a key");
1228
+ }
1229
+ const usable = doc.keys.filter(isJwk);
1230
+ const resolver = this.jose.createLocalJWKSet({ keys: usable });
1231
+ this.#resolver = resolver;
1232
+ const etag = res.headers.get("etag");
1233
+ this.#etag = etag !== null && Buffer.byteLength(etag) <= 256 && !/[\x00-\x1f\x7f]/.test(etag) ? etag : void 0;
1234
+ this.#anchorMs = Date.now();
1235
+ this.#ttlMs = ttlFromResponse(res);
1236
+ }
1237
+ };
899
1238
  var CLOCK_SKEW_LEEWAY_SEC = 60;
900
- function createJwksVerifier(jwksUri) {
1239
+ function createJwksVerifier(jwksUri, tlsOptions) {
901
1240
  let jwksPromise = null;
902
1241
  async function getJwks() {
903
1242
  if (!jwksPromise) {
904
- jwksPromise = import('jose').then(
905
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
906
- cooldownDuration: COOLDOWN_DURATION_MS,
907
- timeoutDuration: TIMEOUT_DURATION_MS
908
- })
909
- );
1243
+ jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));
910
1244
  }
911
- return jwksPromise;
1245
+ return (await jwksPromise).getKey;
912
1246
  }
913
1247
  return {
914
1248
  async verifyAccessToken(token, expectations, proofs = {}) {
915
1249
  const { jwtVerify } = await import('jose');
1250
+ assertAccessTokenHeader(token);
916
1251
  const jwks = await getJwks();
917
1252
  const { payload } = await jwtVerify(token, jwks, {
918
1253
  algorithms: ["EdDSA"],
@@ -922,6 +1257,7 @@ function createJwksVerifier(jwksUri) {
922
1257
  ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
923
1258
  });
924
1259
  assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
1260
+ assertNoPurposeClaim(payload);
925
1261
  const claims = payload;
926
1262
  verifyTokenBinding(claims, proofs);
927
1263
  return claims;
@@ -960,6 +1296,40 @@ function createJwksVerifier(jwksUri) {
960
1296
  }
961
1297
  };
962
1298
  }
1299
+ function assertAccessTokenHeader(token) {
1300
+ let header;
1301
+ try {
1302
+ const segments = token.split(".");
1303
+ if (segments.length !== 3) {
1304
+ throw new Error("not three segments");
1305
+ }
1306
+ const parsed = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
1307
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1308
+ throw new Error("header is not an object");
1309
+ }
1310
+ header = parsed;
1311
+ } catch {
1312
+ throw new AuthError("access token is not a well-formed JWS");
1313
+ }
1314
+ if (typeof header.kid !== "string" || header.kid.length === 0) {
1315
+ throw new AuthError("access token carries no kid header (CONTRACT.md \xA710.1 rule 12)");
1316
+ }
1317
+ if (header.typ !== void 0 && !isAccessTokenTyp(header.typ)) {
1318
+ throw new AuthError("token typ is not at+jwt: not an access token (CONTRACT.md \xA710.1 rule 10)");
1319
+ }
1320
+ }
1321
+ function assertNoPurposeClaim(payload) {
1322
+ if (Object.prototype.hasOwnProperty.call(payload, "purpose")) {
1323
+ throw new AuthError("token carries a purpose claim: not an access token (CONTRACT.md \xA710.1 rule 11)");
1324
+ }
1325
+ }
1326
+ function isAccessTokenTyp(typ) {
1327
+ if (typeof typ !== "string") {
1328
+ return false;
1329
+ }
1330
+ const lower = typ.toLowerCase();
1331
+ return lower === "at+jwt" || lower === "application/at+jwt";
1332
+ }
963
1333
  function assertTenantClaim(claim, expected) {
964
1334
  if (typeof expected !== "string" || expected === "") {
965
1335
  throw new AuthError(
@@ -1039,6 +1409,8 @@ async function authenticateRequest(session, token, proofs = {}) {
1039
1409
  throw new AuthError("invalid sub claim");
1040
1410
  }
1041
1411
  assertTenantClaim(claims.tenant_id, session.tenantHeaderValue);
1412
+ assertAccessTokenHeader(token);
1413
+ assertNoPurposeClaim(claims);
1042
1414
  const sid = claims.sid;
1043
1415
  if (session.revocationFeed && typeof sid === "string" && sid.length > 0) {
1044
1416
  if (await session.revocationFeed.isRevoked(sid)) {
@@ -1047,11 +1419,15 @@ async function authenticateRequest(session, token, proofs = {}) {
1047
1419
  );
1048
1420
  }
1049
1421
  }
1050
- const roles = (claims.scope ?? "").split(" ").filter(Boolean);
1422
+ const rawRoles = claims.roles;
1423
+ const roles = Array.isArray(rawRoles) && rawRoles.every((role) => typeof role === "string") ? [...rawRoles] : void 0;
1424
+ const rawScope = claims.scope;
1425
+ const scopes = typeof rawScope === "string" ? rawScope.split(" ").filter(Boolean) : void 0;
1051
1426
  return {
1052
1427
  userId: claims.sub,
1053
1428
  tenantId: claims.tenant_id,
1054
- roles
1429
+ ...roles !== void 0 ? { roles } : {},
1430
+ ...scopes !== void 0 ? { scopes } : {}
1055
1431
  };
1056
1432
  }
1057
1433
 
@@ -1180,9 +1556,33 @@ function requireRole(session, ...roles) {
1180
1556
  next();
1181
1557
  };
1182
1558
  }
1559
+ function requireScope(session, ...scopes) {
1560
+ const challenges = mcpGuardChallenges(session, "requireScope");
1561
+ return (req, res, next) => {
1562
+ const axiamUser = req.axiamUser;
1563
+ if (!axiamUser) {
1564
+ if (challenges) {
1565
+ res.setHeader(
1566
+ "WWW-Authenticate",
1567
+ challengeFor401(challenges, req.headers.cookie, req.headers.authorization)
1568
+ );
1569
+ }
1570
+ res.status(401).json(missingAuthBody());
1571
+ return;
1572
+ }
1573
+ if (!hasAnyScope(axiamUser.scopes, scopes)) {
1574
+ res.status(403).json(authzDeniedBody("missing required scope"));
1575
+ return;
1576
+ }
1577
+ next();
1578
+ };
1579
+ }
1183
1580
  function sendOidcOutcome(res, outcome) {
1581
+ if (outcome.setCookie !== void 0) {
1582
+ res.append("Set-Cookie", outcome.setCookie);
1583
+ }
1184
1584
  if (outcome.kind === "redirect") {
1185
- res.redirect(outcome.url);
1585
+ res.redirect(encodeRedirectLocation(outcome.url));
1186
1586
  return;
1187
1587
  }
1188
1588
  if (outcome.kind === "json") {
@@ -1196,17 +1596,29 @@ function oidcLoginHandlers(options) {
1196
1596
  const returnTo = typeof req.query.returnTo === "string" ? req.query.returnTo : void 0;
1197
1597
  sendOidcOutcome(res, await beginOidcLogin(options, returnTo));
1198
1598
  };
1599
+ const bindingCookieName = oidcBindingCookieName(options.redirectUri);
1199
1600
  const callback = async (req, res) => {
1200
- const query = req.query;
1201
- sendOidcOutcome(
1202
- res,
1203
- await completeOidcLogin(options, {
1204
- ...typeof query.state === "string" ? { state: query.state } : {},
1205
- ...typeof query.code === "string" ? { code: query.code } : {},
1206
- ...typeof query.error === "string" ? { error: query.error } : {},
1207
- ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
1208
- })
1209
- );
1601
+ let outcome;
1602
+ try {
1603
+ const query = req.query;
1604
+ const bindingCookie = parseCookieHeader(req.headers.cookie)[bindingCookieName];
1605
+ outcome = await completeOidcLogin(
1606
+ options,
1607
+ {
1608
+ ...typeof query.state === "string" ? { state: query.state } : {},
1609
+ ...typeof query.code === "string" ? { code: query.code } : {},
1610
+ ...typeof query.error === "string" ? { error: query.error } : {},
1611
+ ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
1612
+ },
1613
+ { request: req, ...bindingCookie !== void 0 ? { bindingCookie } : {} }
1614
+ );
1615
+ } catch (err) {
1616
+ if (!res.headersSent) {
1617
+ res.append("Set-Cookie", oidcBindingClearCookie(options.redirectUri));
1618
+ }
1619
+ throw err;
1620
+ }
1621
+ sendOidcOutcome(res, outcome);
1210
1622
  };
1211
1623
  return { login, callback };
1212
1624
  }
@@ -1343,9 +1755,32 @@ function requireRoleHook(session, ...roles) {
1343
1755
  }
1344
1756
  };
1345
1757
  }
1758
+ function requireScopeHook(session, ...scopes) {
1759
+ const challenges = mcpGuardChallenges(session, "requireScopeHook");
1760
+ return async (request, reply) => {
1761
+ const axiamUser = request.axiamUser;
1762
+ if (!axiamUser) {
1763
+ if (challenges) {
1764
+ void reply.header(
1765
+ "WWW-Authenticate",
1766
+ challengeFor401(challenges, request.headers.cookie, request.headers.authorization)
1767
+ );
1768
+ }
1769
+ await reply.code(401).send(missingAuthBody());
1770
+ return;
1771
+ }
1772
+ if (!hasAnyScope(axiamUser.scopes, scopes)) {
1773
+ await reply.code(403).send(authzDeniedBody("missing required scope"));
1774
+ return;
1775
+ }
1776
+ };
1777
+ }
1346
1778
  async function sendOidcOutcome2(reply, outcome) {
1779
+ if (outcome.setCookie !== void 0) {
1780
+ void reply.header("set-cookie", outcome.setCookie);
1781
+ }
1347
1782
  if (outcome.kind === "redirect") {
1348
- await reply.code(302).header("location", outcome.url).send();
1783
+ await reply.code(302).header("location", encodeRedirectLocation(outcome.url)).send();
1349
1784
  return;
1350
1785
  }
1351
1786
  if (outcome.kind === "json") {
@@ -1357,6 +1792,7 @@ async function sendOidcOutcome2(reply, outcome) {
1357
1792
  var oidcLoginPlugin = (options) => {
1358
1793
  const loginPath = options.loginPath ?? "/auth/login";
1359
1794
  const callbackPath = options.callbackPath ?? "/auth/callback";
1795
+ const bindingCookieName = oidcBindingCookieName(options.redirectUri);
1360
1796
  const plugin = async (fastify) => {
1361
1797
  fastify.get(loginPath, async (request, reply) => {
1362
1798
  const query = request.query;
@@ -1364,16 +1800,27 @@ var oidcLoginPlugin = (options) => {
1364
1800
  await sendOidcOutcome2(reply, await beginOidcLogin(options, returnTo));
1365
1801
  });
1366
1802
  fastify.get(callbackPath, async (request, reply) => {
1367
- const query = request.query;
1368
- await sendOidcOutcome2(
1369
- reply,
1370
- await completeOidcLogin(options, {
1371
- ...typeof query.state === "string" ? { state: query.state } : {},
1372
- ...typeof query.code === "string" ? { code: query.code } : {},
1373
- ...typeof query.error === "string" ? { error: query.error } : {},
1374
- ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
1375
- })
1376
- );
1803
+ let outcome;
1804
+ try {
1805
+ const query = request.query;
1806
+ const bindingCookie = parseCookieHeader(request.headers.cookie)[bindingCookieName];
1807
+ outcome = await completeOidcLogin(
1808
+ options,
1809
+ {
1810
+ ...typeof query.state === "string" ? { state: query.state } : {},
1811
+ ...typeof query.code === "string" ? { code: query.code } : {},
1812
+ ...typeof query.error === "string" ? { error: query.error } : {},
1813
+ ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
1814
+ },
1815
+ { request, ...bindingCookie !== void 0 ? { bindingCookie } : {} }
1816
+ );
1817
+ } catch (err) {
1818
+ if (!reply.sent) {
1819
+ void reply.header("set-cookie", oidcBindingClearCookie(options.redirectUri));
1820
+ }
1821
+ throw err;
1822
+ }
1823
+ await sendOidcOutcome2(reply, outcome);
1377
1824
  });
1378
1825
  };
1379
1826
  plugin[/* @__PURE__ */ Symbol.for("fastify.display-name")] = "axiam-oidc-login";
@@ -1460,6 +1907,19 @@ async function withRetry(fn, options) {
1460
1907
  }
1461
1908
  throw new NetworkError("retry loop exhausted without a result");
1462
1909
  }
1910
+ var sessionTlsOptions = /* @__PURE__ */ new WeakMap();
1911
+ function nodeTlsOptionsOf(session, targetUrl) {
1912
+ const tls = sessionTlsOptions.get(session);
1913
+ if (tls === void 0 || targetUrl === void 0) return tls;
1914
+ let sameOrigin = false;
1915
+ try {
1916
+ sameOrigin = new URL(targetUrl).origin === new URL(session.baseUrl).origin;
1917
+ } catch {
1918
+ sameOrigin = false;
1919
+ }
1920
+ if (sameOrigin) return tls;
1921
+ return tls.ca !== void 0 ? { ca: tls.ca } : void 0;
1922
+ }
1463
1923
  var CODE_CHALLENGE_METHOD_S256 = "S256";
1464
1924
  var CSPRNG_BYTES = 32;
1465
1925
  function randomUrlSafeToken(bytes = CSPRNG_BYTES) {
@@ -1619,14 +2079,14 @@ var DiscoveryCache = class {
1619
2079
  if (pending) {
1620
2080
  return pending;
1621
2081
  }
1622
- const fetch = fetcher().then((document2) => {
2082
+ const fetch2 = fetcher().then((document2) => {
1623
2083
  this.#documents.set(originKey, { document: document2, expiresAt: Date.now() + this.#ttlMs });
1624
2084
  return document2;
1625
2085
  }).finally(() => {
1626
2086
  this.#inFlight.delete(originKey);
1627
2087
  });
1628
- this.#inFlight.set(originKey, fetch);
1629
- return fetch;
2088
+ this.#inFlight.set(originKey, fetch2);
2089
+ return fetch2;
1630
2090
  }
1631
2091
  };
1632
2092
  function normalizeOrigin(url) {
@@ -1640,6 +2100,9 @@ function normalizeOrigin(url) {
1640
2100
  function exposeSecret(value) {
1641
2101
  return typeof value === "string" ? value : value.expose();
1642
2102
  }
2103
+ function refreshFlightKey(refreshToken, resolvedTenantId) {
2104
+ return crypto.createHash("sha256").update(resolvedTenantId.toLowerCase()).update("\0").update(exposeSecret(refreshToken)).digest("hex");
2105
+ }
1643
2106
  function axiosStatus(err) {
1644
2107
  if (err && typeof err === "object" && "response" in err) {
1645
2108
  return err.response?.status;
@@ -1885,9 +2348,20 @@ var OidcClient = class {
1885
2348
  /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */
1886
2349
  #adoptedCredential = null;
1887
2350
  #adoptionInterceptorInstalled = false;
1888
- /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */
1889
- #pendingRefresh = null;
2351
+ /**
2352
+ * In-flight `oidcRefresh` calls, one per refresh token (§9 rule 2: a burst is the callers of ONE
2353
+ * token). Keyed by {@link refreshFlightKey}, a SHA-256 digest, never the raw token. A key's slot is
2354
+ * removed once its flight has settled.
2355
+ */
2356
+ #pendingRefresh = /* @__PURE__ */ new Map();
2357
+ /** @internal Test hook: the number of occupied single-flight slots. */
2358
+ _pendingRefreshSlots() {
2359
+ return this.#pendingRefresh.size;
2360
+ }
1890
2361
  constructor(session, options) {
2362
+ if (options.clockSkewSec !== void 0) {
2363
+ resolveClockSkewSec(options.clockSkewSec);
2364
+ }
1891
2365
  this.#session = session;
1892
2366
  this.#options = options;
1893
2367
  this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);
@@ -1994,32 +2468,42 @@ var OidcClient = class {
1994
2468
  // -------------------------------------------------------------------------
1995
2469
  /**
1996
2470
  * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an
1997
- * {@link OidcTokenSet}, under the §9 single-flight refresh guard.
2471
+ * {@link OidcTokenSet}, single-flight per refresh token (§9).
1998
2472
  *
1999
2473
  * @remarks
2000
2474
  * This is a **distinct operation** from `AxiamClient.refresh()`, which drives
2001
2475
  * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The
2002
2476
  * two are never merged or aliased and neither falls back to the other
2003
- * (§12.1). They do share the session's §9 guard, so at most one refresh of
2004
- * either kind is ever in flight for a session.
2477
+ * (§12.1), and they do not share a lock: the single-flight here is keyed per
2478
+ * refresh token, so refreshes of different tokens run concurrently.
2005
2479
  *
2006
- * Concurrent `oidcRefresh` calls collapse into one HTTP request and all
2007
- * receive the same token set — §9 rule 2's result sharing.
2480
+ * Concurrent `oidcRefresh` calls presenting the SAME refresh token (and
2481
+ * tenant) collapse into one HTTP request and all receive the same token set
2482
+ * — §9 rule 2's result sharing. A different token gets its own request and
2483
+ * its own result.
2008
2484
  *
2009
2485
  * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;
2010
2486
  * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce
2011
2487
  * in a refresh-issued ID token.
2012
2488
  */
2013
2489
  oidcRefresh(params) {
2014
- const existing = this.#pendingRefresh;
2490
+ let tenantId;
2491
+ let key;
2492
+ try {
2493
+ tenantId = this.#resolveTenantId(params.tenantId).toLowerCase();
2494
+ key = refreshFlightKey(params.refreshToken, tenantId);
2495
+ } catch (err) {
2496
+ return Promise.reject(err);
2497
+ }
2498
+ const existing = this.#pendingRefresh.get(key);
2015
2499
  if (existing) {
2016
2500
  return existing;
2017
2501
  }
2018
- const pending = this.#refreshUnderGuard(params);
2019
- this.#pendingRefresh = pending;
2502
+ const pending = this.#refreshFlight({ ...params, tenantId });
2503
+ this.#pendingRefresh.set(key, pending);
2020
2504
  const clear = () => {
2021
- if (this.#pendingRefresh === pending) {
2022
- this.#pendingRefresh = null;
2505
+ if (this.#pendingRefresh.get(key) === pending) {
2506
+ this.#pendingRefresh.delete(key);
2023
2507
  }
2024
2508
  };
2025
2509
  pending.then(clear, clear);
@@ -3026,8 +3510,14 @@ var OidcClient = class {
3026
3510
  * Every check exists because skipping it has a name:
3027
3511
  *
3028
3512
  * 1. **Signature**, through the same §12.4 JWKS verifier the ID-token path
3029
- * uses — no second key-fetching path — with the same `kid`-required
3030
- * discipline.
3513
+ * uses — no second key-fetching path. The key is selected **by `kid`**
3514
+ * (contract 1.69): the server signs every logout token with the header
3515
+ * `{"alg":"EdDSA","typ":"logout+jwt","kid":"<kid>"}`. A token with no
3516
+ * `kid` is refused as `unknown_kid` (no single-key fallback, no trying
3517
+ * every key), and an unknown `kid` causes at most one JWKS re-fetch per
3518
+ * cooldown window and is then refused as `unknown_kid`. §10.1 rules 10
3519
+ * and 11 (`typ` `at+jwt`, no `purpose`) apply to the access-token path
3520
+ * only, not here.
3031
3521
  * 2. **`iss`/`aud`**: a token minted for another RP is not accepted here.
3032
3522
  * 3. **`events` carries the back-channel-logout key.** This is what
3033
3523
  * distinguishes a logout token from an ID token; skipping it means
@@ -3055,11 +3545,19 @@ var OidcClient = class {
3055
3545
  throw new AuthError(`logout token alg must be EdDSA, got ${String(header.alg)}`);
3056
3546
  }
3057
3547
  if (!header.kid) {
3058
- throw new AuthError("logout token carries no kid header");
3548
+ throw new AuthError("logout token carries no kid header (unknown_kid)", "unknown_kid");
3549
+ }
3550
+ let claims;
3551
+ try {
3552
+ claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
3553
+ token
3554
+ );
3555
+ } catch (err) {
3556
+ if (typeof err === "object" && err !== null && err.code === "ERR_JWKS_NO_MATCHING_KEY") {
3557
+ throw new AuthError("no JWKS key matches the logout token kid (unknown_kid)", "unknown_kid");
3558
+ }
3559
+ throw err;
3059
3560
  }
3060
- const claims = await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(
3061
- token
3062
- );
3063
3561
  if (claims.iss !== config.issuer) {
3064
3562
  throw new AuthError("logout token issuer does not match the discovery document");
3065
3563
  }
@@ -3104,17 +3602,13 @@ var OidcClient = class {
3104
3602
  // internals
3105
3603
  // -------------------------------------------------------------------------
3106
3604
  /**
3107
- * Run one `refresh_token` grant under the session's §9 single-flight guard.
3108
- *
3109
- * The guard's callback signature returns `void`, so the token set is
3110
- * published through a local variable. When the callback does NOT run, the
3111
- * guard was already busy with a *different* refresh (the §1 cookie-session
3112
- * path, which cannot produce an `OidcTokenSet`); rather than return a stale
3113
- * or wrong result we simply try again now that the other refresh has
3114
- * settled. Bounded, so a pathologically busy guard fails loudly instead of
3115
- * spinning.
3605
+ * One `oidcRefresh` wire call: the unit the per-token single-flight map shares. It deliberately holds
3606
+ * NO session-wide lock across the call (§9 rules 5 and 7, contract clarification): flights of
3607
+ * different refresh tokens run independently and concurrently, and the §1 cookie-session refresh
3608
+ * (the session's own `refreshGuard`) neither waits for nor fails them. The per-key map in
3609
+ * {@link OidcClient.oidcRefresh} is the guard; a refresh token namespace is not the session cookie's.
3116
3610
  */
3117
- async #refreshUnderGuard(params) {
3611
+ async #refreshFlight(params) {
3118
3612
  const configuration = params.configuration ?? await this.oidcDiscover();
3119
3613
  const form = new URLSearchParams();
3120
3614
  form.set("grant_type", "refresh_token");
@@ -3124,19 +3618,8 @@ var OidcClient = class {
3124
3618
  if (params.scope !== void 0) {
3125
3619
  form.set("scope", params.scope);
3126
3620
  }
3127
- for (let attempt = 0; attempt < 3; attempt += 1) {
3128
- let refreshed;
3129
- await this.#session.refreshGuard(async () => {
3130
- const wire = await this.#postToken(configuration, form, params.tenantId);
3131
- refreshed = await this.#toTokenSet(wire, configuration, void 0);
3132
- });
3133
- if (refreshed) {
3134
- return refreshed;
3135
- }
3136
- }
3137
- throw new AuthError(
3138
- "oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md \xA79); another refresh kept it busy."
3139
- );
3621
+ const wire = await this.#postToken(configuration, form, params.tenantId);
3622
+ return this.#toTokenSet(wire, configuration, void 0);
3140
3623
  }
3141
3624
  // -------------------------------------------------------------------------
3142
3625
  // §33 CIBA — client-initiated backchannel authentication (contract 1.58)
@@ -3531,7 +4014,7 @@ var OidcClient = class {
3531
4014
  if (existing) {
3532
4015
  return existing;
3533
4016
  }
3534
- const verifier = createJwksVerifier(jwksUri);
4017
+ const verifier = createJwksVerifier(jwksUri, nodeTlsOptionsOf(this.#session, jwksUri));
3535
4018
  this.#verifiers.set(jwksUri, verifier);
3536
4019
  return verifier;
3537
4020
  }
@@ -3859,60 +4342,6 @@ var PROTOCOL_SAML = "Saml";
3859
4342
  var HANDOFF_QUERY_PARAM = "axiam_handoff";
3860
4343
  var HANDOFF_CODE_TTL_SECS = 60;
3861
4344
 
3862
- // src/node/oidcState.ts
3863
- var OIDC_STATE_TTL_MS = 6e5;
3864
- var MemoryOidcStateStore = class {
3865
- #entries = /* @__PURE__ */ new Map();
3866
- #ttlMs;
3867
- /**
3868
- * @param ttlMs entry lifetime in milliseconds. Defaults to
3869
- * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
3870
- * shorter TTL is honoured (useful in tests), a longer one is reduced,
3871
- * because §12.3 rule 1 fixes 10 minutes as the maximum.
3872
- */
3873
- constructor(ttlMs = OIDC_STATE_TTL_MS) {
3874
- this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
3875
- }
3876
- /** Number of unexpired entries currently held. Intended for tests and metrics. */
3877
- get size() {
3878
- this.#sweep();
3879
- return this.#entries.size;
3880
- }
3881
- /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
3882
- async save(entry) {
3883
- this.#sweep();
3884
- this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
3885
- }
3886
- /**
3887
- * Atomically return and delete the entry for `state`. Deletion happens
3888
- * before the expiry check, so even an expired hit is removed rather than
3889
- * left to accumulate — and a second call can never return the same entry
3890
- * twice regardless of timing (JavaScript's single-threaded event loop makes
3891
- * this get-then-delete pair genuinely atomic; a store backed by real
3892
- * concurrency must use an atomic primitive such as Redis `GETDEL`).
3893
- */
3894
- async consume(state) {
3895
- const held = this.#entries.get(state);
3896
- if (!held) {
3897
- return void 0;
3898
- }
3899
- this.#entries.delete(state);
3900
- if (held.expiresAt <= Date.now()) {
3901
- return void 0;
3902
- }
3903
- return held.entry;
3904
- }
3905
- /** Drop every expired entry. Lazy housekeeping — no background timer. */
3906
- #sweep() {
3907
- const now = Date.now();
3908
- for (const [state, held] of this.#entries) {
3909
- if (held.expiresAt <= now) {
3910
- this.#entries.delete(state);
3911
- }
3912
- }
3913
- }
3914
- };
3915
-
3916
4345
  exports.ACCESS_COOKIE_NAME = ACCESS_COOKIE_NAME;
3917
4346
  exports.CLOCK_SKEW_LEEWAY_SEC = CLOCK_SKEW_LEEWAY_SEC;
3918
4347
  exports.CSRF_COOKIE_NAME = CSRF_COOKIE_NAME;
@@ -3925,6 +4354,9 @@ exports.MAX_ENTRIES = MAX_ENTRIES;
3925
4354
  exports.MIN_DISCOVERY_TTL_MS = MIN_DISCOVERY_TTL_MS;
3926
4355
  exports.MIN_POLL_INTERVAL_MS = MIN_POLL_INTERVAL_MS;
3927
4356
  exports.MemoryOidcStateStore = MemoryOidcStateStore;
4357
+ exports.OIDC_BINDING_COOKIE_NAME = OIDC_BINDING_COOKIE_NAME;
4358
+ exports.OIDC_BINDING_COOKIE_NAME_LOOPBACK = OIDC_BINDING_COOKIE_NAME_LOOPBACK;
4359
+ exports.OIDC_STATE_MAX_ENTRIES = OIDC_STATE_MAX_ENTRIES;
3928
4360
  exports.OIDC_STATE_TTL_MS = OIDC_STATE_TTL_MS;
3929
4361
  exports.OidcClient = OidcClient;
3930
4362
  exports.PROTECTED_RESOURCE_METADATA_PREFIX = PROTECTED_RESOURCE_METADATA_PREFIX;
@@ -3950,10 +4382,14 @@ exports.extractCredential = extractCredential;
3950
4382
  exports.extractToken = extractToken;
3951
4383
  exports.fromParam = fromParam;
3952
4384
  exports.hasAnyRole = hasAnyRole;
4385
+ exports.hasAnyScope = hasAnyScope;
3953
4386
  exports.isAccessDenied = isAccessDenied;
3954
4387
  exports.isCsrfValid = isCsrfValid;
3955
4388
  exports.isExpiredToken = isExpiredToken;
3956
4389
  exports.isSafeMethod = isSafeMethod;
4390
+ exports.isSafeReturnTo = isSafeReturnTo;
4391
+ exports.oidcBindingClearCookie = oidcBindingClearCookie;
4392
+ exports.oidcBindingCookieName = oidcBindingCookieName;
3957
4393
  exports.oidcLoginHandlers = oidcLoginHandlers;
3958
4394
  exports.oidcLoginPlugin = oidcLoginPlugin;
3959
4395
  exports.parseCookieHeader = parseCookieHeader;
@@ -3964,6 +4400,8 @@ exports.requireAuth = requireAuth;
3964
4400
  exports.requireAuthHook = requireAuthHook;
3965
4401
  exports.requireRole = requireRole;
3966
4402
  exports.requireRoleHook = requireRoleHook;
4403
+ exports.requireScope = requireScope;
4404
+ exports.requireScopeHook = requireScopeHook;
3967
4405
  exports.resolveResourceId = resolveResourceId;
3968
4406
  exports.serveProtectedResourceMetadata = serveProtectedResourceMetadata;
3969
4407
  exports.verifyCertificateBinding = verifyCertificateBinding;