aws-cognito-jwt-verifier 1.3.7 → 2.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2026 Marjun Villegas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,117 +1,333 @@
1
- # AWS Cognito JWT Verifier (TypeScript)
1
+ # AWS Cognito JWT Verifier
2
2
 
3
- AWS Cognito JWT Verifier is a Typescript library that will help to secure your application by checking if your JWT token is valid.
3
+ Verify JSON Web Tokens issued by an AWS Cognito user pool, with no runtime dependencies.
4
4
 
5
- **This library will check if your cognito JWT Token is:**
5
+ > **Backend only (Node.js 20 or later).** Use it in your API server, not in browser code.
6
6
 
7
- - Invalid Token
8
- - Expired Token
9
- - Invalid Publickey
7
+ It checks that a token:
10
8
 
11
- ###**NOTE:**
12
- **Supported** :
9
+ - is a well-formed JWT signed with RS256
10
+ - has a valid signature, using the user pool's public keys (JWKS), which are downloaded once and cached
11
+ - was issued by your user pool (`iss`)
12
+ - has not expired (`exp`) and is already active (`nbf`)
13
+ - is the expected kind of token (`token_use`: `access` or `id`)
14
+ - was issued to one of your app clients (`client_id` for access tokens, `aud` for ID tokens)
13
15
 
14
- - NodeJS (TypeScript)
15
- - Angular (TypeScript)
16
- - TypeScript
16
+ Works with Node.js 20 or later, in TypeScript, CommonJS and ES modules.
17
17
 
18
- **_Not Supported_ **:
19
- These libraries below are not supported yet;
18
+ ## Where it runs
20
19
 
21
- - ReactJS ** [not supported]**
22
- - VueJS **[not supported]**
20
+ This library uses Node.js's built-in `crypto` module, so it runs only in server code.
23
21
 
24
- ## Installation
22
+ | Environment | Supported |
23
+ |---|---|
24
+ | Express, Fastify, Koa, NestJS, Hapi | ✅ |
25
+ | AWS Lambda (Node.js 20 or 22), including API Gateway Lambda authorizers | ✅ |
26
+ | Next.js and Nuxt server code on the Node.js runtime (API routes, server actions, Nitro handlers) | ✅ |
27
+ | Bun | ✅ |
28
+ | Browser apps: React, Vue, Angular, Svelte | ❌ |
29
+ | React Native | ❌ |
30
+ | Edge runtimes: Cloudflare Workers, Next.js Edge runtime | ❌ |
25
31
 
26
- Use the NPM to install **_AWS Cognito JWT Verifier_**.
32
+ ### Using it with a React, Vue or Angular front end
27
33
 
28
- ```bash
29
- npm i aws-cognito-jwt-verifier --save
34
+ Checking a token in the browser can't protect anything: users control the browser and can skip or change the check. Verify tokens on the server that serves your data:
35
+
36
+ 1. The front end signs in with Cognito (for example with Amplify or the Cognito hosted UI) and gets the tokens.
37
+ 2. The front end sends the access token to your API in the `Authorization: Bearer <token>` header.
38
+ 3. Your API verifies the token with this library before handling the request.
39
+
40
+ To show the user's name or groups in the UI, decode the token without verifying it, for example with [`jwt-decode`](https://www.npmjs.com/package/jwt-decode). Never use a decoded but unverified token to decide what a user is allowed to do.
41
+
42
+ ### Example: Express middleware
43
+
44
+ ```typescript
45
+ import express from "express";
46
+ import { CognitoJwtVerifier } from "aws-cognito-jwt-verifier";
47
+
48
+ const app = express();
49
+ const verifier = new CognitoJwtVerifier();
50
+
51
+ app.use(async (req, res, next) => {
52
+ const token = req.headers.authorization?.replace(/^Bearer /, "");
53
+ if (!token) return res.status(401).json({ message: "Missing token" });
54
+ try {
55
+ res.locals.user = await verifier.verify(token, {
56
+ region: "ap-southeast-1",
57
+ userPoolId: "ap-southeast-1_AbCdEfGhI",
58
+ tokenUse: "access",
59
+ clientId: "your-app-client-id",
60
+ });
61
+ next();
62
+ } catch {
63
+ res.status(401).json({ message: "Invalid token" });
64
+ }
65
+ });
30
66
  ```
31
67
 
32
- ## Required Parameters
68
+ ## Installation
33
69
 
34
- - **Token** - Your aws cognito generated token.
35
- - **Region** - Your aws region where you cognito user pool residing.
36
- - **UserPoolID** - Your aws cognito user pool id.
70
+ ```bash
71
+ npm install aws-cognito-jwt-verifier
72
+ ```
37
73
 
38
74
  ## Usage
39
75
 
40
- _TypeScript Code _
76
+ The package works in both TypeScript and plain JavaScript. It ships compiled JavaScript with type definitions included, so you don't need to install any `@types` package.
77
+
78
+ In every example, create **one** verifier and reuse it, so the user pool's public keys stay cached between requests.
79
+
80
+ `verify()` takes these options:
81
+
82
+ | Option | Description |
83
+ |---|---|
84
+ | `region` | AWS region of the user pool, e.g. `ap-southeast-1` |
85
+ | `userPoolId` | Cognito user pool ID, e.g. `ap-southeast-1_AbCdEfGhI` |
86
+ | `tokenUse` | `"access"`, `"id"`, or `null` to accept both |
87
+ | `clientId` | Your app client ID: a string, an array of strings, or `null` to skip the check |
88
+
89
+ ### TypeScript
41
90
 
42
91
  ```typescript
