@mi9-identity/jwt-verifier 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # @mi9-identity/jwt-verifier
2
+
3
+ All notable changes to this package are documented here. **Manually maintained** —
4
+ versions are semver and the three publishable `@mi9-identity/*` packages are
5
+ released in lockstep at the same version. Releases up to `2026.8.21` used calver
6
+ (`YYYY.M.D`).
7
+
8
+ ## 1.0.0
9
+
10
+ - **First public release on npmjs.com**, under the **Apache-2.0** license. Earlier versions were published only to an internal Mi9 registry.
11
+ - **Versioning changes from calver (`YYYY.M.D`) to semver**, starting at `1.0.0`. The three `@mi9-identity/*` packages stay in lockstep at one version. Issuer compatibility is still signalled by the `/api/v{N}` URL, not by the package version.
12
+ - **No functional change compared with `2026.8.21`** — same public API, same wire shapes, same behaviour.
13
+
14
+ ## 2026.8.21
15
+
16
+ - **BREAKING — `mi9IdentityEndpoints()` is replaced by `mi9IdentityJwksEndpoint()`, and it returns a bare `string`.** Inbound verification is this package's only role, so it no longer derives the mint (`/oauth/token`) or credential-claim (`/credentials/me`) URLs; those moved to `mi9IdentityEndpoints()` in `@mi9-identity/token-client`, which returns `{ tokenEndpoint, credentialEndpoint }`. Deriving all three here forced an outbound-only consumer to install this package — and its `jose` dependency — to concatenate two strings.
17
+
18
+ Migration is mechanical:
19
+
20
+ ```diff
21
+ - import { mi9IdentityEndpoints } from '@mi9-identity/jwt-verifier';
22
+ - const { jwksUri } = mi9IdentityEndpoints(issuer);
23
+ + import { mi9IdentityJwksEndpoint } from '@mi9-identity/jwt-verifier';
24
+ + const jwksUri = mi9IdentityJwksEndpoint(issuer);
25
+ ```
26
+
27
+ If you read `tokenEndpoint` or `credentialEndpoint` off this package, take them from `@mi9-identity/token-client` instead. TypeScript flags every affected call site — there is no silent-`undefined` path. Trailing-slash stripping and the no-`/api/v{N}`-literal guarantee (ADR-13) are unchanged.
28
+
29
+ ## 2026.7.24
30
+
31
+ - **`jwksFetchTimeoutMs` option.** Configures the per-fetch timeout for JWKS downloads (`jose`'s `timeoutDuration`). Default 5_000 ms, matching `jose`'s own default — no behavior change for existing consumers that don't set it.
32
+
33
+ ## 2026.6.1
34
+
35
+ - The optional `logger` now emits a single `warn` (`jwt-verifier.jwks_unavailable`) when verification fails because the JWKS is unavailable (fetch failed and no fresh cached key set). Previously the option was accepted but never written to — observability beyond that one event stays the adapter's job.
36
+
37
+ ## 2026.5.27
38
+
39
+ - **Multiple audiences per token** (ADR-6 amended). The verifier accepts both `aud` forms — a scalar string and a JSON array (array `aud` is no longer rejected); `AuthContext.aud` widens to `string | string[]`, matched by OR-membership against the configured audiences.
40
+ - **`/api/v1` cutover** (ADR-13). Consumers point their issuer URL at the versioned value (`.../api/v1`); the `mi9IdentityEndpoints()` helper derives the three Mi9 endpoint URLs from that single value (the package carries no `/api/v{N}` literal).
41
+
42
+ ## 0.1.0
43
+
44
+ - Version reset to pre-1.0 (`0.1.0`); the earlier `1.0.0` placeholder is superseded.
45
+ - **Breaking**: wire-naming aligned with ADR-12. Mi9 custom-claim namespace URL keys changed from snake_case to camelCase: `https://mi9retail.com/retailerId`, `https://mi9retail.com/storeCode`, `https://mi9retail.com/authClass`.
46
+ - **Breaking**: `AuthContext` field renames: `retailer_id` → `retailerId`, `store_code` → `storeCode`. Consumers update `req.auth.retailer_id` → `req.auth.retailerId` and `req.auth.store_code` → `req.auth.storeCode`.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mi9 Retail
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,220 @@
1
+ # @mi9-identity/jwt-verifier
2
+
3
+ Pure RS256/JWKS verifier for Mi9-issued JWTs. Framework-agnostic — used as
4
+ the verification core by `@mi9-identity/auth-middleware-express`, raw HTTP handlers,
5
+ and operational scripts.
6
+
7
+ Apache-2.0-licensed and free to use; access to the Mi9 Identity Platform whose
8
+ tokens it verifies is governed by your commercial agreement with Mi9 Retail.
9
+
10
+ ## Which package do I need?
11
+
12
+ | Package | Use it when |
13
+ | --- | --- |
14
+ | [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client) | Your service **calls** a Mi9 API and needs a token. |
15
+ | **`@mi9-identity/jwt-verifier`** (this one) | Your service **receives** Mi9-issued tokens and must verify them. |
16
+ | [`@mi9-identity/auth-middleware-express`](https://www.npmjs.com/package/@mi9-identity/auth-middleware-express) | The same, and your service is an Express 5 app — it wraps this verifier as middleware. |
17
+
18
+ A service that both calls Mi9 APIs and serves Mi9-authenticated requests
19
+ installs two of them.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install @mi9-identity/jwt-verifier@1.0.0
25
+ ```
26
+
27
+ Versions are **semver**, and the three `@mi9-identity/*` packages
28
+ (`jwt-verifier`, `token-client`, `auth-middleware-express`) are released in
29
+ lockstep at the same version — pin an exact version rather than a `^` or `~`
30
+ range. A breaking change to the HTTP wire shapes ships as a new API path
31
+ version (`/api/v2`), not as a package major bump.
32
+
33
+ The package targets ESM and Node 24+. Use `await import()` if you consume it
34
+ from CommonJS.
35
+
36
+ ## Configuration
37
+
38
+ Verifying needs **no credential**: the signing keys are public and served from
39
+ the issuer's JWKS URL. You need two values, both given to you by your Mi9
40
+ contact when your service is registered — the issuer URL, and the audience
41
+ identifier assigned to your service.
42
+
43
+ Configure one issuer URL and one audience:
44
+
45
+ ```
46
+ MI9_IDENTITY_ISSUER # https://identity.mi9retail.com/api/v1 — matches the JWT `iss` claim
47
+ MI9_IDENTITY_AUDIENCE # this service's own audience identifier (a full URL)
48
+ ```
49
+
50
+ The issuer URL is the **versioned** one: `/api/v1` (or a future `/api/v2`) is
51
+ part of the configured value, and every endpoint URL is derived from it.
52
+
53
+ Audience values are always full URLs of the form `https://<host>/<path>`, never
54
+ a bare service name — for example `https://merchant.mi9retail.com/api`, not
55
+ `merchant`. A token is valid for your service when your configured audience
56
+ appears in its `aud`.
57
+
58
+ ## Usage
59
+
60
+ ```ts
61
+ import { createVerifier, mi9IdentityJwksEndpoint } from '@mi9-identity/jwt-verifier';
62
+
63
+ const jwksUri = mi9IdentityJwksEndpoint('https://identity.mi9retail.com/api/v1');
64
+
65
+ const verifier = createVerifier({
66
+ jwksUri,
67
+ issuers: ['https://identity.mi9retail.com/api/v1'],
68
+ audience: 'https://merchant.mi9retail.com/api',
69
+ });
70
+
71
+ const ctx = await verifier.verify(token);
72
+ console.log(ctx.retailerId, ctx.product);
73
+ ```
74
+
75
+ ### `mi9IdentityJwksEndpoint` — single-source-of-truth helper
76
+
77
+ Consumers configure one issuer URL (`MI9_IDENTITY_ISSUER`) that matches the
78
+ JWT `iss` claim — e.g. `https://identity.mi9retail.com/api/v1`. The helper
79
+ appends the bare JWKS path to that single value. It contains no `/api/v1`
80
+ literal; the version lives in the caller's issuer URL, so a future `v2`
81
+ cutover is a one-env-var change at each consumer.
82
+
83
+ Inbound verification is this package's only role, so the mint and
84
+ credential-claim URLs are **not** derived here — `mi9IdentityEndpoints(issuer)`
85
+ in [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client)
86
+ returns `{ tokenEndpoint, credentialEndpoint }`. Neither package depends on the
87
+ other, so an outbound-only service never installs a JOSE stack for a string
88
+ concat.
89
+
90
+ The Mi9 Identity Service does **not** publish
91
+ `/.well-known/openid-configuration`. Generic OAuth client libraries that
92
+ auto-discover will fail; configure the issuer URL, the JWKS URI, and the token
93
+ endpoint explicitly, as above.
94
+
95
+ ## `VerifierOptions` reference
96
+
97
+ | Option | Required | Default | Purpose |
98
+ | --- | --- | --- | --- |
99
+ | `jwksUri` | **yes** | — | Full JWKS URL; use `mi9IdentityJwksEndpoint(...)`. |
100
+ | `issuers` | **yes** | — | Allowlist of acceptable `iss` values (no wildcards). |
101
+ | `audience` | **yes** | — | `string \| string[]` — the token's `aud` must intersect this. |
102
+ | `clockToleranceSec` | no | `30` | Leeway for `exp`/`iat`/`nbf`, in seconds. |
103
+ | `jwksCacheTtlMs` | no | `3_600_000` (1 h) | How long a fetched JWKS is served before a re-fetch. |
104
+ | `jwksInitialJitterMs` | no | `30_000` | Random delay before the first JWKS fetch — thundering-herd guard. |
105
+ | `jwksCooldownMs` | no | `30_000` | Min interval between unknown-`kid` re-fetches. |
106
+ | `jwksFetchTimeoutMs` | no | `5_000` | Per-fetch timeout for a JWKS download (`jose`'s `timeoutDuration`). |
107
+ | `logger` | no | none | Optional pino-shaped `Logger`; see [Logging](#logging) below. |
108
+
109
+ ## Logging
110
+
111
+ Pass a pino-compatible `Logger` to receive observability events from the
112
+ verifier core. The verifier emits exactly **one** log event:
113
+
114
+ - **`warn`** — `event: 'jwks_unavailable'`, message `'jwt-verifier.jwks_unavailable'`:
115
+ fired when `JwksUnavailableError` is thrown (JWKS fetch failed and no fresh
116
+ cache is available). This is the only event the framework-agnostic core emits;
117
+ richer observability (per-request audit, scope/retailer guard events) is the
118
+ adapter's job.
119
+
120
+ See the **JWKS availability** section below for the failure semantics this event
121
+ signals.
122
+
123
+ ## Validation pipeline
124
+
125
+ 1. Extract Bearer token (caller's responsibility — verifier accepts the raw
126
+ string).
127
+ 2. Decode header, read `kid` and `iss`.
128
+ 3. `iss` must be in the configured allowlist.
129
+ 4. Fetch JWKS from the explicitly-configured `jwksUri` (the verifier never
130
+ derives the URL from `iss`). The underlying `jose.createRemoteJWKSet`
131
+ caches the document for `jwksCacheTtlMs` (default 1h) and applies a
132
+ `cooldownDuration` (default 30s) between unknown-`kid` refreshes — so an
133
+ unknown `kid` triggers a single re-fetch and is then memoised for the
134
+ cooldown window before retrying.
135
+ 5. Verify RS256 signature against the key for `kid`.
136
+ 6. Validate `aud` (OR-membership against configured audiences) and
137
+ `exp` / `nbf` / `iat` with a 30-second default clock skew leeway.
138
+ 7. Extract custom claims and return `AuthContext`.
139
+
140
+ ## `AuthContext`
141
+
142
+ Returned on success:
143
+
144
+ | Field | Type | Notes |
145
+ | --- | --- | --- |
146
+ | `iss` | `string` | Issuer (versioned, e.g. `…/api/v1`). |
147
+ | `sub` | `string` | **Is the `clientId`** (UUIDv7) — no separate `clientId` claim. |
148
+ | `aud` | `string \| string[]` | Scalar for one audience, array for several. |
149
+ | `exp` / `iat` / `nbf` | `number` | Unix seconds. |
150
+ | `jti` | `string` | Token id. |
151
+ | `scope` | `string` | Raw space-separated scope string. **Empty today** — Mi9 credentials are provisioned with no authorized scopes, so do not authorize on it. |
152
+ | `scopes` | `readonly string[]` | Pre-split, deduped view of `scope`. Empty today. |
153
+ | `retailerId` | `string` | From the `https://mi9retail.com/retailerId` claim. |
154
+ | `product` | `string` | Product the credential belongs to. |
155
+ | `storeCode` | `string \| null` | Always present; `null` unless the credential is store-bound. |
156
+
157
+ The `authClass` claim (issuer-internal, used only by the rotation-pickup
158
+ path) is **stripped** before `AuthContext` is returned. The verifier
159
+ exposes only an explicit allowlist of fields — anything else is dropped, so
160
+ future internal claims added by the issuer cannot leak to gateway code.
161
+
162
+ ## Error taxonomy
163
+
164
+ Typed errors thrown on failure:
165
+
166
+ | Error | When |
167
+ | --------------------------- | ---------------------------------------------- |
168
+ | `MissingTokenError` | (Adapter-level — the verifier itself receives a string.) |
169
+ | `InvalidTokenError` | Signature mismatch, malformed token, decode failure. |
170
+ | `TokenExpiredError` | `exp` in the past (after leeway). |
171
+ | `IssuerNotAllowedError` | `iss` not in allowlist. |
172
+ | `AudienceMismatchError` | `aud` does not intersect configured audiences. |
173
+ | `AlgorithmNotAllowedError` | Header `alg` ≠ `RS256`. |
174
+ | `MissingRequiredClaimError` | Required claim absent (e.g. `retailerId`). |
175
+ | `JwksUnavailableError` | JWKS fetch failed and no *fresh* cached key set (within `jwksCacheTtlMs`) is available. |
176
+
177
+ ## JWKS availability
178
+
179
+ `jose.createRemoteJWKSet` serves keys from its in-memory cache only while the
180
+ cache is **fresh** — younger than `jwksCacheTtlMs` (default 1h). Once the cache
181
+ is stale, the next `verify()` triggers a refetch; if that refetch fails, the
182
+ verifier throws `JwksUnavailableError` (a `503`-shaped error). A *fresh* cache
183
+ is still served through a transient endpoint outage, so a blip shorter than the
184
+ TTL is invisible — but a stale cache is **not** used as a fallback. **The
185
+ verifier never falls back to an unauthenticated path; it never fails open.**
186
+
187
+ ### Unknown `kid` after signing-key rotation
188
+
189
+ A token signed by a newly-rotated signing key whose `kid` is not yet in the
190
+ cached JWKS maps to `InvalidTokenError` (401), not `JwksUnavailableError`
191
+ (503): the JWKS is reachable, the key is simply absent from it for now. `jose`
192
+ refetches once on an unknown `kid`, then memoises the miss for `jwksCooldownMs`
193
+ (default 30s) before retrying — so such tokens 401 for at most that window,
194
+ then recover on the next mint. This is deliberately conservative; the issuer
195
+ publishes a rotated signing key to the JWKS document ahead of minting tokens
196
+ under it, so the window should not arise in a normal rotation.
197
+
198
+ Signing-key rotation is otherwise transparent to consumers — there is nothing
199
+ to configure or rotate on your side.
200
+
201
+ ## Troubleshooting
202
+
203
+ | Symptom | Likely cause | Fix |
204
+ | --- | --- | --- |
205
+ | Requests fail with `JwksUnavailableError` (503) | The JWKS document is unreachable and no fresh cache is left | Transient; confirm your service can reach `${issuer}/.well-known/jwks.json`. |
206
+ | 401s right after a deploy or a signing-key rotation | The token was signed by a key not yet in the cached JWKS | Self-heals within `jwksCooldownMs`; callers recover on their next mint. |
207
+ | `AudienceMismatchError` | The configured audience is a bare name, or does not match the token's `aud` | Set it to the full-URL audience the issuer mints for your service. |
208
+ | `IssuerNotAllowedError` | The configured issuer URL omits the `/api/v1` path segment | Configure the versioned issuer URL, exactly as it appears in the token's `iss`. |
209
+
210
+ ---
211
+
212
+ Outbound token acquisition lives in
213
+ [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client);
214
+ the Express 5 adapter — scope/retailer guards and the RFC 6750 error mapping —
215
+ lives in
216
+ [`@mi9-identity/auth-middleware-express`](https://www.npmjs.com/package/@mi9-identity/auth-middleware-express).
217
+
218
+ ## License
219
+
220
+ Apache-2.0. The full text ships in the package as `LICENSE`.
@@ -0,0 +1,11 @@
1
+ import type { AuthContext } from './types.js';
2
+ /**
3
+ * Map a verified `jose` JWT payload into the canonical `AuthContext` surface,
4
+ * stripping anything that is not in the explicit allowlist.
5
+ *
6
+ * @param { Record<string, unknown> } payload The verified JWT payload from `jose.jwtVerify`.
7
+ * @returns { AuthContext } The canonical `AuthContext` projection.
8
+ * @throws { MissingRequiredClaimError } When any required claim is missing or malformed.
9
+ */
10
+ export declare const toAuthContext: (payload: Record<string, unknown>) => AuthContext;
11
+ //# sourceMappingURL=claims.d.ts.map
package/dist/claims.js ADDED
@@ -0,0 +1,82 @@
1
+ import { z } from 'zod';
2
+ import { MissingRequiredClaimError } from './errors.js';
3
+ /**
4
+ * UUIDv7 shape (8-4-4-4-12 hex with version nibble `7` and variant nibble in
5
+ * `[89ab]`). The issuer mints `clientId` as UUIDv7 per design doc §6, and
6
+ * `sub` IS `clientId` — this regex is the verifier's defense against an
7
+ * issuer that ever drifts off the contract.
8
+ */
9
+ const UUIDV7_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ /**
11
+ * The shape of namespaced custom claims emitted by the issuer. Issuer-internal
12
+ * claims (notably `authClass`) are intentionally NOT listed — `jose` surfaces
13
+ * them on `payload`, but the strip-and-allowlist below drops every key that
14
+ * is not in this schema's output.
15
+ *
16
+ * The schema is closed (no `.passthrough()`) on purpose — adding it would
17
+ * silently leak issuer-internal claims into `AuthContext`. Don't.
18
+ */
19
+ const claimsSchema = z.object({
20
+ iss: z.url(),
21
+ scope: z.string(),
22
+ exp: z.number().int(),
23
+ iat: z.number().int(),
24
+ nbf: z.number().int(),
25
+ jti: z.string().min(1),
26
+ sub: z.string().regex(UUIDV7_PATTERN),
27
+ 'https://mi9retail.com/product': z.string().min(1),
28
+ 'https://mi9retail.com/retailerId': z.string().min(1),
29
+ 'https://mi9retail.com/storeCode': z.union([z.string(), z.null()]),
30
+ aud: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
31
+ });
32
+ /**
33
+ * Whitespace-split + dedupe `scope` into a stable `scopes` array. Empty
34
+ * `scope` resolves to an empty array, NOT undefined — keeps the surface
35
+ * type predictable for guards.
36
+ *
37
+ * @param { string } scope The raw `scope` claim value.
38
+ * @returns { readonly string[] } The deduplicated list of scope strings.
39
+ */
40
+ const splitScopes = (scope) => {
41
+ const parts = scope
42
+ .trim()
43
+ .split(/\s+/u)
44
+ .filter((s) => s.length > 0);
45
+ return Array.from(new Set(parts));
46
+ };
47
+ /**
48
+ * Map a verified `jose` JWT payload into the canonical `AuthContext` surface,
49
+ * stripping anything that is not in the explicit allowlist.
50
+ *
51
+ * @param { Record<string, unknown> } payload The verified JWT payload from `jose.jwtVerify`.
52
+ * @returns { AuthContext } The canonical `AuthContext` projection.
53
+ * @throws { MissingRequiredClaimError } When any required claim is missing or malformed.
54
+ */
55
+ export const toAuthContext = (payload) => {
56
+ // `aud` may be a scalar string (single-audience token) or an array of
57
+ // strings (multi-audience token) per ADR-6 (amended). `jose.jwtVerify`
58
+ // already accepted both by membership; the schema below now mirrors that.
59
+ const parsed = claimsSchema.safeParse(payload);
60
+ if (!parsed.success) {
61
+ const issue = parsed.error.issues[0];
62
+ /* v8 ignore next -- defensive; Zod always produces at least one issue when safeParse fails */
63
+ const path = issue?.path.join('.') ?? '<unknown>';
64
+ throw new MissingRequiredClaimError(`Required claim missing or malformed: ${path}`);
65
+ }
66
+ const c = parsed.data;
67
+ return {
68
+ iss: c.iss,
69
+ sub: c.sub,
70
+ aud: c.aud,
71
+ exp: c.exp,
72
+ iat: c.iat,
73
+ nbf: c.nbf,
74
+ jti: c.jti,
75
+ scope: c.scope,
76
+ scopes: splitScopes(c.scope),
77
+ product: c['https://mi9retail.com/product'],
78
+ storeCode: c['https://mi9retail.com/storeCode'],
79
+ retailerId: c['https://mi9retail.com/retailerId'],
80
+ };
81
+ };
82
+ //# sourceMappingURL=claims.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Derive the Mi9 Identity JWKS URI from a single issuer URL. Inbound
3
+ * verification is this package's only role, so the mint and credential-claim
4
+ * endpoints belong to `@mi9-identity/token-client` — a service that verifies
5
+ * but never mints has no use for them, and deriving them here is what forced
6
+ * token-client consumers to install a JOSE stack for a string concat.
7
+ *
8
+ * @param { string } issuerUrl Configured issuer URL (matches the JWT `iss` claim, e.g. `https://identity.mi9retail.com/api/v1`). Trailing slash tolerated.
9
+ * @returns { string } Full JWKS URL.
10
+ */
11
+ export declare const mi9IdentityJwksEndpoint: (issuerUrl: string) => string;
12
+ //# sourceMappingURL=endpoints.d.ts.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Derive the Mi9 Identity JWKS URI from a single issuer URL. Inbound
3
+ * verification is this package's only role, so the mint and credential-claim
4
+ * endpoints belong to `@mi9-identity/token-client` — a service that verifies
5
+ * but never mints has no use for them, and deriving them here is what forced
6
+ * token-client consumers to install a JOSE stack for a string concat.
7
+ *
8
+ * @param { string } issuerUrl Configured issuer URL (matches the JWT `iss` claim, e.g. `https://identity.mi9retail.com/api/v1`). Trailing slash tolerated.
9
+ * @returns { string } Full JWKS URL.
10
+ */
11
+ export const mi9IdentityJwksEndpoint = (issuerUrl) => `${issuerUrl.replace(/\/+$/, '')}/.well-known/jwks.json`;
12
+ //# sourceMappingURL=endpoints.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Base class for all token-verification failures. Adapters map subclasses to
3
+ * RFC 6750 §3 status codes; see `@mi9-identity/auth-middleware-express` for the
4
+ * default mapping.
5
+ */
6
+ export declare class InvalidTokenError extends Error {
7
+ readonly name: string;
8
+ }
9
+ /**
10
+ * Token signature verified but `exp` (with clock tolerance) is in the past.
11
+ */
12
+ export declare class TokenExpiredError extends InvalidTokenError {
13
+ readonly name: string;
14
+ }
15
+ /**
16
+ * The token's `iss` claim was not in the configured `issuers` allowlist.
17
+ * Rejected before signature verification — cheap fail.
18
+ */
19
+ export declare class IssuerNotAllowedError extends InvalidTokenError {
20
+ readonly name: string;
21
+ }
22
+ /**
23
+ * The token's `aud` did not match any of the configured audiences
24
+ * (OR-membership semantics — `aud` may be a scalar string or an array; see
25
+ * design doc §6 / ADR-6).
26
+ */
27
+ export declare class AudienceMismatchError extends InvalidTokenError {
28
+ readonly name: string;
29
+ }
30
+ /**
31
+ * Token header `alg` was not RS256. The verifier accepts no other algorithm
32
+ * regardless of what JWKS publishes, defending against `alg` substitution
33
+ * attacks.
34
+ */
35
+ export declare class AlgorithmNotAllowedError extends InvalidTokenError {
36
+ readonly name: string;
37
+ }
38
+ /**
39
+ * Token is otherwise valid but is missing one of the namespaced custom
40
+ * claims required to populate `AuthContext` (e.g. `retailerId`, `product`).
41
+ */
42
+ export declare class MissingRequiredClaimError extends InvalidTokenError {
43
+ readonly name: string;
44
+ }
45
+ /**
46
+ * Distinct from the `InvalidToken*` family because the failure is server-side
47
+ * (JWKS endpoint unreachable, DNS, timeout, no cached key set). Adapters map
48
+ * this to HTTP 503 with `Retry-After`. The verifier never falls back to an
49
+ * unauthenticated path — failing open would defeat JWT-based auth.
50
+ */
51
+ export declare class JwksUnavailableError extends Error {
52
+ readonly name: string;
53
+ }
54
+ //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Base class for all token-verification failures. Adapters map subclasses to
3
+ * RFC 6750 §3 status codes; see `@mi9-identity/auth-middleware-express` for the
4
+ * default mapping.
5
+ */
6
+ export class InvalidTokenError extends Error {
7
+ name = 'InvalidTokenError';
8
+ }
9
+ /**
10
+ * Token signature verified but `exp` (with clock tolerance) is in the past.
11
+ */
12
+ export class TokenExpiredError extends InvalidTokenError {
13
+ name = 'TokenExpiredError';
14
+ }
15
+ /**
16
+ * The token's `iss` claim was not in the configured `issuers` allowlist.
17
+ * Rejected before signature verification — cheap fail.
18
+ */
19
+ export class IssuerNotAllowedError extends InvalidTokenError {
20
+ name = 'IssuerNotAllowedError';
21
+ }
22
+ /**
23
+ * The token's `aud` did not match any of the configured audiences
24
+ * (OR-membership semantics — `aud` may be a scalar string or an array; see
25
+ * design doc §6 / ADR-6).
26
+ */
27
+ export class AudienceMismatchError extends InvalidTokenError {
28
+ name = 'AudienceMismatchError';
29
+ }
30
+ /**
31
+ * Token header `alg` was not RS256. The verifier accepts no other algorithm
32
+ * regardless of what JWKS publishes, defending against `alg` substitution
33
+ * attacks.
34
+ */
35
+ export class AlgorithmNotAllowedError extends InvalidTokenError {
36
+ name = 'AlgorithmNotAllowedError';
37
+ }
38
+ /**
39
+ * Token is otherwise valid but is missing one of the namespaced custom
40
+ * claims required to populate `AuthContext` (e.g. `retailerId`, `product`).
41
+ */
42
+ export class MissingRequiredClaimError extends InvalidTokenError {
43
+ name = 'MissingRequiredClaimError';
44
+ }
45
+ /**
46
+ * Distinct from the `InvalidToken*` family because the failure is server-side
47
+ * (JWKS endpoint unreachable, DNS, timeout, no cached key set). Adapters map
48
+ * this to HTTP 503 with `Retry-After`. The verifier never falls back to an
49
+ * unauthenticated path — failing open would defeat JWT-based auth.
50
+ */
51
+ export class JwksUnavailableError extends Error {
52
+ name = 'JwksUnavailableError';
53
+ }
54
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,5 @@
1
+ export { createVerifier } from './verifier.js';
2
+ export { mi9IdentityJwksEndpoint } from './endpoints.js';
3
+ export { InvalidTokenError, TokenExpiredError, JwksUnavailableError, AudienceMismatchError, IssuerNotAllowedError, AlgorithmNotAllowedError, MissingRequiredClaimError, } from './errors.js';
4
+ export type { AuthContext, Logger, Verifier, VerifierOptions } from './types.js';
5
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createVerifier } from './verifier.js';
2
+ export { mi9IdentityJwksEndpoint } from './endpoints.js';
3
+ export { InvalidTokenError, TokenExpiredError, JwksUnavailableError, AudienceMismatchError, IssuerNotAllowedError, AlgorithmNotAllowedError, MissingRequiredClaimError, } from './errors.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Narrowing type guards, duplicated per package by design (see CLAUDE.md) —
3
+ * mirrored from the identity service's canonical `utils/type-guards.ts`, plus
4
+ * a package-local `isFunction` (the canonical set has no function guard).
5
+ */
6
+ /**
7
+ * Primitive string check.
8
+ *
9
+ * @param { unknown } value Value to test.
10
+ * @returns { value is string } True iff `typeof value === 'string'`.
11
+ * @example
12
+ * isString('hello'); // true
13
+ * isString(''); // true
14
+ * isString(42); // false
15
+ * isString(new String('hello')); // false (boxed String, not primitive)
16
+ */
17
+ export declare const isString: (value: unknown) => value is string;
18
+ /**
19
+ * Callable check. Narrowing preserves the callable member of a union so the
20
+ * value stays invocable with its original signature.
21
+ *
22
+ * @param { unknown } value Value to test.
23
+ * @returns { value is (...args: never[]) => unknown } True iff `typeof value === 'function'`.
24
+ * @example
25
+ * isFunction(() => 1); // true
26
+ * isFunction(class {}); // true (classes are callable)
27
+ * isFunction(42); // false
28
+ */
29
+ export declare const isFunction: (value: unknown) => value is (...args: never[]) => unknown;
30
+ //# sourceMappingURL=type-guards.d.ts.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Narrowing type guards, duplicated per package by design (see CLAUDE.md) —
3
+ * mirrored from the identity service's canonical `utils/type-guards.ts`, plus
4
+ * a package-local `isFunction` (the canonical set has no function guard).
5
+ */
6
+ /**
7
+ * Primitive string check.
8
+ *
9
+ * @param { unknown } value Value to test.
10
+ * @returns { value is string } True iff `typeof value === 'string'`.
11
+ * @example
12
+ * isString('hello'); // true
13
+ * isString(''); // true
14
+ * isString(42); // false
15
+ * isString(new String('hello')); // false (boxed String, not primitive)
16
+ */
17
+ export const isString = (value) => typeof value === 'string';
18
+ /**
19
+ * Callable check. Narrowing preserves the callable member of a union so the
20
+ * value stays invocable with its original signature.
21
+ *
22
+ * @param { unknown } value Value to test.
23
+ * @returns { value is (...args: never[]) => unknown } True iff `typeof value === 'function'`.
24
+ * @example
25
+ * isFunction(() => 1); // true
26
+ * isFunction(class {}); // true (classes are callable)
27
+ * isFunction(42); // false
28
+ */
29
+ export const isFunction = (value) => typeof value === 'function';
30
+ //# sourceMappingURL=type-guards.js.map
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Structural logger contract — any pino-compatible object satisfies this.
3
+ * Exported so adapters and the token client can declare a logger option
4
+ * without a runtime dependency on a logger package.
5
+ */
6
+ export interface Logger {
7
+ debug(obj: unknown, msg?: string): void;
8
+ info(obj: unknown, msg?: string): void;
9
+ warn(obj: unknown, msg?: string): void;
10
+ error(obj: unknown, msg?: string): void;
11
+ }
12
+ /**
13
+ * Configuration for `createVerifier`. Defaults match the design doc:
14
+ * 30 s clock tolerance, 1 h JWKS cache, 30 s startup jitter, 30 s cooldown
15
+ * between unknown-kid refresh storms.
16
+ */
17
+ export interface VerifierOptions {
18
+ /** Full URL of the issuer's JWKS document, e.g. `${ISSUER_URL}/.well-known/jwks.json`. */
19
+ jwksUri: string;
20
+ /** Explicit allowlist of acceptable `iss` values. No wildcards — Mi9 issuer URL only. */
21
+ issuers: readonly string[];
22
+ /** OR-membership: the token's `aud` (scalar or array) must intersect these. Pass-through to `jose.jwtVerify`. */
23
+ audience: string | readonly string[];
24
+ /** `leeway` for `exp`/`iat`/`nbf`. Default 30 s. */
25
+ clockToleranceSec?: number;
26
+ /** JWKS cache lifetime. Default 3_600_000 ms (1 h, design doc §3.2). */
27
+ jwksCacheTtlMs?: number;
28
+ /** Uniform random delay (0–N ms) before the first JWKS fetch — thundering-herd mitigation. Default 30_000 ms. */
29
+ jwksInitialJitterMs?: number;
30
+ /** Cooldown between unknown-kid refresh attempts. Default 30_000 ms (matches `jose`'s `cooldownDuration`). */
31
+ jwksCooldownMs?: number;
32
+ /**
33
+ * Per-fetch timeout for JWKS downloads. Default 5_000 ms (jose's `timeoutDuration`).
34
+ */
35
+ jwksFetchTimeoutMs?: number;
36
+ /** Optional structured logger; receives a single `warn` when JWKS becomes unavailable (the only event this framework-agnostic core emits — richer observability is the adapter's job). */
37
+ logger?: Logger;
38
+ }
39
+ /**
40
+ * Canonical post-verification surface — same name and shape as
41
+ * design doc §3.3 `AuthContext`. Namespaced URI claims
42
+ * (`https://mi9retail.com/<key>`) are mapped to unprefixed fields here.
43
+ *
44
+ * Issuer-internal claims (notably `authClass`) are NEVER surfaced here — the
45
+ * verifier strips them via an explicit allowlist before returning.
46
+ */
47
+ export interface AuthContext {
48
+ iss: string;
49
+ /** `sub` IS the `clientId` (UUIDv7); no separate `clientId` claim is issued. */
50
+ sub: string;
51
+ /** Mirrors the issuer's `aud` — a scalar string or an array of strings, echoing the requested `audience` shape verbatim (design doc §5.4 / ADR-6, amended). */
52
+ aud: string | string[];
53
+ exp: number;
54
+ iat: number;
55
+ nbf: number;
56
+ jti: string;
57
+ /** Raw space-separated string from the JWT. */
58
+ scope: string;
59
+ /** Pre-split, deduped convenience view of `scope`. */
60
+ scopes: readonly string[];
61
+ retailerId: string;
62
+ product: string;
63
+ /** `null` when the token was not minted for a Tier 3 / store-bound credential. */
64
+ storeCode: string | null;
65
+ }
66
+ /**
67
+ * Verifier handle returned by `createVerifier`. Stateless from the caller's
68
+ * perspective; internally holds a `jose` `RemoteJWKSet` with TTL and cooldown
69
+ * caching.
70
+ */
71
+ export interface Verifier {
72
+ /**
73
+ * Verify a Bearer token. Resolves to `AuthContext` on success; rejects with
74
+ * one of the typed error classes from `./errors.ts` on failure.
75
+ */
76
+ verify(token: string): Promise<AuthContext>;
77
+ }
78
+ //# sourceMappingURL=types.d.ts.map
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,12 @@
1
+ import type { Verifier, VerifierOptions } from './types.js';
2
+ /**
3
+ * Build a verifier bound to one issuer's JWKS. Construction is side-effect
4
+ * free; the JWKS document is fetched lazily on first `verify()` (modulo
5
+ * startup jitter).
6
+ *
7
+ * @param { VerifierOptions } opts Verifier configuration (JWKS URI, issuers, audience, cache/jitter knobs).
8
+ * @returns { Verifier } The configured verifier with its bound `verify` method.
9
+ * @throws { Error } If `issuers` is empty or `audience` is an empty array.
10
+ */
11
+ export declare const createVerifier: (opts: VerifierOptions) => Verifier;
12
+ //# sourceMappingURL=verifier.d.ts.map
@@ -0,0 +1,168 @@
1
+ import { inspect } from 'node:util';
2
+ import { createRemoteJWKSet, errors as joseErrors, jwtVerify } from 'jose';
3
+ import { toAuthContext } from './claims.js';
4
+ import { isFunction, isString } from './type-guards.js';
5
+ import { InvalidTokenError, TokenExpiredError, JwksUnavailableError, AudienceMismatchError, IssuerNotAllowedError, AlgorithmNotAllowedError, MissingRequiredClaimError, } from './errors.js';
6
+ const DEFAULT_CLOCK_TOLERANCE_SEC = 30;
7
+ const DEFAULT_JWKS_COOLDOWN_MS = 30_000;
8
+ const DEFAULT_JWKS_CACHE_TTL_MS = 3_600_000;
9
+ const DEFAULT_JWKS_FETCH_TIMEOUT_MS = 5_000;
10
+ const DEFAULT_JWKS_INITIAL_JITTER_MS = 30_000;
11
+ /**
12
+ * One-shot delay scheduled at construction time. The first `verify()` call
13
+ * awaits this gate so a fleet of consumer pods that all boot at once does
14
+ * not synchronously hammer the JWKS endpoint.
15
+ *
16
+ * @param { number } jitterMaxMs Upper bound (inclusive) for the random delay; non-positive disables jitter.
17
+ * @returns { Promise<void> } Resolves after the random delay (or immediately when disabled).
18
+ */
19
+ const scheduleStartupJitter = (jitterMaxMs) => {
20
+ if (jitterMaxMs <= 0) {
21
+ return Promise.resolve();
22
+ }
23
+ const delayMs = Math.floor(Math.random() * jitterMaxMs);
24
+ if (delayMs === 0) {
25
+ return Promise.resolve();
26
+ }
27
+ return new Promise((resolve) => {
28
+ const timer = setTimeout(resolve, delayMs);
29
+ /* v8 ignore next 3 -- defensive cross-runtime guard; setTimeout in Node always returns a Timeout with unref */
30
+ if (isFunction(timer.unref)) {
31
+ timer.unref();
32
+ }
33
+ });
34
+ };
35
+ /**
36
+ * Translate a `jose` error into the verifier's typed error hierarchy. Falls
37
+ * back to a generic `InvalidTokenError` for unrecognized codes so callers
38
+ * never see a `jose`-specific class. Returns the mapped error so the caller
39
+ * throws once at the call site (`throw mapJoseError(err)`).
40
+ *
41
+ * @param { unknown } err The raw error thrown by `jose` (or downstream).
42
+ * @returns { Error } The mapped error from the verifier's typed hierarchy.
43
+ */
44
+ const mapJoseError = (err) => {
45
+ if (err instanceof joseErrors.JWTExpired) {
46
+ return new TokenExpiredError(err.message, { cause: err });
47
+ }
48
+ if (err instanceof joseErrors.JOSEAlgNotAllowed) {
49
+ return new AlgorithmNotAllowedError(err.message, { cause: err });
50
+ }
51
+ if (err instanceof joseErrors.JWTClaimValidationFailed) {
52
+ if (err.claim === 'iss') {
53
+ return new IssuerNotAllowedError(err.message, { cause: err });
54
+ }
55
+ if (err.claim === 'aud') {
56
+ return new AudienceMismatchError(err.message, { cause: err });
57
+ }
58
+ return new InvalidTokenError(err.message, { cause: err });
59
+ }
60
+ if (err instanceof joseErrors.JWKSNoMatchingKey) {
61
+ // Unknown `kid`: the JWKS is reachable but this token's key is absent
62
+ // from it right now — most plausibly a token signed by a freshly-rotated
63
+ // signing key whose `kid` has not yet landed in the cached JWKS. `jose`
64
+ // refetches once on an unknown `kid`, then memoises the miss for
65
+ // `cooldownDuration` (jwksCooldownMs, default 30s) before retrying, so
66
+ // such a token 401s for at most that window. Mapped to InvalidTokenError
67
+ // (401), NOT JwksUnavailableError (503): the document is fetchable, the
68
+ // key is genuinely not in it. Conservative by design — a brief
69
+ // post-rotation 401 is safer than failing open.
70
+ return new InvalidTokenError(err.message, { cause: err });
71
+ }
72
+ if (err instanceof joseErrors.JWKSMultipleMatchingKeys) {
73
+ // Duplicate `kid` in the JWKS document — issuer-side configuration
74
+ // bug, not a token validity issue. Surface as 503 so consumers retry
75
+ // rather than rejecting the user with 401.
76
+ return new JwksUnavailableError(err.message, { cause: err });
77
+ }
78
+ if (err instanceof joseErrors.JWKSTimeout || err instanceof joseErrors.JWKSInvalid) {
79
+ return new JwksUnavailableError(err.message, { cause: err });
80
+ }
81
+ if (err instanceof joseErrors.JOSEError) {
82
+ return new InvalidTokenError(err.message, { cause: err });
83
+ }
84
+ if (err instanceof TypeError) {
85
+ // `fetch` throws `TypeError` on DNS / network failure; the JWKS endpoint
86
+ // is unreachable rather than the token being malformed.
87
+ return new JwksUnavailableError(err.message, { cause: err });
88
+ }
89
+ if (err instanceof Error) {
90
+ return err;
91
+ }
92
+ if (isString(err)) {
93
+ return new Error(err);
94
+ }
95
+ try {
96
+ /* v8 ignore next -- `?? inspect(err)` covers `JSON.stringify(undefined)`; not reachable from jose error shapes */
97
+ return new Error(JSON.stringify(err) ?? inspect(err));
98
+ /* v8 ignore next 3 -- defensive; JSON.stringify on the synthetic shapes thrown by jose does not throw in practice */
99
+ }
100
+ catch {
101
+ return new Error(inspect(err));
102
+ }
103
+ };
104
+ /**
105
+ * Build a verifier bound to one issuer's JWKS. Construction is side-effect
106
+ * free; the JWKS document is fetched lazily on first `verify()` (modulo
107
+ * startup jitter).
108
+ *
109
+ * @param { VerifierOptions } opts Verifier configuration (JWKS URI, issuers, audience, cache/jitter knobs).
110
+ * @returns { Verifier } The configured verifier with its bound `verify` method.
111
+ * @throws { Error } If `issuers` is empty or `audience` is an empty array.
112
+ */
113
+ export const createVerifier = (opts) => {
114
+ if (opts.issuers.length === 0) {
115
+ throw new Error('createVerifier: `issuers` must contain at least one entry');
116
+ }
117
+ const audience = isString(opts.audience) ? opts.audience : Array.from(opts.audience);
118
+ /* v8 ignore next 3 -- string-audience path skips this guard; type system already excludes empty-string at the call site */
119
+ if (Array.isArray(audience) && audience.length === 0) {
120
+ throw new Error('createVerifier: `audience` must be a non-empty string or array');
121
+ }
122
+ const issuer = Array.from(opts.issuers);
123
+ const cacheMaxAge = opts.jwksCacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
124
+ const cooldownDuration = opts.jwksCooldownMs ?? DEFAULT_JWKS_COOLDOWN_MS;
125
+ const clockTolerance = opts.clockToleranceSec ?? DEFAULT_CLOCK_TOLERANCE_SEC;
126
+ const jitterMaxMs = opts.jwksInitialJitterMs ?? DEFAULT_JWKS_INITIAL_JITTER_MS;
127
+ const timeoutDuration = opts.jwksFetchTimeoutMs ?? DEFAULT_JWKS_FETCH_TIMEOUT_MS;
128
+ const jwks = createRemoteJWKSet(new URL(opts.jwksUri), {
129
+ cacheMaxAge,
130
+ timeoutDuration,
131
+ cooldownDuration,
132
+ });
133
+ const startupGate = scheduleStartupJitter(jitterMaxMs);
134
+ const verify = async (token) => {
135
+ if (!isString(token) || token.length === 0) {
136
+ throw new InvalidTokenError('Token is empty');
137
+ }
138
+ await startupGate;
139
+ let payload;
140
+ try {
141
+ const result = await jwtVerify(token, jwks, {
142
+ issuer,
143
+ audience,
144
+ clockTolerance,
145
+ algorithms: ['RS256'],
146
+ });
147
+ payload = result.payload;
148
+ }
149
+ catch (err) {
150
+ const mapped = mapJoseError(err);
151
+ if (mapped instanceof JwksUnavailableError) {
152
+ opts.logger?.warn({ event: 'jwks_unavailable', jwksUri: opts.jwksUri, err: mapped.message }, 'jwt-verifier.jwks_unavailable');
153
+ }
154
+ throw mapped;
155
+ }
156
+ try {
157
+ return toAuthContext(payload);
158
+ }
159
+ catch (err) {
160
+ if (err instanceof MissingRequiredClaimError) {
161
+ throw err;
162
+ }
163
+ throw new InvalidTokenError('Failed to map verified payload to AuthContext', { cause: err });
164
+ }
165
+ };
166
+ return { verify };
167
+ };
168
+ //# sourceMappingURL=verifier.js.map
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@mi9-identity/jwt-verifier",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "description": "Mi9 JWT verifier — pure RS256/JWKS core for verifying tokens issued by the Mi9 Identity Service. Framework-agnostic.",
6
+ "keywords": [
7
+ "mi9",
8
+ "identity",
9
+ "oauth2",
10
+ "jwt",
11
+ "rs256",
12
+ "jwks",
13
+ "m2m"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "author": "Mi9 Retail",
17
+ "homepage": "https://mi9retail.com",
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=24.0.0"
21
+ },
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "!dist/**/*.map",
34
+ "!dist/.tsbuildinfo",
35
+ "README.md",
36
+ "CHANGELOG.md",
37
+ "LICENSE"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "dependencies": {
43
+ "jose": "^6.2.9",
44
+ "zod": "^4.4.3"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "24.13.3",
48
+ "@vitest/coverage-v8": "4.1.11",
49
+ "vitest": "4.1.11",
50
+ "@mi9-identity/tsconfig": "^1.0.0"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -b",
54
+ "typecheck": "tsc --noEmit",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest",
57
+ "test:cov": "vitest run --coverage",
58
+ "lint": "biome lint .",
59
+ "lint:fix": "biome lint --write .",
60
+ "clean": "rimraf dist .turbo"
61
+ }
62
+ }