@mi9-identity/auth-middleware-express 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,35 @@
1
+ # @mi9-identity/auth-middleware-express
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.7.24
15
+
16
+ - No user-facing changes. Internal: adds a package-local `type-guards.ts` (`isNull` / `isUndefined` / `isNil` / `isString` / `isEmpty` / `isFunction`, not exported from the package entrypoint) and routes the inline nullish, string, empty-length, and callable checks in `adapter.ts`, `guards.ts`, `default-error-mapping.ts`, `errors.ts`, and `event.ts` through it. Every predicate is equivalent to the expression it replaced — no public API, RFC 6750 wire shape, or `AuthEvent` field changed. Lockstep version bump with the rest of the family.
17
+
18
+ ## 2026.6.3
19
+
20
+ - **BREAKING**: drops Express 4 support. The minimum Express is now 5 (peer `express: ">=5.0.0"`, `@types/express: ^5.0.0`). The adapter source is version-neutral, so no public API or wire-shape changed — but the peer-dep floor is raised. Consumers still on Express 4 must pin the prior `@mi9-identity/*` release. Decision and migration review recorded in ADR-15.
21
+
22
+ ## 2026.6.1
23
+
24
+ - No user-facing changes. Internal: the case-insensitive header lookup (`headerString`) and the `X-Request-ID` default header are now sourced once from `event.ts` and shared by the adapter and guards (removes a duplicated helper + constant). Lockstep version bump with the rest of the family.
25
+
26
+ ## 2026.5.27
27
+
28
+ - **Multiple audiences per token** (ADR-6 amended). Follows `@mi9-identity/jwt-verifier` — `AuthContext.aud` widens to `string | string[]`; the scope/retailer guards are unaffected.
29
+ - **`/api/v1` cutover** (ADR-13). Consumers configure the versioned issuer URL; `mi9IdentityEndpoints()` (from `@mi9-identity/jwt-verifier`) derives the endpoints.
30
+
31
+ ## 0.1.0
32
+
33
+ - Version reset to pre-1.0 (`0.1.0`); the earlier `1.0.0` placeholder is superseded.
34
+ - **Breaking**: follows `@mi9-identity/jwt-verifier@0.1.0` `AuthContext` rename — `requireRetailer` now reads `auth.retailerId` instead of `auth.retailer_id`. Audit-event field names (`retailer_code`, `client_id`, `latency_ms`, …) keep snake_case — independent surface (analyst convention) per ADR-12.
35
+ - Depends on `@mi9-identity/jwt-verifier` (peer, `workspace:^`).
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,234 @@
1
+ # @mi9-identity/auth-middleware-express
2
+
3
+ Express middleware that verifies Mi9-issued JWTs, attaches `AuthContext` to
4
+ `req.auth`, and ships scope/retailer guard factories. Layered on
5
+ [`@mi9-identity/jwt-verifier`](https://www.npmjs.com/package/@mi9-identity/jwt-verifier).
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/auth-middleware-express`** (this one) | Your service **receives** Mi9-issued tokens and is an Express 5 app. |
15
+ | [`@mi9-identity/jwt-verifier`](https://www.npmjs.com/package/@mi9-identity/jwt-verifier) | The same, but not Express — the framework-agnostic verifier this package wraps. Installed alongside this one. |
16
+ | [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client) | Your service **calls** a Mi9 API and needs a token. |
17
+
18
+ A service that both calls Mi9 APIs and serves Mi9-authenticated requests
19
+ installs the token client too.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install @mi9-identity/auth-middleware-express@1.0.0 @mi9-identity/jwt-verifier@1.0.0
25
+ ```
26
+
27
+ `express` is a peer dependency. **Express 5** is required (peer `>=5.0.0`);
28
+ Express 4 is no longer supported. Packages are **ESM-only** and require **Node 24+**.
29
+
30
+ Versions are **semver**, and the three `@mi9-identity/*` packages
31
+ (`auth-middleware-express`, `jwt-verifier`, `token-client`) are released in
32
+ lockstep at the same version — pin an exact version, not a `^` range. Breaking
33
+ wire changes ship as new API path versions, not as new package majors.
34
+
35
+ ## Configuration
36
+
37
+ Verifying needs **no credential**: the signing keys are public and served from
38
+ the issuer's JWKS URL. You need two values, both given to you by your Mi9
39
+ contact when your service is registered — the issuer URL, and the audience
40
+ identifier assigned to your service.
41
+
42
+ Configure one issuer URL and one audience for your own service:
43
+
44
+ ```
45
+ MI9_IDENTITY_ISSUER # https://identity.mi9retail.com/api/v1 — matches the JWT `iss` claim
46
+ MI9_IDENTITY_AUDIENCE # this service's own audience identifier (a full URL)
47
+ ```
48
+
49
+ The issuer URL is the **versioned** one, and the JWKS URI is derived from it
50
+ with `mi9IdentityJwksEndpoint(issuer)` from `@mi9-identity/jwt-verifier`.
51
+ Audience values are full URLs (`https://merchant.mi9retail.com/api`), never a
52
+ bare service name.
53
+
54
+ ## Usage
55
+
56
+ ```ts
57
+ import express, { type Request } from 'express';
58
+ import { createVerifier } from '@mi9-identity/jwt-verifier';
59
+ import { mi9Auth, requireRetailer } from '@mi9-identity/auth-middleware-express';
60
+
61
+ const verifier = createVerifier({
62
+ jwksUri: process.env.MI9_IDENTITY_JWKS_URI,
63
+ issuers: ['https://identity.mi9retail.com/api/v1'],
64
+ audience: 'https://merchant.mi9retail.com/api',
65
+ });
66
+
67
+ const resolveRetailerCode = (req: Request): string => {
68
+ const code = req.params.retailerCode;
69
+ if (typeof code !== 'string' || code.length === 0) {
70
+ throw new Error('retailerCode path parameter is required');
71
+ }
72
+ return code;
73
+ };
74
+
75
+ const app = express();
76
+ app.use(mi9Auth({ verifier }));
77
+
78
+ app.get(
79
+ '/retailer/:retailerCode/orders',
80
+ requireRetailer(resolveRetailerCode),
81
+ (req, res) => res.json({ retailer: req.auth?.retailerId }),
82
+ );
83
+ ```
84
+
85
+ > **The scope guards are not usable today.** `requireScope` and
86
+ > `requireAnyScope` are exported and work, but Mi9 credentials are provisioned
87
+ > with an empty authorized-scope list, so issued tokens carry an empty `scope`
88
+ > claim and every scope guard rejects with 403 `insufficient_scope`. Authorize
89
+ > on the retailer, the product or the audience instead. Use the scope guards
90
+ > only once your Mi9 administrator confirms that your credentials carry
91
+ > authorized scopes.
92
+
93
+ ### `Mi9AuthOptions` reference
94
+
95
+ | Option | Required | Default | Purpose |
96
+ | --- | --- | --- | --- |
97
+ | `verifier` | **yes** | — | A `Verifier` from `createVerifier(...)`. |
98
+ | `headerName` | no | `'authorization'` | Inbound header to read the Bearer token from (case-insensitive). |
99
+ | `requestIdHeader` | no | `'X-Request-ID'` | Inbound correlation-id header; its value flows to `AuthEvent.request_id`. |
100
+ | `onAuthEvent` | no | no-op | Sink for the structured `AuthEvent` (wire your logger / analytics here). |
101
+ | `onError` | no | RFC 6750 §3 mapping | Override the error envelope (status + headers + body) — see `defaultErrorMapping`. |
102
+
103
+ ### `req.auth` — `AuthContext`
104
+
105
+ On a successful verify, `mi9Auth` attaches the verified token payload to
106
+ `req.auth`. The type is `AuthContext` from `@mi9-identity/jwt-verifier`:
107
+
108
+ ```ts
109
+ import type { AuthContext } from '@mi9-identity/jwt-verifier';
110
+ ```
111
+
112
+ | Field | Type | Notes |
113
+ | --- | --- | --- |
114
+ | `iss` | `string` | Issuer (versioned, e.g. `…/api/v1`). |
115
+ | `sub` | `string` | **Is the `clientId`** (UUIDv7) — no separate `clientId` claim. |
116
+ | `aud` | `string \| string[]` | Scalar for one audience, array for several. |
117
+ | `exp` / `iat` / `nbf` | `number` | Unix seconds. |
118
+ | `jti` | `string` | Token id. |
119
+ | `scope` | `string` | Raw space-separated scope string. Empty today — see the note under [Usage](#usage). |
120
+ | `scopes` | `readonly string[]` | Pre-split, deduped view of `scope`. Empty today. |
121
+ | `retailerId` | `string` | From the `https://mi9retail.com/retailerId` claim. |
122
+ | `product` | `string` | Product the credential belongs to. |
123
+ | `storeCode` | `string \| null` | Always present; `null` unless the credential is store-bound. |
124
+
125
+ Issuer-internal claims are stripped by the verifier before `AuthContext` is
126
+ built, so nothing outside this table reaches `req.auth`.
127
+
128
+ ### `createGuards` — guards bound to an audit sink
129
+
130
+ The top-level `requireScope` / `requireAnyScope` / `requireRetailer` exports are convenience wrappers that emit nothing on rejection. Production consumers should call `createGuards({ onAuthEvent })` so scope and retailer failures land in the same `AuthEvent` stream as token verification failures — otherwise an entire class of authorization rejection becomes invisible to your audit sink.
131
+
132
+ ```ts
133
+ import { createGuards } from '@mi9-identity/auth-middleware-express';
134
+
135
+ const { requireScope, requireAnyScope, requireRetailer } = createGuards({
136
+ onAuthEvent: (event) => log.info(event, event.event),
137
+ });
138
+ ```
139
+
140
+ The returned object satisfies the `Guards` interface and is otherwise drop-in compatible with the top-level guard primitives.
141
+
142
+ ### Express version
143
+
144
+ This adapter requires **Express 5** (peer `>=5.0.0`). The adapter calls
145
+ `next(err)` itself, so `mi9Auth` works without additional wrappers. Express 5
146
+ also propagates rejections from `async` middleware automatically, so any custom
147
+ middleware you write around `req.auth` can be plain `async` — no
148
+ `express-async-handler` needed.
149
+
150
+ ### Default error mapping (RFC 6750 §3)
151
+
152
+ | Error | Status | `WWW-Authenticate` `error=` | Body `error` |
153
+ | ------------------------------ | ------ | ---------------------------------------- | -------------------- |
154
+ | `MissingTokenError` | 401 | _omitted_ (RFC 6750 §3.1) | _omitted_ |
155
+ | `InvalidTokenError` family¹ | 401 | `invalid_token` | `invalid_token` |
156
+ | `InsufficientScopeError` | 403 | `insufficient_scope` + `scope="..."`² | `insufficient_scope` |
157
+ | `RetailerMismatchError` | 403 | `mi9_retailer_mismatch`⁴ | `mi9_retailer_mismatch` |
158
+ | `JwksUnavailableError` | 503 | `invalid_token` + `Retry-After: 30`³ | `invalid_token` |
159
+
160
+ ¹ Includes `TokenExpiredError`, `IssuerNotAllowedError`, `AudienceMismatchError`, `AlgorithmNotAllowedError`, `MissingRequiredClaimError`, `InvalidTokenError`.
161
+ ² `scope="..."` parameter is appended automatically when `requireScope` / `requireAnyScope` is the source. Space-delimited per RFC 6749 §3.3.
162
+ ³ `temporarily_unavailable` is registered for the authorization endpoint (RFC 6749 §4.1.2.1), not the resource server. RFC 6750 §6.2.1 registers only `invalid_request`, `invalid_token`, `insufficient_scope`. We use `invalid_token` + 503 + `Retry-After` to convey transience without emitting an unregistered code.
163
+ ⁴ Mi9-private (non-standard). The token is fully valid — signature, `exp`, and `aud` all pass — but the `retailerId` claim does not match the resource. Registered codes don't fit: `insufficient_scope` is a scope shortage, `invalid_token` is a token defect. RFC 6750 §3 does not restrict the `error=` parameter to registered codes; the `mi9_` namespace prefix marks it as application-specific.
164
+
165
+ The body shape is `{ error, error_description }` for every row except `MissingTokenError`. RFC 6750 §3.1 forbids the `error=` parameter on a bare 401 challenge, so `MissingTokenError` emits a body of `{ error_description }` only — clients narrowing on `body.error` must tolerate `undefined`. `defaultErrorMapping` is exported as a load-bearing primitive — consumers who want to override one error class while delegating the rest can compose:
166
+
167
+ ```ts
168
+ mi9Auth({
169
+ verifier,
170
+ onError: (err) => err instanceof MyCustomError ? customResponse(err) : defaultErrorMapping(err),
171
+ });
172
+ ```
173
+
174
+ To emit `scope="..."` in your own `InsufficientScopeError` instances, pass the required scope list to the constructor: `new InsufficientScopeError('msg', ['orders:read', 'pos:write'])`.
175
+
176
+ This RFC 6750 surface, which your resource server returns to **its** callers,
177
+ keeps the snake_case `error` / `error_description` names that RFC 6750 defines.
178
+ It is not the same shape as the issuer's own error envelope, whose
179
+ `errorDescription` field is camelCase — that one is handled by
180
+ [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client).
181
+
182
+ If you override the envelope via `onError`, keep the `WWW-Authenticate`
183
+ parameters: proxies and clients key off them.
184
+
185
+ ### `AuthEvent` shape is a contract
186
+
187
+ `onAuthEvent` receives a fixed-shape object that analytics sinks consume.
188
+ Don't rename or drop fields — pass it straight to your structured logger:
189
+
190
+ ```ts
191
+ mi9Auth({ verifier, onAuthEvent: (e) => log.info(e, e.event) });
192
+ ```
193
+
194
+ Field names are **snake_case** by analyst convention, independent of the
195
+ camelCase wire surface:
196
+
197
+ ```ts
198
+ interface AuthEvent {
199
+ event: 'auth_succeeded' | 'auth_failed';
200
+ request_id: string;
201
+ client_id?: string; // present on success
202
+ retailer_code?: string; // present on success
203
+ product?: string; // present on success
204
+ success: boolean;
205
+ latency_ms: number;
206
+ jti?: string; // present on success
207
+ failure_reason?: // present on failure
208
+ | 'missing_token' | 'invalid_token' | 'token_expired'
209
+ | 'issuer_not_allowed' | 'audience_mismatch' | 'algorithm_not_allowed'
210
+ | 'missing_required_claim' | 'insufficient_scope'
211
+ | 'retailer_mismatch' | 'jwks_unavailable';
212
+ }
213
+ ```
214
+
215
+ ## Troubleshooting
216
+
217
+ | Symptom | Likely cause | Fix |
218
+ | --- | --- | --- |
219
+ | Every request 401s with `invalid_token` right after a deploy | The token was signed by a key not yet in the cached JWKS | Self-heals within the verifier's unknown-`kid` cooldown (30 s by default). |
220
+ | Requests 503 with `Retry-After: 30` | `JwksUnavailableError` — the JWKS is unreachable and no fresh cache is left | Transient; confirm the service can reach `${issuer}/.well-known/jwks.json`. |
221
+ | 401 `invalid_token` with `audience_mismatch` in the audit event | 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. |
222
+ | Scope rejections never appear in your logs | The top-level guards were used instead of `createGuards({ onAuthEvent })` | Build the guards with `createGuards` so rejections emit an `AuthEvent`. |
223
+
224
+ ---
225
+
226
+ Inbound verification internals (JWKS caching, key rotation, the error taxonomy)
227
+ live in
228
+ [`@mi9-identity/jwt-verifier`](https://www.npmjs.com/package/@mi9-identity/jwt-verifier);
229
+ outbound token acquisition lives in
230
+ [`@mi9-identity/token-client`](https://www.npmjs.com/package/@mi9-identity/token-client).
231
+
232
+ ## License
233
+
234
+ Apache-2.0. The full text ships in the package as `LICENSE`.
@@ -0,0 +1,12 @@
1
+ import type { RequestHandler } from 'express';
2
+ import type { Mi9AuthOptions } from './types.js';
3
+ /**
4
+ * Build the Express middleware that verifies the inbound Bearer token,
5
+ * populates `req.auth`, and emits an `AuthEvent`. Errors short-circuit to
6
+ * the configured `onError` (default: RFC 6750 §3 mapping).
7
+ *
8
+ * @param { Mi9AuthOptions } opts Middleware configuration (verifier, header name, event sink, error mapper).
9
+ * @returns { RequestHandler } The configured Express request handler.
10
+ */
11
+ export declare const mi9Auth: (opts: Mi9AuthOptions) => RequestHandler;
12
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1,89 @@
1
+ import { isNull, isUndefined } from './type-guards.js';
2
+ import { defaultErrorMapping } from './default-error-mapping.js';
3
+ import { MissingTokenError } from './errors.js';
4
+ import { buildFailureEvent, buildSuccessEvent, DEFAULT_REQUEST_ID_HEADER, headerString, resolveRequestId } from './event.js';
5
+ /**
6
+ * RFC 7235 §2.1: scheme name is case-insensitive. RFC 6750 §2.1 permits
7
+ * one or more SP between scheme and token; HTAB is allowed by RFC 7230 §3.2
8
+ * for header field whitespace.
9
+ */
10
+ const BEARER_SCHEME = /^Bearer[ \t]+(.+)$/i;
11
+ const DEFAULT_HEADER_NAME = 'authorization';
12
+ /**
13
+ * Parse the inbound `Authorization` header into a Bearer token string. Empty,
14
+ * missing, or non-Bearer headers raise `MissingTokenError` so the adapter can
15
+ * map them onto the RFC 6750 §3.1 wire shape.
16
+ *
17
+ * @param { string | undefined } header The raw `Authorization` header value.
18
+ * @returns { string } The trimmed Bearer token.
19
+ * @throws { MissingTokenError } If the header is missing, not a Bearer scheme, or empty after trimming.
20
+ */
21
+ const extractToken = (header) => {
22
+ if (isUndefined(header)) {
23
+ throw new MissingTokenError('Authorization header missing');
24
+ }
25
+ const match = BEARER_SCHEME.exec(header);
26
+ if (isNull(match)) {
27
+ throw new MissingTokenError('Authorization header is not a Bearer token');
28
+ }
29
+ /* v8 ignore next -- regex with one mandatory capture group always populates match[1]; fallback covers TS narrowing */
30
+ const token = (match[1] ?? '').trim();
31
+ if (token.length === 0) {
32
+ throw new MissingTokenError('Bearer token is empty');
33
+ }
34
+ return token;
35
+ };
36
+ /**
37
+ * Build the Express middleware that verifies the inbound Bearer token,
38
+ * populates `req.auth`, and emits an `AuthEvent`. Errors short-circuit to
39
+ * the configured `onError` (default: RFC 6750 §3 mapping).
40
+ *
41
+ * @param { Mi9AuthOptions } opts Middleware configuration (verifier, header name, event sink, error mapper).
42
+ * @returns { RequestHandler } The configured Express request handler.
43
+ */
44
+ export const mi9Auth = (opts) => {
45
+ const headerName = opts.headerName ?? DEFAULT_HEADER_NAME;
46
+ const requestIdHeader = opts.requestIdHeader ?? DEFAULT_REQUEST_ID_HEADER;
47
+ const emitEvent = opts.onAuthEvent ?? (() => undefined);
48
+ const mapError = opts.onError ?? defaultErrorMapping;
49
+ return (req, res, next) => {
50
+ const startedAt = Date.now();
51
+ const requestId = resolveRequestId(req, requestIdHeader);
52
+ // Guards built via `createGuards` read this so guard-rejection
53
+ // `auth_failed` rows keep the same request_id and measure latency
54
+ // from the same anchor as the adapter's success event.
55
+ req.mi9AuthState = { startedAt, requestId };
56
+ const fail = (err) => {
57
+ const latencyMs = Date.now() - startedAt;
58
+ emitEvent(buildFailureEvent(err, requestId, latencyMs));
59
+ const mapped = mapError(err);
60
+ /* v8 ignore next 5 -- defaultErrorMapping always populates headers; branch covers custom onError that omits them */
61
+ if (!isUndefined(mapped.headers)) {
62
+ for (const [k, v] of Object.entries(mapped.headers)) {
63
+ res.setHeader(k, v);
64
+ }
65
+ }
66
+ res.status(mapped.status).json(mapped.body);
67
+ };
68
+ let token;
69
+ try {
70
+ token = extractToken(headerString(req, headerName));
71
+ }
72
+ catch (err) {
73
+ fail(err);
74
+ return;
75
+ }
76
+ opts.verifier
77
+ .verify(token)
78
+ .then((ctx) => {
79
+ req.auth = ctx;
80
+ const latencyMs = Date.now() - startedAt;
81
+ emitEvent(buildSuccessEvent(ctx, requestId, latencyMs));
82
+ next();
83
+ })
84
+ .catch((err) => {
85
+ fail(err);
86
+ });
87
+ };
88
+ };
89
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1,11 @@
1
+ import type { ErrorResponse } from './types.js';
2
+ import { type VerifierError } from './errors.js';
3
+ /**
4
+ * RFC 6750 §3 default mapping. Keep deterministic: identical input must
5
+ * always produce identical output for downstream caching / observability.
6
+ *
7
+ * @param { VerifierError } err The error to map onto a wire-shape response.
8
+ * @returns { ErrorResponse } The RFC 6750-compliant response envelope.
9
+ */
10
+ export declare const defaultErrorMapping: (err: VerifierError) => ErrorResponse;
11
+ //# sourceMappingURL=default-error-mapping.d.ts.map