43
- import {CognitoJwtVerifier} from 'aws-cognito-jwt-verifier';
92
+ import {
93
+ CognitoJwtVerifier,
94
+ JwtVerificationError,
95
+ type CognitoJwtPayload,
96
+ } from "aws-cognito-jwt-verifier";
97
+
98
+ const verifier = new CognitoJwtVerifier();
99
+
100
+ export async function getUser(token: string): Promise<CognitoJwtPayload | null> {
101
+ try {
102
+ const payload = await verifier.verify(token, {
103
+ region: "ap-southeast-1",
104
+ userPoolId: "ap-southeast-1_AbCdEfGhI",
105
+ tokenUse: "access",
106
+ clientId: "your-app-client-id",
107
+ });
108
+ console.log(payload.sub, payload["cognito:groups"]);
109
+ return payload;
110
+ } catch (err) {
111
+ if (err instanceof JwtVerificationError) {
112
+ console.log(err.reason); // e.g. "TokenExpired", "InvalidSignature"
113
+ }
114
+ return null;
115
+ }
116
+ }
117
+ ```
44
118
 
45
- const verify = new CognitoJwtVerifier();
119
+ ### JavaScript (CommonJS, `require`)
46
120
 
47
- async function verifyToken{
48
- return await verify.checkJwt('<cognitoJwtToken>', '<region>', '<userPool>');
121
+ ```javascript
122
+ const { CognitoJwtVerifier, JwtVerificationError } = require("aws-cognito-jwt-verifier");
123
+
124
+ const verifier = new CognitoJwtVerifier();
125
+
126
+ async function getUser(token) {
127
+ try {
128
+ const payload = await verifier.verify(token, {
129
+ region: "ap-southeast-1",
130
+ userPoolId: "ap-southeast-1_AbCdEfGhI",
131
+ tokenUse: "access",
132
+ clientId: "your-app-client-id",
133
+ });
134
+ console.log(payload.sub, payload["cognito:groups"]);
135
+ return payload;
136
+ } catch (err) {
137
+ if (err instanceof JwtVerificationError) {
138
+ console.log(err.reason); // e.g. "TokenExpired", "InvalidSignature"
139
+ }
140
+ return null;
141
+ }
49
142
  }
50
143
 
51
- verifyToken();
144
+ module.exports = { getUser };
52
145
  ```
53
146
 
54
- NodeJS
147
+ With promises instead of `async`/`await`:
55
148
 
56
149
  ```javascript
