micro509 0.16.0 → 0.17.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.
@@ -0,0 +1,187 @@
1
+ import { successResult as e, throwMicro509Error as t } from "../result/result.js";
2
+ import { isJsonArray as n } from "../internal/jose/strict-json.js";
3
+ import { joseFailure as r } from "./errors.js";
4
+ import { decodeJsonObject as i, isUncheckedPolicy as a, mediaTypeKey as o, parseCompactJws as s, prepareVerify as c, resolveJoseLimits as l, signCompactJws as u, verifyPrepared as d } from "./jws.js";
5
+ // src/jose/jwt.ts
6
+ /** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */
7
+ const f = 600;
8
+ function decodeClaims(e, t, n) {
9
+ return e.cty !== void 0 && o(e.cty) === "application/jwt" ? r("unsupported_nested_jwt", "Nested JWTs (cty \"JWT\") are not supported") : i(t, n, "payload", "invalid_payload");
10
+ }
11
+ /** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */
12
+ function decodeJwtUnverified(t, n) {
13
+ let r = l(n);
14
+ if (!r.ok) return r;
15
+ let i = s(t, r.value);
16
+ if (!i.ok) return i;
17
+ let a = decodeClaims(i.value.header, i.value.payload, r.value);
18
+ return a.ok ? e({
19
+ verified: !1,
20
+ header: i.value.header,
21
+ claims: a.value
22
+ }) : a;
23
+ }
24
+ function claimFailure(e, t, n) {
25
+ return r(e, t, { claim: n });
26
+ }
27
+ function numericDate(t, n) {
28
+ if (!Object.hasOwn(t, n)) return e(void 0);
29
+ let r = t[n];
30
+ return typeof r != "number" || !Number.isFinite(r) ? claimFailure("invalid_claim", `Claim "${n}" is not a NumericDate`, n) : e(r);
31
+ }
32
+ function stringClaim(t, n) {
33
+ if (!Object.hasOwn(t, n)) return e(void 0);
34
+ let r = t[n];
35
+ return typeof r == "string" ? e(r) : claimFailure("invalid_claim", `Claim "${n}" is not a string`, n);
36
+ }
37
+ function audienceClaim(t) {
38
+ if (!Object.hasOwn(t, "aud")) return e(void 0);
39
+ let r = t.aud;
40
+ if (typeof r == "string") return e(r);
41
+ if (!n(r)) return claimFailure("invalid_claim", "Claim \"aud\" is neither a string nor an array", "aud");
42
+ let i = [];
43
+ for (let e of r) {
44
+ if (typeof e != "string") return claimFailure("invalid_claim", "Claim \"aud\" holds a non-string", "aud");
45
+ i.push(e);
46
+ }
47
+ return e(i);
48
+ }
49
+ function registeredClaims(t) {
50
+ let n = stringClaim(t, "iss");
51
+ if (!n.ok) return n;
52
+ let r = stringClaim(t, "sub");
53
+ if (!r.ok) return r;
54
+ let i = stringClaim(t, "jti");
55
+ if (!i.ok) return i;
56
+ let a = audienceClaim(t);
57
+ if (!a.ok) return a;
58
+ let o = numericDate(t, "exp");
59
+ if (!o.ok) return o;
60
+ let s = numericDate(t, "nbf");
61
+ if (!s.ok) return s;
62
+ let c = numericDate(t, "iat");
63
+ return c.ok ? e({
64
+ ...n.value === void 0 ? {} : { iss: n.value },
65
+ ...r.value === void 0 ? {} : { sub: r.value },
66
+ ...a.value === void 0 ? {} : { aud: a.value },
67
+ ...o.value === void 0 ? {} : { exp: o.value },
68
+ ...s.value === void 0 ? {} : { nbf: s.value },
69
+ ...c.value === void 0 ? {} : { iat: c.value },
70
+ ...i.value === void 0 ? {} : { jti: i.value }
71
+ }) : c;
72
+ }
73
+ function expectedValues(t) {
74
+ return typeof t == "string" ? e([t]) : a(t) ? e(void 0) : Array.isArray(t) && t.length > 0 && t.every((e) => typeof e == "string") ? e([...t]) : r("invalid_options", "issuer and audience need expected values or { unchecked: true }");
75
+ }
76
+ function prepareClaims(t) {
77
+ if (typeof t != "object" || !t) return r("invalid_options", "A claims policy is required");
78
+ let n = t.clockToleranceSeconds ?? 0;
79
+ if (typeof n != "number" || !Number.isFinite(n) || n < 0 || n > 600) return r("invalid_options", "clockToleranceSeconds must be between 0 and 600");
80
+ let i = t.maxAgeSeconds;
81
+ if (i !== void 0 && (typeof i != "number" || !Number.isFinite(i) || i < 0)) return r("invalid_options", "maxAgeSeconds must be a non-negative number");
82
+ let a = t.requiredClaims ?? ["exp"];
83
+ if (!Array.isArray(a) || !a.every((e) => typeof e == "string")) return r("invalid_options", "requiredClaims must be an array of strings");
84
+ if (t.futureIssuedAt !== void 0 && t.futureIssuedAt !== "reject" && t.futureIssuedAt !== "allow") return r("invalid_options", "futureIssuedAt must be 'reject' or 'allow'");
85
+ if (t.now !== void 0 && typeof t.now != "function") return r("invalid_options", "now must be a function");
86
+ let o = expectedValues(t.issuer);
87
+ if (!o.ok) return o;
88
+ let s = expectedValues(t.audience);
89
+ return s.ok ? e({
90
+ issuers: o.value,
91
+ audiences: s.value,
92
+ required: [...a],
93
+ now: t.now ?? (() => /* @__PURE__ */ new Date()),
94
+ toleranceSeconds: n,
95
+ maxAgeSeconds: i,
96
+ allowFutureIssuedAt: t.futureIssuedAt === "allow"
97
+ }) : s;
98
+ }
99
+ function checkIdentity(e, t) {
100
+ let { issuers: n, audiences: r } = t;
101
+ if (n !== void 0 && (e.iss === void 0 || !n.includes(e.iss))) return claimFailure("issuer_mismatch", "The token issuer is not accepted", "iss");
102
+ if (r !== void 0 && !(typeof e.aud == "string" ? [e.aud] : e.aud ?? []).some((e) => r.includes(e))) return claimFailure("audience_mismatch", "The token audience is not accepted", "aud");
103
+ }
104
+ function checkTimes(e, t, n) {
105
+ let r = t.toleranceSeconds, { exp: i, nbf: a, iat: o } = e;
106
+ if (i !== void 0 && n >= i + r) return claimFailure("expired", "The token has expired", "exp");
107
+ if (a !== void 0 && n < a - r) return claimFailure("not_yet_valid", "The token is not valid yet", "nbf");
108
+ if (o !== void 0 && !t.allowFutureIssuedAt && o - r > n) return claimFailure("issued_in_future", "The token was issued in the future", "iat");
109
+ if (t.maxAgeSeconds !== void 0) {
110
+ if (o === void 0) return claimFailure("missing_claim", "Claim \"iat\" is required by maxAgeSeconds", "iat");
111
+ if (n - o > t.maxAgeSeconds + r) return claimFailure("token_too_old", "The token is older than the maximum age", "iat");
112
+ }
113
+ }
114
+ function clockSeconds(t) {
115
+ let n;
116
+ try {
117
+ n = t.now();
118
+ } catch {
119
+ return r("invalid_options", "The claims clock threw");
120
+ }
121
+ return !(n instanceof Date) || !Number.isFinite(n.getTime()) ? r("invalid_options", "The claims clock did not return a valid Date") : e(n.getTime() / 1e3);
122
+ }
123
+ function validateClaims(e, t) {
124
+ for (let n of t.required) if (!Object.hasOwn(e, n)) return claimFailure("missing_claim", `Claim "${n}" is required`, n);
125
+ let n = registeredClaims(e);
126
+ if (!n.ok) return n;
127
+ let r = checkIdentity(n.value, t);
128
+ if (r !== void 0) return r;
129
+ let i = clockSeconds(t);
130
+ if (!i.ok) return i;
131
+ let a = checkTimes(n.value, t, i.value);
132
+ return a === void 0 ? n : a;
133
+ }
134
+ /**
135
+ * Verifies a JWT: the signature and `tokenType` policy as {@linkcode verifyCompactJws} applies
136
+ * them, then the payload as a duplicate-free JSON object, then `claims`.
137
+ *
138
+ * `iss` and `aud` must be stated explicitly. Time claims follow RFC 7519 §4.1.4 and §4.1.5: the
139
+ * token is expired when the clock is at or after `exp` and not yet valid when it is before
140
+ * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never
141
+ * coerced. `exp` is required unless `requiredClaims` says otherwise.
142
+ */
143
+ async function verifyJwt(t, n) {
144
+ if (typeof n != "object" || !n) return r("invalid_options", "Verification options are required");
145
+ let i = prepareClaims(n.claims);
146
+ if (!i.ok) return i;
147
+ let a = c(n);
148
+ if (!a.ok) return a;
149
+ let o = await d(t, a.value);
150
+ if (!o.ok) return o;
151
+ let s = decodeClaims(o.value.header, o.value.payload, a.value.limits);
152
+ if (!s.ok) return s;
153
+ let l = validateClaims(s.value, i.value);
154
+ return l.ok ? e({
155
+ verified: !0,
156
+ header: o.value.header,
157
+ claims: s.value,
158
+ registered: l.value
159
+ }) : l;
160
+ }
161
+ /**
162
+ * Signs a JWT. The header carries `typ: "JWT"` unless `header.typ` says otherwise.
163
+ *
164
+ * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and
165
+ * `invalid_claims` when `claims` cannot be serialized.
166
+ */
167
+ async function signJwt(e) {
168
+ let n;
169
+ try {
170
+ n = JSON.stringify(e.claims);
171
+ } catch {
172
+ n = void 0;
173
+ }
174
+ if (typeof n != "string") return t("invalid_claims", "JWT claims are not JSON-serializable");
175
+ let { claims: r, ...i } = e;
176
+ return await u({
177
+ ...i,
178
+ payload: new TextEncoder().encode(n),
179
+ header: {
180
+ typ: "JWT",
181
+ ...e.header
182
+ }
183
+ });
184
+ }
185
+ export { f as MAX_CLOCK_TOLERANCE_SECONDS, decodeJwtUnverified, signJwt, verifyJwt };
186
+
187
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.js","names":["MAX_CLOCK_TOLERANCE_SECONDS","header","mediaTypeKey","joseFailure","decodeJsonObject","payload","limits","bounds","resolveJoseLimits","parsed","parseCompactJws","token","claims","successResult","code","message","name","value","isJsonArray","audiences","entry","iss","sub","jti","aud","exp","nbf","iat","expectation","isUncheckedPolicy","policy","tolerance","maxAge","required","issuers","registered","nowSeconds","reading","identity","now","times","options","claimsPolicy","prepared","prepareVerify","jws","verifyPrepared","input","throwMicro509Error","_claims","rest","signCompactJws"],"sources":["../../src/jose/jwt.ts"],"sourcesContent":["/**\n * JWT (RFC 7519) validation on top of compact JWS. Signature verification and the claims policy\n * are separate steps with separate types: {@linkcode decodeJwtUnverified} yields an\n * {@linkcode UnverifiedJwt}, and only {@linkcode verifyJwt} yields a {@linkcode VerifiedJwt}.\n *\n * @module\n */\n\nimport type { JsonObject } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tVerifyJwtErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type {\n\tJoseLimits,\n\tJwsAlgorithm,\n\tJwsHeader,\n\tSignJwsInput,\n\tUnchecked,\n\tVerifyJwsOptions,\n} from '#micro509/jose/jws';\nimport {\n\tdecodeJsonObject,\n\tisUncheckedPolicy,\n\tmediaTypeKey,\n\tparseCompactJws,\n\tprepareVerify,\n\tresolveJoseLimits,\n\tsignCompactJws,\n\tverifyPrepared,\n} from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */\nexport const MAX_CLOCK_TOLERANCE_SECONDS = 600;\n\n/** The RFC 7519 §4.1 registered claims, each checked against its defined type. */\nexport interface RegisteredClaims {\n\t/** Issuer. */\n\treadonly iss?: string;\n\t/** Subject. */\n\treadonly sub?: string;\n\t/** Audience, as the token carried it: a string or an array of strings. */\n\treadonly aud?: string | readonly string[];\n\t/** Expiration time in seconds since the epoch. */\n\treadonly exp?: number;\n\t/** Not-before time in seconds since the epoch. */\n\treadonly nbf?: number;\n\t/** Issued-at time in seconds since the epoch. */\n\treadonly iat?: number;\n\t/** Token identifier. */\n\treadonly jti?: string;\n}\n\n/** A decoded JWT whose signature has not been checked. */\nexport interface UnverifiedJwt {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The claims, unauthenticated and not policy-checked. */\n\treadonly claims: JsonObject;\n}\n\n/** A JWT whose signature and claims both passed the caller's policy. */\nexport interface VerifiedJwt {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** Every authenticated claim, exactly as the token carried it. */\n\treadonly claims: JsonObject;\n\t/** The registered claims, validated against their types. */\n\treadonly registered: RegisteredClaims;\n}\n\n/** Whether an `iat` later than the clock is accepted. */\nexport type FutureIssuedAtPolicy = 'reject' | 'allow';\n\n/** Claims policy for {@linkcode verifyJwt}. Application authorization stays with the caller. */\nexport interface JwtClaimsPolicy {\n\t/** Accepted `iss` values (any one may match), or `{ unchecked: true }`. */\n\treadonly issuer: string | readonly string[] | Unchecked;\n\t/** Accepted `aud` values (any one may match), or `{ unchecked: true }`. */\n\treadonly audience: string | readonly string[] | Unchecked;\n\t/** Claims that must be present. Default `['exp']`. */\n\treadonly requiredClaims?: readonly string[];\n\t/** The clock. Default is the system time. */\n\treadonly now?: () => Date;\n\t/** Leeway in seconds for `exp`, `nbf` and `iat`, from 0 to 600. Default `0`. */\n\treadonly clockToleranceSeconds?: number;\n\t/** Oldest acceptable token age in seconds, measured from `iat`. Requires `iat`. */\n\treadonly maxAgeSeconds?: number;\n\t/** Whether `iat` after the clock is accepted. Default `'reject'`. */\n\treadonly futureIssuedAt?: FutureIssuedAtPolicy;\n}\n\n/** Options for {@linkcode verifyJwt}. */\nexport interface VerifyJwtOptions extends VerifyJwsOptions {\n\t/** Claims policy. */\n\treadonly claims: JwtClaimsPolicy;\n}\n\n/** Input for {@linkcode signJwt}. */\nexport interface SignJwtInput extends Omit<SignJwsInput, 'payload'> {\n\t/** The claims to sign. Must be JSON-serializable. */\n\treadonly claims: JsonObject;\n}\n\nfunction decodeClaims(\n\theader: JwsHeader,\n\tpayload: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JsonObject, JwsParseErrorCode> {\n\tif (header.cty !== undefined && mediaTypeKey(header.cty) === 'application/jwt') {\n\t\treturn joseFailure('unsupported_nested_jwt', 'Nested JWTs (cty \"JWT\") are not supported');\n\t}\n\treturn decodeJsonObject(payload, limits, 'payload', 'invalid_payload');\n}\n\n/** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */\nexport function decodeJwtUnverified(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJwt, JwsParseErrorCode | 'invalid_options'> {\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\tconst parsed = parseCompactJws(token, bounds.value);\n\tif (!parsed.ok) return parsed;\n\tconst claims = decodeClaims(parsed.value.header, parsed.value.payload, bounds.value);\n\tif (!claims.ok) return claims;\n\treturn successResult({ verified: false, header: parsed.value.header, claims: claims.value });\n}\n\nfunction claimFailure<TCode extends VerifyJwtErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tclaim: string,\n): JoseErrorResult<TCode> {\n\treturn joseFailure(code, message, { claim });\n}\n\nfunction numericDate(\n\tclaims: JsonObject,\n\tname: 'exp' | 'nbf' | 'iat',\n): JoseResult<number | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a NumericDate`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction stringClaim(\n\tclaims: JsonObject,\n\tname: 'iss' | 'sub' | 'jti',\n): JoseResult<string | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'string') {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a string`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction audienceClaim(\n\tclaims: JsonObject,\n): JoseResult<string | readonly string[] | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, 'aud')) return successResult(undefined);\n\tconst value = claims.aud;\n\tif (typeof value === 'string') return successResult(value);\n\tif (!isJsonArray(value)) {\n\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" is neither a string nor an array', 'aud');\n\t}\n\tconst audiences: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== 'string') {\n\t\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" holds a non-string', 'aud');\n\t\t}\n\t\taudiences.push(entry);\n\t}\n\treturn successResult(audiences);\n}\n\nfunction registeredClaims(claims: JsonObject): JoseResult<RegisteredClaims, 'invalid_claim'> {\n\tconst iss = stringClaim(claims, 'iss');\n\tif (!iss.ok) return iss;\n\tconst sub = stringClaim(claims, 'sub');\n\tif (!sub.ok) return sub;\n\tconst jti = stringClaim(claims, 'jti');\n\tif (!jti.ok) return jti;\n\tconst aud = audienceClaim(claims);\n\tif (!aud.ok) return aud;\n\tconst exp = numericDate(claims, 'exp');\n\tif (!exp.ok) return exp;\n\tconst nbf = numericDate(claims, 'nbf');\n\tif (!nbf.ok) return nbf;\n\tconst iat = numericDate(claims, 'iat');\n\tif (!iat.ok) return iat;\n\treturn successResult({\n\t\t...(iss.value === undefined ? {} : { iss: iss.value }),\n\t\t...(sub.value === undefined ? {} : { sub: sub.value }),\n\t\t...(aud.value === undefined ? {} : { aud: aud.value }),\n\t\t...(exp.value === undefined ? {} : { exp: exp.value }),\n\t\t...(nbf.value === undefined ? {} : { nbf: nbf.value }),\n\t\t...(iat.value === undefined ? {} : { iat: iat.value }),\n\t\t...(jti.value === undefined ? {} : { jti: jti.value }),\n\t});\n}\n\n/** Claims policy validated once and copied, so later changes by the caller cannot alter a run. */\ninterface PreparedClaims {\n\treadonly issuers: readonly string[] | undefined;\n\treadonly audiences: readonly string[] | undefined;\n\treadonly required: readonly string[];\n\treadonly now: () => Date;\n\treadonly toleranceSeconds: number;\n\treadonly maxAgeSeconds: number | undefined;\n\treadonly allowFutureIssuedAt: boolean;\n}\n\nfunction expectedValues(\n\texpectation: unknown,\n): JoseResult<readonly string[] | undefined, 'invalid_options'> {\n\tif (typeof expectation === 'string') return successResult([expectation]);\n\tif (isUncheckedPolicy(expectation)) return successResult(undefined);\n\tif (\n\t\tArray.isArray(expectation) &&\n\t\texpectation.length > 0 &&\n\t\texpectation.every((value) => typeof value === 'string')\n\t) {\n\t\treturn successResult([...expectation]);\n\t}\n\treturn joseFailure(\n\t\t'invalid_options',\n\t\t'issuer and audience need expected values or { unchecked: true }',\n\t);\n}\n\nfunction prepareClaims(policy: JwtClaimsPolicy): JoseResult<PreparedClaims, 'invalid_options'> {\n\tif (typeof policy !== 'object' || policy === null) {\n\t\treturn joseFailure('invalid_options', 'A claims policy is required');\n\t}\n\tconst tolerance = policy.clockToleranceSeconds ?? 0;\n\tif (\n\t\ttypeof tolerance !== 'number' ||\n\t\t!Number.isFinite(tolerance) ||\n\t\ttolerance < 0 ||\n\t\ttolerance > MAX_CLOCK_TOLERANCE_SECONDS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`clockToleranceSeconds must be between 0 and ${MAX_CLOCK_TOLERANCE_SECONDS}`,\n\t\t);\n\t}\n\tconst maxAge = policy.maxAgeSeconds;\n\tif (\n\t\tmaxAge !== undefined &&\n\t\t(typeof maxAge !== 'number' || !Number.isFinite(maxAge) || maxAge < 0)\n\t) {\n\t\treturn joseFailure('invalid_options', 'maxAgeSeconds must be a non-negative number');\n\t}\n\tconst required = policy.requiredClaims ?? ['exp'];\n\tif (!Array.isArray(required) || !required.every((name) => typeof name === 'string')) {\n\t\treturn joseFailure('invalid_options', 'requiredClaims must be an array of strings');\n\t}\n\tif (\n\t\tpolicy.futureIssuedAt !== undefined &&\n\t\tpolicy.futureIssuedAt !== 'reject' &&\n\t\tpolicy.futureIssuedAt !== 'allow'\n\t) {\n\t\treturn joseFailure('invalid_options', \"futureIssuedAt must be 'reject' or 'allow'\");\n\t}\n\tif (policy.now !== undefined && typeof policy.now !== 'function') {\n\t\treturn joseFailure('invalid_options', 'now must be a function');\n\t}\n\tconst issuers = expectedValues(policy.issuer);\n\tif (!issuers.ok) return issuers;\n\tconst audiences = expectedValues(policy.audience);\n\tif (!audiences.ok) return audiences;\n\treturn successResult({\n\t\tissuers: issuers.value,\n\t\taudiences: audiences.value,\n\t\trequired: [...required],\n\t\tnow: policy.now ?? (() => new Date()),\n\t\ttoleranceSeconds: tolerance,\n\t\tmaxAgeSeconds: maxAge,\n\t\tallowFutureIssuedAt: policy.futureIssuedAt === 'allow',\n\t});\n}\n\nfunction checkIdentity(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst { issuers, audiences } = policy;\n\tif (\n\t\tissuers !== undefined &&\n\t\t(registered.iss === undefined || !issuers.includes(registered.iss))\n\t) {\n\t\treturn claimFailure('issuer_mismatch', 'The token issuer is not accepted', 'iss');\n\t}\n\tif (audiences !== undefined) {\n\t\tconst carried = typeof registered.aud === 'string' ? [registered.aud] : (registered.aud ?? []);\n\t\tif (!carried.some((entry) => audiences.includes(entry))) {\n\t\t\treturn claimFailure('audience_mismatch', 'The token audience is not accepted', 'aud');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction checkTimes(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n\tnowSeconds: number,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst tolerance = policy.toleranceSeconds;\n\tconst { exp, nbf, iat } = registered;\n\tif (exp !== undefined && nowSeconds >= exp + tolerance) {\n\t\treturn claimFailure('expired', 'The token has expired', 'exp');\n\t}\n\tif (nbf !== undefined && nowSeconds < nbf - tolerance) {\n\t\treturn claimFailure('not_yet_valid', 'The token is not valid yet', 'nbf');\n\t}\n\tif (iat !== undefined && !policy.allowFutureIssuedAt && iat - tolerance > nowSeconds) {\n\t\treturn claimFailure('issued_in_future', 'The token was issued in the future', 'iat');\n\t}\n\tif (policy.maxAgeSeconds !== undefined) {\n\t\tif (iat === undefined) {\n\t\t\treturn claimFailure('missing_claim', 'Claim \"iat\" is required by maxAgeSeconds', 'iat');\n\t\t}\n\t\tif (nowSeconds - iat > policy.maxAgeSeconds + tolerance) {\n\t\t\treturn claimFailure('token_too_old', 'The token is older than the maximum age', 'iat');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction clockSeconds(policy: PreparedClaims): JoseResult<number, 'invalid_options'> {\n\tlet reading: unknown;\n\ttry {\n\t\treading = policy.now();\n\t} catch {\n\t\treturn joseFailure('invalid_options', 'The claims clock threw');\n\t}\n\tif (!(reading instanceof Date) || !Number.isFinite(reading.getTime())) {\n\t\treturn joseFailure('invalid_options', 'The claims clock did not return a valid Date');\n\t}\n\treturn successResult(reading.getTime() / 1000);\n}\n\nfunction validateClaims(\n\tclaims: JsonObject,\n\tpolicy: PreparedClaims,\n): JoseResult<RegisteredClaims, VerifyJwtErrorCode> {\n\tfor (const name of policy.required) {\n\t\tif (!Object.hasOwn(claims, name)) {\n\t\t\treturn claimFailure('missing_claim', `Claim \"${name}\" is required`, name);\n\t\t}\n\t}\n\tconst registered = registeredClaims(claims);\n\tif (!registered.ok) return registered;\n\tconst identity = checkIdentity(registered.value, policy);\n\tif (identity !== undefined) return identity;\n\tconst now = clockSeconds(policy);\n\tif (!now.ok) return now;\n\tconst times = checkTimes(registered.value, policy, now.value);\n\tif (times !== undefined) return times;\n\treturn registered;\n}\n\n/**\n * Verifies a JWT: the signature and `tokenType` policy as {@linkcode verifyCompactJws} applies\n * them, then the payload as a duplicate-free JSON object, then `claims`.\n *\n * `iss` and `aud` must be stated explicitly. Time claims follow RFC 7519 §4.1.4 and §4.1.5: the\n * token is expired when the clock is at or after `exp` and not yet valid when it is before\n * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never\n * coerced. `exp` is required unless `requiredClaims` says otherwise.\n */\nexport async function verifyJwt(\n\ttoken: string,\n\toptions: VerifyJwtOptions,\n): Promise<JoseResult<VerifiedJwt, VerifyJwtErrorCode>> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst claimsPolicy = prepareClaims(options.claims);\n\tif (!claimsPolicy.ok) return claimsPolicy;\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\tconst jws = await verifyPrepared(token, prepared.value);\n\tif (!jws.ok) return jws;\n\tconst claims = decodeClaims(jws.value.header, jws.value.payload, prepared.value.limits);\n\tif (!claims.ok) return claims;\n\tconst registered = validateClaims(claims.value, claimsPolicy.value);\n\tif (!registered.ok) return registered;\n\treturn successResult({\n\t\tverified: true,\n\t\theader: jws.value.header,\n\t\tclaims: claims.value,\n\t\tregistered: registered.value,\n\t});\n}\n\n/**\n * Signs a JWT. The header carries `typ: \"JWT\"` unless `header.typ` says otherwise.\n *\n * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and\n * `invalid_claims` when `claims` cannot be serialized.\n */\nexport async function signJwt(input: SignJwtInput): Promise<string> {\n\tlet payload: string | undefined;\n\ttry {\n\t\tpayload = JSON.stringify(input.claims);\n\t} catch {\n\t\tpayload = undefined;\n\t}\n\tif (typeof payload !== 'string') {\n\t\treturn throwMicro509Error('invalid_claims', 'JWT claims are not JSON-serializable');\n\t}\n\tconst { claims: _claims, ...rest } = input;\n\treturn await signCompactJws({\n\t\t...rest,\n\t\tpayload: new TextEncoder().encode(payload),\n\t\theader: { typ: 'JWT', ...input.header },\n\t});\n}\n"],"mappings":";;;;;;AAsCA,MAAaA,IAA8B;AA2E3C,SAAS,aACR,GACA,GACA,GAC4C;CAI5C,OAHIC,EAAO,QAAQ,KAAA,KAAaC,EAAaD,EAAO,GAAG,MAAM,oBACrDE,EAAY,0BAA0B,6CAA2C,IAElFC,EAAiBC,GAASC,GAAQ,WAAW,iBAAiB;AACtE;;AAGA,SAAgB,oBACf,GACA,GACmE;CACnE,IAAMC,IAASC,EAAkBF,CAAM;CACvC,IAAI,CAACC,EAAO,IAAI,OAAOA;CACvB,IAAME,IAASC,EAAgBC,GAAOJ,EAAO,KAAK;CAClD,IAAI,CAACE,EAAO,IAAI,OAAOA;CACvB,IAAMG,IAAS,aAAaH,EAAO,MAAM,QAAQA,EAAO,MAAM,SAASF,EAAO,KAAK;CAEnF,OADKK,EAAO,KACLC,EAAc;EAAE,UAAU;EAAO,QAAQJ,EAAO,MAAM;EAAQ,QAAQG,EAAO;CAAM,CAAC,IADpEA;AAExB;AAEA,SAAS,aACR,GACA,GACA,GACyB;CACzB,OAAOT,EAAYW,GAAMC,GAAS,EAAE,SAAM,CAAC;AAC5C;AAEA,SAAS,YACR,GACA,GACkD;CAClD,IAAI,CAAC,OAAO,OAAOH,GAAQI,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I,YAAY,CAAC,CAAC,OAAO7C,CAAO;EACzC,QAAQ;GAAE,KAAK;GAAO,GAAG0C,EAAM;EAAO;CACvC,CAAC;AACF"}
@@ -0,0 +1,95 @@
1
+ import { JwsKeyResolver } from "./jws.js";
2
+ /** The request {@linkcode JwksTransport} must issue. */
3
+ export interface JwksRequestInit {
4
+ /** Always `GET`. */
5
+ readonly method: "GET";
6
+ /** Always `manual`: the resolver validates every redirect destination itself. */
7
+ readonly redirect: "manual";
8
+ /** Always `omit`. */
9
+ readonly credentials: "omit";
10
+ /** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */
11
+ readonly cache: "no-store";
12
+ /** Configured request headers. Withheld from any origin other than the configured URL's. */
13
+ readonly headers: Readonly<Record<string, string>>;
14
+ /** Aborts on timeout, cancellation or when no verification still waits for the response. */
15
+ readonly signal: AbortSignal;
16
+ }
17
+ /**
18
+ * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,
19
+ * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver
20
+ * already validated.
21
+ */
22
+ export type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;
23
+ /** Redirect handling for a remote JWK Set. By default redirects are refused. */
24
+ export interface RemoteJwksRedirectPolicy {
25
+ /** Maximum redirects followed per fetch. */
26
+ readonly maxRedirects: number;
27
+ /**
28
+ * Approves a redirect destination. Default: same origin as the hop it came from. The scheme
29
+ * rule applies first: `https`, or `http` for a loopback host.
30
+ */
31
+ readonly allow?: (destination: URL, from: URL) => boolean;
32
+ }
33
+ /** Configuration of {@linkcode createRemoteJwksKeyResolver}. */
34
+ export interface RemoteJwksConfig {
35
+ /** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */
36
+ readonly url: string | URL;
37
+ /** Request transport. Default: `globalThis.fetch`. */
38
+ readonly transport?: JwksTransport;
39
+ /** Request headers, sent only to the configured URL's origin. */
40
+ readonly headers?: Readonly<Record<string, string>>;
41
+ /** Whole-request deadline in milliseconds, response body included. Default `5000`. */
42
+ readonly timeoutMs?: number;
43
+ /** Maximum response body in bytes, enforced while streaming. Default `65536`. */
44
+ readonly maxResponseBytes?: number;
45
+ /** Maximum keys in the set. Default `32`. */
46
+ readonly maxKeys?: number;
47
+ /** Redirect handling. Default: refuse every redirect. */
48
+ readonly redirects?: RemoteJwksRedirectPolicy;
49
+ /** Freshness applied when the response states none, in milliseconds. Default `600000`. */
50
+ readonly defaultTtlMs?: number;
51
+ /** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */
52
+ readonly maxTtlMs?: number;
53
+ /**
54
+ * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often
55
+ * unknown `kid` values, expired responses and failures can cause a request, and does not
56
+ * lengthen how long a response stays fresh. Default `30000`.
57
+ */
58
+ readonly cooldownMs?: number;
59
+ /** The clock in milliseconds since the epoch. Default `Date.now`. */
60
+ readonly now?: () => number;
61
+ }
62
+ /** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */
63
+ export type RemoteJwksConfigErrorCode = "invalid_remote_jwks_config";
64
+ /**
65
+ * Creates a key resolver that reads a JWK Set from one trusted URL.
66
+ *
67
+ * Behaviour, per resolver:
68
+ *
69
+ * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the
70
+ * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the
71
+ * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),
72
+ * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set
73
+ * serves the verification that fetched it and nothing after. No heuristic freshness is applied.
74
+ * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no
75
+ * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until
76
+ * it expires.
77
+ * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.
78
+ * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that
79
+ * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share
80
+ * a single request, and unknown `kid` values are never cached.
81
+ * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new
82
+ * set is read. Rotation must therefore introduce a new `kid`.
83
+ * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when
84
+ * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,
85
+ * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting
86
+ * verification aborts the request, and a response that finishes afterwards is discarded.
87
+ * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never
88
+ * used.
89
+ *
90
+ * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.
91
+ * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and
92
+ * the transport; this module cannot see DNS answers, and browsers hide redirect targets.
93
+ */
94
+ export declare function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver;
95
+ //# sourceMappingURL=remote-jwks.d.ts.map
@@ -0,0 +1,298 @@
1
+ import { successResult as e, throwMicro509Error as t } from "../result/result.js";
2
+ import { joseFailure as n } from "./errors.js";
3
+ import { importJwkEntry as r, parseJwks as i, selectJwk as a } from "./jwks.js";
4
+ // src/jose/remote-jwks.ts
5
+ const o = Symbol("micro509.jose.aborted"), s = {
6
+ timeoutMs: 5e3,
7
+ maxResponseBytes: 65536,
8
+ maxKeys: 32,
9
+ defaultTtlMs: 6e5,
10
+ maxTtlMs: 864e5,
11
+ cooldownMs: 3e4
12
+ }, c = /* @__PURE__ */ new Set([
13
+ 301,
14
+ 302,
15
+ 303,
16
+ 307,
17
+ 308
18
+ ]), l = /* @__PURE__ */ new Set([
19
+ "localhost",
20
+ "127.0.0.1",
21
+ "[::1]"
22
+ ]);
23
+ function isPermittedUrl(e) {
24
+ return e.protocol === "https:" || e.protocol === "http:" && l.has(e.hostname);
25
+ }
26
+ function positiveInteger(e, n, r) {
27
+ let i = e ?? n;
28
+ return !Number.isSafeInteger(i) || i <= 0 ? t("invalid_remote_jwks_config", `${r} must be a positive integer`) : i;
29
+ }
30
+ function resolveConfig(e) {
31
+ let n;
32
+ try {
33
+ n = new URL(e.url);
34
+ } catch {
35
+ return t("invalid_remote_jwks_config", "url is not an absolute URL");
36
+ }
37
+ if (!isPermittedUrl(n)) return t("invalid_remote_jwks_config", "url must use https, or http on a loopback host");
38
+ if (n.username !== "" || n.password !== "") return t("invalid_remote_jwks_config", "url must not embed credentials");
39
+ let r = e.redirects?.maxRedirects ?? 0;
40
+ if (!Number.isSafeInteger(r) || r < 0 || r > 10) return t("invalid_remote_jwks_config", "maxRedirects must be an integer from 0 to 10");
41
+ let i = positiveInteger(e.maxTtlMs, s.maxTtlMs, "maxTtlMs"), a = positiveInteger(e.cooldownMs, s.cooldownMs, "cooldownMs");
42
+ return {
43
+ url: n,
44
+ transport: e.transport ?? ((e, t) => globalThis.fetch(e, t)),
45
+ headers: { ...e.headers },
46
+ timeoutMs: positiveInteger(e.timeoutMs, s.timeoutMs, "timeoutMs"),
47
+ maxResponseBytes: positiveInteger(e.maxResponseBytes, s.maxResponseBytes, "maxResponseBytes"),
48
+ maxKeys: positiveInteger(e.maxKeys, s.maxKeys, "maxKeys"),
49
+ maxRedirects: r,
50
+ allowRedirect: e.redirects?.allow ?? ((e, t) => e.origin === t.origin),
51
+ defaultTtlMs: positiveInteger(e.defaultTtlMs, s.defaultTtlMs, "defaultTtlMs"),
52
+ maxTtlMs: i,
53
+ cooldownMs: a,
54
+ now: e.now ?? Date.now
55
+ };
56
+ }
57
+ function unavailable(e, t) {
58
+ return n("jwks_unavailable", e, t === void 0 ? void 0 : { status: t });
59
+ }
60
+ function secondsHeader(e, t) {
61
+ let n = e.get(t);
62
+ return n !== null && /^\d{1,10}$/.test(n) ? Number(n) * 1e3 : NaN;
63
+ }
64
+ /**
65
+ * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.
66
+ *
67
+ * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`
68
+ * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the
69
+ * larger of the apparent age from `Date` and the `Age` header plus the transit delay
70
+ * (RFC 9111 §4.2.3).
71
+ */
72
+ function freshnessMs(e, t, n, r) {
73
+ let i = (e.get("cache-control") ?? "").split(",").map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0);
74
+ if (i.includes("no-store") || i.includes("no-cache")) return 0;
75
+ let a = Date.parse(e.get("date") ?? ""), o = Number.isNaN(a) ? 0 : Math.max(0, n - a), s = secondsHeader(e, "age"), c = Math.max(0, n - t), l = Math.max(o, (Number.isNaN(s) ? 0 : s) + c), u = i.find((e) => e.startsWith("max-age")), d = r.defaultTtlMs;
76
+ if (u !== void 0) {
77
+ let e = /^max-age=("?)(\d{1,10})\1$/.exec(u);
78
+ d = e?.[2] === void 0 ? 0 : Number(e[2]) * 1e3;
79
+ } else if (e.has("expires")) {
80
+ let t = Date.parse(e.get("expires") ?? "");
81
+ d = Number.isNaN(t) ? 0 : t - (Number.isNaN(a) ? n : a);
82
+ }
83
+ return Math.min(r.maxTtlMs, Math.max(0, d - l));
84
+ }
85
+ async function readBounded(t, r, i) {
86
+ let a = n("jwks_malformed", `The JWKS response exceeds ${r} bytes`), o = t.headers.get("content-length");
87
+ if (o !== null && /^\d+$/.test(o) && Number(o) > r) return await t.body?.cancel(), a;
88
+ if (t.body === null) return e(/* @__PURE__ */ new Uint8Array());
89
+ let s = t.body.getReader(), release = () => {
90
+ s.cancel().catch(() => void 0);
91
+ };
92
+ i.addEventListener("abort", release, { once: !0 });
93
+ try {
94
+ let t = [], n = 0;
95
+ for (;;) {
96
+ let { done: e, value: o } = await s.read();
97
+ if (i.aborted) return unavailable("The JWKS request was cancelled");
98
+ if (e) break;
99
+ if (n += o.byteLength, n > r) return release(), a;
100
+ t.push(o);
101
+ }
102
+ let o = new Uint8Array(n), c = 0;
103
+ for (let e of t) o.set(e, c), c += e.byteLength;
104
+ return e(o);
105
+ } finally {
106
+ i.removeEventListener("abort", release);
107
+ }
108
+ }
109
+ function nextHop(t, n, r, i) {
110
+ let a = r.headers.get("location");
111
+ if (i >= t.maxRedirects || a === null) return unavailable("The JWKS endpoint redirected", r.status);
112
+ let o;
113
+ try {
114
+ o = new URL(a, n);
115
+ } catch {
116
+ return unavailable("The JWKS redirect target is not a URL", r.status);
117
+ }
118
+ return !isPermittedUrl(o) || o.username !== "" || o.password !== "" || !t.allowRedirect(o, n) ? unavailable("The JWKS redirect target is not permitted", r.status) : e(o);
119
+ }
120
+ async function readJwks(t, r, a, o) {
121
+ if (r.status !== 200) return await r.body?.cancel(), unavailable("The JWKS endpoint did not answer 200", r.status);
122
+ let s = t.now(), c = await readBounded(r, t.maxResponseBytes, o);
123
+ if (!c.ok) return c;
124
+ let l = i(c.value, {
125
+ maxBytes: t.maxResponseBytes,
126
+ maxKeys: t.maxKeys
127
+ });
128
+ return l.ok ? e({
129
+ jwks: l.value,
130
+ expiresAt: s + freshnessMs(r.headers, a, s, t)
131
+ }) : n("jwks_malformed", l.message);
132
+ }
133
+ async function fetchJwks(e, t, n) {
134
+ let r = e.url;
135
+ for (let i = 0;; i++) {
136
+ let a = await e.transport(r.href, {
137
+ method: "GET",
138
+ redirect: "manual",
139
+ credentials: "omit",
140
+ cache: "no-store",
141
+ headers: r.origin === e.url.origin ? e.headers : {},
142
+ signal: t
143
+ });
144
+ if (t.aborted) return await a.body?.cancel(), unavailable("The JWKS request was cancelled");
145
+ if (a.type === "opaqueredirect") return unavailable("The runtime hides redirects, so they cannot be validated");
146
+ if (!c.has(a.status)) return await readJwks(e, a, n, t);
147
+ await a.body?.cancel();
148
+ let o = nextHop(e, r, a, i);
149
+ if (!o.ok) return o;
150
+ r = o.value;
151
+ }
152
+ }
153
+ function entryKey(e) {
154
+ return `${e.n}.${e.e}`;
155
+ }
156
+ function carryOver(e, t) {
157
+ let n = /* @__PURE__ */ new Map();
158
+ for (let r of e.jwks.keys) {
159
+ let e = r.kind === "rsa" ? t?.imported.get(entryKey(r)) : void 0;
160
+ r.kind === "rsa" && e !== void 0 && n.set(entryKey(r), e);
161
+ }
162
+ return {
163
+ jwks: e.jwks,
164
+ expiresAt: e.expiresAt,
165
+ imported: n
166
+ };
167
+ }
168
+ const u = Symbol("micro509.jose.timedOut");
169
+ /**
170
+ * Creates a key resolver that reads a JWK Set from one trusted URL.
171
+ *
172
+ * Behaviour, per resolver:
173
+ *
174
+ * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the
175
+ * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the
176
+ * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),
177
+ * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set
178
+ * serves the verification that fetched it and nothing after. No heuristic freshness is applied.
179
+ * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no
180
+ * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until
181
+ * it expires.
182
+ * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.
183
+ * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that
184
+ * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share
185
+ * a single request, and unknown `kid` values are never cached.
186
+ * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new
187
+ * set is read. Rotation must therefore introduce a new `kid`.
188
+ * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when
189
+ * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,
190
+ * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting
191
+ * verification aborts the request, and a response that finishes afterwards is discarded.
192
+ * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never
193
+ * used.
194
+ *
195
+ * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.
196
+ * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and
197
+ * the transport; this module cannot see DNS answers, and browsers hide redirect targets.
198
+ */
199
+ function createRemoteJwksKeyResolver(t) {
200
+ let i = resolveConfig(t), s, c, l;
201
+ function startRefresh() {
202
+ let e = new AbortController(), t = i.now(), n = l, r = s;
203
+ l = t;
204
+ async function run() {
205
+ let n, a = new Promise((e) => {
206
+ n = setTimeout(() => e(u), i.timeoutMs);
207
+ }), o = fetchJwks(i, e.signal, t);
208
+ o.catch(() => void 0);
209
+ try {
210
+ let t = await Promise.race([o, a]);
211
+ return t === u ? (e.abort(), {
212
+ kind: "failed",
213
+ failure: unavailable("The JWKS request timed out")
214
+ }) : t.ok ? {
215
+ kind: "fresh",
216
+ snapshot: carryOver(t.value, r)
217
+ } : {
218
+ kind: "failed",
219
+ failure: t
220
+ };
221
+ } catch {
222
+ return e.signal.aborted ? { kind: "abandoned" } : {
223
+ kind: "failed",
224
+ failure: unavailable("The JWKS request failed")
225
+ };
226
+ } finally {
227
+ clearTimeout(n);
228
+ }
229
+ }
230
+ let a = run().then((e) => c?.promise === a ? (e.kind === "fresh" && (s = e.snapshot), e) : { kind: "abandoned" }).finally(() => {
231
+ c?.promise === a && (c = void 0);
232
+ });
233
+ return {
234
+ promise: a,
235
+ controller: e,
236
+ startedAt: t,
237
+ previousAttemptAt: n,
238
+ waiters: 0
239
+ };
240
+ }
241
+ async function awaitRefresh(e) {
242
+ if (e?.aborted === !0) return o;
243
+ c ??= startRefresh();
244
+ let t = c;
245
+ return t.waiters++, e === void 0 ? await t.promise : await new Promise((n) => {
246
+ let r = !1, finish = () => {
247
+ r = !0, e.removeEventListener("abort", onAbort);
248
+ }, onAbort = () => {
249
+ r || (finish(), t.waiters--, t.waiters === 0 && (c === t && (c = void 0), l === t.startedAt && (l = t.previousAttemptAt), t.controller.abort()), n(o));
250
+ };
251
+ e.addEventListener("abort", onAbort, { once: !0 }), e.aborted && onAbort(), t.promise.then((e) => {
252
+ r || (finish(), n(e));
253
+ });
254
+ });
255
+ }
256
+ function refreshAllowed() {
257
+ return c !== void 0 || l === void 0 || i.now() - l >= i.cooldownMs;
258
+ }
259
+ async function obtain(t) {
260
+ if (!refreshAllowed()) return e(void 0);
261
+ let r = await awaitRefresh(t);
262
+ return r === o || r.kind === "abandoned" ? n("aborted", "Key resolution was cancelled") : r.kind === "failed" ? r.failure : e(r.snapshot);
263
+ }
264
+ async function importFrom(e, t) {
265
+ let n = entryKey(t), i = e.imported.get(n);
266
+ if (i !== void 0) return await i;
267
+ let a = r(t);
268
+ return e.imported.set(n, a), await a;
269
+ }
270
+ async function currentSnapshot(t) {
271
+ if (s !== void 0 && i.now() < s.expiresAt) return e(s);
272
+ s = void 0;
273
+ let n = await obtain(t);
274
+ return n.ok ? n.value === void 0 ? unavailable("The JWKS endpoint is in cooldown") : e(n.value) : n;
275
+ }
276
+ async function select(e, t, r) {
277
+ let i = e, o = a(i.jwks, t);
278
+ if (!o.ok && o.code === "key_not_found") {
279
+ let e = await obtain(r);
280
+ if (!e.ok) return e;
281
+ e.value !== void 0 && (i = e.value, o = a(i.jwks, t));
282
+ }
283
+ if (!o.ok) return o;
284
+ let s = await importFrom(i, o.value);
285
+ return r?.aborted === !0 ? n("aborted", "Key resolution was cancelled") : s;
286
+ }
287
+ return async (e) => {
288
+ if (e.signal?.aborted === !0) return n("aborted", "Key resolution was cancelled");
289
+ let t = await currentSnapshot(e.signal);
290
+ return t.ok ? await select(t.value, {
291
+ algorithm: e.algorithm,
292
+ ...e.kid === void 0 ? {} : { kid: e.kid }
293
+ }, e.signal) : t;
294
+ };
295
+ }
296
+ export { createRemoteJwksKeyResolver };
297
+
298
+ //# sourceMappingURL=remote-jwks.js.map