aws-cognito-jwt-verifier 1.3.7 → 2.0.2

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/dist/jwks.js ADDED
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JwksCache = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const errors_1 = require("./errors");
6
+ const issuer_1 = require("./issuer");
7
+ /** Don't download the keys again for an unknown kid more often than this. */
8
+ const MIN_REFETCH_INTERVAL_MS = 60_000;
9
+ /** After a failed download, wait this long before trying again. */
10
+ const RETRY_AFTER_FAILURE_MS = 5_000;
11
+ /** While refreshes keep failing, keep using expired keys for at most this long past their TTL. */
12
+ const MAX_STALE_MS = 24 * 60 * 60 * 1000;
13
+ class JwksCache {
14
+ #options;
15
+ #sets = new Map();
16
+ #inflight = new Map();
17
+ #failures = new Map();
18
+ constructor(options) {
19
+ this.#options = options;
20
+ }
21
+ /** @throws JwtVerificationError with reason `InvalidKid` or `JwksFetchFailed`. */
22
+ async getKey(issuer, kid) {
23
+ let set = await this.#load(issuer, false);
24
+ let entry = set.keys.get(kid);
25
+ // Unknown kid: Cognito may have rotated its keys, so refresh (rate-limited).
26
+ if (!entry && Date.now() - set.fetchedAt >= MIN_REFETCH_INTERVAL_MS) {
27
+ set = await this.#load(issuer, true);
28
+ entry = set.keys.get(kid);
29
+ }
30
+ if (!entry) {
31
+ throw new errors_1.JwtVerificationError("InvalidKid", "Invalid kid");
32
+ }
33
+ return entry.key;
34
+ }
35
+ /** @throws JwtVerificationError with reason `JwksFetchFailed`. */
36
+ async getKeys(issuer) {
37
+ return (await this.#load(issuer, false)).keys;
38
+ }
39
+ async #load(issuer, forceRefresh) {
40
+ const cached = this.#sets.get(issuer);
41
+ if (!forceRefresh && cached && Date.now() - cached.fetchedAt < this.#options.ttlMs) {
42
+ return cached;
43
+ }
44
+ // A download failed recently: don't hit the endpoint again yet (stops request floods
45
+ // during an outage). Use the expired keys meanwhile if we still may.
46
+ const failure = this.#failures.get(issuer);
47
+ if (failure && Date.now() - failure.at < RETRY_AFTER_FAILURE_MS) {
48
+ const stale = this.#usableStale(cached);
49
+ if (stale)
50
+ return stale;
51
+ throw new errors_1.JwtVerificationError("JwksFetchFailed", failure.error.message, { cause: failure.error });
52
+ }
53
+ const pending = this.#inflight.get(issuer);
54
+ if (pending)
55
+ return pending;
56
+ const download = this.#download(issuer)
57
+ .then((set) => {
58
+ this.#sets.set(issuer, set);
59
+ this.#failures.delete(issuer);
60
+ return set;
61
+ }, (cause) => {
62
+ const error = cause instanceof errors_1.JwtVerificationError
63
+ ? cause
64
+ : new errors_1.JwtVerificationError("JwksFetchFailed", `Could not fetch JWKS for ${issuer}`, { cause });
65
+ this.#failures.set(issuer, { at: Date.now(), error });
66
+ // Refresh failed: keep the keys we already have rather than rejecting every token.
67
+ const stale = this.#usableStale(cached);
68
+ if (stale)
69
+ return stale;
70
+ throw error;
71
+ })
72
+ .finally(() => this.#inflight.delete(issuer));
73
+ this.#inflight.set(issuer, download);
74
+ return download;
75
+ }
76
+ /** Expired cached keys, if they are not too old to keep trusting while refreshes fail. */
77
+ #usableStale(cached) {
78
+ if (cached && Date.now() - cached.fetchedAt < this.#options.ttlMs + MAX_STALE_MS) {
79
+ return cached;
80
+ }
81
+ return undefined;
82
+ }
83
+ async #download(issuer) {
84
+ const url = (0, issuer_1.jwksUrl)(issuer);
85
+ let body;
86
+ try {
87
+ const res = await this.#options.fetch(url, {
88
+ signal: AbortSignal.timeout(this.#options.fetchTimeoutMs),
89
+ redirect: "error", // the real Cognito endpoint never redirects
90
+ });
91
+ if (!res.ok)
92
+ throw new Error(`HTTP ${res.status}`);
93
+ body = await res.json();
94
+ }
95
+ catch (cause) {
96
+ throw new errors_1.JwtVerificationError("JwksFetchFailed", `Could not fetch JWKS from ${url}`, { cause });
97
+ }
98
+ return { keys: parseKeys(body, url), fetchedAt: Date.now() };
99
+ }
100
+ }
101
+ exports.JwksCache = JwksCache;
102
+ /** Turns a JWKS document into usable RSA public keys, skipping any key that isn't one. */
103
+ function parseKeys(body, url) {
104
+ const list = body?.keys;
105
+ if (!Array.isArray(list)) {
106
+ throw new errors_1.JwtVerificationError("JwksFetchFailed", `JWKS from ${url} has no keys`);
107
+ }
108
+ const keys = new Map();
109
+ for (const jwk of list) {
110
+ if (jwk?.kty !== "RSA" || typeof jwk.kid !== "string")
111
+ continue;
112
+ try {
113
+ keys.set(jwk.kid, { jwk, key: (0, node_crypto_1.createPublicKey)({ key: jwk, format: "jwk" }) });
114
+ }
115
+ catch {
116
+ // Not a valid RSA public key: skip it rather than failing the whole set.
117
+ }
118
+ }
119
+ return keys;
120
+ }
121
+ //# sourceMappingURL=jwks.js.map
@@ -0,0 +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,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,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ACvD,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"]}
@@ -0,0 +1,3 @@
1
+ import type { CognitoJwtPayload } from "./types";
2
+ export declare function legacySuccess(data: CognitoJwtPayload): string;
3
+ export declare function legacyFailure(error: unknown): string;
package/dist/legacy.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.legacySuccess = legacySuccess;
4
+ exports.legacyFailure = legacyFailure;
5
+ /**
6
+ * Support for the v1.x `checkJwt()` result format. Kept only for backward compatibility.
7
+ */
8
+ const errors_1 = require("./errors");
9
+ function legacySuccess(data) {
10
+ const result = { status: true, code: 200, message: "Congrats! Your token is valid", data };
11
+ return JSON.stringify(result);
12
+ }
13
+ function legacyFailure(error) {
14
+ const result = { status: false, code: 401, message: legacyMessage(error) };
15
+ return JSON.stringify(result);
16
+ }
17
+ /** The error message v1.x would have returned (jsonwebtoken naming where it applies). */
18
+ function legacyMessage(error) {
19
+ if (!(error instanceof errors_1.JwtVerificationError)) {
20
+ return error instanceof Error ? error.message : String(error);
21
+ }
22
+ switch (error.reason) {
23
+ case "MalformedToken":
24
+ return "Not a valid JWT Token";
25
+ case "InvalidKid":
26
+ case "InvalidConfiguration":
27
+ case "JwksFetchFailed":
28
+ return error.message;
29
+ default:
30
+ return error.legacyName;
31
+ }
32
+ }
33
+ //# sourceMappingURL=legacy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy.js","sourceRoot":"","sources":["../src/legacy.ts"],"names":[],"mappings":";;AAMA,sCAGC;AAED,sCAGC;AAdD;;GAEG;AACH,qCAAgD;AAGhD,SAAgB,aAAa,CAAC,IAAuB;IACnD,MAAM,MAAM,GAAmB,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,+BAA+B,EAAE,IAAI,EAAE,CAAC;IAC3G,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED,SAAgB,aAAa,CAAC,KAAc;IAC1C,MAAM,MAAM,GAAmB,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;IAC3F,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED,yFAAyF;AACzF,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,CAAC,CAAC,KAAK,YAAY,6BAAoB,CAAC,EAAE,CAAC;QAC7C,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAChE,CAAC;IACD,QAAQ,KAAK,CAAC,MAAM,EAAE,CAAC;QACrB,KAAK,gBAAgB;YACnB,OAAO,uBAAuB,CAAC;QACjC,KAAK,YAAY,CAAC;QAClB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,iBAAiB;YACpB,OAAO,KAAK,CAAC,OAAO,CAAC;QACvB;YACE,OAAO,KAAK,CAAC,UAAU,CAAC;IAC5B,CAAC;AACH,CAAC","sourcesContent":["/**\n * Support for the v1.x `checkJwt()` result format. Kept only for backward compatibility.\n */\nimport { JwtVerificationError } from \"./errors\";\nimport type { CheckJwtResult, CognitoJwtPayload } from \"./types\";\n\nexport function legacySuccess(data: CognitoJwtPayload): string {\n const result: CheckJwtResult = { status: true, code: 200, message: \"Congrats! Your token is valid\", data };\n return JSON.stringify(result);\n}\n\nexport function legacyFailure(error: unknown): string {\n const result: CheckJwtResult = { status: false, code: 401, message: legacyMessage(error) };\n return JSON.stringify(result);\n}\n\n/** The error message v1.x would have returned (jsonwebtoken naming where it applies). */\nfunction legacyMessage(error: unknown): string {\n if (!(error instanceof JwtVerificationError)) {\n return error instanceof Error ? error.message : String(error);\n }\n switch (error.reason) {\n case \"MalformedToken\":\n return \"Not a valid JWT Token\";\n case \"InvalidKid\":\n case \"InvalidConfiguration\":\n case \"JwksFetchFailed\":\n return error.message;\n default:\n return error.legacyName;\n }\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import type { CognitoJwtVerifierOptions, FetchLike } from "./types";
2
+ export declare const DEFAULT_OPTIONS: {
3
+ readonly jwksCacheTtlMs: number;
4
+ readonly fetchTimeoutMs: 5000;
5
+ readonly clockToleranceSec: 0;
6
+ readonly maxTokenLength: 16384;
7
+ };
8
+ /** Constructor options with defaults applied and every value validated. */
9
+ export interface ResolvedOptions {
10
+ jwksCacheTtlMs: number;
11
+ fetchTimeoutMs: number;
12
+ clockToleranceSec: number;
13
+ maxTokenLength: number;
14
+ fetch: FetchLike;
15
+ }
16
+ export declare function resolveOptions(options: CognitoJwtVerifierOptions): ResolvedOptions;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_OPTIONS = void 0;
4
+ exports.resolveOptions = resolveOptions;
5
+ const errors_1 = require("./errors");
6
+ /** Largest delay Node timers accept; bigger values would fire immediately. */
7
+ const MAX_TIMER_MS = 2_147_483_647;
8
+ exports.DEFAULT_OPTIONS = {
9
+ jwksCacheTtlMs: 60 * 60 * 1000,
10
+ fetchTimeoutMs: 5000,
11
+ clockToleranceSec: 0,
12
+ maxTokenLength: 16384,
13
+ };
14
+ function resolveOptions(options) {
15
+ const fetchImpl = options.fetch ?? globalThis.fetch;
16
+ if (typeof fetchImpl !== "function") {
17
+ throw new errors_1.JwtVerificationError("InvalidConfiguration", "fetch must be a function");
18
+ }
19
+ return {
20
+ jwksCacheTtlMs: numberOption("jwksCacheTtlMs", options.jwksCacheTtlMs, exports.DEFAULT_OPTIONS.jwksCacheTtlMs, 0),
21
+ fetchTimeoutMs: numberOption("fetchTimeoutMs", options.fetchTimeoutMs, exports.DEFAULT_OPTIONS.fetchTimeoutMs, 1, MAX_TIMER_MS),
22
+ clockToleranceSec: numberOption("clockToleranceSec", options.clockToleranceSec, exports.DEFAULT_OPTIONS.clockToleranceSec, 0),
23
+ maxTokenLength: numberOption("maxTokenLength", options.maxTokenLength, exports.DEFAULT_OPTIONS.maxTokenLength, 1),
24
+ fetch: fetchImpl,
25
+ };
26
+ }
27
+ function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
28
+ if (value === undefined)
29
+ return fallback;
30
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) {
31
+ return value;
32
+ }
33
+ const range = max === Number.MAX_SAFE_INTEGER
34
+ ? `${name} must be a finite number of at least ${min}`
35
+ : `${name} must be a number from ${min} to ${max}`;
36
+ const hint = typeof value === "string" ? " (got a string: convert it with Number())" : "";
37
+ throw new errors_1.JwtVerificationError("InvalidConfiguration", range + hint);
38
+ }
39
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":";;;AAsBA,wCAuBC;AA7CD,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;AAWX,SAAgB,cAAc,CAAC,OAAkC;IAC/D,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC;IACpD,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;QACpC,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,0BAA0B,CAAC,CAAC;IACrF,CAAC;IACD,OAAO;QACL,cAAc,EAAE,YAAY,CAAC,gBAAgB,EAAE,OAAO,CAAC,cAAc,EAAE,uBAAe,CAAC,cAAc,EAAE,CAAC,CAAC;QACzG,cAAc,EAAE,YAAY,CAC1B,gBAAgB,EAChB,OAAO,CAAC,cAAc,EACtB,uBAAe,CAAC,cAAc,EAC9B,CAAC,EACD,YAAY,CACb;QACD,iBAAiB,EAAE,YAAY,CAC7B,mBAAmB,EACnB,OAAO,CAAC,iBAAiB,EACzB,uBAAe,CAAC,iBAAiB,EACjC,CAAC,CACF;QACD,cAAc,EAAE,YAAY,CAAC,gBAAgB,EAAE,OAAO,CAAC,cAAc,EAAE,uBAAe,CAAC,cAAc,EAAE,CAAC,CAAC;QACzG,KAAK,EAAE,SAAS;KACjB,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CACnB,IAAY,EACZ,KAAc,EACd,QAAgB,EAChB,GAAW,EACX,MAAc,MAAM,CAAC,gBAAgB;IAErC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IACzC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,GAAG,IAAI,KAAK,IAAI,GAAG,EAAE,CAAC;QACxF,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,KAAK,GACT,GAAG,KAAK,MAAM,CAAC,gBAAgB;QAC7B,CAAC,CAAC,GAAG,IAAI,wCAAwC,GAAG,EAAE;QACtD,CAAC,CAAC,GAAG,IAAI,0BAA0B,GAAG,OAAO,GAAG,EAAE,CAAC;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","sourcesContent":["import { JwtVerificationError } from \"./errors\";\nimport type { CognitoJwtVerifierOptions, FetchLike } 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"]}
@@ -0,0 +1,14 @@
1
+ import type { KeyObject } from "node:crypto";
2
+ export type JsonObject = Record<string, unknown>;
3
+ /** A JWT split into its parts. Nothing in it is trusted until the signature is verified. */
4
+ export interface DecodedToken {
5
+ header: JsonObject;
6
+ payload: JsonObject;
7
+ /** `<header>.<payload>` exactly as in the token: the bytes the signature covers. */
8
+ signingInput: string;
9
+ signature: Buffer;
10
+ }
11
+ export declare function decodeToken(token: unknown, maxLength: number): DecodedToken;
12
+ export declare function readKeyId(header: JsonObject): string;
13
+ /** @throws JwtVerificationError with reason `InvalidSignature`. */
14
+ export declare function assertValidSignature(token: DecodedToken, key: KeyObject): void;
package/dist/token.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeToken = decodeToken;
4
+ exports.readKeyId = readKeyId;
5
+ exports.assertValidSignature = assertValidSignature;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const errors_1 = require("./errors");
8
+ /** Characters allowed in one JWT segment (unpadded base64url). */
9
+ const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
10
+ function decodeToken(token, maxLength) {
11
+ if (typeof token !== "string") {
12
+ throw new errors_1.JwtVerificationError("MalformedToken", "Not a valid JWT");
13
+ }
14
+ if (token.length > maxLength) {
15
+ throw new errors_1.JwtVerificationError("MalformedToken", "Token too large");
16
+ }
17
+ const parts = token.split(".");
18
+ if (parts.length !== 3 || !parts.every(isCanonicalBase64Url)) {
19
+ throw new errors_1.JwtVerificationError("MalformedToken", "Not a valid JWT");
20
+ }
21
+ const [h = "", p = "", s = ""] = parts;
22
+ try {
23
+ const header = JSON.parse(Buffer.from(h, "base64url").toString("utf8"));
24
+ const payload = JSON.parse(Buffer.from(p, "base64url").toString("utf8"));
25
+ if (!isJsonObject(header) || !isJsonObject(payload))
26
+ throw new Error("not a JSON object");
27
+ return { header, payload, signingInput: `${h}.${p}`, signature: Buffer.from(s, "base64url") };
28
+ }
29
+ catch (cause) {
30
+ throw new errors_1.JwtVerificationError("MalformedToken", "Not a valid JWT", { cause });
31
+ }
32
+ }
33
+ function readKeyId(header) {
34
+ if (header.alg !== "RS256") {
35
+ throw new errors_1.JwtVerificationError("UnsupportedAlgorithm", "Unsupported algorithm");
36
+ }
37
+ if (typeof header.kid !== "string") {
38
+ throw new errors_1.JwtVerificationError("InvalidKid", "Token header has no kid");
39
+ }
40
+ return header.kid;
41
+ }
42
+ /** @throws JwtVerificationError with reason `InvalidSignature`. */
43
+ function assertValidSignature(token, key) {
44
+ if (!(0, node_crypto_1.verify)("RSA-SHA256", Buffer.from(token.signingInput), key, token.signature)) {
45
+ throw new errors_1.JwtVerificationError("InvalidSignature", "Invalid signature");
46
+ }
47
+ }
48
+ /** Strict base64url that re-encodes to exactly the same text (no padding, no spare bits set). */
49
+ function isCanonicalBase64Url(part) {
50
+ return BASE64URL_RE.test(part) && Buffer.from(part, "base64url").toString("base64url") === part;
51
+ }
52
+ function isJsonObject(value) {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+ //# sourceMappingURL=token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":";;AAkBA,kCAoBC;AAED,8BAQC;AAGD,oDAIC;AAvDD,6CAAqD;AAErD,qCAAgD;AAEhD,kEAAkE;AAClE,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAaxC,SAAgB,WAAW,CAAC,KAAc,EAAE,SAAiB;IAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,6BAAoB,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAAC;IACtE,CAAC;IACD,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;QAC7B,MAAM,IAAI,6BAAoB,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,oBAAoB,CAAC,EAAE,CAAC;QAC7D,MAAM,IAAI,6BAAoB,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;IACvC,IAAI,CAAC;QACH,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,CAAC,CAA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EAAE,mBAAmB,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC;AAED,iGAAiG;AACjG,SAAS,oBAAoB,CAAC,IAAY;IACxC,OAAO,YAAY,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 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"]}
@@ -0,0 +1,69 @@
1
+ /** Claims of a Cognito access or ID token, as returned by `verify()`. */
2
+ export interface CognitoJwtPayload {
3
+ sub: string;
4
+ iss: string;
5
+ exp: number;
6
+ iat: number;
7
+ token_use: "access" | "id";
8
+ auth_time?: number;
9
+ client_id?: string;
10
+ aud?: string;
11
+ username?: string;
12
+ scope?: string;
13
+ "cognito:groups"?: string[];
14
+ [claim: string]: unknown;
15
+ }
16
+ /** A JSON Web Key as published in the user pool's `/.well-known/jwks.json`. */
17
+ export interface Jwk {
18
+ kty: string;
19
+ kid?: string;
20
+ alg?: string;
21
+ use?: string;
22
+ n?: string;
23
+ e?: string;
24
+ [param: string]: unknown;
25
+ }
26
+ /** Minimal fetch signature the verifier needs; the global `fetch` satisfies it. */
27
+ export type FetchLike = (url: string, init: {
28
+ signal: any;
29
+ redirect: "error";
30
+ }) => Promise<{
31
+ ok: boolean;
32
+ status: number;
33
+ json(): Promise<unknown>;
34
+ }>;
35
+ /** Options for `CognitoJwtVerifier.verify()`. */
36
+ export interface VerifyOptions {
37
+ /** AWS region of the user pool, e.g. `ap-southeast-1`. */
38
+ region: string;
39
+ /** Cognito user pool ID, e.g. `ap-southeast-1_AbCdEfGhI`. */
40
+ userPoolId: string;
41
+ /** Required `token_use` claim. Pass `null` to accept both access and ID tokens. */
42
+ tokenUse: "access" | "id" | null;
43
+ /** Allowed app client ID(s), checked against `client_id` (access) or `aud` (ID). `null` skips the check. */
44
+ clientId: string | string[] | null;
45
+ }
46
+ /** Options for the `CognitoJwtVerifier` constructor. */
47
+ export interface CognitoJwtVerifierOptions {
48
+ /** How long a downloaded JWKS is reused, in ms. A number of 0 or more. Default: 1 hour. */
49
+ jwksCacheTtlMs?: number;
50
+ /** Timeout for the JWKS request, in ms. A number above 0. Default: 5 seconds. */
51
+ fetchTimeoutMs?: number;
52
+ /** Allowed clock skew for `exp` / `nbf`, in seconds. A number of 0 or more. Default: 0. */
53
+ clockToleranceSec?: number;
54
+ /** Custom fetch implementation (proxies, tests). Default: global `fetch`. */
55
+ fetch?: FetchLike;
56
+ /** Longest token accepted, in characters; longer tokens are rejected before decoding. A number above 0. Default: 16384. */
57
+ maxTokenLength?: number;
58
+ }
59
+ /** Shape of the JSON string returned by the legacy `checkJwt()` method. */
60
+ export type CheckJwtResult = {
61
+ status: true;
62
+ code: 200;
63
+ message: string;
64
+ data: CognitoJwtPayload;
65
+ } | {
66
+ status: false;
67
+ code: 401;
68
+ message: string;
69
+ };
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["/** Claims of a Cognito access or ID token, as returned by `verify()`. */\nexport interface CognitoJwtPayload {\n sub: string;\n iss: string;\n exp: number;\n iat: number;\n token_use: \"access\" | \"id\";\n auth_time?: number;\n client_id?: string;\n aud?: string;\n username?: string;\n scope?: string;\n \"cognito:groups\"?: string[];\n [claim: string]: unknown;\n}\n\n/** A JSON Web Key as published in the user pool's `/.well-known/jwks.json`. */\nexport interface Jwk {\n kty: string;\n kid?: string;\n alg?: string;\n use?: string;\n n?: string;\n e?: string;\n [param: string]: unknown;\n}\n\n/** Minimal fetch signature the verifier needs; the global `fetch` satisfies it. */\nexport type FetchLike = (\n url: string,\n // `any` so the declarations need neither @types/node nor the DOM lib for AbortSignal.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n init: { signal: any; redirect: \"error\" },\n) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\n/** Options for `CognitoJwtVerifier.verify()`. */\nexport interface VerifyOptions {\n /** AWS region of the user pool, e.g. `ap-southeast-1`. */\n region: string;\n /** Cognito user pool ID, e.g. `ap-southeast-1_AbCdEfGhI`. */\n userPoolId: string;\n /** Required `token_use` claim. Pass `null` to accept both access and ID tokens. */\n tokenUse: \"access\" | \"id\" | null;\n /** Allowed app client ID(s), checked against `client_id` (access) or `aud` (ID). `null` skips the check. */\n clientId: string | string[] | null;\n}\n\n/** Options for the `CognitoJwtVerifier` constructor. */\nexport interface CognitoJwtVerifierOptions {\n /** How long a downloaded JWKS is reused, in ms. A number of 0 or more. Default: 1 hour. */\n jwksCacheTtlMs?: number;\n /** Timeout for the JWKS request, in ms. A number above 0. Default: 5 seconds. */\n fetchTimeoutMs?: number;\n /** Allowed clock skew for `exp` / `nbf`, in seconds. A number of 0 or more. Default: 0. */\n clockToleranceSec?: number;\n /** Custom fetch implementation (proxies, tests). Default: global `fetch`. */\n fetch?: FetchLike;\n /** Longest token accepted, in characters; longer tokens are rejected before decoding. A number above 0. Default: 16384. */\n maxTokenLength?: number;\n}\n\n/** Shape of the JSON string returned by the legacy `checkJwt()` method. */\nexport type CheckJwtResult =\n { status: true; code: 200; message: string; data: CognitoJwtPayload } | { status: false; code: 401; message: string };\n"]}
@@ -0,0 +1,16 @@
1
+ import type { CognitoJwtPayload, CognitoJwtVerifierOptions, Jwk, VerifyOptions } from "./types";
2
+ /**
3
+ * Verifies JWTs issued by AWS Cognito user pools.
4
+ *
5
+ * Create one instance and reuse it: it caches each user pool's public keys.
6
+ */
7
+ export declare class CognitoJwtVerifier {
8
+ #private;
9
+ constructor(options?: CognitoJwtVerifierOptions);
10
+ verify(token: string, options: VerifyOptions): Promise<CognitoJwtPayload>;
11
+ checkJwt(tokenData: string, region: string, userPoolId: string): Promise<string>;
12
+ getPublicKey(cognitoIssuer: string): Promise<Record<string, {
13
+ instance: Jwk;
14
+ pem: string;
15
+ }>>;
16
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CognitoJwtVerifier = void 0;
4
+ const claims_1 = require("./claims");
5
+ const issuer_1 = require("./issuer");
6
+ const jwks_1 = require("./jwks");
7
+ const legacy_1 = require("./legacy");
8
+ const options_1 = require("./options");
9
+ const token_1 = require("./token");
10
+ /**
11
+ * Verifies JWTs issued by AWS Cognito user pools.
12
+ *
13
+ * Create one instance and reuse it: it caches each user pool's public keys.
14
+ */
15
+ class CognitoJwtVerifier {
16
+ #options;
17
+ #jwks;
18
+ constructor(options = {}) {
19
+ this.#options = (0, options_1.resolveOptions)(options);
20
+ this.#jwks = new jwks_1.JwksCache({
21
+ ttlMs: this.#options.jwksCacheTtlMs,
22
+ fetchTimeoutMs: this.#options.fetchTimeoutMs,
23
+ fetch: this.#options.fetch,
24
+ });
25
+ }
26
+ async verify(token, options) {
27
+ const issuer = (0, issuer_1.issuerFor)(options.region, options.userPoolId);
28
+ const decoded = (0, token_1.decodeToken)(token, this.#options.maxTokenLength);
29
+ const kid = (0, token_1.readKeyId)(decoded.header);
30
+ // Checked before downloading keys, so tokens from other issuers cost no network request.
31
+ (0, claims_1.assertIssuer)(decoded.payload, issuer);
32
+ const key = await this.#jwks.getKey(issuer, kid);
33
+ (0, token_1.assertValidSignature)(decoded, key);
34
+ return (0, claims_1.assertClaims)(decoded.payload, {
35
+ clockToleranceSec: this.#options.clockToleranceSec,
36
+ tokenUse: options.tokenUse,
37
+ clientId: options.clientId,
38
+ });
39
+ }
40
+ async checkJwt(tokenData, region, userPoolId) {
41
+ try {
42
+ return (0, legacy_1.legacySuccess)(await this.verify(tokenData, { region, userPoolId, tokenUse: null, clientId: null }));
43
+ }
44
+ catch (error) {
45
+ return (0, legacy_1.legacyFailure)(error);
46
+ }
47
+ }
48
+ async getPublicKey(cognitoIssuer) {
49
+ const keys = await this.#jwks.getKeys((0, issuer_1.parseIssuerUrl)(cognitoIssuer));
50
+ // Object.fromEntries defines own properties, so a kid like "__proto__" can't replace the prototype.
51
+ return Object.fromEntries([...keys].map(([kid, { jwk, key }]) => [
52
+ kid,
53
+ { instance: jwk, pem: key.export({ type: "spki", format: "pem" }).toString() },
54
+ ]));
55
+ }
56
+ }
57
+ exports.CognitoJwtVerifier = CognitoJwtVerifier;
58
+ //# sourceMappingURL=verifier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifier.js","sourceRoot":"","sources":["../src/verifier.ts"],"names":[],"mappings":";;;AAAA,qCAAsD;AACtD,qCAAqD;AACrD,iCAAmC;AACnC,qCAAwD;AACxD,uCAA2C;AAE3C,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,K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AG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAA,uBAAc,EAAC,aAAa,CAAC,CAAC,CAAC;QACrE,oGAAoG;QACpG,OAAO,MAAM,CAAC,WAAW,CACvB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,GAAG;YACH,EAAE,QAAQ,EAAE,GAAG,EAAE,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;AAhDD,gDAgDC","sourcesContent":["import { assertClaims, assertIssuer } from \"./claims\";\nimport { issuerFor, parseIssuerUrl } from \"./issuer\";\nimport { JwksCache } from \"./jwks\";\nimport { legacyFailure, legacySuccess } from \"./legacy\";\nimport { resolveOptions } 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 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: options.tokenUse,\n clientId: options.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"]}
package/package.json CHANGED
@@ -1,31 +1,72 @@
1
1
  {
2
2
  "name": "aws-cognito-jwt-verifier",
3
- "version": "1.3.7",
4
- "description": "AWS Cognito JWT Verifier is a Typescript library that will help to secure your application by checking if your JWT token is valid.",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "scripts": {
8
- "build": "tsc",
9
- "prepare": "npm run build"
10
- },
11
- "files": [
12
- "dist"
13
- ],
3
+ "version": "2.0.2",
4
+ "description": "Verify AWS Cognito JWTs (access and ID tokens) in Node.js. Zero dependencies, TypeScript types included.",
14
5
  "keywords": [
6
+ "aws",
15
7
  "aws cognito",
16
- "access token",
17
8
  "cognito",
9
+ "cognito user pool",
18
10
  "jwt",
19
- "token",
11
+ "jwks",
12
+ "json web token",
20
13
  "jwt verify",
21
14
  "token verification",
22
- "json web token verify"
15
+ "access token",
16
+ "id token",
17
+ "authentication",
18
+ "node",
19
+ "backend",
20
+ "express",
21
+ "lambda",
22
+ "typescript"
23
23
  ],
24
24
  "author": "Marjun Villegas",
25
- "license": "ISC",
26
- "dependencies": {
27
- "axios": "^0.19.2",
28
- "jsonwebtoken": "^8.5.1",
29
- "jwk-to-pem": "^2.0.3"
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/marjunvillegas29/aws-cognito-jwt-verifier.git"
29
+ },
30
+ "homepage": "https://github.com/marjunvillegas29/aws-cognito-jwt-verifier#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/marjunvillegas29/aws-cognito-jwt-verifier/issues"
33
+ },
34
+ "type": "commonjs",
35
+ "main": "dist/index.js",
36
+ "types": "dist/index.d.ts",
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "default": "./dist/index.js"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "sideEffects": false,
48
+ "engines": {
49
+ "node": ">=20"
50
+ },
51
+ "scripts": {
52
+ "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
53
+ "build": "npm run clean && tsc",
54
+ "typecheck": "tsc --noEmit",
55
+ "lint": "eslint .",
56
+ "format": "prettier --write .",
57
+ "format:check": "prettier --check .",
58
+ "test": "npm run build && node --test test/*.test.js",
59
+ "check": "npm run typecheck && npm run lint && npm run format:check && npm test",
60
+ "check:real-token": "npm run build && node scripts/check-real-token.js",
61
+ "prepublishOnly": "npm run check"
62
+ },
63
+ "devDependencies": {
64
+ "@eslint/js": "^9.39.5",
65
+ "@types/node": "^20.19.0",
66
+ "eslint": "^9.39.5",
67
+ "globals": "^17.15.0",
68
+ "prettier": "^3.10.2",
69
+ "typescript": "^5.9.0",
70
+ "typescript-eslint": "^8.74.0"
30
71
  }
31
72
  }
@@ -1,4 +0,0 @@
1
- export declare class CognitoJwtVerifier {
2
- getPublicKey(cognitoIssuer: any): Promise<any>;
3
- checkJwt(tokenData: string, region: string, userPoolId: string): Promise<any>;
4
- }