57
- var awsCognitoVerifier = require("aws-cognito-jwt-verifier");
58
- var verify = new awsCognitoVerifier.CognitoJwtVerifier();
59
- var result = verify.checkJwt("<token>", "<region>", "<userPoolID>");
60
-
61
- result
62
- .then((res) => {
63
- console.log(res); //json string result
150
+ verifier
151
+ .verify(token, {
152
+ region: "ap-southeast-1",
153
+ userPoolId: "ap-southeast-1_AbCdEfGhI",
154
+ tokenUse: "access",
155
+ clientId: "your-app-client-id",
64
156
  })
65
- .catch((err) => {
66
- console.log(err);
67
- });
157
+ .then((payload) => console.log(payload.sub))
158
+ .catch((err) => console.log(err.reason));
68
159
  ```
69
160
 
70
- ## Results
71
-
72
- If the token is valid, this will be the return, it is a **json string**, so you need to parse the result from your end to make this data more readable and usable.
73
-
74
- **SUCCESS**
75
- _I am sure this is what you need?_
76
-
77
- ```json
78
- {
79
- "status": true,
80
- "code": 200,
81
- "message": "Congrats! Your token is valid",
82
- "data": {
83
- "sub": "0f5c033b-bd32-44d2-a91a-b552ef17c3c2",
84
- "cognito:groups": ["Group1", "Group2"],
85
- "event_id": "e14169b1-284d-404f-8a95-717d9ae7d07e",
86
- "token_use": "access",
87
- "scope": "aws.cognito.signin.user.admin",
88
- "auth_time": 1587560894,
89
- "iss": "https://cognito-idp.ap-southeast-1.amazonaws.com/ap-southeast-xxx",
90
- "exp": 1587564494,
91
- "iat": 1587560894,
92
- "jti": "b7024e23-da89-4898-ba62-c6dd53b389bd",
93
- "client_id": "xxxxxx",
94
- "username": "0f5c033b-bd32-44d2-a91a-b552ef17c3c2"
161
+ ### JavaScript (ES modules, `import`)
162
+
163
+ Use this in `.mjs` files, or when your `package.json` has `"type": "module"`.
164
+
165
+ ```javascript
166
+ import { CognitoJwtVerifier, JwtVerificationError } from "aws-cognito-jwt-verifier";
167
+
168
+ const verifier = new CognitoJwtVerifier();
169
+
170
+ export async function getUser(token) {
171
+ try {
172
+ return await verifier.verify(token, {
173
+ region: "ap-southeast-1",
174
+ userPoolId: "ap-southeast-1_AbCdEfGhI",
175
+ tokenUse: "access",
176
+ clientId: "your-app-client-id",
177
+ });
178
+ } catch (err) {
179
+ if (err instanceof JwtVerificationError) {
180
+ console.log(err.reason);
181
+ }
182
+ return null;
95
183
  }
96
184
  }
97
185
  ```
98
186
 
99
- **FAIL**
187
+ In plain JavaScript, editors such as VS Code still read the bundled type definitions, so you get autocomplete for the options and for `err.reason`.
100
188
 
101
- ```json
102
- {
103
- "status": false,
104
- "code": 401,
105
- "message": "TokenExpiredError"
106
- }
189
+ ### Error reasons
190
+
191
+ `JwtVerificationError.reason` is one of:
192
+
193
+ `MalformedToken`, `UnsupportedAlgorithm`, `InvalidIssuer`, `InvalidKid`, `InvalidSignature`, `TokenExpired`, `TokenNotYetValid`, `InvalidTokenUse`, `InvalidClientId`, `JwksFetchFailed`, `InvalidConfiguration`.
194
+
195
+ ### Options
196
+
197
+ ```typescript
198
+ new CognitoJwtVerifier({
199
+ jwksCacheTtlMs: 3600000, // how long to reuse downloaded keys (default 1 hour)
200
+ fetchTimeoutMs: 5000, // timeout for downloading keys (default 5 seconds)
201
+ clockToleranceSec: 0, // allowed clock skew for exp/nbf (default 0)
202
+ fetch: customFetch, // optional fetch implementation, e.g. for a proxy
203
+ maxTokenLength: 16384, // longer tokens are rejected before decoding (default 16384)
204
+ });
107
205
  ```
108
206
 
109
- ## Contributing
207
+ Numbers must be real numbers. The constructor throws a `JwtVerificationError` with reason `InvalidConfiguration` for anything else: strings, `NaN`, `Infinity`, negative values, or `0` where it isn't allowed. A setting that can't be read would otherwise switch a check off quietly; for example, a `NaN` clock tolerance would let expired tokens through. Convert environment variables first:
208
+
209
+ ```javascript
210
+ new CognitoJwtVerifier({ clockToleranceSec: Number(process.env.JWT_CLOCK_TOLERANCE ?? 0) });
211
+ ```
212
+
213
+ How the public keys are downloaded:
214
+
215
+ - If a token uses a key ID the verifier hasn't seen, which happens after Cognito rotates its keys, it downloads the keys again, at most once a minute.
216
+ - If a download fails, it waits 5 seconds before trying again, so an outage doesn't send a download request for every incoming token.
217
+ - If refreshing expired keys fails, it keeps using the keys it already has for up to 24 hours, so a short Cognito outage doesn't reject every token.
218
+ - Redirects are not followed.
219
+
220
+ ## Legacy API (v1)
221
+
222
+ > **Warning:** `checkJwt()` is kept only so 1.x code keeps working. Use `verify()` in new code. `checkJwt()` is less safe in two ways:
223
+ >
224
+ > - It accepts **any** token from the user pool: ID tokens where you expect access tokens, and tokens issued to **any** app client in the pool.
225
+ > - It always returns a string, even when the token is invalid, and a non-empty string is always truthy. Code like `if (await verifier.checkJwt(...))` lets **every** token through. Always `JSON.parse()` the result and check `status === true`.
226
+
227
+ `checkJwt()` still works the way it did in 1.x. It resolves, and never rejects, with a **JSON string**:
228
+
229
+ TypeScript:
230
+
231
+ ```typescript
232
+ import { CognitoJwtVerifier, type CheckJwtResult } from "aws-cognito-jwt-verifier";
233
+
234
+ const verifier = new CognitoJwtVerifier();
235
+ const result: CheckJwtResult = JSON.parse(
236
+ await verifier.checkJwt(token, "ap-southeast-1", "ap-southeast-1_AbCdEfGhI"),
237
+ );
238
+ // { status: true, code: 200, message: "Congrats! Your token is valid", data: { ...payload } }
239
+ // { status: false, code: 401, message: "TokenExpiredError" }
240
+ ```
241
+
242
+ JavaScript:
243
+
244
+ ```javascript
245
+ const { CognitoJwtVerifier } = require("aws-cognito-jwt-verifier");
246
+
247
+ const verifier = new CognitoJwtVerifier();
248
+ verifier.checkJwt(token, "ap-southeast-1", "ap-southeast-1_AbCdEfGhI").then((res) => {
249
+ const result = JSON.parse(res);
250
+ console.log(result.status, result.message);
251
+ });
252
+ ```
253
+
254
+ ## Upgrading from 1.x
255
+
256
+ The full list of changes is in [CHANGELOG.md](CHANGELOG.md).
257
+
258
+ - Requires Node.js 20 or later. `axios`, `jsonwebtoken` and `jwk-to-pem` are no longer needed.
259
+ - Fixes a bug where tokens signed with the first key in the user pool's JWKS were always rejected.
260
+ - An unknown `kid` now returns `"Invalid kid"` instead of failing with an internal error.
261
+ - Error messages no longer include values taken from the token (such as `kid`, `iss` or `alg`), so they are safe to log.
262
+ - Tokens must be strict base64url, so each token has exactly one valid spelling. Tokens longer than `maxTokenLength` (16384 characters by default) are rejected.
263
+ - `getPublicKey()` only accepts Cognito issuer URLs (`https://cognito-idp.<region>.amazonaws.com/<userPoolId>`).
264
+ - Constructor options are validated. Invalid values, such as a string or `NaN` for `clockToleranceSec`, now throw instead of being used.
265
+ - Error messages no longer contain the token, and errors are no longer written to `console.log`.
266
+ - `checkJwt()` and `getPublicKey()` keep their signatures. `getPublicKey()` now returns every key.
267
+ - `checkJwt()` returns error messages in the 1.x format, such as `TokenExpiredError` and `JsonWebTokenError`. A malformed token now gives `"Not a valid JWT Token"`, without the token itself.
268
+
269
+ ## Security notes
270
+
271
+ - **Hard-code the region and user pool ID, or read them from your own configuration.** Never take them from the request or from the token itself. Anyone can create their own Cognito user pool, so an app that verifies against whichever pool a token names would accept an attacker's tokens.
272
+ - **Always set `tokenUse` and `clientId`.** Passing `null` accepts ID tokens where you expect access tokens, and tokens issued to any app client in the pool.
273
+ - **Revoked tokens stay valid until they expire.** Verification happens locally, without calling AWS, so a token that was revoked (for example with Cognito's `RevokeToken` or global sign-out) still passes until its `exp` time. Keep token lifetimes short. If you need instant revocation, also keep a blocklist of the `jti` or `origin_jti` claim.
274
+ - **Only show `err.reason` or a generic message to users.** Error messages never include values from the token, but they're meant for your logs, not for end users.
275
+
276
+ To report a security problem, please follow [SECURITY.md](SECURITY.md) instead of opening a public issue.
277
+
278
+ ## Development
279
+
280
+ ```bash
281
+ npm install
282
+ npm test # build with tsc, then run the tests with node --test
283
+ npm run check # typecheck + lint + format check + tests (also runs before npm publish)
284
+ npm run format # format the code with Prettier
285
+ ```
286
+
287
+ Project layout:
288
+
289
+ ```text
290
+ src/
291
+ index.ts public exports (the only entry point)
292
+ verifier.ts CognitoJwtVerifier: verify(), plus the legacy checkJwt() and getPublicKey()
293
+ token.ts splitting and decoding a JWT, algorithm and signature checks
294
+ claims.ts issuer, expiry, token_use and client ID checks
295
+ jwks.ts downloading and caching the user pool's public keys
296
+ issuer.ts building and validating Cognito issuer URLs
297
+ options.ts constructor option defaults and validation
298
+ legacy.ts the v1.x checkJwt() result format
299
+ errors.ts JwtVerificationError and its reasons
300
+ types.ts public TypeScript types
301
+ test/ tests run against the built dist/, the way users load the package
302
+ scripts/ check-real-token.js, for testing against a real user pool
303
+ ```
304
+
305
+ To check the build against real tokens from your own user pool (tokens are read from environment variables and never printed):
306
+
307
+ ```bash
308
+ COGNITO_REGION=ap-southeast-1 COGNITO_USER_POOL_ID=ap-southeast-1_AbCdEfGhI \
309
+ COGNITO_CLIENT_ID=your-app-client-id ACCESS_TOKEN=eyJ... ID_TOKEN=eyJ... \
310
+ npm run check:real-token
311
+ ```
312
+
313
+ ### Releasing
314
+
315
+ Releases are published to npm by GitHub Actions ([release.yml](.github/workflows/release.yml)) when a version tag is pushed.
110
316
 
111
- Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
317
+ 1. Commit your changes and add an entry to [CHANGELOG.md](CHANGELOG.md).
318
+ 2. Bump the version. This updates `package.json`, commits, and creates the `vX.Y.Z` tag:
319
+ ```bash
320
+ npm version patch # bug fixes 2.0.0 -> 2.0.1
321
+ npm version minor # new features 2.0.0 -> 2.1.0
322
+ npm version major # breaking changes 2.0.0 -> 3.0.0
323
+ ```
324
+ 3. Push the commit and the tag:
325
+ ```bash
326
+ git push --follow-tags
327
+ ```
112
328
 
113
- Please make sure to update tests as appropriate.
329
+ The workflow runs every check on Node 20, 22 and 24, makes sure the tag matches `package.json`, and publishes. Prereleases such as `2.1.0-beta.0` (made with `npm version prerelease --preid=beta`) are published under the `beta` dist-tag, so `npm install aws-cognito-jwt-verifier` keeps installing the latest stable version.
114
330
 
115
331
  ## License
116
332
 
117
- [MIT](https://choosealicense.com/licenses/mit/)
333
+ [MIT](LICENSE)
@@ -0,0 +1,10 @@
1
+ import type { JsonObject } from "./token";
2
+ import type { CognitoJwtPayload, VerifyOptions } from "./types";
3
+ /** @throws JwtVerificationError with reason `InvalidIssuer`. */
4
+ export declare function assertIssuer(payload: JsonObject, issuer: string): void;
5
+ export interface ClaimRules {
6
+ clockToleranceSec: number;
7
+ tokenUse: VerifyOptions["tokenUse"];
8
+ clientId: VerifyOptions["clientId"];
9
+ }
10
+ export declare function assertClaims(payload: JsonObject, rules: ClaimRules, nowSec?: number): CognitoJwtPayload;
package/dist/claims.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertIssuer = assertIssuer;
4
+ exports.assertClaims = assertClaims;
5
+ const errors_1 = require("./errors");
6
+ /** @throws JwtVerificationError with reason `InvalidIssuer`. */
7
+ function assertIssuer(payload, issuer) {
8
+ if (payload.iss !== issuer) {
9
+ throw new errors_1.JwtVerificationError("InvalidIssuer", "Invalid issuer");
10
+ }
11
+ }
12
+ function assertClaims(payload, rules, nowSec = Math.floor(Date.now() / 1000)) {
13
+ const { clockToleranceSec, tokenUse, clientId } = rules;
14
+ if (typeof payload.exp !== "number") {
15
+ throw new errors_1.JwtVerificationError("MalformedToken", "Token has no exp claim");
16
+ }
17
+ if (nowSec >= payload.exp + clockToleranceSec) {
18
+ throw new errors_1.JwtVerificationError("TokenExpired", "Token expired");
19
+ }
20
+ if (typeof payload.nbf === "number" && nowSec + clockToleranceSec < payload.nbf) {
21
+ throw new errors_1.JwtVerificationError("TokenNotYetValid", "Token not active yet");
22
+ }
23
+ if (tokenUse !== null && payload.token_use !== tokenUse) {
24
+ throw new errors_1.JwtVerificationError("InvalidTokenUse", `Expected an ${tokenUse} token`);
25
+ }
26
+ if (clientId !== null) {
27
+ const allowed = Array.isArray(clientId) ? clientId : [clientId];
28
+ // Cognito puts the app client in `client_id` for access tokens and in `aud` for ID tokens.
29
+ const actual = payload.token_use === "id" ? payload.aud : payload.client_id;
30
+ if (typeof actual !== "string" || !allowed.includes(actual)) {
31
+ throw new errors_1.JwtVerificationError("InvalidClientId", "Client ID not allowed");
32
+ }
33
+ }
34
+ return payload;
35
+ }
36
+ //# sourceMappingURL=claims.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claims.js","sourceRoot":"","sources":["../src/claims.ts"],"names":[],"mappings":";;AAKA,oCAIC;AAQD,oCA+BC;AAhDD,qCAAgD;AAIhD,gEAAgE;AAChE,SAAgB,YAAY,CAAC,OAAmB,EAAE,MAAc;IAC9D,IAAI,OAAO,CAAC,GAAG,KAAK,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,6BAAoB,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;IACpE,CAAC;AACH,CAAC;AAQD,SAAgB,YAAY,CAC1B,OAAmB,EACnB,KAAiB,EACjB,SAAiB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IAE9C,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAExD,IAAI,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QACpC,MAAM,IAAI,6BAAoB,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,MAAM,IAAI,OAAO,CAAC,GAAG,GAAG,iBAAiB,EAAE,CAAC;QAC9C,MAAM,IAAI,6BAAoB,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;IAClE,CAAC;IACD,IAAI,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ,IAAI,MAAM,GAAG,iBAAiB,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;QAChF,MAAM,IAAI,6BAAoB,CAAC,kBAAkB,EAAE,sBAAsB,CAAC,CAAC;IAC7E,CAAC;IAED,IAAI,QAAQ,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;QACxD,MAAM,IAAI,6BAAoB,CAAC,iBAAiB,EAAE,eAAe,QAAQ,QAAQ,CAAC,CAAC;IACrF,CAAC;IAED,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;QAChE,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,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC5D,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 clientId: VerifyOptions[\"clientId\"];\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 if (tokenUse !== null && payload.token_use !== tokenUse) {\n throw new JwtVerificationError(\"InvalidTokenUse\", `Expected an ${tokenUse} token`);\n }\n\n if (clientId !== null) {\n const allowed = Array.isArray(clientId) ? clientId : [clientId];\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\" || !allowed.includes(actual)) {\n throw new JwtVerificationError(\"InvalidClientId\", \"Client ID not allowed\");\n }\n }\n\n return payload as CognitoJwtPayload;\n}\n"]}
@@ -0,0 +1,10 @@
1
+ export type JwtErrorReason = "MalformedToken" | "UnsupportedAlgorithm" | "InvalidIssuer" | "InvalidKid" | "InvalidSignature" | "TokenExpired" | "TokenNotYetValid" | "InvalidTokenUse" | "InvalidClientId" | "JwksFetchFailed" | "InvalidConfiguration";
2
+ /** Thrown by `CognitoJwtVerifier.verify()` when a token is rejected. */
3
+ export declare class JwtVerificationError extends Error {
4
+ readonly reason: JwtErrorReason;
5
+ constructor(reason: JwtErrorReason, message: string, options?: {
6
+ cause?: unknown;
7
+ });
8
+ /** Error name as reported by v1.x (jsonwebtoken naming), used by `checkJwt()`. */
9
+ get legacyName(): string;
10
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JwtVerificationError = void 0;
4
+ /** Thrown by `CognitoJwtVerifier.verify()` when a token is rejected. */
5
+ class JwtVerificationError extends Error {
6
+ reason;
7
+ constructor(reason, message, options) {
8
+ super(message, options);
9
+ this.name = "JwtVerificationError";
10
+ this.reason = reason;
11
+ }
12
+ /** Error name as reported by v1.x (jsonwebtoken naming), used by `checkJwt()`. */
13
+ get legacyName() {
14
+ switch (this.reason) {
15
+ case "TokenExpired":
16
+ return "TokenExpiredError";
17
+ case "TokenNotYetValid":
18
+ return "NotBeforeError";
19
+ default:
20
+ return "JsonWebTokenError";
21
+ }
22
+ }
23
+ }
24
+ exports.JwtVerificationError = JwtVerificationError;
25
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAaA,wEAAwE;AACxE,MAAa,oBAAqB,SAAQ,KAAK;IACpC,MAAM,CAAiB;IAEhC,YAAY,MAAsB,EAAE,OAAe,EAAE,OAA6B;QAChF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,kFAAkF;IAClF,IAAI,UAAU;QACZ,QAAQ,IAAI,CAAC,MAAM,EAAE,CAAC;YACpB,KAAK,cAAc;gBACjB,OAAO,mBAAmB,CAAC;YAC7B,KAAK,kBAAkB;gBACrB,OAAO,gBAAgB,CAAC;YAC1B;gBACE,OAAO,mBAAmB,CAAC;QAC/B,CAAC;IACH,CAAC;CACF;AApBD,oDAoBC","sourcesContent":["export type JwtErrorReason =\n | \"MalformedToken\"\n | \"UnsupportedAlgorithm\"\n | \"InvalidIssuer\"\n | \"InvalidKid\"\n | \"InvalidSignature\"\n | \"TokenExpired\"\n | \"TokenNotYetValid\"\n | \"InvalidTokenUse\"\n | \"InvalidClientId\"\n | \"JwksFetchFailed\"\n | \"InvalidConfiguration\";\n\n/** Thrown by `CognitoJwtVerifier.verify()` when a token is rejected. */\nexport class JwtVerificationError extends Error {\n readonly reason: JwtErrorReason;\n\n constructor(reason: JwtErrorReason, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"JwtVerificationError\";\n this.reason = reason;\n }\n\n /** Error name as reported by v1.x (jsonwebtoken naming), used by `checkJwt()`. */\n get legacyName(): string {\n switch (this.reason) {\n case \"TokenExpired\":\n return \"TokenExpiredError\";\n case \"TokenNotYetValid\":\n return \"NotBeforeError\";\n default:\n return \"JsonWebTokenError\";\n }\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1 +1,4 @@
1
- export * from "./cognito-jwt-verifier";
1
+ export { CognitoJwtVerifier } from "./verifier";
2
+ export { JwtVerificationError } from "./errors";
3
+ export type { JwtErrorReason } from "./errors";
4
+ export type { CheckJwtResult, CognitoJwtPayload, CognitoJwtVerifierOptions, FetchLike, Jwk, VerifyOptions, } from "./types";
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
- function __export(m) {
3
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
- }
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- __export(require("./cognito-jwt-verifier"));
3
+ exports.JwtVerificationError = exports.CognitoJwtVerifier = void 0;
4
+ var verifier_1 = require("./verifier");
5
+ Object.defineProperty(exports, "CognitoJwtVerifier", { enumerable: true, get: function () { return verifier_1.CognitoJwtVerifier; } });
6
+ var errors_1 = require("./errors");
7
+ Object.defineProperty(exports, "JwtVerificationError", { enumerable: true, get: function () { return errors_1.JwtVerificationError; } });
7
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,4CAAuC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uCAAgD;AAAvC,8GAAA,kBAAkB,OAAA;AAC3B,mCAAgD;AAAvC,8GAAA,oBAAoB,OAAA","sourcesContent":["export { CognitoJwtVerifier } from \"./verifier\";\nexport { JwtVerificationError } from \"./errors\";\nexport type { JwtErrorReason } from \"./errors\";\nexport type {\n CheckJwtResult,\n CognitoJwtPayload,\n CognitoJwtVerifierOptions,\n FetchLike,\n Jwk,\n VerifyOptions,\n} from \"./types\";\n"]}
@@ -0,0 +1,4 @@
1
+ export declare function issuerFor(region: string, userPoolId: string): string;
2
+ export declare function parseIssuerUrl(url: unknown): string;
3
+ /** URL of the user pool's public keys. */
4
+ export declare function jwksUrl(issuer: string): string;
package/dist/issuer.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.issuerFor = issuerFor;
4
+ exports.parseIssuerUrl = parseIssuerUrl;
5
+ exports.jwksUrl = jwksUrl;
6
+ const errors_1 = require("./errors");
7
+ const REGION_RE = /^[a-z]{2}(-[a-z]+)+-\d+$/;
8
+ const USER_POOL_ID_RE = /^[a-z]{2}(-[a-z]+)+-\d+_[0-9A-Za-z]+$/;
9
+ const ISSUER_URL_RE = /^https:\/\/cognito-idp\.([a-z0-9-]+)\.amazonaws\.com\/([A-Za-z0-9_-]+)$/;
10
+ function issuerFor(region, userPoolId) {
11
+ if (typeof region !== "string" || !REGION_RE.test(region)) {
12
+ throw new errors_1.JwtVerificationError("InvalidConfiguration", "Invalid region");
13
+ }
14
+ if (typeof userPoolId !== "string" || !USER_POOL_ID_RE.test(userPoolId)) {
15
+ throw new errors_1.JwtVerificationError("InvalidConfiguration", "Invalid user pool ID");
16
+ }
17
+ return `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`;
18
+ }
19
+ function parseIssuerUrl(url) {
20
+ const match = typeof url === "string" ? ISSUER_URL_RE.exec(url) : null;
21
+ if (!match) {
22
+ throw new errors_1.JwtVerificationError("InvalidConfiguration", "Not a Cognito issuer URL");
23
+ }
24
+ const [, region = "", userPoolId = ""] = match;
25
+ return issuerFor(region, userPoolId);
26
+ }
27
+ /** URL of the user pool's public keys. */
28
+ function jwksUrl(issuer) {
29
+ return `${issuer}/.well-known/jwks.json`;
30
+ }
31
+ //# sourceMappingURL=issuer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"issuer.js","sourceRoot":"","sources":["../src/issuer.ts"],"names":[],"mappings":";;AAMA,8BAQC;AAED,wCAOC;AAGD,0BAEC;AA5BD,qCAAgD;AAEhD,MAAM,SAAS,GAAG,0BAA0B,CAAC;AAC7C,MAAM,eAAe,GAAG,uCAAuC,CAAC;AAChE,MAAM,aAAa,GAAG,yEAAyE,CAAC;AAEhG,SAAgB,SAAS,CAAC,MAAc,EAAE,UAAkB;IAC1D,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,gBAAgB,CAAC,CAAC;IAC3E,CAAC;IACD,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACxE,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,sBAAsB,CAAC,CAAC;IACjF,CAAC;IACD,OAAO,uBAAuB,MAAM,kBAAkB,UAAU,EAAE,CAAC;AACrE,CAAC;AAED,SAAgB,cAAc,CAAC,GAAY;IACzC,MAAM,KAAK,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACvE,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,6BAAoB,CAAC,sBAAsB,EAAE,0BAA0B,CAAC,CAAC;IACrF,CAAC;IACD,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,UAAU,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;IAC/C,OAAO,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AACvC,CAAC;AAED,0CAA0C;AAC1C,SAAgB,OAAO,CAAC,MAAc;IACpC,OAAO,GAAG,MAAM,wBAAwB,CAAC;AAC3C,CAAC","sourcesContent":["import { JwtVerificationError } from \"./errors\";\n\nconst REGION_RE = /^[a-z]{2}(-[a-z]+)+-\\d+$/;\nconst USER_POOL_ID_RE = /^[a-z]{2}(-[a-z]+)+-\\d+_[0-9A-Za-z]+$/;\nconst ISSUER_URL_RE = /^https:\\/\\/cognito-idp\\.([a-z0-9-]+)\\.amazonaws\\.com\\/([A-Za-z0-9_-]+)$/;\n\nexport function issuerFor(region: string, userPoolId: string): string {\n if (typeof region !== \"string\" || !REGION_RE.test(region)) {\n throw new JwtVerificationError(\"InvalidConfiguration\", \"Invalid region\");\n }\n if (typeof userPoolId !== \"string\" || !USER_POOL_ID_RE.test(userPoolId)) {\n throw new JwtVerificationError(\"InvalidConfiguration\", \"Invalid user pool ID\");\n }\n return `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`;\n}\n\nexport function parseIssuerUrl(url: unknown): string {\n const match = typeof url === \"string\" ? ISSUER_URL_RE.exec(url) : null;\n if (!match) {\n throw new JwtVerificationError(\"InvalidConfiguration\", \"Not a Cognito issuer URL\");\n }\n const [, region = \"\", userPoolId = \"\"] = match;\n return issuerFor(region, userPoolId);\n}\n\n/** URL of the user pool's public keys. */\nexport function jwksUrl(issuer: string): string {\n return `${issuer}/.well-known/jwks.json`;\n}\n"]}
package/dist/jwks.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { KeyObject } from "node:crypto";
2
+ import type { FetchLike, Jwk } from "./types";
3
+ export interface PublicKey {
4
+ jwk: Jwk;
5
+ key: KeyObject;
6
+ }
7
+ export interface JwksCacheOptions {
8
+ ttlMs: number;
9
+ fetchTimeoutMs: number;
10
+ fetch: FetchLike;
11
+ }
12
+ export declare class JwksCache {
13
+ #private;
14
+ constructor(options: JwksCacheOptions);
15
+ /** @throws JwtVerificationError with reason `InvalidKid` or `JwksFetchFailed`. */
16
+ getKey(issuer: string, kid: string): Promise<KeyObject>;
17
+ /** @throws JwtVerificationError with reason `JwksFetchFailed`. */
18
+ getKeys(issuer: string): Promise<ReadonlyMap<string, PublicKey>>;
19
+ }