@bymax-one/nest-auth 1.4.5 → 1.4.8

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 CHANGED
@@ -18,6 +18,632 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.8] - 2026-10-31
22
+
23
+ ### Apply to a derived backend
24
+
25
+ What a backend built on this library does about the changes below. The first item is a
26
+ compile-time change to the resolver's parameter type; the rest change behaviour or add opt-in
27
+ surface.
28
+
29
+ - **`tenantIdResolver` is now typed `(req: TenantResolverRequest) => ...`, not `(req: Request) => ...`.**
30
+ `TenantResolverRequest` is a new exported type with `headers`, `url` and `hostname`. A resolver
31
+ annotated `(req: Request)` must be re-annotated to `TenantResolverRequest` or left to infer; one
32
+ that reads `cookies`, `ip` or `ips` no longer compiles, so move that data into a header or the
33
+ hostname. An Express request still satisfies the type, so HTTP behaviour is unchanged.
34
+ - **`enforceTenantBinding` now holds on WebSockets.** `WsJwtGuard` previously never consulted it, so
35
+ a ticket or token minted for tenant A opened a socket resolved to tenant B even though the HTTP
36
+ guard refused the same credential. It now calls your `tenantIdResolver` on both credential
37
+ channels and answers `auth.token_invalid` on a mismatch. No option changes. **Read your
38
+ resolver:** an upgrade has no Express request, so it receives a request-like object with only
39
+ `headers` (lowercased), `url` and `hostname` (from `Host`, port cut). `cookies`, `ip`, `ips` and
40
+ trust-proxy behaviour are absent, and a resolver that throws on their absence, or returns another
41
+ tenant, **refuses** the connection rather than binding it wrongly. A resolver that
42
+ reads a cookie or `req.ip` and still compiles (an untyped one) will refuse every socket until it
43
+ resolves from `headers` or `hostname`. Nothing changes when `enforceTenantBinding` is off.
44
+ - **`AuthTokenVerifierService.verifyAccessToken` takes an optional `request`.** Pass the
45
+ handshake (or any object with `headers` and `url`, an Express request included) and, with
46
+ `enforceTenantBinding` on, the dashboard plane applies the same resolver check as `WsJwtGuard`,
47
+ with the same limited request and the same refusal (`auth.token_invalid`). Existing callers are
48
+ not broken: without `request` the token verifies as before, and with the binding on one warning
49
+ per service instance says it was not applied. To close the gap, pass `request: socket.handshake`.
50
+ - **Service API keys (new, opt-in).** To authenticate a machine caller, set `apiKeys` in the
51
+ factory (`enabled`, `pepper`, `scopes`) and provide `BYMAX_AUTH_API_KEY_REPOSITORY` in
52
+ `extraProviders`; either one alone fails at startup. Implement `IApiKeyRepository`, protect a
53
+ route with `@ServiceKey('read')`, and read the caller with `@CurrentApiKey()`. A backend that
54
+ keeps its own interim guard can delete it once its keys are re-issued (digests are not
55
+ portable across peppers) and its route-gate tests pass against `ApiKeyGuard`.
56
+ - **Three new error codes** in the catalog and in `AUTH_ERROR_CODES` of both subpaths:
57
+ `auth.api_key_invalid` (401), `auth.api_key_scope_insufficient` (403) and
58
+ `auth.api_key_not_found` (404). A client that switches on `error.code` need not handle them
59
+ unless it calls routes behind `@ServiceKey`.
60
+ - **`rust-auth` is to mirror the key format, the digest, the scope rules, the audit event and the
61
+ three codes.** They are pinned in the new `apiKeys` section of `conformance/wire-contract.json`,
62
+ with a digest vector, so the two libraries cannot drift unnoticed.
63
+ - **An OAuth sign-in now records the last login and runs `afterLogin`.** Until now only a password
64
+ login did. If your `afterLogin` hook sends a notification or writes an audit row, OAuth sign-ins
65
+ will now reach it; if you read `lastLoginAt`, OAuth sign-ins now move it. An account with MFA
66
+ gets both when the challenge completes, for password and OAuth sign-ins alike, on the dashboard
67
+ and the platform plane: before, an MFA account's last login never changed.
68
+ - **The default `onOAuthLogin` no longer keeps a link when the provider has not verified the
69
+ address.** It answers `reject` (`Email not verified`) instead of `link`. Nothing changes if you
70
+ supply your own `onOAuthLogin`. The `existingUser` it receives was always the user already
71
+ linked to the provider identity, found by provider id, not by email; the documentation said the
72
+ latter and is corrected.
73
+
74
+ ### Security
75
+
76
+ - `WsJwtGuard` enforces `enforceTenantBinding` on the bearer-header and ticket paths, and `verifyAccessToken` can now enforce it when given the request.
77
+
78
+ ### Fixed
79
+
80
+ - **An MFA account's last login was never recorded.** The password step stopped at the challenge
81
+ and the challenge completion did not write it, so `lastLoginAt` never moved for a password
82
+ account with MFA, on the dashboard or the platform plane. Completing the challenge now records
83
+ it and runs `afterLogin`, for password and OAuth sign-ins alike.
84
+ - **A host `afterLogin` hook that threw synchronously could fail an MFA sign-in that had already
85
+ passed.** Completing the challenge now runs the hook detached, so neither a throw nor a
86
+ rejection changes the outcome, and the log line carries a label and the error's shape only.
87
+
88
+ ### Added
89
+
90
+ - **Scoped service API keys for machine callers.** `ApiKeyGuard` and the `@ServiceKey(...scopes)`
91
+ decorator (scopes, the user-JWT bypass and the guard in one), `@ApiKeyScopes`, `@CurrentApiKey`,
92
+ `ApiKeyService` (`issue`, `revoke`, `rotate`), `IApiKeyRepository` and the
93
+ `onApiKeyRequest` audit hook.
94
+ - Keys are stored only as `HMAC-SHA-256(pepper, secret)`; the plaintext is returned once.
95
+ - Every key takes the same verification steps (a dummy row and digest stand in for a missing
96
+ one) and every bad credential answers the same `401`.
97
+ - Scopes are route metadata; a bound route with no declaration is refused. A key must hold all
98
+ declared scopes, with no hierarchy and no wildcard.
99
+ - Several active keys may share a label, which is what an overlapping rotation uses.
100
+ - Last-used tracking is coalesced in memory and flushed in batches, so a verified request costs
101
+ no store write. With N instances a key is written up to N times per window.
102
+ - The hook receives the label, the route pattern and the outcome of every guarded request,
103
+ refusals included. `apiKeys.auditMode: 'required'` awaits it and denies the request if it
104
+ throws.
105
+ - A scope that is not in `apiKeys.scopes` stops the application at startup.
106
+ - `issue`, `revoke` and `rotate` emit no hook: they run inside the host's own admin route.
107
+ - Rate limiting is not built in; the README shows `@nestjs/throttler` keyed on the verified key
108
+ id, and an end-to-end test exercises that example.
109
+
110
+ ## [1.4.6] - 2026-10-31
111
+
112
+ ### Apply to a derived backend
113
+
114
+ What a backend built on this library does about the changes below. Nothing here is a breaking
115
+ change to the public API; the items that change behaviour are the ones to read.
116
+
117
+ - **`identifierKey` (new, optional).** Nothing to do unless you rotate `jwt.secret`. Set
118
+ `identifierKey` to the current secret before a rotation to keep sessions, token epochs and MFA
119
+ state where they are. Choosing a new value keeps today's behaviour, and recovery codes then stop
120
+ verifying unless the old secret stays in `jwt.previousSecrets`.
121
+ - **`AuthTokenVerifierService` (new, exported by `BymaxAuthModule`).** Inject it where a long-lived
122
+ transport must establish the same facts a guarded route does:
123
+ `verifyAccessToken(token, { plane, requireMfa?, checkStatus? })` resolves `{ plane, payload }` and
124
+ rejects with an `AuthException`. It checks the account status before the MFA policy.
125
+ - **`AuthEmailContext` (new, exported).** A catalogue that implements the renderers keeps
126
+ compiling; read `tenantId` and `email` from the new argument where a URL needs them.
127
+ - **Refresh keeps the second factor.** A session that completed the MFA challenge now stays
128
+ `mfaVerified` across rotations. Refresh sessions stored before the deploy carry no field and stay
129
+ unverified until the user next completes the challenge. A backend that stores the record itself
130
+ must carry `mfaVerified` forward, written only as `true` and read strictly.
131
+ - **WebSocket tickets.** A ticket is refused after its minting token is revoked, and it expires no
132
+ later than that token. The stored `wst:` record needs `jti` and `epoch`, so a ticket minted before
133
+ the deploy is refused at redemption; it lives at most 30 seconds, and a client that holds one asks
134
+ for a new one. Read `expiresIn` from `POST {prefix}/ws-ticket` rather than assuming 30 seconds.
135
+ - **`next` peer floor `^16.4.1`.** Applies only to a deployment that uses the `./nextjs` subpath:
136
+ upgrade `next` to 16.4.1 or later.
137
+ - **A request without a body to `POST …/mfa/setup`.** It now answers exactly as it does for `{}`
138
+ instead of 500; a client needs no change.
139
+ - **`onLockout` when the store cannot answer.** Nothing to do beyond upgrading. If the reads that
140
+ decide whether the hook fires fail, the login still answers `auth.invalid_credentials`; the hook is
141
+ skipped when the lock cannot be confirmed. If only the remaining time cannot be read after the lock
142
+ was confirmed, the hook fires with `retryAfterSeconds` set to `bruteForce.windowSeconds`, an upper
143
+ bound. A handler that treats the value as exact should read it as at most that long.
144
+
145
+ ### Added
146
+
147
+ - **`identifierKey` — rotate `jwt.secret` without moving the Redis identifiers.** Every name that
148
+ identifies an account (the session index, the token epoch, the MFA keys, the recent-authentication
149
+ marker, the OTP and rate-limit identifiers) derives from one key, which was always derived from
150
+ `jwt.secret`; rotating the secret therefore renamed all of them. The new optional top-level
151
+ `identifierKey` is the secret those names derive from instead, validated like `jwt.secret`, never
152
+ used to sign or verify a token, and defaulting to `jwt.secret`, so a deployment that does not set
153
+ it derives exactly the keys it derives today. Setting it to the current `jwt.secret` before a
154
+ rotation keeps sessions, token epochs and MFA state where they are; choosing a new value keeps
155
+ today's behaviour for a rotation that must cut the link. `jwt.previousSecrets` and the keys derived
156
+ from it are unchanged. Choosing a new `identifierKey` has two consequences: the stored MFA
157
+ recovery-code digests are an HMAC under the same derived key, so recovery codes stop verifying
158
+ unless the old secret stays in `jwt.previousSecrets`, and sessions leave the session list until
159
+ their next refresh (opaque refresh tokens keep working). The README gains a rotation guide with both paths, and
160
+ `conformance/wire-contract.json` states where the identifier secret comes from.
161
+
162
+ - **`AccountStatusService.invalidate({ userId, tenantId })` — a supported way to drop an account's
163
+ cached status.** Status is read through a Redis cache with a `userStatusCacheTtlSeconds`
164
+ lifetime, and nothing invalidated it on a change made outside this library. A host suspending a
165
+ user through its own admin surface therefore had two options, and both were bad: accept up to a
166
+ full TTL of continued access for a suspended account, or reach into
167
+ `<namespace>:us:{tenantId}:{userId}` and delete the key itself.
168
+
169
+ The canonical consumer chose the second, correctly — the first is worse — and documented it as a
170
+ workaround. **The format it depends on was never a contract**, and the failure when a format
171
+ moves is silent: the delete stops matching, nothing raises, and a security control quietly
172
+ degrades to "takes effect within a TTL". The format has moved once already, in 1.3.2, which added
173
+ the tenant segment.
174
+
175
+ `us` and `uev` were also absent from the key table in `AGENTS.md` and from
176
+ `conformance/wire-contract.json`, so the prefix a consumer actually reached for was the one
177
+ nothing had ever stated. `src/server/AGENTS.md` now lists both, with the rule that the format is not the
178
+ interface. **The wire contract deliberately still does not**: it is the parity artefact shared
179
+ with `rust-auth`, and adding a prefix there asserts a cross-implementation claim this change has
180
+ not verified. Whether these caches are part of that contract at all is a question for the two
181
+ libraries, not something to settle by editing one side's file.
182
+
183
+ The method drops both cached facts rather than only the one a caller has in mind — they are
184
+ written together, and the extra delete costs one repository read against an API where the caller
185
+ must know which of two entries their change invalidated. It is idempotent.
186
+
187
+ **What it does not promise, stated rather than left to be discovered.** The read path fills the
188
+ cache in two steps — resolve from the repository, then write — so a request that resolved the old
189
+ value just before your update lands will write it back afterwards with a full TTL, however
190
+ promptly you invalidate. The window shrinks from one TTL to one repository read; it does not
191
+ reach zero. Persist the status change **before** invalidating, so only genuinely concurrent
192
+ requests can lose the race. Closing it entirely needs the fill to be conditional on nothing
193
+ having invalidated in between — a per-account generation — which is a mechanism this service does
194
+ not have and which is tracked rather than implied here.
195
+
196
+ It refuses an empty or blank id with a `TypeError` rather than attempting the delete. An empty
197
+ tenant builds `us::{userId}`, a key no read ever wrote, so the delete would remove nothing and
198
+ resolve normally — the caller's admin surface reporting a suspension that never took effect,
199
+ which is the precise failure this method exists to eliminate. An unset resolver value, or an
200
+ `undefined` coerced by a JavaScript host, is how it arrives.
201
+
202
+ - **`AuthTokenVerifierService` — the whole identity chain for an access token, in one call.** A
203
+ guarded HTTP route establishes a chain of facts before a handler runs. A long-lived transport has no
204
+ guard in front of it and must establish the same ones itself, on a cadence, for as long as the
205
+ connection lives. Until now this library exported the parts and not the chain, and the parts do
206
+ not compose into it by inspection: `AuthRevocationService` answers two revocation channels and
207
+ says so, but a bridge calling it alone has checked a signature and a blacklist while checking
208
+ neither the token's **type**, nor its **`exp`**, nor whether the **account** behind it still
209
+ exists. `verifyWithRotation`, `assertValidJti`, `assertValidSub`, `assertValidTenantId` and
210
+ `assertTokenType` — the pieces that close those — were all internal.
211
+
212
+ `verifyAccessToken(token, { plane })` performs, in the order the refusals fire: the signature
213
+ under the pinned algorithm, the configured `issuer`/`audience` and any secret retired by a
214
+ rotation; `exp`; the claim shapes that become Redis keys downstream; the token type; both revocation
215
+ channels; the MFA claim shape; the account's **current** status;
216
+ and last the MFA policy (`MFA_REQUIRED`). The last two checks are opt-out (`checkStatus`,
217
+ `requireMfa`), defaulting to on.
218
+
219
+ **The plane is the caller's to declare and is never inferred from the token's own `type` claim.**
220
+ Inferring it would make the plane attacker-chosen — a platform token would open a dashboard
221
+ stream by saying it is one. It is returned on the result for the reason `HookContext.plane`
222
+ exists: a tenant cannot answer the question, because a platform token carries no tenant claim.
223
+
224
+ Two of them are worth naming for what they catch that a signature does not. A refresh mints
225
+ `mfaEnabled: true, mfaVerified: false`, so a token that is otherwise entirely valid can represent
226
+ a session that never completed its second factor — the type does not imply it. And the `status`
227
+ claim a token carries is a snapshot taken at issuance, so a suspension landing between two
228
+ reconnects is invisible to anything that reads the token alone; this asks the account.
229
+
230
+ **What it still does not do is stated rather than implied**, in the JSDoc and in the README:
231
+ route authorization is the consumer's and belongs on every message a stream carries rather than
232
+ on the handshake alone; `enforceTenantBinding` needs the request its resolver reads, which a
233
+ redeemed ticket no longer has; and the call holds no subscription, so a stream that asks once at
234
+ connect is authorized for the lifetime of the token rather than of the session.
235
+
236
+ **Two limits are stated rather than left to be discovered.** On the dashboard plane the status
237
+ check reads the `us:`/`uev:` cache. Email verification drops it, but a status change made by the
238
+ host's own code is seen only after `userStatusCacheTtlSeconds` (default 60 s) unless the host
239
+ calls `AccountStatusService.invalidate({ userId, tenantId })` after persisting the change. So its
240
+ freshness is bounded by that TTL and not by how often you call: a stream re-verifying every five
241
+ seconds still serves a banned account for up to a minute without the invalidation. The platform plane is uncached and genuinely current.
242
+ And a `plane` that is neither value throws a `TypeError` instead of falling through — the
243
+ fall-through arm would be the cross-tenant platform one, so a `'Dashboard'` from an unnarrowed
244
+ config value would verify a real platform token for a connection meant to be tenant-scoped.
245
+
246
+ Refusals mirror the code the equivalent guard already answers, so a consumer moving a surface
247
+ onto this service keeps branching on what it branched on before. That includes the asymmetry:
248
+ a wrong token type is `PLATFORM_AUTH_REQUIRED` on the platform plane, as `JwtPlatformGuard`
249
+ answers, and `TOKEN_INVALID` on the dashboard one, as `JwtAuthGuard` does.
250
+
251
+ The server entry exports the service together with the types `AuthPlane`, `VerifiedAccessToken`
252
+ and `VerifyAccessTokenOptions`, and `BymaxAuthModule` exports `AuthTokenVerifierService` and
253
+ `AccountStatusService`.
254
+
255
+ Closes the first candidate change in [#172](https://github.com/bymaxone/nest-auth/issues/172),
256
+ the one that removes the most from a consumer's plate.
257
+
258
+ - **`AccountStatusService`**, exported alongside it. It is the account lifecycle gate
259
+ `UserStatusGuard` already applied, lifted out of that guard so the verifier could share it rather
260
+ than carry a second copy of the cache key shape, the miss path and the order of the two refusals
261
+ — a guarded route and a long-lived transport have to reach the same verdict about the same
262
+ account, and one rule with two implementations is how that stops being true. Exported for the
263
+ narrower case too: a consumer already holding a verified payload can re-ask the one question
264
+ whose answer changes while a stream is open.
265
+
266
+ It also answers on the **platform** plane, which nothing did before: there is no
267
+ `PlatformUserStatusGuard`, and #172 recorded the absence as "no platform equivalent exists". That
268
+ is true of the guard and not of the capability — `IPlatformUserRepository.findById` and
269
+ `AuthPlatformUser.status` were already in the contract, so a platform administrator's suspension
270
+ was checkable and simply never checked. The platform read is uncached, unlike the dashboard one:
271
+ there is no tenant to scope a cache key by, and the population is small enough that a read per
272
+ call beats a keyspace no flow invalidates. It has no email-verification arm —
273
+ `emailVerification.required` gates tenant registration, and an administrator is provisioned.
274
+
275
+ **It fails closed when the platform repository is absent.** A deployment without
276
+ `controllers.platform` registers no repository and also mints no platform token, so that branch
277
+ answers a token which cannot have been issued there — which is exactly the case that must not be
278
+ waved through. Skipping a gate because its collaborator is missing is how a gate stops gating.
279
+
280
+ **Apply to a derived backend.** Nothing to do in the ordinary case: `UserStatusGuard` behaves
281
+ identically, `BymaxAuthModule` exports the new service, and `@UseGuards(UserStatusGuard)`
282
+ resolves exactly as before. **One narrow break:** the guard's constructor now takes a single
283
+ `AccountStatusService`, in place of the Redis service, the repository token and the options
284
+ token. If you register `UserStatusGuard` in your OWN module's `providers` rather than relying on
285
+ the auth module's export — or construct it directly in a test — list `AccountStatusService`
286
+ there and drop the three. A `useValue` double now needs one method,
287
+ `assertDashboardAccountUsable({ userId, tenantId })`, instead of a fake Redis and a fake
288
+ repository.
289
+
290
+ - **`afterPlatformLogout`, the first hook `PlatformAuthService` emits.** That service fired none at
291
+ all — it did not even receive the hooks provider — so a consumer holding a live platform stream
292
+ had no way to learn that the administrator behind it had signed out: the access token stayed
293
+ presentable until it expired and nothing observed the session's removal.
294
+
295
+ The platform **plane** was not silent, which is a narrower and more useful thing to know: it
296
+ already emits `afterLogin` from the platform branch of `MfaService.challenge`, and
297
+ `onRefreshTokenReuseDetected` from `TokenManagerService.reissuePlatformTokens`. What had no
298
+ signal was the logout, and only from this service.
299
+
300
+ Separate from `afterLogout` rather than sharing it, deliberately: an existing `afterLogout`
301
+ handler was written for dashboard users and may resolve a tenant, so routing platform events into
302
+ it would change what that handler receives without the handler asking. A new optional member is
303
+ additive and unambiguous.
304
+
305
+ - **`HookContext.plane`** — `'dashboard'` or `'platform'`, set on every context this library
306
+ builds. It exists because the tenant cannot answer that question: `MfaService` renders a platform
307
+ administrator as a `SafeAuthUser` carrying the sentinel `tenantId: ''` because the type demands
308
+ the field, while a platform access token has no tenant claim and reads `undefined`. A consumer
309
+ correlating a hook against a live connection by comparing those two matched nothing on the
310
+ platform plane and silently skipped every platform admin after an MFA enable, disable or
311
+ administrative reset. Branch on `plane` instead of on the shape of `tenantId`.
312
+ Every `HookContext` literal built under `src/server` carries it, including the one
313
+ `TokenManagerService.emitReuseDetected` hands to `onRefreshTokenReuseDetected`.
314
+
315
+ ### Changed
316
+
317
+ - **Every `AuthEmailCatalogue` renderer now receives the tenant and the recipient.** The provider's
318
+ methods hold both (`tenantId`, and the address the message goes to), but the renderer that builds
319
+ the body was handed only its own fields, so a link built inside it could not carry `tenantId`: a
320
+ recipient opening it in a browser with no tenant cookie was refused by a `tenantIdResolver`. The
321
+ two workarounds are both bad, a field stashed on the singleton provider races across concurrent
322
+ requests and can put one tenant's link in another's mail, and re-implementing a renderer
323
+ re-implements its HTML escaping. All ten renderers now take an `AuthEmailContext`
324
+ (`{ tenantId, email, locale? }`, exported) together with their own fields, so any message that
325
+ builds a URL has the tenant and the recipient available. `email` is always
326
+ the address the message is delivered to: the new address for `emailChangeVerification`, the
327
+ previous one for `emailChanged`, which still receives `oldEmail` and `newEmail`. **Apply to a
328
+ derived backend:** a catalogue that implements these renderers keeps compiling, since a function
329
+ that reads fewer fields is assignable; read `tenantId` and `email` from the input where a URL
330
+ needs them.
331
+
332
+ - **`AuthTokenVerifierService` checks the account status before the MFA policy.** Both planes now
333
+ consult `assertDashboardAccountUsable` / `assertPlatformAccountUsable` first and only then
334
+ `requireMfa`. Only an account the status gate refuses, holding a token that predates its MFA
335
+ challenge, changes its error code, in two ways: a blocked account now receives the matching
336
+ `ACCOUNT_*` / `EMAIL_NOT_VERIFIED` code instead of `MFA_REQUIRED`, and a deleted account now
337
+ receives `TOKEN_INVALID` instead of `MFA_REQUIRED`. A usable account with a pending challenge
338
+ still receives `MFA_REQUIRED`, a missing or non-boolean `mfaEnabled` claim still answers
339
+ `TOKEN_INVALID` ahead of the lookup, and `checkStatus: false` still skips the lookup.
340
+
341
+ **Apply to a derived backend:** a client that branched on `MFA_REQUIRED` for a
342
+ blocked account must handle the `ACCOUNT_*` code there.
343
+
344
+ ### Fixed
345
+
346
+ - **A store fault while deciding whether to fire `onLockout` no longer replaces the login
347
+ answer.** The two reads that exist only to feed the hook ran unguarded after the failure was
348
+ recorded, so a Redis error answered the request in place of `auth.invalid_credentials`. They are
349
+ now best-effort: an unreadable lock state skips the hook and logs one warning (the error class,
350
+ a masked address); an unreadable remaining time after a confirmed lock fires the hook with
351
+ `bruteForce.windowSeconds`. Recording the failure and the lockout pre-check still fail closed.
352
+ - **A request without a body to `POST …/mfa/setup` now behaves like an empty object instead of
353
+ answering 500.** The validation pipe returned a missing body as `undefined` to a handler that reads
354
+ `dto.password`; it now hands the handler an empty DTO, so the route answers exactly as it does for
355
+ `{}` (`auth.invalid_credentials` for an account with a password, success for an OAuth-only one).
356
+ The platform route and any DTO whose fields are all optional are covered by the same pipe.
357
+
358
+ - **A served OpenAPI document described every request body as `{}`.** This package is built without
359
+ the `@nestjs/swagger` CLI plugin, so `@nestjs/swagger` registered each of its DTOs as
360
+ `{"type":"object","properties":{}}` — valid, resolvable, and invisible to a dangling-`$ref`
361
+ sweep — and a client generated from the document typed `login(body: {})`. The contributor that
362
+ already describes the security posture now also offers the request-body schema of every DTO the
363
+ mounted controllers take, taken from `conformance/openapi-request-schemas.json` (compiled into the
364
+ bundle as a generated module, since `conformance/` is not published, with a gate that fails when
365
+ it differs from what the decorators produce). Only the controllers a deployment mounted
366
+ contribute, so a deployment without MFA, platform or invitations gets no unreferenced component. Measured in a scratch application
367
+ (outside this repository's suite) with `@bymax-one/nest-core` 1.6.1 and 1.6.3 over the package's
368
+ 16 exported request DTOs: all 16 were empty before and carried their properties after, with
369
+ nothing reported as discarded. **Request schemas appear with `@bymax-one/nest-core` ≥ 1.6.1; older versions ignore the
370
+ contribution without a signal** — through 1.6.0 the empty placeholder wins and nothing reports it.
371
+ The two OAuth query DTOs are not request bodies and get no schema. No public export, option or
372
+ dependency is added; the server bundle grows by about 0.6 KiB brotli, and its size budget moves
373
+ from 122 to 129 KiB.
374
+
375
+ - **A refresh rotation dropped the second factor, locking every MFA user out of `MfaRequiredGuard`
376
+ routes at the first rotation.** The guard refuses a token whose claims say
377
+ `mfaEnabled && !mfaVerified`. A session that completed the MFA challenge carries
378
+ `mfaVerified: true`, but the refresh-session record stored only `mfaEnabled`, so every rotation
379
+ minted `mfaVerified: false`, and no route lets an authenticated session re-acquire the claim.
380
+ After `jwt.accessExpiresIn` the user was refused everywhere behind the guard until they signed in
381
+ again. The record now carries `mfaVerified`, written only as `true` and read back strictly (a
382
+ record without the field, or with any value other than the boolean `true`, reads as not
383
+ verified), and every rotation and grace-window recovery copies it forward on both planes. A
384
+ session opened without the challenge gains nothing, so no rotation can turn into a way around the
385
+ guard. This follows NIST SP 800-63B-4 §5: "A session SHOULD inherit the AAL properties of the
386
+ authentication event that triggered its creation"
387
+ (<https://pages.nist.gov/800-63-4/sp800-63b/session/>). Sessions already stored carry no field
388
+ and stay unverified until the user next completes the challenge. `conformance/wire-contract.json`
389
+ states the field under `refreshSession` (`optionalFields`), so `rust-auth` must carry the same.
390
+
391
+ - **The `uev:` key format was stated twice inside this library, and no test could see them
392
+ disagree.** `AccountStatusService` derived it; `AuthService.verifyEmail` hand-built the same
393
+ string inline to drop the flag after a verification. They agreed, and nothing kept them
394
+ agreeing — the consumer-facing risk this release fixes already existed one level in, between two
395
+ files in this package.
396
+
397
+ **The suites would have stayed green through the drift**, which is the part worth recording.
398
+ Each side was pinned by its own literal — `'uev:tenant-1:user-1'` in one spec,
399
+ `` `uev:tenant-1:${USER.id}` `` in the other — so changing the derivation would have been
400
+ absorbed by updating the spec that owns it, while the other stayed green against its unchanged
401
+ inline copy. Both passing, the two keys naming different entries, and a just-verified account
402
+ keeping a stale `0` until the TTL expired. Nothing fails; a user is simply locked out of the
403
+ routes they just earned.
404
+
405
+ `verifyEmail` now calls `invalidate` and the derivation lives in one place
406
+ (a module-private helper, deliberately not exported). The specs assert the delegation rather than
407
+ a key literal, which removes the second statement instead of pinning it, and a new test reads both
408
+ the write and the delete path and asserts they name the same keys.
409
+
410
+ **What that test guards, precisely.** With one derivation the two paths cannot disagree, so it
411
+ cannot fail on a format change — single-sourcing is what makes that unreachable, not the test.
412
+ What it catches is the reintroduction of a second statement: inline a key in either path, as
413
+ `verifyEmail` did, and it goes red. Verified that way rather than assumed — restoring an inline
414
+ derivation on one side turns it red, including on the delimiter and unicode cases.
415
+
416
+ The comment that stood where the inline key was had described this exact hazard — "the key must
417
+ be byte-identical to the guard's… or the delete misses" — and prevented none of it. It had also
418
+ gone stale within hours: it named the guard, which stopped building that key when
419
+ `AccountStatusService` was extracted.
420
+
421
+ **Apply to a derived backend.** Nothing changes for a consumer that uses `BymaxAuthModule` — the
422
+ service is registered and exported unconditionally, and every shipped flow resolves it through
423
+ the container.
424
+
425
+ **One narrow break:** `AuthService`'s constructor takes an additional `AccountStatusService` as
426
+ its last parameter, because `verifyEmail` now invalidates through it instead of naming the cache
427
+ key itself. That reaches you only if you construct `AuthService` yourself or provide it through a
428
+ custom factory rather than letting the module register it — add `AccountStatusService` to that
429
+ argument list, or to the `inject` array of your factory. A `useValue` double needs one method,
430
+ `invalidate({ userId, tenantId })`.
431
+
432
+ If you delete these cache keys yourself, replace that with
433
+ `AccountStatusService.invalidate({ userId, tenantId })`. Your delete works today and is not
434
+ guaranteed to keep working, and the day it stops there will be no error to notice.
435
+
436
+ - **Two hooks discarded the account scope they were holding.** `afterLogout` received an empty
437
+ `HookContext` and `onSessionEvicted` a context naming neither the user nor the tenant — in both
438
+ cases while the emitting method had both values in hand. `logout` reads `{ userId, tenantId }`
439
+ from `readSessionOwner` and keys its own session revoke on them; `enforceSessionLimit` takes
440
+ `userId` and `tenantId` as parameters. Neither value was ever unavailable.
441
+
442
+ **This is the same defect 1.4.4 fixed on `onRefreshTokenReuseDetected`**, whose entry noted that
443
+ the emit "built `createEmptyHookContext()` anyway". Two more sites had it and were missed then.
444
+
445
+ It costs more than tidiness, because of what these hooks are for. A consumer wiring them to
446
+ disconnect a user's live connections must match the **tenant as well as the id**: a repository id
447
+ is unique only within a tenant — `findById` takes one precisely because ids may collide — so
448
+ acting on a bare id drops another tenant's user, and repeated logouts in one tenant become a
449
+ denial of service against another. A hook that names only the id cannot be acted on safely, which
450
+ left the only correct response to it being to ignore it.
451
+
452
+ `ip` and `userAgent` stay empty on `afterLogout` deliberately: `logout` receives two tokens and no
453
+ request, so there is nothing to report and an invented value would be worse than an empty string
454
+ a consumer can see is empty. `tenantId` is omitted rather than set to `undefined` when the session
455
+ record predates the tenant-scoped write, so its absence reads as "the record did not say" rather
456
+ than as a tenant literally named `undefined`.
457
+
458
+ **Both specs asserted the context loosely, which is why this shipped.** One used
459
+ `expect.anything()` and the other `expect.objectContaining({ ip, userAgent })` — neither can
460
+ distinguish a populated context from an empty one, the exact weakness the 1.4.4 entry called out
461
+ on the hook it fixed. Both now pin the context exactly.
462
+
463
+ **The rest of the family was checked, and two sites are deliberately left alone.**
464
+ `afterEmailVerified` and `afterPasswordReset` pass a context carrying only `plane: 'dashboard'`;
465
+ their first argument is a `SafeAuthUser` carrying `id` and `tenantId`, so a consumer can already scope them and there
466
+ is no defect to fix. `onRefreshTokenReuseDetected` is the one real remainder: it names the account
467
+ in its `details` object but the tenant is genuinely not in scope at the emit — `emitReuseDetected`
468
+ receives no tenant — so scoping it means threading the
469
+ tenant down from its callers. That is a larger change than this one and is tracked separately
470
+ rather than smuggled in here.
471
+
472
+ **Apply to a derived backend.** Nothing breaks: the fields are additions to a context whose type
473
+ already declared them as optional. If you consume either hook, you can now scope its effect —
474
+ and if you disconnect sockets or invalidate caches on them, you should, because doing it on the
475
+ bare `userId` reaches other tenants' accounts.
476
+
477
+ - **`AuthProvider` invented a tenant, so `useAuth().login` and `useAuth().forgotPassword` could not
478
+ reach a multi-tenant deployment at all.** Both applied the literal fallback `'default'` when the
479
+ caller omitted `tenantId`, and there was no way to suppress it — passing `undefined` produced the
480
+ fallback too. Since 1.4.2 the server refuses **any** body naming a tenant when the deployment
481
+ configures `tenantIdResolver`, so every login through the hook answered `400 auth.validation`
482
+ with `details[0].field === 'tenantId'` before the credentials were read.
483
+
484
+ The refusal is correct and stays: it is what stops a caller from choosing the tenant its own
485
+ request is scoped to. The defect was one layer up — this library naming a tenant on the caller's
486
+ behalf, then sending the invented name to a server that had already been told not to accept one.
487
+
488
+ **A cross-layer regression inside a single package.** The server changed in 1.4.2 and `/client`
489
+ followed in 1.4.3, where `LoginInput.tenantId` became optional and `forgotPassword` learned to
490
+ spread the field so an absent tenant is an absent KEY rather than a present-but-undefined one.
491
+ `/react` was the layer that never followed, and it sat directly on top of the one that had. The
492
+ lesson generalises past this fix: a change to what the server accepts is not finished at the
493
+ transport client while a higher layer still constructs the body.
494
+
495
+ Both call sites now forward the caller's value exactly — omitted stays omitted, given is given —
496
+ using the spread `/client` already documents. That form is not a style preference here:
497
+ `exactOptionalPropertyTypes` is on, so assigning `tenantId: options?.tenantId` against an
498
+ optional property does not compile, and only an absent key survives `JSON.stringify` as an absent
499
+ wire field.
500
+
501
+ **The specs pinned the defect rather than the contract.** Both asserted the outgoing `'default'`,
502
+ so they passed for as long as the bug existed and would have failed had it been fixed. They now
503
+ pin the absence of the key itself — `'tenantId' in input` — because `toEqual` treats an
504
+ undefined-valued key as absent and therefore cannot tell a pass-through from a reintroduced
505
+ assignment.
506
+
507
+ `register` and `resetPassword` were checked and are untouched: both forward the caller's input
508
+ object unchanged, so a consumer can already omit the field.
509
+
510
+ **Apply to a derived backend.** No server change, and nothing to do if your deployment configures
511
+ `tenantIdResolver` — that is the case this repairs. **The change is breaking for the other
512
+ cohort:** a resolver-**less** single-tenant frontend that relied on the implicit `'default'` now
513
+ sends no tenant at all, so it receives the other arm of the same validation error — the one
514
+ reading `tenantId is required`. Two ways out, both one line: pass `{ tenantId: 'default' }` at
515
+ the `login` call sites and `forgotPassword(email, 'default')`, or configure
516
+ `tenantIdResolver: () => 'default'` on the module and delete the argument everywhere. Prefer the
517
+ resolver — it puts the answer in the deployment that owns it instead of in every component that
518
+ asks.
519
+
520
+ The alternative fix — special-casing `'default'` server-side — was rejected. It would accept a
521
+ client-supplied tenant under a resolver, which is precisely the hole 1.4.2 closed.
522
+
523
+ ### Security
524
+
525
+ - **A WebSocket ticket expires no later than the access token that minted it.** A logout blacklists
526
+ the token's `jti` only for the token's remaining life, because nothing later can present that
527
+ token. A ticket minted from a token with a few seconds left still received the full 30, so the
528
+ blacklist entry expired with the token while the ticket stayed redeemable: the user's epoch is
529
+ unchanged, and the ticket redeemed although its session had ended. The lifetime is now the smaller
530
+ of 30 seconds and the token's remaining seconds less a one-second margin that covers the write
531
+ reaching Redis, and a token with no life left mints nothing (`auth.token_invalid`). The `expiresIn` that
532
+ `POST {prefix}/ws-ticket` returns is that capped value, in seconds. `conformance/wire-contract.json`
533
+ states the lifetime as "at most 30 s and never beyond the minting access token's own expiry".
534
+ **Apply to a derived backend:** cap the ticket's Redis TTL the same way when you mint, and report
535
+ the capped value as `expiresIn`; a client that assumed 30 seconds must read `expiresIn`.
536
+
537
+ - **A WebSocket ticket no longer outlives the session that minted it.** A ticket carried only
538
+ identity and account state, so one minted before a logout, a sign-out-everywhere, a password
539
+ change or an MFA reset still opened a socket for the rest of its 30 seconds, and a socket admitted
540
+ from it is authenticated once and never revalidated. The ticket now carries the `jti` and `epoch`
541
+ of the access token that minted it, and `WsTicketService.redeem` refuses it, with the same
542
+ `auth.token_invalid` as every other refusal, when that token is blacklisted or stamped below the
543
+ user's current epoch. This is the same two-channel check a bearer token gets at the handshake.
544
+ OWASP's WebSocket Security Cheat Sheet asks for exactly this: "Maintain a mapping of sessions to
545
+ active connections so you can invalidate WebSocket access the moment logout occurs"
546
+ (<https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html>).
547
+ **Apply to a derived backend:** the stored `wst:` record gains two required fields, `jti` (a
548
+ non-empty string) and `epoch` (a non-negative integer, `0` when the token carried none); a record
549
+ missing either is no longer a ticket, so a ticket minted before the deploy, or by a backend that
550
+ does not yet write them, is refused at redemption. A ticket lives 30 seconds, so the effect is a
551
+ brief window in which a client that already holds one asks for a new one. `WsTicketSnapshot` gains the same two fields, and
552
+ `conformance/wire-contract.json` declares them. A logout
553
+ blacklists only the access token it was given and does not move the epoch, so a ticket minted
554
+ from an access token that a refresh had already replaced is not refused after that logout, as a
555
+ bearer token of that kind is not; it is refused only after a later epoch bump (a password reset or
556
+ change, an MFA enable, disable or reset, or revoking another session or all of them).
557
+
558
+ - **The `next` peer dependency floor is `^16.4.1`.** The previous floor, `^16.2.11`, admitted `next`
559
+ releases with published advisories: GHSA-673q-mjm6-r5xr and GHSA-2464-fhr4-w9xw (both critical,
560
+ unauthenticated remote code execution, fixed in 16.4.1 for the 16 line). A consumer of the
561
+ `./nextjs` subpath on `next` below 16.4.1 should upgrade `next`; `next` stays an optional peer,
562
+ so a deployment that does not use `./nextjs` is unaffected. A test holds the floor.
563
+
564
+ - **Rotating `jwt.secret` no longer has to reset the token epoch.** Without `identifierKey`, a
565
+ rotation renamed the epoch key, every epoch read zero, and an access token that a password reset
566
+ or a revoke-all had refused was accepted again until it expired. With `identifierKey` pinned
567
+ before the rotation the epoch survives it. Deployments that rotate should set it first; the
568
+ README guide says how, and what a rotation after a compromise should do instead.
569
+
570
+ - **`fast-uri` and `qs` floored above the 2026-09-02 advisories.** Resolved versions were
571
+ `fast-uri@3.1.5` and `qs@6.15.3`. Now `fast-uri@3.1.9` and `qs@6.17.0` (floors `^3.1.9` and `^6.16.1`). Severities and summaries
572
+ read per advisory rather than carried across as a group, because they are not one wave:
573
+
574
+ | advisory | severity | what it is |
575
+ | ------------------- | ---------- | ------------------------------------------------------------------------------------- |
576
+ | GHSA-5jgf-p345-68v8 | 7.5 high | `fast-uri` host confusion, skipped IDN canonicalization on scheme-relative references |
577
+ | GHSA-jqff-g426-hqxp | 7.5 high | `fast-uri` host confusion, percent-encoded scheme normalization |
578
+ | GHSA-f65p-4m7j-42xc | 7.5 high | `fast-uri` **SSRF**, malformed IPv6 normalization |
579
+ | GHSA-fph4-wmhf-6fwf | 7.5 high | `fast-uri` **SSRF**, repeated hostname percent-decoding |
580
+ | GHSA-4mjr-xmp4-gh2g | 5.3 medium | `qs` denial of service via attacker-controlled `isBuffer` |
581
+ | GHSA-x5fp-wj9c-mxmx | 3.7 low | `qs` array-limit bypass via bracket-key comma parsing |
582
+
583
+ Two of the four `fast-uri` advisories are SSRF rather than host confusion, and the `qs` pair is
584
+ 5.3 and 3.7 rather than a single higher figure — both distinctions are lost by summarising a
585
+ batch, and a reader deciding urgency needs the per-ID numbers.
586
+
587
+ **How they reach this tree**, read from the lockfile rather than assumed: `qs` through `express`,
588
+ `body-parser`, `superagent` and `typed-rest-client`; `fast-uri` through `ajv`. Neither arrives via
589
+ `@stryker-mutator/core`.
590
+
591
+ `package.json` declares **no runtime dependencies at all**, so nothing this package publishes
592
+ carries either one. The floor is on this repository's own tree.
593
+
594
+ **It does not cover a consumer, and the reason matters.** `express` is a _peer_ dependency here,
595
+ so a consumer installs its own and resolves its own `qs` through it. An override is not published
596
+ — it applies to this lockfile and no other. A consumer wanting the same floor sets it in their
597
+ own workspace; reading this entry as protection they inherit would be the same mistake the entry
598
+ below documents.
599
+
600
+ **The `qs` entry is the finding worth keeping.** An override already existed —
601
+ `'qs@>=6.11.1 <=6.15.1': '>=6.15.2'` — and had stopped protecting anything. It fired once, the
602
+ resolved version moved to `6.15.3`, that left the selector's window, and the override silently
603
+ ceased to match. It still read in the config as coverage. **A selector-based override protects
604
+ against the advisory it was written for and nothing after it**, and nothing announces the moment
605
+ it stops applying. `fast-uri` had no override at all, so its appearance of coverage came from
606
+ nowhere in particular.
607
+
608
+ The only check that catches this is reading the **resolved** version in `pnpm-lock.yaml`. A
609
+ config range is a statement of intent, not of outcome.
610
+
611
+ **Swept the rest of the family rather than fixing only the two reported.** The remaining selector
612
+ overrides — `esbuild`, `postcss`, `tmp`, `ws` — resolve above their bounds today and are inert:
613
+ harmless now, and the same shape that made `qs` dangerous, since each will read as protection and
614
+ provide none the moment an advisory names a range above its bound. `brace-expansion` (major 5) and
615
+ `sharp` were re-floored by the later OSV sweep below and are active.
616
+
617
+ **Apply to a derived backend.** Check your own resolved versions. This package publishes no
618
+ runtime dependencies, so nothing here reaches you through it — but `express` is a peer, and your
619
+ own `express` brings its own `qs`. Floor it in your workspace if your resolution is below
620
+ `6.16.1`; our override cannot do it for you.
621
+
622
+ - **OSV advisories in the dev tree cleared.** Advisories in the
623
+ `pnpm-lock.yaml` transitive dev tree. Overrides now floor `fast-uri@3` at `^3.1.9`, `qs` at
624
+ `^6.16.1`, `sharp` at `>=0.35.5` and `brace-expansion@5` at `^5.0.12` (scoped to major 5, because
625
+ forcing every line onto 5.x broke `minimatch.braceExpand`), and add `body-parser@2`, `engine.io@6`,
626
+ `handlebars@4`, `js-yaml@3`/`4`, `multer@2`, `proxy-addr@2`, `source-map-js@1` and `zod@4`.
627
+ Dev-only `next` is raised to `^16.4.3`. `GHSA-gcqx-w48m-w2h4` (`deepmerge`, no patched release,
628
+ reached only through `jest-config`) is ignored in `osv-scanner.toml` until 2027-01-27. No
629
+ `peerDependencies` change and nothing under `src/`; the published package has no runtime
630
+ dependencies.
631
+
632
+ ### Documentation
633
+
634
+ - **The proxy route lists say how an entry matches, and two examples no longer mislead.** An entry
635
+ matches the path equal to it and anything under it, takes no wildcards, and a `'/'` entry is a
636
+ plain prefix that matches every path. In `publicRoutes` that never opens a protected route
637
+ (protected patterns are tried first); in `publicRoutesRedirectIfAuthenticated` it redirects a
638
+ signed-in user away from every unprotected page. The specification's `'/auth/*'` public route
639
+ (which matches nothing) is now `'/auth'`, and the redirect examples in the guide and the
640
+ specification no longer list `'/'`. Text and tests only: the matcher is unchanged.
641
+
642
+ - **`conformance/wire-contract.json` names the key the token epoch is stored under.**
643
+ `accessTokenClaims.epoch.storedUnder` now reads `{ep|pep}:{hmac_sha256(hmacKey, userSubject)}`,
644
+ the derived key the epoch is written to, instead of the bare `{ep|pep}:{userId}`. Text only: the
645
+ key the library derives is unchanged.
646
+
21
647
  ## [1.4.5] - 2026-08-29
22
648
 
23
649
  ### Added
@@ -2179,8 +2805,10 @@ follows it. For a rolling upgrade this release dual-writes the anti-replay marke
2179
2805
  failure counters (every read consults both the old plane-only key and the new tenant-scoped key,
2180
2806
  every write touches both) and dual-acquires the transition lock, so old and new pods stay
2181
2807
  consistent while both are live. A later release drops the legacy arm; deploying it before this one
2182
- has fully rolled out would split the anti-replay and lockout state across the two key shapes. No
2183
- host code changes: the tenant is sourced from the authenticated account, never from the request.
2808
+ has fully rolled out would split the anti-replay and lockout state across the two key shapes. Host
2809
+ code changes: every `IUserRepository.updateMfa` implementation takes the tenant and scopes its
2810
+ write by it, and any direct dashboard call into `MfaService` passes one. The tenant is sourced from
2811
+ the authenticated account, never from the request.
2184
2812
 
2185
2813
  ## [1.3.1] - 2026-08-08
2186
2814
 
@@ -3448,7 +4076,9 @@ ever installable.
3448
4076
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
3449
4077
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
3450
4078
 
3451
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...HEAD
4079
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...HEAD
4080
+ [1.4.8]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...v1.4.8
4081
+ [1.4.6]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...v1.4.6
3452
4082
  [1.4.5]: https://github.com/bymaxone/nest-auth/compare/v1.4.4...v1.4.5
3453
4083
  [1.4.4]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...v1.4.4
3454
4084
  [1.4.3]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...v1.4.3