aws-cognito-jwt-verifier 2.0.2 → 2.1.1
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 +2 -0
- package/dist/claims.d.ts +2 -1
- package/dist/claims.js +8 -2
- package/dist/claims.js.map +1 -1
- package/dist/jwks.js +3 -0
- package/dist/jwks.js.map +1 -1
- package/dist/options.d.ts +15 -1
- package/dist/options.js +23 -0
- package/dist/options.js.map +1 -1
- package/dist/token.js +5 -0
- package/dist/token.js.map +1 -1
- package/dist/verifier.js +3 -2
- package/dist/verifier.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -86,6 +86,8 @@ In every example, create **one** verifier and reuse it, so the user pool's publi
|
|
|
86
86
|
| `tokenUse` | `"access"`, `"id"`, or `null` to accept both |
|
|
87
87
|
| `clientId` | Your app client ID: a string, an array of strings, or `null` to skip the check |
|
|
88
88
|
|
|
89
|
+
`tokenUse` and `clientId` are required. A missing or invalid value, such as `tokenUse: "Access"` or `clientId: []`, makes `verify()` reject with reason `InvalidConfiguration` instead of rejecting every token with a misleading reason.
|
|
90
|
+
|
|
89
91
|
### TypeScript
|
|
90
92
|
|
|
91
93
|
```typescript
|
package/dist/claims.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export declare function assertIssuer(payload: JsonObject, issuer: string): void;
|
|
|
5
5
|
export interface ClaimRules {
|
|
6
6
|
clockToleranceSec: number;
|
|
7
7
|
tokenUse: VerifyOptions["tokenUse"];
|
|
8
|
-
|
|
8
|
+
/** Allowed app client IDs, already validated; `null` skips the check. */
|
|
9
|
+
clientId: readonly string[] | null;
|
|
9
10
|
}
|
|
10
11
|
export declare function assertClaims(payload: JsonObject, rules: ClaimRules, nowSec?: number): CognitoJwtPayload;
|
package/dist/claims.js
CHANGED
|
@@ -20,14 +20,20 @@ function assertClaims(payload, rules, nowSec = Math.floor(Date.now() / 1000)) {
|
|
|
20
20
|
if (typeof payload.nbf === "number" && nowSec + clockToleranceSec < payload.nbf) {
|
|
21
21
|
throw new errors_1.JwtVerificationError("TokenNotYetValid", "Token not active yet");
|
|
22
22
|
}
|
|
23
|
+
// Every Cognito token has these; checking them makes the returned CognitoJwtPayload type true.
|
|
24
|
+
if (payload.token_use !== "access" && payload.token_use !== "id") {
|
|
25
|
+
throw new errors_1.JwtVerificationError("MalformedToken", "Token has no valid token_use claim");
|
|
26
|
+
}
|
|
27
|
+
if (typeof payload.sub !== "string" || typeof payload.iat !== "number") {
|
|
28
|
+
throw new errors_1.JwtVerificationError("MalformedToken", "Token is missing the sub or iat claim");
|
|
29
|
+
}
|
|
23
30
|
if (tokenUse !== null && payload.token_use !== tokenUse) {
|
|
24
31
|
throw new errors_1.JwtVerificationError("InvalidTokenUse", `Expected an ${tokenUse} token`);
|
|
25
32
|
}
|
|
26
33
|
if (clientId !== null) {
|
|
27
|
-
const allowed = Array.isArray(clientId) ? clientId : [clientId];
|
|
28
34
|
// Cognito puts the app client in `client_id` for access tokens and in `aud` for ID tokens.
|
|
29
35
|
const actual = payload.token_use === "id" ? payload.aud : payload.client_id;
|
|
30
|
-
if (typeof actual !== "string" || !
|
|
36
|
+
if (typeof actual !== "string" || !clientId.includes(actual)) {
|
|
31
37
|
throw new errors_1.JwtVerificationError("InvalidClientId", "Client ID not allowed");
|
|
32
38
|
}
|
|
33
39
|
}
|
package/dist/claims.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claims.js","sourceRoot":"","sources":["../src/claims.ts"],"names":[],"mappings":";;AAKA,oCAIC;
|
|
1
|
+
{"version":3,"file":"claims.js","sourceRoot":"","sources":["../src/claims.ts"],"names":[],"mappings":";;AAKA,oCAIC;AASD,oCAsCC;AAxDD,qCAAgD;AAIhD,gEAAgE;AAChE,SAAgB,YAAY,CAAC,OAAmB,EAAE,MAAc;IAC9D,IAAI,OAAO,CAAC,GAAG,KAAK,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,6BAAoB,CAA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,eAAe,QAAQ,QAAQ,CAAC,CAAC;IACrF,CAAC;IAED,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,2FAA2F;QAC3F,MAAM,MAAM,GAAG,OAAO,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC;QAC5E,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7D,MAAM,IAAI,6BAAoB,CAAC,iBAAiB,EAAE,uBAAuB,CAAC,CAAC;QAC7E,CAAC;IACH,CAAC;IAED,OAAO,OAA4B,CAAC;AACtC,CAAC","sourcesContent":["import { JwtVerificationError } from \"./errors\";\nimport type { JsonObject } from \"./token\";\nimport type { CognitoJwtPayload, VerifyOptions } from \"./types\";\n\n/** @throws JwtVerificationError with reason `InvalidIssuer`. */\nexport function assertIssuer(payload: JsonObject, issuer: string): void {\n if (payload.iss !== issuer) {\n throw new JwtVerificationError(\"InvalidIssuer\", \"Invalid issuer\");\n }\n}\n\nexport interface ClaimRules {\n clockToleranceSec: number;\n tokenUse: VerifyOptions[\"tokenUse\"];\n /** Allowed app client IDs, already validated; `null` skips the check. */\n clientId: readonly string[] | null;\n}\n\nexport function assertClaims(\n payload: JsonObject,\n rules: ClaimRules,\n nowSec: number = Math.floor(Date.now() / 1000),\n): CognitoJwtPayload {\n const { clockToleranceSec, tokenUse, clientId } = rules;\n\n if (typeof payload.exp !== \"number\") {\n throw new JwtVerificationError(\"MalformedToken\", \"Token has no exp claim\");\n }\n if (nowSec >= payload.exp + clockToleranceSec) {\n throw new JwtVerificationError(\"TokenExpired\", \"Token expired\");\n }\n if (typeof payload.nbf === \"number\" && nowSec + clockToleranceSec < payload.nbf) {\n throw new JwtVerificationError(\"TokenNotYetValid\", \"Token not active yet\");\n }\n\n // Every Cognito token has these; checking them makes the returned CognitoJwtPayload type true.\n if (payload.token_use !== \"access\" && payload.token_use !== \"id\") {\n throw new JwtVerificationError(\"MalformedToken\", \"Token has no valid token_use claim\");\n }\n if (typeof payload.sub !== \"string\" || typeof payload.iat !== \"number\") {\n throw new JwtVerificationError(\"MalformedToken\", \"Token is missing the sub or iat claim\");\n }\n\n if (tokenUse !== null && payload.token_use !== tokenUse) {\n throw new JwtVerificationError(\"InvalidTokenUse\", `Expected an ${tokenUse} token`);\n }\n\n if (clientId !== null) {\n // Cognito puts the app client in `client_id` for access tokens and in `aud` for ID tokens.\n const actual = payload.token_use === \"id\" ? payload.aud : payload.client_id;\n if (typeof actual !== \"string\" || !clientId.includes(actual)) {\n throw new JwtVerificationError(\"InvalidClientId\", \"Client ID not allowed\");\n }\n }\n\n return payload as CognitoJwtPayload;\n}\n"]}
|
package/dist/jwks.js
CHANGED
|
@@ -109,6 +109,9 @@ function parseKeys(body, url) {
|
|
|
109
109
|
for (const jwk of list) {
|
|
110
110
|
if (jwk?.kty !== "RSA" || typeof jwk.kid !== "string")
|
|
111
111
|
continue;
|
|
112
|
+
// Only keys meant for RS256 signatures (a key without `use` or `alg` is accepted, as the spec allows).
|
|
113
|
+
if ((jwk.use !== undefined && jwk.use !== "sig") || (jwk.alg !== undefined && jwk.alg !== "RS256"))
|
|
114
|
+
continue;
|
|
112
115
|
try {
|
|
113
116
|
keys.set(jwk.kid, { jwk, key: (0, node_crypto_1.createPublicKey)({ key: jwk, format: "jwk" }) });
|
|
114
117
|
}
|
package/dist/jwks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwks.js","sourceRoot":"","sources":["../src/jwks.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAE9C,qCAAgD;AAChD,qCAAmC;AAGnC,6EAA6E;AAC7E,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,mEAAmE;AACnE,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,kGAAkG;AAClG,MAAM,YAAY,GAAG,E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ACnD,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,6BAAoB,CAAC,iBAAiB,EAAE,6BAA6B,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;IAC/D,CAAC;CACF;AA/FD,8BA+FC;AAED,0FAA0F;AAC1F,SAAS,SAAS,CAAC,IAAa,EAAE,GAAW;IAC3C,MAAM,IAAI,GAAI,IAAkC,EAAE,IAAI,CAAC;IACvD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,6BAAoB,CAAC,iBAAiB,EAAE,aAAa,GAAG,cAAc,CAAC,CAAC;IACpF,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAqB,CAAC;IAC1C,KAAK,MAAM,GAAG,IAAI,IAAsB,EAAE,CAAC;QACzC,IAAI,GAAG,EAAE,GAAG,KAAK,KAAK,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ;YAAE,SAAS;QAChE,IAAI,CAAC;YACH,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAA,6BAAe,EAAC,EAAE,GAAG,EAAE,GAAiB,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QAC9F,CAAC;QAAC,MAAM,CAAC;YACP,yEAAyE;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { createPublicKey } from \"node:crypto\";\nimport type { JsonWebKey, KeyObject } from \"node:crypto\";\nimport { JwtVerificationError } from \"./errors\";\nimport { jwksUrl } from \"./issuer\";\nimport type { FetchLike, Jwk } from \"./types\";\n\n/** Don't download the keys again for an unknown kid more often than this. */\nconst MIN_REFETCH_INTERVAL_MS = 60_000;\n/** After a failed download, wait this long before trying again. */\nconst RETRY_AFTER_FAILURE_MS = 5_000;\n/** While refreshes keep failing, keep using expired keys for at most this long past their TTL. */\nconst MAX_STALE_MS = 24 * 60 * 60 * 1000;\n\nexport interface PublicKey {\n jwk: Jwk;\n key: KeyObject;\n}\n\ninterface KeySet {\n keys: ReadonlyMap<string, PublicKey>;\n fetchedAt: number;\n}\n\ninterface FetchFailure {\n at: number;\n error: JwtVerificationError;\n}\n\nexport interface JwksCacheOptions {\n ttlMs: number;\n fetchTimeoutMs: number;\n fetch: FetchLike;\n}\n\nexport class JwksCache {\n readonly #options: JwksCacheOptions;\n readonly #sets = new Map<string, KeySet>();\n readonly #inflight = new Map<string, Promise<KeySet>>();\n readonly #failures = new Map<string, FetchFailure>();\n\n constructor(options: JwksCacheOptions) {\n this.#options = options;\n }\n\n /** @throws JwtVerificationError with reason `InvalidKid` or `JwksFetchFailed`. */\n async getKey(issuer: string, kid: string): Promise<KeyObject> {\n let set = await this.#load(issuer, false);\n let entry = set.keys.get(kid);\n // Unknown kid: Cognito may have rotated its keys, so refresh (rate-limited).\n if (!entry && Date.now() - set.fetchedAt >= MIN_REFETCH_INTERVAL_MS) {\n set = await this.#load(issuer, true);\n entry = set.keys.get(kid);\n }\n if (!entry) {\n throw new JwtVerificationError(\"InvalidKid\", \"Invalid kid\");\n }\n return entry.key;\n }\n\n /** @throws JwtVerificationError with reason `JwksFetchFailed`. */\n async getKeys(issuer: string): Promise<ReadonlyMap<string, PublicKey>> {\n return (await this.#load(issuer, false)).keys;\n }\n\n async #load(issuer: string, forceRefresh: boolean): Promise<KeySet> {\n const cached = this.#sets.get(issuer);\n if (!forceRefresh && cached && Date.now() - cached.fetchedAt < this.#options.ttlMs) {\n return cached;\n }\n\n // A download failed recently: don't hit the endpoint again yet (stops request floods\n // during an outage). Use the expired keys meanwhile if we still may.\n const failure = this.#failures.get(issuer);\n if (failure && Date.now() - failure.at < RETRY_AFTER_FAILURE_MS) {\n const stale = this.#usableStale(cached);\n if (stale) return stale;\n throw new JwtVerificationError(\"JwksFetchFailed\", failure.error.message, { cause: failure.error });\n }\n\n const pending = this.#inflight.get(issuer);\n if (pending) return pending;\n\n const download = this.#download(issuer)\n .then(\n (set) => {\n this.#sets.set(issuer, set);\n this.#failures.delete(issuer);\n return set;\n },\n (cause: unknown) => {\n const error =\n cause instanceof JwtVerificationError\n ? cause\n : new JwtVerificationError(\"JwksFetchFailed\", `Could not fetch JWKS for ${issuer}`, { cause });\n this.#failures.set(issuer, { at: Date.now(), error });\n // Refresh failed: keep the keys we already have rather than rejecting every token.\n const stale = this.#usableStale(cached);\n if (stale) return stale;\n throw error;\n },\n )\n .finally(() => this.#inflight.delete(issuer));\n this.#inflight.set(issuer, download);\n return download;\n }\n\n /** Expired cached keys, if they are not too old to keep trusting while refreshes fail. */\n #usableStale(cached: KeySet | undefined): KeySet | undefined {\n if (cached && Date.now() - cached.fetchedAt < this.#options.ttlMs + MAX_STALE_MS) {\n return cached;\n }\n return undefined;\n }\n\n async #download(issuer: string): Promise<KeySet> {\n const url = jwksUrl(issuer);\n let body: unknown;\n try {\n const res = await this.#options.fetch(url, {\n signal: AbortSignal.timeout(this.#options.fetchTimeoutMs),\n redirect: \"error\", // the real Cognito endpoint never redirects\n });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n body = await res.json();\n } catch (cause) {\n throw new JwtVerificationError(\"JwksFetchFailed\", `Could not fetch JWKS from ${url}`, { cause });\n }\n return { keys: parseKeys(body, url), fetchedAt: Date.now() };\n }\n}\n\n/** Turns a JWKS document into usable RSA public keys, skipping any key that isn't one. */\nfunction parseKeys(body: unknown, url: string): Map<string, PublicKey> {\n const list = (body as { keys?: unknown } | null)?.keys;\n if (!Array.isArray(list)) {\n throw new JwtVerificationError(\"JwksFetchFailed\", `JWKS from ${url} has no keys`);\n }\n const keys = new Map<string, PublicKey>();\n for (const jwk of list as (Jwk | null)[]) {\n if (jwk?.kty !== \"RSA\" || typeof jwk.kid !== \"string\") continue;\n try {\n keys.set(jwk.kid, { jwk, key: createPublicKey({ key: jwk as JsonWebKey, format: \"jwk\" }) });\n } catch {\n // Not a valid RSA public key: skip it rather than failing the whole set.\n }\n }\n return keys;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"jwks.js","sourceRoot":"","sources":["../src/jwks.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAE9C,qCAAgD;AAChD,qCAAmC;AAGnC,6EAA6E;AAC7E,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,mEAAmE;AACnE,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,kGAAkG;AAClG,MAAM,YAAY,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAuBzC,MAAa,SAAS;IACX,QAAQ,CAAmB;IAC3B,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IAClC,SAAS,GAAG,IAAI,GAAG,EAA2B,CAAC;IAC/C,SAAS,GAAG,IAAI,GAAG,EAAwB,CAAC;IAErD,YAAY,OAAyB;QACnC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED,kFAAkF;IAClF,KAAK,CAAC,MAAM,CAAC,MAAc,EAAE,GAAW;QACtC,IAAI,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC1C,IAAI,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC9B,6EAA6E;QAC7E,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,SAAS,IAAI,uBAAuB,EAAE,CAAC;YACpE,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC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CAAC;QACzC,IAAI,GAAG,EAAE,GAAG,KAAK,KAAK,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ;YAAE,SAAS;QAChE,uGAAuG;QACvG,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,GAAG,KAAK,OAAO,CAAC;YAAE,SAAS;QAC7G,IAAI,CAAC;YACH,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAA,6BAAe,EAAC,EAAE,GAAG,EAAE,GAAiB,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QAC9F,CAAC;QAAC,MAAM,CAAC;YACP,yEAAyE;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { createPublicKey } from \"node:crypto\";\nimport type { JsonWebKey, KeyObject } from \"node:crypto\";\nimport { JwtVerificationError } from \"./errors\";\nimport { jwksUrl } from \"./issuer\";\nimport type { FetchLike, Jwk } from \"./types\";\n\n/** Don't download the keys again for an unknown kid more often than this. */\nconst MIN_REFETCH_INTERVAL_MS = 60_000;\n/** After a failed download, wait this long before trying again. */\nconst RETRY_AFTER_FAILURE_MS = 5_000;\n/** While refreshes keep failing, keep using expired keys for at most this long past their TTL. */\nconst MAX_STALE_MS = 24 * 60 * 60 * 1000;\n\nexport interface PublicKey {\n jwk: Jwk;\n key: KeyObject;\n}\n\ninterface KeySet {\n keys: ReadonlyMap<string, PublicKey>;\n fetchedAt: number;\n}\n\ninterface FetchFailure {\n at: number;\n error: JwtVerificationError;\n}\n\nexport interface JwksCacheOptions {\n ttlMs: number;\n fetchTimeoutMs: number;\n fetch: FetchLike;\n}\n\nexport class JwksCache {\n readonly #options: JwksCacheOptions;\n readonly #sets = new Map<string, KeySet>();\n readonly #inflight = new Map<string, Promise<KeySet>>();\n readonly #failures = new Map<string, FetchFailure>();\n\n constructor(options: JwksCacheOptions) {\n this.#options = options;\n }\n\n /** @throws JwtVerificationError with reason `InvalidKid` or `JwksFetchFailed`. */\n async getKey(issuer: string, kid: string): Promise<KeyObject> {\n let set = await this.#load(issuer, false);\n let entry = set.keys.get(kid);\n // Unknown kid: Cognito may have rotated its keys, so refresh (rate-limited).\n if (!entry && Date.now() - set.fetchedAt >= MIN_REFETCH_INTERVAL_MS) {\n set = await this.#load(issuer, true);\n entry = set.keys.get(kid);\n }\n if (!entry) {\n throw new JwtVerificationError(\"InvalidKid\", \"Invalid kid\");\n }\n return entry.key;\n }\n\n /** @throws JwtVerificationError with reason `JwksFetchFailed`. */\n async getKeys(issuer: string): Promise<ReadonlyMap<string, PublicKey>> {\n return (await this.#load(issuer, false)).keys;\n }\n\n async #load(issuer: string, forceRefresh: boolean): Promise<KeySet> {\n const cached = this.#sets.get(issuer);\n if (!forceRefresh && cached && Date.now() - cached.fetchedAt < this.#options.ttlMs) {\n return cached;\n }\n\n // A download failed recently: don't hit the endpoint again yet (stops request floods\n // during an outage). Use the expired keys meanwhile if we still may.\n const failure = this.#failures.get(issuer);\n if (failure && Date.now() - failure.at < RETRY_AFTER_FAILURE_MS) {\n const stale = this.#usableStale(cached);\n if (stale) return stale;\n throw new JwtVerificationError(\"JwksFetchFailed\", failure.error.message, { cause: failure.error });\n }\n\n const pending = this.#inflight.get(issuer);\n if (pending) return pending;\n\n const download = this.#download(issuer)\n .then(\n (set) => {\n this.#sets.set(issuer, set);\n this.#failures.delete(issuer);\n return set;\n },\n (cause: unknown) => {\n const error =\n cause instanceof JwtVerificationError\n ? cause\n : new JwtVerificationError(\"JwksFetchFailed\", `Could not fetch JWKS for ${issuer}`, { cause });\n this.#failures.set(issuer, { at: Date.now(), error });\n // Refresh failed: keep the keys we already have rather than rejecting every token.\n const stale = this.#usableStale(cached);\n if (stale) return stale;\n throw error;\n },\n )\n .finally(() => this.#inflight.delete(issuer));\n this.#inflight.set(issuer, download);\n return download;\n }\n\n /** Expired cached keys, if they are not too old to keep trusting while refreshes fail. */\n #usableStale(cached: KeySet | undefined): KeySet | undefined {\n if (cached && Date.now() - cached.fetchedAt < this.#options.ttlMs + MAX_STALE_MS) {\n return cached;\n }\n return undefined;\n }\n\n async #download(issuer: string): Promise<KeySet> {\n const url = jwksUrl(issuer);\n let body: unknown;\n try {\n const res = await this.#options.fetch(url, {\n signal: AbortSignal.timeout(this.#options.fetchTimeoutMs),\n redirect: \"error\", // the real Cognito endpoint never redirects\n });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n body = await res.json();\n } catch (cause) {\n throw new JwtVerificationError(\"JwksFetchFailed\", `Could not fetch JWKS from ${url}`, { cause });\n }\n return { keys: parseKeys(body, url), fetchedAt: Date.now() };\n }\n}\n\n/** Turns a JWKS document into usable RSA public keys, skipping any key that isn't one. */\nfunction parseKeys(body: unknown, url: string): Map<string, PublicKey> {\n const list = (body as { keys?: unknown } | null)?.keys;\n if (!Array.isArray(list)) {\n throw new JwtVerificationError(\"JwksFetchFailed\", `JWKS from ${url} has no keys`);\n }\n const keys = new Map<string, PublicKey>();\n for (const jwk of list as (Jwk | null)[]) {\n if (jwk?.kty !== \"RSA\" || typeof jwk.kid !== \"string\") continue;\n // Only keys meant for RS256 signatures (a key without `use` or `alg` is accepted, as the spec allows).\n if ((jwk.use !== undefined && jwk.use !== \"sig\") || (jwk.alg !== undefined && jwk.alg !== \"RS256\")) continue;\n try {\n keys.set(jwk.kid, { jwk, key: createPublicKey({ key: jwk as JsonWebKey, format: \"jwk\" }) });\n } catch {\n // Not a valid RSA public key: skip it rather than failing the whole set.\n }\n }\n return keys;\n}\n"]}
|
package/dist/options.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CognitoJwtVerifierOptions, FetchLike } from "./types";
|
|
1
|
+
import type { CognitoJwtVerifierOptions, FetchLike, VerifyOptions } from "./types";
|
|
2
2
|
export declare const DEFAULT_OPTIONS: {
|
|
3
3
|
readonly jwksCacheTtlMs: number;
|
|
4
4
|
readonly fetchTimeoutMs: 5000;
|
|
@@ -14,3 +14,17 @@ export interface ResolvedOptions {
|
|
|
14
14
|
fetch: FetchLike;
|
|
15
15
|
}
|
|
16
16
|
export declare function resolveOptions(options: CognitoJwtVerifierOptions): ResolvedOptions;
|
|
17
|
+
/** The token rules from `verify()` options, validated. */
|
|
18
|
+
export interface TokenRules {
|
|
19
|
+
tokenUse: VerifyOptions["tokenUse"];
|
|
20
|
+
clientId: readonly string[] | null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Validates the `tokenUse` and `clientId` options of `verify()`.
|
|
24
|
+
*
|
|
25
|
+
* A missing or misspelled value would otherwise reject every token with a confusing reason
|
|
26
|
+
* (e.g. "Expected an undefined token"), so it is reported as a configuration error instead.
|
|
27
|
+
*
|
|
28
|
+
* @throws JwtVerificationError with reason `InvalidConfiguration`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function resolveTokenRules(options: VerifyOptions): TokenRules;
|
package/dist/options.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.DEFAULT_OPTIONS = void 0;
|
|
4
4
|
exports.resolveOptions = resolveOptions;
|
|
5
|
+
exports.resolveTokenRules = resolveTokenRules;
|
|
5
6
|
const errors_1 = require("./errors");
|
|
6
7
|
/** Largest delay Node timers accept; bigger values would fire immediately. */
|
|
7
8
|
const MAX_TIMER_MS = 2_147_483_647;
|
|
@@ -36,4 +37,26 @@ function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER)
|
|
|
36
37
|
const hint = typeof value === "string" ? " (got a string: convert it with Number())" : "";
|
|
37
38
|
throw new errors_1.JwtVerificationError("InvalidConfiguration", range + hint);
|
|
38
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Validates the `tokenUse` and `clientId` options of `verify()`.
|
|
42
|
+
*
|
|
43
|
+
* A missing or misspelled value would otherwise reject every token with a confusing reason
|
|
44
|
+
* (e.g. "Expected an undefined token"), so it is reported as a configuration error instead.
|
|
45
|
+
*
|
|
46
|
+
* @throws JwtVerificationError with reason `InvalidConfiguration`.
|
|
47
|
+
*/
|
|
48
|
+
function resolveTokenRules(options) {
|
|
49
|
+
// Read as unknown: JavaScript callers can pass anything, whatever the TypeScript types say.
|
|
50
|
+
const { tokenUse, clientId } = options;
|
|
51
|
+
if (tokenUse !== "access" && tokenUse !== "id" && tokenUse !== null) {
|
|
52
|
+
throw new errors_1.JwtVerificationError("InvalidConfiguration", 'tokenUse must be "access", "id" or null');
|
|
53
|
+
}
|
|
54
|
+
if (clientId === null)
|
|
55
|
+
return { tokenUse, clientId: null };
|
|
56
|
+
const list = Array.isArray(clientId) ? clientId : [clientId];
|
|
57
|
+
if (list.length === 0 || !list.every((id) => typeof id === "string" && id.length > 0)) {
|
|
58
|
+
throw new errors_1.JwtVerificationError("InvalidConfiguration", "clientId must be a non-empty string, a non-empty array of non-empty strings, or null");
|
|
59
|
+
}
|
|
60
|
+
return { tokenUse, clientId: list };
|
|
61
|
+
}
|
|
39
62
|
//# sourceMappingURL=options.js.map
|
package/dist/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":";;;AAsBA,wCAuBC;
|
|
1
|
+
{"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":";;;AAsBA,wCAuBC;AAmCD,8CAeC;AA/FD,qCAAgD;AAGhD,8EAA8E;AAC9E,MAAM,YAAY,GAAG,aAAa,CAAC;AAEtB,QAAA,eAAe,GAAG;IAC7B,cAAc,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;IAC9B,cAAc,EAAE,IAAI;IACpB,iBAAiB,EAAE,CAAC;IACpB,cAAc,EAAE,KAAK;CACb,CAAC;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;IACvD,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,2CAA2C,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1F,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC;AACvE,CAAC;AAQD;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,OAAsB;IACtD,4FAA4F;IAC5F,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,OAAmD,CAAC;IACnF,IAAI,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACpE,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,yCAAyC,CAAC,CAAC;IACpG,CAAC;IACD,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC3D,MAAM,IAAI,GAAc,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACxE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC;QACtF,MAAM,IAAI,6BAAoB,CAC5B,sBAAsB,EACtB,sFAAsF,CACvF,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAgB,EAAE,CAAC;AAClD,CAAC","sourcesContent":["import { JwtVerificationError } from \"./errors\";\nimport type { CognitoJwtVerifierOptions, FetchLike, VerifyOptions } from \"./types\";\n\n/** Largest delay Node timers accept; bigger values would fire immediately. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\nexport const DEFAULT_OPTIONS = {\n jwksCacheTtlMs: 60 * 60 * 1000,\n fetchTimeoutMs: 5000,\n clockToleranceSec: 0,\n maxTokenLength: 16384,\n} as const;\n\n/** Constructor options with defaults applied and every value validated. */\nexport interface ResolvedOptions {\n jwksCacheTtlMs: number;\n fetchTimeoutMs: number;\n clockToleranceSec: number;\n maxTokenLength: number;\n fetch: FetchLike;\n}\n\nexport function resolveOptions(options: CognitoJwtVerifierOptions): ResolvedOptions {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new JwtVerificationError(\"InvalidConfiguration\", \"fetch must be a function\");\n }\n return {\n jwksCacheTtlMs: numberOption(\"jwksCacheTtlMs\", options.jwksCacheTtlMs, DEFAULT_OPTIONS.jwksCacheTtlMs, 0),\n fetchTimeoutMs: numberOption(\n \"fetchTimeoutMs\",\n options.fetchTimeoutMs,\n DEFAULT_OPTIONS.fetchTimeoutMs,\n 1,\n MAX_TIMER_MS,\n ),\n clockToleranceSec: numberOption(\n \"clockToleranceSec\",\n options.clockToleranceSec,\n DEFAULT_OPTIONS.clockToleranceSec,\n 0,\n ),\n maxTokenLength: numberOption(\"maxTokenLength\", options.maxTokenLength, DEFAULT_OPTIONS.maxTokenLength, 1),\n fetch: fetchImpl,\n };\n}\n\nfunction numberOption(\n name: string,\n value: unknown,\n fallback: number,\n min: number,\n max: number = Number.MAX_SAFE_INTEGER,\n): number {\n if (value === undefined) return fallback;\n if (typeof value === \"number\" && Number.isFinite(value) && value >= min && value <= max) {\n return value;\n }\n const range =\n max === Number.MAX_SAFE_INTEGER\n ? `${name} must be a finite number of at least ${min}`\n : `${name} must be a number from ${min} to ${max}`;\n const hint = typeof value === \"string\" ? \" (got a string: convert it with Number())\" : \"\";\n throw new JwtVerificationError(\"InvalidConfiguration\", range + hint);\n}\n\n/** The token rules from `verify()` options, validated. */\nexport interface TokenRules {\n tokenUse: VerifyOptions[\"tokenUse\"];\n clientId: readonly string[] | null;\n}\n\n/**\n * Validates the `tokenUse` and `clientId` options of `verify()`.\n *\n * A missing or misspelled value would otherwise reject every token with a confusing reason\n * (e.g. \"Expected an undefined token\"), so it is reported as a configuration error instead.\n *\n * @throws JwtVerificationError with reason `InvalidConfiguration`.\n */\nexport function resolveTokenRules(options: VerifyOptions): TokenRules {\n // Read as unknown: JavaScript callers can pass anything, whatever the TypeScript types say.\n const { tokenUse, clientId } = options as { tokenUse: unknown; clientId: unknown };\n if (tokenUse !== \"access\" && tokenUse !== \"id\" && tokenUse !== null) {\n throw new JwtVerificationError(\"InvalidConfiguration\", 'tokenUse must be \"access\", \"id\" or null');\n }\n if (clientId === null) return { tokenUse, clientId: null };\n const list: unknown[] = Array.isArray(clientId) ? clientId : [clientId];\n if (list.length === 0 || !list.every((id) => typeof id === \"string\" && id.length > 0)) {\n throw new JwtVerificationError(\n \"InvalidConfiguration\",\n \"clientId must be a non-empty string, a non-empty array of non-empty strings, or null\",\n );\n }\n return { tokenUse, clientId: list as string[] };\n}\n"]}
|
package/dist/token.js
CHANGED
|
@@ -34,6 +34,11 @@ function readKeyId(header) {
|
|
|
34
34
|
if (header.alg !== "RS256") {
|
|
35
35
|
throw new errors_1.JwtVerificationError("UnsupportedAlgorithm", "Unsupported algorithm");
|
|
36
36
|
}
|
|
37
|
+
// RFC 7515: a `crit` header lists extensions the receiver must understand. We support none,
|
|
38
|
+
// and Cognito never sets it, so any token carrying it is rejected.
|
|
39
|
+
if (header.crit !== undefined) {
|
|
40
|
+
throw new errors_1.JwtVerificationError("MalformedToken", "Unsupported crit header");
|
|
41
|
+
}
|
|
37
42
|
if (typeof header.kid !== "string") {
|
|
38
43
|
throw new errors_1.JwtVerificationError("InvalidKid", "Token header has no kid");
|
|
39
44
|
}
|
package/dist/token.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.js","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":";;AAkBA,kCAoBC;AAED,
|
|
1
|
+
{"version":3,"file":"token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Y,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,KAAK,IAAI,CAAC;AAClG,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { verify as cryptoVerify } from \"node:crypto\";\nimport type { KeyObject } from \"node:crypto\";\nimport { JwtVerificationError } from \"./errors\";\n\n/** Characters allowed in one JWT segment (unpadded base64url). */\nconst BASE64URL_RE = /^[A-Za-z0-9_-]+$/;\n\nexport type JsonObject = Record<string, unknown>;\n\n/** A JWT split into its parts. Nothing in it is trusted until the signature is verified. */\nexport interface DecodedToken {\n header: JsonObject;\n payload: JsonObject;\n /** `<header>.<payload>` exactly as in the token: the bytes the signature covers. */\n signingInput: string;\n signature: Buffer;\n}\n\nexport function decodeToken(token: unknown, maxLength: number): DecodedToken {\n if (typeof token !== \"string\") {\n throw new JwtVerificationError(\"MalformedToken\", \"Not a valid JWT\");\n }\n if (token.length > maxLength) {\n throw new JwtVerificationError(\"MalformedToken\", \"Token too large\");\n }\n const parts = token.split(\".\");\n if (parts.length !== 3 || !parts.every(isCanonicalBase64Url)) {\n throw new JwtVerificationError(\"MalformedToken\", \"Not a valid JWT\");\n }\n const [h = \"\", p = \"\", s = \"\"] = parts;\n try {\n const header: unknown = JSON.parse(Buffer.from(h, \"base64url\").toString(\"utf8\"));\n const payload: unknown = JSON.parse(Buffer.from(p, \"base64url\").toString(\"utf8\"));\n if (!isJsonObject(header) || !isJsonObject(payload)) throw new Error(\"not a JSON object\");\n return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, \"base64url\") };\n } catch (cause) {\n throw new JwtVerificationError(\"MalformedToken\", \"Not a valid JWT\", { cause });\n }\n}\n\nexport function readKeyId(header: JsonObject): string {\n if (header.alg !== \"RS256\") {\n throw new JwtVerificationError(\"UnsupportedAlgorithm\", \"Unsupported algorithm\");\n }\n // RFC 7515: a `crit` header lists extensions the receiver must understand. We support none,\n // and Cognito never sets it, so any token carrying it is rejected.\n if (header.crit !== undefined) {\n throw new JwtVerificationError(\"MalformedToken\", \"Unsupported crit header\");\n }\n if (typeof header.kid !== \"string\") {\n throw new JwtVerificationError(\"InvalidKid\", \"Token header has no kid\");\n }\n return header.kid;\n}\n\n/** @throws JwtVerificationError with reason `InvalidSignature`. */\nexport function assertValidSignature(token: DecodedToken, key: KeyObject): void {\n if (!cryptoVerify(\"RSA-SHA256\", Buffer.from(token.signingInput), key, token.signature)) {\n throw new JwtVerificationError(\"InvalidSignature\", \"Invalid signature\");\n }\n}\n\n/** Strict base64url that re-encodes to exactly the same text (no padding, no spare bits set). */\nfunction isCanonicalBase64Url(part: string): boolean {\n return BASE64URL_RE.test(part) && Buffer.from(part, \"base64url\").toString(\"base64url\") === part;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
package/dist/verifier.js
CHANGED
|
@@ -25,6 +25,7 @@ class CognitoJwtVerifier {
|
|
|
25
25
|
}
|
|
26
26
|
async verify(token, options) {
|
|
27
27
|
const issuer = (0, issuer_1.issuerFor)(options.region, options.userPoolId);
|
|
28
|
+
const rules = (0, options_1.resolveTokenRules)(options);
|
|
28
29
|
const decoded = (0, token_1.decodeToken)(token, this.#options.maxTokenLength);
|
|
29
30
|
const kid = (0, token_1.readKeyId)(decoded.header);
|
|
30
31
|
// Checked before downloading keys, so tokens from other issuers cost no network request.
|
|
@@ -33,8 +34,8 @@ class CognitoJwtVerifier {
|
|
|
33
34
|
(0, token_1.assertValidSignature)(decoded, key);
|
|
34
35
|
return (0, claims_1.assertClaims)(decoded.payload, {
|
|
35
36
|
clockToleranceSec: this.#options.clockToleranceSec,
|
|
36
|
-
tokenUse:
|
|
37
|
-
clientId:
|
|
37
|
+
tokenUse: rules.tokenUse,
|
|
38
|
+
clientId: rules.clientId,
|
|
38
39
|
});
|
|
39
40
|
}
|
|
40
41
|
async checkJwt(tokenData, region, userPoolId) {
|
package/dist/verifier.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifier.js","sourceRoot":"","sources":["../src/verifier.ts"],"names":[],"mappings":";;;AAAA,qCAAsD;AACtD,qCAAqD;AACrD,iCAAmC;AACnC,qCAAwD;AACxD,
|
|
1
|
+
{"version":3,"file":"verifier.js","sourceRoot":"","sources":["../src/verifier.ts"],"names":[],"mappings":";;;AAAA,qCAAsD;AACtD,qCAAqD;AACrD,iCAAmC;AACnC,qCAAwD;AACxD,uCAA8D;AAE9D,mCAAuE;AAGvE;;;;GAIG;AACH,MAAa,kBAAkB;IACpB,QAAQ,CAAkB;IAC1B,KAAK,CAAY;IAE1B,YAAY,UAAqC,EAAE;QACjD,IAAI,CAAC,QAAQ,GAAG,IAAA,wBAAc,EAAC,OAAO,CAAC,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,gBAAS,CAAC;YACzB,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,cAAc;YACnC,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,cAAc;YAC5C,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK;SAC3B,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAa,EAAE,OAAsB;QAChD,MAAM,MAAM,GAAG,IAAA,kBAAS,EAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QAC7D,MAAM,KAAK,GAAG,IAAA,2BAAiB,EAAC,OAAO,CAAC,CAAC;QACzC,MAAM,OAAO,GAAG,IAAA,mBAAW,EAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QACjE,MAAM,GAAG,GAAG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E,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE,EAAE;SAC/E,CAAC,CACH,CAAC;IACJ,CAAC;CACF;AAjDD,gDAiDC","sourcesContent":["import { assertClaims, assertIssuer } from \"./claims\";\nimport { issuerFor, parseIssuerUrl } from \"./issuer\";\nimport { JwksCache } from \"./jwks\";\nimport { legacyFailure, legacySuccess } from \"./legacy\";\nimport { resolveOptions, resolveTokenRules } from \"./options\";\nimport type { ResolvedOptions } from \"./options\";\nimport { assertValidSignature, decodeToken, readKeyId } from \"./token\";\nimport type { CognitoJwtPayload, CognitoJwtVerifierOptions, Jwk, VerifyOptions } from \"./types\";\n\n/**\n * Verifies JWTs issued by AWS Cognito user pools.\n *\n * Create one instance and reuse it: it caches each user pool's public keys.\n */\nexport class CognitoJwtVerifier {\n readonly #options: ResolvedOptions;\n readonly #jwks: JwksCache;\n\n constructor(options: CognitoJwtVerifierOptions = {}) {\n this.#options = resolveOptions(options);\n this.#jwks = new JwksCache({\n ttlMs: this.#options.jwksCacheTtlMs,\n fetchTimeoutMs: this.#options.fetchTimeoutMs,\n fetch: this.#options.fetch,\n });\n }\n\n async verify(token: string, options: VerifyOptions): Promise<CognitoJwtPayload> {\n const issuer = issuerFor(options.region, options.userPoolId);\n const rules = resolveTokenRules(options);\n const decoded = decodeToken(token, this.#options.maxTokenLength);\n const kid = readKeyId(decoded.header);\n // Checked before downloading keys, so tokens from other issuers cost no network request.\n assertIssuer(decoded.payload, issuer);\n\n const key = await this.#jwks.getKey(issuer, kid);\n assertValidSignature(decoded, key);\n\n return assertClaims(decoded.payload, {\n clockToleranceSec: this.#options.clockToleranceSec,\n tokenUse: rules.tokenUse,\n clientId: rules.clientId,\n });\n }\n\n async checkJwt(tokenData: string, region: string, userPoolId: string): Promise<string> {\n try {\n return legacySuccess(await this.verify(tokenData, { region, userPoolId, tokenUse: null, clientId: null }));\n } catch (error) {\n return legacyFailure(error);\n }\n }\n\n async getPublicKey(cognitoIssuer: string): Promise<Record<string, { instance: Jwk; pem: string }>> {\n const keys = await this.#jwks.getKeys(parseIssuerUrl(cognitoIssuer));\n // Object.fromEntries defines own properties, so a kid like \"__proto__\" can't replace the prototype.\n return Object.fromEntries(\n [...keys].map(([kid, { jwk, key }]) => [\n kid,\n { instance: jwk, pem: key.export({ type: \"spki\", format: \"pem\" }).toString() },\n ]),\n );\n }\n}\n"]}
|