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