@bymax-one/nest-auth 1.4.1 → 1.4.3

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
@@ -16,6 +16,794 @@ Strict SemVer starts when the API is declared stable, and that transition will b
16
16
  upgrading. Every breaking change carries an **Apply to a derived backend** note saying exactly
17
17
  what moves, and that note is the compatibility contract until strict SemVer begins.
18
18
 
19
+ ## [Unreleased]
20
+
21
+ ## [1.4.3] - 2026-08-15
22
+
23
+ ### Changed
24
+
25
+ - **BREAKING — the bulk session revocation moved to `POST {prefix}/sessions/revoke-all`.** It was
26
+ `DELETE {prefix}/sessions/all`, and the verb was the defect. The handler reads the refresh token
27
+ that names the caller's own session — the one session it must NOT revoke — and under
28
+ `tokenDelivery: 'bearer'` that token arrives in the request body. OpenAPI 3.0.3 defers to
29
+ RFC 7231 there: a payload on DELETE has no defined semantics, so `requestBody` on it **SHALL be
30
+ ignored by consumers**. A generated client therefore sent no body, the server found no refresh
31
+ token, and every call answered `auth.session_not_found` — an operation the document could not
32
+ describe and a generated client could not reach, in the delivery mode a mobile or cross-origin
33
+ consumer runs. POST is the method whose body semantics are defined.
34
+
35
+ Found in review of the contributed OpenAPI fragment rather than by a failing test, which is the
36
+ uncomfortable part: the e2e suite drove the endpoint with a hand-written request that DID carry
37
+ a body, so it passed throughout. The suite proved the server works; nothing proved a client
38
+ built from the document could reach it.
39
+
40
+ Two smaller truths came out of the same reading. `GET {prefix}/sessions` reads the same token to
41
+ mark which session is the caller's, and a GET has no body either — so on a bearer-only
42
+ deployment the cookie is its only channel, the fragment no longer contributes a body it would
43
+ never receive, and the listing simply marks nothing as current. And `test/e2e` now asserts, from
44
+ the router Nest actually built, that no contributed `requestBody` lands on a method without
45
+ payload semantics; the rule is enforced rather than remembered.
46
+
47
+ **Apply to a derived backend.** Change `DELETE {prefix}/sessions/all` to
48
+ `POST {prefix}/sessions/revoke-all` wherever a client calls it — or read it from
49
+ `AUTH_ROUTES.sessions.revokeAll`, which is what that constant is for. The request body,
50
+ response (`204`), guards, rate limit and error codes are unchanged; only the method and the last
51
+ path segment move. `DELETE {prefix}/sessions/:id` is untouched, and no longer has to out-rank a
52
+ static sibling in routing.
53
+
54
+ ### Added
55
+
56
+ - **Nine routes this library serves were missing from `AUTH_ROUTES`,** which is the map a client
57
+ composes URLs with — so a consumer reaching any of them had to hardcode the path the constants
58
+ exist to spare them, and would keep it hardcoded through a rename. Added:
59
+ `AUTH_DASHBOARD_ROUTES.wsTicket`, `AUTH_MFA_ROUTES.recoveryCodes`,
60
+ `AUTH_PASSWORD_ROUTES.changePassword`, the whole `AUTH_PLATFORM_MFA_ROUTES` family (setup,
61
+ verify-enable, disable, recovery-codes) and `AUTH_OAUTH_ROUTES` (initiate, callback).
62
+ `AUTH_EMAIL_CHANGE_ROUTES` and the two new families are exported from `./shared` by name, the
63
+ way every other family already was.
64
+
65
+ A test now compares the map against `PATH_METADATA` on the controllers — the same metadata Nest
66
+ routes with — in **both** directions: no route served without a constant, and no constant
67
+ pointing at a route nobody serves. It is worth saying how the platform MFA family was found,
68
+ because it is the failure mode this test exists for: a manual sweep reported those four paths as
69
+ present, because they appear elsewhere in the same file (in the refresh skip list) and a grep
70
+ for the literal cannot tell one list from another. The test reads the map, not the file.
71
+
72
+ ### Fixed
73
+
74
+ - **A wrong password no longer spends a refresh — and ten of them no longer sign the user out.**
75
+ `createAuthFetch` treated every 401 outside its path skip list as an expired session. A consumer
76
+ measured what that costs on a live instance: a wrong `currentPassword` on
77
+ `POST {prefix}/password/change` answers `401 auth.invalid_credentials`, the client refreshed,
78
+ and the retry then surfaced the real error — one refresh per typo. Ten typos inside a minute
79
+ exhaust the refresh limiter (`429 auth.too_many_requests`), the client read **that** as an
80
+ irrecoverable expiry and called `onSessionExpired`.
81
+
82
+ The session was never revoked: `GET {prefix}/me` answered `200` throughout. The sign-out was
83
+ entirely client-side — the wrapper discarding a session the server still honoured, triggered by
84
+ a rate limit that exists for something else. Behind a proxy with `clientIpSource: 'peer'` the
85
+ bucket is shared, so the ten are the whole deployment's.
86
+
87
+ **The skip list could not fix it, which is the finding under the finding.** That route is behind
88
+ the JWT guard: an expired token 401s there too. One path, two meanings — so the decision moved
89
+ to the error **code**, the only thing that separates them. `auth.token_invalid` is the expiry
90
+ (every guard collapses expired, revoked, malformed and absent onto it deliberately); every other
91
+ code is the server answering about something else, and a new token would not change its mind.
92
+
93
+ Measured across the family rather than fixing the one route reported: `password/change`,
94
+ `mfa/recovery-codes` and `email/change` all answer a non-expiry 401 and none was on the list,
95
+ while `mfa/setup` and `mfa/disable` answer the same codes and were. The list was three entries
96
+ short, not one — which is why the mechanism changed instead of the data.
97
+
98
+ **And the whole platform surface joined it.** The list carried five platform routes and left
99
+ out `platform/me` and all four `platform/mfa/*` — every one of them JWT-**platform**-guarded, so
100
+ an expired platform token answers `auth.token_invalid`, the code that means "refresh me" on the
101
+ dashboard plane. A dashboard refresh cannot fix another plane's credential: it spends the
102
+ budget and can call `onSessionExpired` for a session that is perfectly healthy. Found in review
103
+ of the paragraph claiming the list already covered the plane.
104
+
105
+ **Three routes left the path skip list**: `mfa/setup`, `mfa/verify-enable` and `mfa/disable`.
106
+ They were there because a wrong password or a wrong TOTP code 401s from them — which the code
107
+ check now recognises — but all three are **JWT-guarded**, so an expired token 401s from them
108
+ too, and skipping the refresh would have left the exact inverse of the defect above: a client
109
+ refusing to refresh a session that only needed refreshing. Found in review, and it is the same
110
+ one-path-two-meanings shape as `password/change`.
111
+
112
+ What remains on the list is the narrower set where a refresh cannot help **whatever** the code
113
+ says: the token endpoints themselves (recursion), the credential-issuing endpoints (no session
114
+ to refresh yet), and the **platform** surface — a dashboard refresh cannot fix a platform
115
+ credential, so attempting one spends the refresh budget and can call `onSessionExpired` for a
116
+ dashboard session that is perfectly healthy.
117
+
118
+ **The classification is time-bounded.** Reading the error body waits at most two seconds; on
119
+ expiry the pre-existing behaviour applies and a refresh is attempted. The request itself has
120
+ already completed and its timeout has already been cleared, so an unbounded read would hang the
121
+ wrapper on a 401 whose body never terminates — including on deployments that disable `timeout`
122
+ for long-polling. This step may narrow what refreshes; it may never suspend the wrapper.
123
+
124
+ **A 401 the client cannot read still refreshes.** No envelope, an empty body, a non-JSON body, a
125
+ code that is not a string — every one behaves exactly as before, so this wrapper stays usable as
126
+ a general fetch against an application's own API. Both envelope shapes are read: this library's
127
+ `{error: {code}}` and the flat `{statusCode, code, …}` a `@bymax-one/nest-core` backend answers
128
+ with. The body is read from a **clone**, so the caller still receives an unconsumed response —
129
+ otherwise every consumer parsing the error body would meet `TypeError: body already used`.
130
+
131
+ **Apply to a derived backend.** No server change. If your frontend relied on the old behaviour —
132
+ a 401 from any endpoint eventually reaching `onSessionExpired` — note that only
133
+ `auth.token_invalid` does now. A 401 your own API answers with no auth envelope is unaffected.
134
+
135
+ - **Two internal-only error codes now say so in the shared catalogue.** `auth.token_expired` and
136
+ `auth.token_revoked` are never on the wire — both implementations collapse them onto
137
+ `auth.token_invalid`, deliberately, because telling a caller "expired" rather than "invalid"
138
+ separates a token that WAS valid from one that never was, which is what an attacker holding a
139
+ captured value wants to learn. `rust-auth` maps them through `AuthErrorCode::to_wire`; this
140
+ library never throws them at all.
141
+
142
+ Three of the five internal-only codes already carried that note (`auth.token_missing`,
143
+ `auth.otp_expired`, `auth.otp_max_attempts`) and these two did not — so a reader concluded,
144
+ reasonably, that the unmarked ones do appear. A consumer seat did exactly that while reviewing
145
+ the refresh fix above, and asked whether it had a hole for `auth.token_expired`. It does not,
146
+ and now the catalogue answers the question without anyone reading the emit sites. **A code in a
147
+ published catalogue is something a consumer will write a branch for**, so an unreachable one has
148
+ to say it is unreachable.
149
+
150
+ ### Added
151
+
152
+ - **The OpenAPI security posture is contributed at the consumer's boot, not shipped as a file.**
153
+ A deployment building its document with `@bymax-one/nest-core` >= 1.4.0 now gets this library's
154
+ operations described automatically: which schemes exist, which operation requires which, and
155
+ which are reachable unauthenticated. The module registers a contributor; nest-core discovers it
156
+ while building the document. Nothing to enable, nothing to import.
157
+
158
+ It cannot be a static file, and that is the whole reason the contract exists. The same build
159
+ serves `/auth/login` here and `/api/v2/identity/login` there, with the credential in a cookie
160
+ on one deployment and an `Authorization` header on the next, under cookie names the consumer
161
+ chose. So the fragment is derived from the options that actually resolved, and keyed by handler
162
+ identity — which survives every prefix, version and mount point.
163
+
164
+ | resolved options | contributed |
165
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
+ | `tokenDelivery: 'cookie'` | `bymaxAuthAccessCookie`, `bymaxAuthRefreshCookie`, carrying the configured cookie names |
167
+ | `tokenDelivery: 'bearer'` | `bymaxAuthAccessBearer` only; `refresh` gets `security: []` and a `{refreshToken}` body that is **required twice** — the body must be sent and the property must be in it, because with no cookie to carry the token a generated client accepting `{}` would be describing a call that fails. `logout` takes the same body **optional**: measured, the two differ, since logout answers 204 with no credential at all where refresh 401s |
168
+ | `tokenDelivery: 'both'` | both access schemes as a **two-entry requirement list**, which OpenAPI reads as OR; the refresh operations add an **empty** alternative beside the cookie — how OpenAPI says "or a credential this member cannot model", without which the document would refuse to describe the valid body-only caller |
169
+ | `controllers.platform: true` | `bymaxPlatformAccessBearer`, in every mode — platform credentials are header-read whatever `tokenDelivery` says. The registration switch decides, not `platform.enabled` |
170
+ | a controller not mounted | no operation, and no scheme only it would have referenced |
171
+
172
+ **Two operations need two credentials at once, and the document says so.** Found in review of
173
+ this PR, against the controllers rather than against the guard stack: `revokeAllSessions` is
174
+ JWT-guarded AND reads the refresh token, because it revokes every session except the caller's
175
+ and cannot spare a session it cannot name — without one it answers `auth.session_not_found`.
176
+ `listSessions` and `changePassword` read the same token and succeed without it, with a lesser
177
+ answer (`isCurrent` false everywhere; every session ended, the caller's included). Describing
178
+ all three as access-only told a bearer-mode client to send no body to an endpoint that refuses
179
+ without one, and a cookie-mode client that the refresh cookie was not read.
180
+
181
+ OpenAPI writes AND as one requirement entry carrying both schemes, so that is what they get —
182
+ and under `'both'` the list is the product of the two channels: each access form, once with the
183
+ refresh cookie beside it and once without, the second being the body-borne token that `security`
184
+ cannot name. The required and the optional case produce the same document in that mode, which is
185
+ a property of OpenAPI rather than a shortcut: once a body-borne alternative exists, no
186
+ requirement list can insist on a credential that might be arriving in the body.
187
+
188
+ **The fragment also carries one sentence of prose, and it is there because a document cannot
189
+ say this any other way.** `logout` requires nothing — an operator whose access token expired
190
+ must still be able to sign out — so `security` renders "requires none" and "accepts and acts on
191
+ whichever arrives" identically to anyone skimming. A consumer read the `@Public()` decorator,
192
+ simplified to `security: []`, and measured what that produced: a logout called with no
193
+ credential answers `204` and revokes **nothing**, with the same access token still getting `200`
194
+ from `/me` afterwards. The user clicks sign out, sees success, and stays signed in, and no layer
195
+ reports a failure. Under `tokenDelivery: 'bearer'` the refresh token in the body is the only
196
+ channel there is, so omitting it is exactly that silent no-op. The operation therefore carries a
197
+ `description` saying so. It is contributed the way everything else is — nest-core merges a
198
+ fragment member only where the scan produced none, so a consumer who wrote their own
199
+ `@ApiOperation` keeps it.
200
+
201
+ **And `logout` names the access token it revokes.** Also found in review, and the one with a
202
+ security consequence rather than an ergonomic one: `logout` is `@Public()` — deliberately, so a
203
+ user whose 15-minute access token expired can still sign out — but it READS that token and
204
+ blacklists its `jti` for whatever life it has left. Described as refresh-only, a generated
205
+ client sent no `Authorization` header, so the refresh session was revoked while a valid access
206
+ token stayed usable until it expired. Every form it reads is now an alternative, richest first,
207
+ with the empty entry last saying that nothing is required. Its platform twin already worked this
208
+ way (`[{platformBearer}, {}]`), which is what made the dashboard side look like the oversight it
209
+ was.
210
+
211
+ The refresh-cookie scheme is now defined when **any** of the three controllers that reference it
212
+ is mounted, not only `auth` — a deployment mounting the session surface alone was referencing a
213
+ scheme its own document never declared.
214
+
215
+ **A scheme the options cannot satisfy is absent**, never defined-and-unreferenced: nest-core
216
+ fails a boot on a requirement naming an undefined scheme, and a document defining a credential
217
+ the server will not read tells a generated client to offer it. Both directions are asserted —
218
+ no dangling reference, and no unreferenced definition — under all three delivery modes.
219
+
220
+ **No coupling at all** — not a dependency, not a peer, not a devDependency, and no import even
221
+ in tests. The contributor class is unexported, the contract revision is inlined and the marker
222
+ is the documented string literal, so nothing published or unpublished names
223
+ `@bymax-one/nest-core`. A conformance gate walks the whole tree and fails on an import of any
224
+ other `@bymax-one/*` package, this package's own subpaths excepted; falsified from both a
225
+ production file and a test file.
226
+
227
+ An earlier draft of this work took nest-core as a devDependency so the conformance suite could
228
+ compare its constants as values, on the reasoning that test files do not ship. That reasoning
229
+ is true and beside the point: **a library does not take a dependency on its consumers' stack in
230
+ order to assert a composition** — the rule this repository already applies to
231
+ `AuthExceptionFilter`. The check moves to the consumer, who can make it better anyway, because
232
+ their suite runs both packages at the versions they installed. The README carries the two
233
+ expectations to write, and says which of the two failures is silent.
234
+
235
+ Two acceptance checks run in both directions over the handler table: every declared key names a
236
+ method that exists on the controller it names, and every route handler on every controller is
237
+ declared. The first matters because a key nest-core cannot resolve **fails a consumer's
238
+ document build** — a renamed handler here would break their repository on upgrade, not ours.
239
+ The second is what stops the table falling quietly behind: a new endpoint that nobody described
240
+ would inherit the consumer's document-level default, which is the wrong answer for a public
241
+ route and an unenforced promise for a protected one.
242
+
243
+ **On nest-core older than 1.4.0 the fragments are silently ignored** — no contributor lane, so
244
+ the document renders exactly as before with no error and no warning. Documented symptom-first
245
+ in the README, with the diagnosis order, because "the contributor has not shipped yet" and "the
246
+ nest-core version is too old" are indistinguishable from the document.
247
+
248
+ **Apply to a derived backend.** If you wrote `securitySchemes` or `openapi.operationSecurity`
249
+ entries for this library's routes by hand, **delete them** — and note what that sentence is
250
+ not saying. Those entries are not stale and not wrong: they are what makes the document correct
251
+ today, and a maintainer told to remove "incorrect config" will go looking for a defect and find
252
+ none. The accurate instruction is _delete the entries that currently do this job correctly,
253
+ because the library now does it_ — the deletion is what transfers the work, and it is needed
254
+ exactly because the entries were doing it. Precedence — read from nest-core's
255
+ `augmentOperation`, not summarised — is: the generated operation's own `security`, then your
256
+ override, then this library's fragment. So the stale vocabulary keeps winning and the
257
+ contributed one never lands.
258
+
259
+ **And your own document test will not catch it.** A consumer seat measured their case: ten
260
+ `operationSecurity` entries, all for this library's routes, and a suite asserting the
261
+ operation-to-posture map with `toEqual`. On adoption every fragment loses to those entries, the
262
+ old scheme names survive, and the suite stays **green** — it is asserting the old answer that is
263
+ still being served. A test that pins your document confirms the staleness instead of finding
264
+ it, so nothing downstream will remind you. Delete the literals, update whatever pins the
265
+ document to the four-name vocabulary, rebuild, and regenerate any typed client.
266
+
267
+ **Not in this change:** per-operation error responses (the `4xx` set each operation can answer,
268
+ read from `errorCatalog.statuses`) and the DTO request schemas. Both are additive to the same
269
+ contributor and are next; the security posture is the half a consumer asserts today.
270
+
271
+ - **`WsJwtGuard` is now driven by a real WebSocket handshake.** 228 lines at **0% e2e coverage**:
272
+ every other guard here is reached by an HTTP request, this one by a socket upgrade, and no
273
+ suite spoke that protocol — so its only proof was unit tests handing it an `ExecutionContext`
274
+ whose `switchToWs()` returned an object literal. That proves the code runs; it cannot prove a
275
+ real handshake presents the credential where the guard looks for it, which is the entire
276
+ question about a guard fed by a transport.
277
+
278
+ The alternative was to exclude it from the e2e-only rule with the residual risk written down.
279
+ The devDependency was taken instead — `@nestjs/platform-socket.io`, `socket.io` and
280
+ `socket.io-client`, dev-only, none of them in the published bundle. Statements 0% → **90.16%**,
281
+ branches → **81.25%**, functions → **100%**, from a gateway declared in the test module the way
282
+ a consumer declares one.
283
+
284
+ Both credential channels are exercised: the single-use ticket in the upgrade query (the only
285
+ path a browser has, since the `WebSocket` API cannot set handshake headers) and the
286
+ `Authorization` header. So are the refusals that matter — a replayed ticket, a token this
287
+ deployment never signed, a token killed by a logout, a token killed by an epoch bump, one
288
+ carrying no `jti`, and a ticket redeeming to a snapshot with **no tenant**, which is the shape
289
+ `rust-auth` writes for a platform ticket into the `wst:` keyspace both libraries share.
290
+
291
+ **A second finding, from taking a review question seriously enough to measure it: the guard
292
+ crashed the socket on the native `ws` adapter.** `WsJwtGuard` reads both credential channels
293
+ from `client.handshake`, and `@nestjs/platform-ws` hands a gateway the raw `ws` socket, which
294
+ has none — so the first property access threw a `TypeError`. Not an `AuthException`, so no
295
+ filter could answer it: the connection dropped with no close frame and the caller learned
296
+ nothing at all. It now **refuses** with `auth.token_invalid`, the same code a missing
297
+ credential gets, and the filter delivers it. The guard still cannot authenticate on that
298
+ adapter — `ws` does not retain the upgrade request — and the README says so where a consumer
299
+ chooses an adapter.
300
+
301
+ **The finding this surfaced, and its fix — `WsAuthExceptionFilter`, exported.** The library's
302
+ error catalogue did not reach the socket: `WsJwtGuard` throws `AuthException`, which extends
303
+ `HttpException`, and Nest's WebSocket exception layer understands only `WsException` — so a
304
+ refused client received `{status: 'error', message: 'Internal server error'}`. The refusal was
305
+ correct (the handler never runs); what was lost is everything the client could act on. A
306
+ reconnect policy cannot tell a dead credential from a crashed handler, and the sensible default
307
+ for an unknown error is to retry, so an expired token became a reconnect loop against an
308
+ endpoint that will refuse it forever.
309
+
310
+ Register it on a gateway that applies the guard (`@UseFilters(new WsAuthExceptionFilter())`) and
311
+ the client reads `error.code` instead. `status: 'error'` is kept — the field Nest itself sets
312
+ and the one socket.io clients branch on — with the envelope added beside it. The
313
+ `AuthException` travels whole, so a `details` payload survives.
314
+
315
+ **Scoped to `AuthException`, and answering both transports.** An argument-less `@Catch()` would
316
+ claim every exception the gateway raises, so a `WsException` an unrelated handler throws — a
317
+ domain error with its own contract — would come back as an `auth.*` code: following the README
318
+ would silently rewrite errors a consumer already ships. Everything that is not this library's
319
+ refusal keeps travelling through Nest's own layer. And a native `ws` client is written to with
320
+ `send`, not emitted on: it extends `EventEmitter`, so `emit` succeeds, dispatches a local event
321
+ and sends the peer nothing — a filter that only emits is inert on exactly the transport whose
322
+ refusal this fix exists to deliver.
323
+
324
+ Opt-in, like its HTTP twin: a library does not get to decide how an application answers
325
+ failures it did not raise. It imports neither `socket.io` nor `@nestjs/websockets` — the client
326
+ is typed structurally — so it costs a consumer with no gateway nothing. The e2e runs **two
327
+ gateways under one application**, one filtered and one not, because the claim is that the two
328
+ answer a refused client differently and one gateway can only show one of the two answers.
329
+
330
+ Three branches remain unreachable through this transport and say so in the suite: the
331
+ missing-`@nestjs/websockets` arm of `onModuleInit`, `assertDashboardSnapshot`'s non-string
332
+ `sub` (`redeemWsTicket` refuses such a record before it becomes a snapshot), and
333
+ `readUpgradeTicket`'s unparseable-URL arm (Socket.IO builds the URL itself).
334
+
335
+ - **`AuthService.refresh` read the account without its tenant.** `findById(session.userId)` with
336
+ no tenant argument, in the path that re-validates the account on every rotation — while the
337
+ interface documents that ids may collide across tenants, and `UserStatusGuard` passes both for
338
+ that reason. On a deployment whose ids are per-tenant, a homonym in another tenant could pass
339
+ the status gate on the caller's behalf, and the re-stamp path a line below would sign **that
340
+ account's tenant and role** into the token handed back. Now scoped to the tenant the session
341
+ already carries, with a test that goes red without it.
342
+
343
+ Found in review of the documentation change below, which was recommending tenant-scoped reads
344
+ to consumers while the library's own refresh path did not do one.
345
+
346
+ - **The access token's `status` claim is documented as point-in-time and never authoritative.**
347
+ Three states, and a client can tell them apart from nothing: minted at login it carries the
348
+ account's value _at that moment_; an ordinary refresh rotation stamps an **empty string**,
349
+ because the session record holds no live status; and a refresh that re-signs — which
350
+ `AuthService.refresh` does when `role`, `tenantId` or `mfaEnabled` changed — stamps the value
351
+ read during _that_ request. `rust-auth` stamps the same empty string on its rotation path, with
352
+ a test pinning it, so the middle state is a shared contract rather than a defect in either
353
+ library.
354
+
355
+ Reported by a consumer seat that measured it on a live boot: `"pending"` before the first
356
+ refresh, `""` after. Nothing in this library's own enforcement reads the claim — `UserStatusGuard`
357
+ resolves status from the cache and the repository — so it is not a bypass. The exposure is a
358
+ derived backend reading `request.user.status`, which is wrong in **both** directions:
359
+ `!== 'active'` refuses everyone once a session has been refreshed, `=== 'suspended'` refuses
360
+ nobody, ever. Both fail quietly, hours from the code that caused them.
361
+
362
+ Every populated value is stale the instant the account changes, because nothing re-stamps a live
363
+ token — so the exceptional re-stamp is the worst of the three for a reader, not the best: it
364
+ makes the claim _usually_ wrong rather than reliably empty. That is also why backfilling the
365
+ rotation path was considered and rejected: it would extend the failure mode that survives
366
+ testing. The empty string is the one state that cannot be mistaken for an answer.
367
+
368
+ Stated in the README as a three-row table and at the call site, with `mfaVerified: false` on
369
+ rotation beside it, and the `userStatusCacheTtlSeconds` window (default 60) that decides how
370
+ quickly a suspension bites.
371
+
372
+ **Apply to a derived backend.** Read status per request — `UserStatusGuard` on the route, and
373
+ for anything richer `findById(request.user.sub, request.user.tenantId)`, **tenant-scoped**, the
374
+ way that guard reads it — and never from the token. The tenant argument matters: ids may collide
375
+ across tenants and `findById` accepts an absent tenant only for deliberately cross-tenant flows,
376
+ so an unscoped read can resolve another tenant's account. If you already gate
377
+ on the claim, that gate is either refusing everyone or nobody depending on which way you wrote
378
+ the comparison.
379
+
380
+ - **The controller layer is now measured by the suite that goes through the framework.** E2E-only
381
+ branch coverage of `src/server/controllers` was **75%**, and the shortfall was mostly whole
382
+ endpoints nobody drove over HTTP. It is now **87%**, and everything still uncovered is named
383
+ below rather than left as a number.
384
+
385
+ What had no e2e at all: the **address-change flow** (`EmailChangeController` sat at 0%
386
+ functions — request, mail, confirm, replay, and the boot-time refusal when the provider cannot
387
+ deliver the token), **invitation revocation**, the **two challenge routes crossed** (a platform
388
+ temp token on the dashboard route and a dashboard one on the platform route — the branches that
389
+ stop a credential from one surface becoming a session on the other), **logout and refresh with
390
+ no credential at all** on both surfaces, and a **host that never mounted a cookie parser**,
391
+ which is a supported deployment this library takes no dependency on.
392
+
393
+ Two of those found real defects: the MFA one is under _Fixed_ below, and the invitation case
394
+ corrected the test rather than the code — revocation is by **rank**, not admin-only, and an
395
+ outranked revoke answers the same `204` a permitted one does, on purpose. Asserting the two
396
+ responses **against each other** is what makes that an anti-enumeration property instead of two
397
+ endpoints agreeing because nothing happened in either; the effect is then read where the
398
+ invitee's token is spent.
399
+
400
+ **What remains, and why it stays uncovered:** eight occurrences of `req.ip ?? ''` and one
401
+ `err instanceof AuthException` fallback. Express sets `req.ip` for every request with a live
402
+ socket, so the fallback needs a socket that is already gone — real, and not producible over
403
+ supertest. They are one duplication rather than nine independent gaps, and folding them into a
404
+ single helper (which would also fix the User-Agent bound being applied by `OAuthController` and
405
+ by nobody else) is its own change.
406
+
407
+ - **The five guards this library exports and never mounts are now driven from a host's own
408
+ controller.** `RolesGuard`, `PlatformRolesGuard`, `MfaRequiredGuard`, `OptionalAuthGuard` and
409
+ `SelfOrAdminGuard` exist for a consumer to apply to their routes, and nothing here applied them
410
+ — so their only proof was unit tests handing each guard an `ExecutionContext` no middleware
411
+ would build. E2E-only branch coverage of `src/server/guards` was **34.19%**; it is now
412
+ **65.16%**, and the five are at 100% apart from two branches named below.
413
+
414
+ The fixture controller is declared in the **test module**, not inside `BymaxAuthModule`, and
415
+ that is the point: `@UseGuards(...)` re-instantiates a guard in the declaring module's injector,
416
+ so it resolves only what this library actually **exports**. The module's export list has carried
417
+ comments claiming that works — `AuthRedisService`, `AuthRevocationService`,
418
+ `BYMAX_AUTH_USER_REPOSITORY`, `WsTicketService` and `JwtModule` are all exported for exactly
419
+ this reason — and nothing exercised the claim until now. It holds: every one of the five mounts
420
+ and runs from a consumer's controller.
421
+
422
+ Three of them are proven by falsification rather than by watching green: admitting a
423
+ user-less request in `RolesGuard`, swallowing an invalid token in `OptionalAuthGuard`, and
424
+ dropping the `mfaEnabled` type check in `MfaRequiredGuard` each turn exactly the case that
425
+ names them red.
426
+
427
+ With the wildcard route and the literal-`admin` deployment both driven, `SelfOrAdminGuard`
428
+ reaches **100% on every axis from e2e alone**, and `RolesGuard`, `OptionalAuthGuard` and
429
+ `MfaRequiredGuard` were already there.
430
+
431
+ **`SelfOrAdminGuard`'s array-valued param is reachable, and is now driven.** The first draft of
432
+ this work called it impossible — Express builds `req.params` from the path, where a name cannot
433
+ repeat — and that was wrong: Express 5 (path-to-regexp 8) fills a **named wildcard**'s param
434
+ with an array of segments, `['abc']` even for a single one. Any consumer writing
435
+ `@Get('files/*path')` behind the guard reaches it on every request, including the URLs that
436
+ look exactly like a plain param. Measured, then covered: the fixture declares a wildcard route
437
+ and the suite drives one segment and three. Refusing is deliberate — picking an element would
438
+ compare an identity against one segment of a caller-chosen path and admit the rest unlooked-at.
439
+
440
+ **One branch is out of reach of the compositions this library supports**, and says so in its own
441
+ source rather than being quietly missing from the report: `PlatformRolesGuard`'s missing
442
+ `platformHierarchy`. Reaching it needs `JwtPlatformGuard`, which needs `platform.enabled`, which
443
+ `resolveOptions` refuses without that map — so nothing this library mounts gets there, while a
444
+ consumer's own guard populating `request.user` does, over HTTP, which is what the arm defends.
445
+ Covered by its unit spec.
446
+
447
+ - **The shared wire contract is pinned by hash, so it cannot change unnoticed.**
448
+ `conformance/wire-contract.json` is the one artifact `rust-auth` and this library are supposed
449
+ to hold **byte-identically** — it is the source on both sides rather than a derivation of one.
450
+ Nothing asserted it had not moved. The conformance suite now pins its SHA-256.
451
+
452
+ **What it catches:** an _unaccompanied_ byte change — an edit that forgets to advance the
453
+ constant, a formatter rewriting the file, a merge resolving it differently. Falsified by
454
+ re-serialising the file with identical data and different bytes.
455
+
456
+ **What it does not catch, stated because the first draft of this note claimed otherwise:**
457
+ cross-implementation divergence. Changing the file _and_ the constant in one commit leaves this
458
+ suite green while `rust-auth`'s untouched pair leaves theirs green too — both green, bytes
459
+ divergent. Two independent local hashes cannot enforce agreement between two repositories,
460
+ because neither reads the other. Closing that needs a real cross-repository comparison (one
461
+ side fetching the other's committed blob in CI, or both consuming an immutable versioned
462
+ artifact); it is proposed and unbuilt.
463
+
464
+ - **The E2E config was the one place the OOM bounds from #41 were never applied.**
465
+ `jest.config.ts` and `jest.coverage.config.ts` both carry `maxWorkers: '50%'` and
466
+ `workerIdleMemoryLimit: '1GB'` — added in #41, _"bound mutation and jest memory to stop OOM
467
+ restarts"_ — and `jest.e2e.config.ts` carried neither. E2E is where they matter most: every spec
468
+ boots a full Nest application with its own `ioredis-mock`, so per-worker memory grows with the
469
+ number of spec **files**, not with the number of tests.
470
+
471
+ Found by adding spec files. Three unrelated suites began failing intermittently — password
472
+ reset, platform MFA, refresh-token reuse — alongside `Test suite failed to run`, which is a
473
+ worker dying rather than a test disagreeing. Which suites break depends on how Jest distributes
474
+ files across workers, so it presents as a flake in whatever spec was added last, and the first
475
+ diagnosis is always the new spec.
476
+
477
+ - **The cookie flags are pinned, and the half no server-side suite can reach is stated as a
478
+ consumer contract.** Cookie delivery exists for one guarantee — the tokens are never readable
479
+ from JavaScript — and a leak into JS-readable storage is invisible from the server: the API
480
+ answers identically, the wire looks correct, and every test here passes. Only a browser
481
+ observes it.
482
+
483
+ This suite now asserts **its half**: `access_token` and `refresh_token` carry `HttpOnly` and
484
+ `Secure`, the refresh cookie is path-scoped to the auth prefix rather than origin-wide, and the
485
+ set of cookies is pinned so a new credential-bearing one cannot appear outside those checks.
486
+ Asserted **per cookie**, not as a blanket rule, because `has_session` is deliberately
487
+ JS-readable — it carries no credential and is what lets a SPA know a session probably exists
488
+ without touching a token. A blanket "everything is HttpOnly" assertion would fail on it, and the
489
+ obvious fix for that would remove the feature silently.
490
+
491
+ The README now states the other half as the consumer's: assert in a browser suite that
492
+ `localStorage` and `sessionStorage` are empty and that `document.cookie` carries neither token.
493
+
494
+ - **The framework-fed layers are now proven by a suite that goes through the framework.**
495
+ Per-layer measurement, which the aggregate 100% hides: filters were at **0%** e2e coverage and
496
+ guards at **30.4% of branches**. A unit test on a controller, guard or filter _invents_ its
497
+ input — it proves the code runs, never that it is reachable.
498
+
499
+ `AuthExceptionFilter` reached 100% on every axis, and was found never to have been registered in
500
+ the harness at all while three specs carried comments crediting it for envelopes it was not
501
+ producing. The guard work drove the **refusals** — every prior e2e exercised guards admitting a
502
+ valid caller on the way somewhere else — including every refusal branch of the CSRF guard, a
503
+ token whose account was deleted after issue, and `/ws-ticket`, which had no e2e of its own.
504
+
505
+ ### Changed
506
+
507
+ - **An OAuth callback carrying neither `code` nor `error` now answers `401 auth.oauth_failed`
508
+ instead of `400 auth.validation`.** Wire change, and the one place this library and `rust-auth`
509
+ still disagreed on the same request.
510
+
511
+ `OAuthCallbackQueryDto.code` no longer carries a requirement: it is validated when it is present
512
+ and `error` is not, so its bounds are unchanged and an empty or oversized `code` is still the
513
+ pipe's to refuse, naming the field. What moved is the **absent** case. The handler already
514
+ carried the answer — `if (query.code === undefined) return this.handleCallbackFailure(...)`,
515
+ written when the "user clicked Cancel" path was fixed — and the DTO's conditional requirement
516
+ made that branch **unreachable over HTTP**: the pipe refused the request first, every time. The
517
+ branch nonetheless read as covered, by a unit test handing the controller a query object the
518
+ HTTP surface could not produce (`{ state } as never`). A test that invents its input proves the
519
+ code runs, never that it is reachable.
520
+
521
+ A codeless callback is a failed authorization, not a malformed request, and both libraries now
522
+ say so in the same code. Under `oauth.errorRedirectUrl` it takes the same `?error=oauth_failed`
523
+ redirect every other OAuth failure takes, rather than escaping the redirect as a validation
524
+ envelope.
525
+
526
+ `conformance/openapi-declared-structures.json` follows the behaviour: the `anyOf` over
527
+ `code | error` was a request structure while the pipe enforced it, and is now a handler refusal
528
+ (`OAuthController.callback#codelessCallback`) with probes both layers answer — the pipe half
529
+ read where the pipe answers, the HTTP half over a bootstrapped application. Falsified by putting
530
+ the requirement back: exactly one case goes red in each suite, and it is the codeless callback
531
+ in both.
532
+
533
+ **Apply to a derived backend.** No code change. If you match on the response to a malformed
534
+ OAuth callback — an error page keyed by `code`, a log alert, an e2e assertion — a callback with
535
+ no `code` and no `error` now arrives as `401 auth.oauth_failed` with no `details` array, where
536
+ it used to arrive as `400 auth.validation` with `details[0].field === 'code'`. The provider's
537
+ own error callback (`?error=access_denied`) is unaffected; it already answered
538
+ `auth.oauth_failed`.
539
+
540
+ ### Fixed
541
+
542
+ - **A malformed `mfaTempToken` answered `500 auth.internal` instead of `401
543
+ auth.mfa_temp_token_invalid`.** `TokenManagerService.verifyMfaTempToken` let the verifier's own
544
+ error propagate — its JSDoc said so — and nothing above catches it, so any garbage in the body's
545
+ `mfaTempToken` or in the `mfa_temp_token` cookie an OAuth callback plants produced a 5xx. Every
546
+ other failure in that method already answered `MFA_TEMP_TOKEN_INVALID`; the verification failure
547
+ now says the same thing.
548
+
549
+ Three consequences, none visible from a unit test that only ever passed it a token it had just
550
+ minted: an attacker-controlled input produced a 5xx (free noise in an operator's error budget,
551
+ and cover for the 500s that mean something); `MfaController` clears the temp cookie only for an
552
+ `AuthException` it recognises, so a browser holding a malformed cookie was never told to drop
553
+ it and replayed the same dead value on every attempt; and **`rust-auth` maps the same failure to
554
+ `MfaTempTokenInvalid`** (`token_manager.rs`,
555
+ `verify_rotating(...).map_err(|_| AuthError::MfaTempTokenInvalid)`), so the two backends
556
+ answered one request differently. Found by driving the cookie path over HTTP for the first
557
+ time.
558
+
559
+ **Apply to a derived backend.** No code change. A request that used to come back `500` now
560
+ comes back `401 auth.mfa_temp_token_invalid`. If you alert on 5xx from `/auth/mfa/challenge`,
561
+ that alert was firing on client input and will now go quiet.
562
+
563
+ - **`AuthExceptionFilter` silently displaces `@bymax-one/nest-core`'s envelope filter.**
564
+ Documented rather than code-changed: the behaviour is correct and only the advice was
565
+ incomplete. **Nothing in this repository verifies it** — doing so would mean depending on
566
+ `@bymax-one/nest-core`, and this library does not depend on its consumers' stack. The
567
+ measurement below was taken once, deliberately, and then the dependency was removed; a consumer
568
+ composing both libraries owns the standing assertion. `useGlobalFilters` binds ahead of an `APP_FILTER` provider and this filter is
569
+ `@Catch()` with no argument, so registering it in a nest-core application means nest-core's
570
+ never runs. Measured — the same request answers `{error: {code, message, details}}` with it and
571
+ the flat `{statusCode, code, message, timestamp, path, details}` without it.
572
+
573
+ **Apply to a derived backend.** Building on `@bymax-one/nest-core`? **Do not register
574
+ `AuthExceptionFilter`.** Take theirs — it already recognises this library's envelope and passes
575
+ the code, message and per-field details through unchanged. Registering both loses `statusCode`,
576
+ `timestamp`, `path` and the correlation id, which is the opposite of what adding a filter looks
577
+ like it should do. The symptom is a body nested under `error` where your other endpoints answer
578
+ flat.
579
+
580
+ - **The declared structural overlay**
581
+ ([`conformance/openapi-declared-structures.json`](conformance/openapi-declared-structures.json)).
582
+ The 1.4.2 schema artifact named three contracts in its own header that it could not express,
583
+ plus the anti-enumeration semantics that are a property of two responses rather than of either
584
+ one. They are now **structure** — `oneOf` for `reset-password`'s exactly-one-of proof set,
585
+ `required` + `anyOf` for the OAuth callback's conditional requirement — and executable probes
586
+ for the two that are not structural at all: the 8-vs-15 password floor and the four endpoints
587
+ that answer identically for an address with no account.
588
+
589
+ Kept honest by three rules. The evaluator understands `required`, `oneOf` and `anyOf` and
590
+ nothing else, and a structure using `allOf` or `not` — both valid OpenAPI 3.0 — is **refused at
591
+ load** rather than skipped, because a keyword nothing evaluates publishes a claim nothing
592
+ checks. Every entry ships probes, split across the two suites that can actually answer them:
593
+ the unit suite evaluates each body against its own structure and enforces the pipe-refused
594
+ ones, the e2e suite answers the service-enforced and response-level ones against a real
595
+ application. And each entry must **discriminate** — a probe set that all expected the same
596
+ refusal would be satisfied by a server that refuses everything, so at least one accepted body
597
+ must be answered differently.
598
+
599
+ Presence, for `required`, means present **and not `null`** — this server's rule rather than
600
+ JSON Schema's. Measured, not assumed: `@IsOptional()` registers a conditional whose predicate is
601
+ `value !== null && value !== undefined`, so `{"token": null, "otp": "…"}` carries one proof, not
602
+ two. The probes carrying an explicit `null` are what prove it.
603
+
604
+ One correction to how the exactly-one-of had been described, including in the 1.4.2 header: it
605
+ is **necessary but not sufficient**. Which of `token`, `otp`, `verifiedToken` is eligible
606
+ depends on the deployment's `passwordReset.method`, and an ineligible proof is refused with the
607
+ same `auth.password_reset_token_invalid` a structural violation gets — indistinguishable to the
608
+ client, and inexpressible in any committed document because it is option-derived. It is declared
609
+ with its own probes, under its own name, so a reader is not left inferring a symmetry that is
610
+ not there.
611
+
612
+ - **`POST {prefix}/password/change` refused the `refreshToken` it reads.**
613
+ The handler takes the caller's own refresh token through
614
+ `TokenDeliveryService.extractRefreshToken`, which reads **the request body** under
615
+ `tokenDelivery: 'bearer'` and body-after-cookie under `'both'` — but `ChangePasswordDto` never
616
+ declared the field, and the controller pipe runs `forbidNonWhitelisted: true`. So a bearer-mode
617
+ caller sending it was answered `auth.validation` naming `refreshToken`, and the only way to
618
+ change a password was to lose every other session. `refreshToken?: string` is now declared, and
619
+ appears in the generated request schema.
620
+
621
+ **A `tokenDelivery: 'cookie'` deployment was never affected** — the credential arrives in the
622
+ cookie and no body field exists — which is why this survived: the default hides it. Confirmed
623
+ live on a derived backend against the published 1.4.2, in both modes: `bearer` answers
624
+ `400 auth.validation` with `details: [{ field: 'refreshToken', message: 'property refreshToken
625
+ should not exist' }]`, and the same call without the field answers `204` while ending every
626
+ other session; `cookie` answers `204` clean.
627
+
628
+ Found by the harness fix below: the global `ValidationPipe` stripped the property before the
629
+ controller's own pipe could refuse it, so every E2E exercised a request production never sees.
630
+
631
+ The README's request-body table is updated in the same release: it had listed the old body, so
632
+ the documentation shipped in the tarball was stale about the very field this fixes. `tenantId`
633
+ aside, the table now names `refreshToken` and says what both answers mean — send it and the
634
+ calling device stays signed in, omit it and every session ends. `check:published` cannot catch
635
+ that class: it compares exported types against the docs and does not see a prose table drift
636
+ from a DTO.
637
+
638
+ - **The E2E harness shadowed the library's own validation pipe, so no E2E had ever seen
639
+ `auth.validation`.** `test/e2e/setup.ts` installed a global `ValidationPipe`, and global pipes
640
+ run **before** the controller-scoped `@UsePipes(createAuthValidationPipe())` every auth
641
+ controller declares. A DTO failure therefore answered with the framework's
642
+ `{ statusCode, message, error }` instead of `{ error: { code: 'auth.validation', details:
643
+ [{ field, message }] } }` — measured: a seven-character `newPassword` came back as
644
+ `{"message":["newPassword must be longer than or equal to 8 characters"],"error":"Bad
645
+ Request","statusCode":400}`.
646
+
647
+ The suite would have stayed green if `createAuthValidationPipe` had stopped producing the
648
+ envelope entirely. The one E2E touching the path asserted `status === 400`, which the
649
+ framework's shape satisfies exactly as well as the library's — the same range-assertion
650
+ blindness that let thirteen wrong statuses survive.
651
+
652
+ The harness now installs **no** global pipe at all, so each auth controller's own runs first.
653
+ Installing the library's pipe globally was not enough: with `whitelist: true` it strips unknown
654
+ properties before the controller's `forbidNonWhitelisted: true` can refuse them, so the harness
655
+ still would not have exercised the production contract — which is how the `refreshToken` defect
656
+ above stayed invisible. That assertion now names the code and the field.
657
+
658
+ **Apply to a derived backend.** This is a test-harness fix, but it names a real deployment
659
+ hazard: **if your application registers `app.useGlobalPipes(new ValidationPipe(...))`, it
660
+ shadows this library's pipe on every auth route.** DTO failures then answer the framework's
661
+ shape rather than `auth.validation`, and a client switching on `error.code` never sees it. With
662
+ `@bymax-one/nest-core`'s envelope filter in front, the failure is re-shaped again and surfaces
663
+ as `BYMAX_VALIDATION_FAILED` with `details: [{ issue }]` — a different code **and** a different
664
+ details shape from the `auth.validation` / `[{ field, message }]` this library and `rust-auth`
665
+ both document.
666
+
667
+ **How to tell in one query:** you have it if a DTO failure on an auth route answers
668
+ `BYMAX_VALIDATION_FAILED` with `details[].issue`; you do not if it answers `auth.validation`
669
+ with `details[].field`. Grep your own error logs for the first pair rather than auditing where
670
+ pipes are registered.
671
+
672
+ **The fix:** scope your global pipe away from the auth routes, or build it with
673
+ `createAuthValidationPipe()`, which is exported for exactly this.
674
+
675
+ **The durable guard — assert the composed envelope in your application's E2E**, because neither
676
+ library can. This library's suite sees its own pipe; `nest-core`'s suite sees its own filter;
677
+ the shape a client actually receives exists only where the two are wired together, which is your
678
+ application. A consumer who fixes the pipe today and adds a global one next quarter is back here
679
+ otherwise. One scenario is enough: drive a real request that fails validation and shape-match
680
+ both `code: 'auth.validation'` and `details: [{ field, … }]`.
681
+
682
+ - **`/client` required a `tenantId` the server refuses, so a consumer had to bypass it.**
683
+ `LoginInput`, `RegisterInput`, `ResetPasswordInput` and `forgotPassword(email, tenantId)` all
684
+ demanded the field. On a deployment with a configured `tenantIdResolver` — the case 1.4.2 made
685
+ breaking — sending it answers `400 auth.validation` with a `tenantId` field detail, so the
686
+ library's own typed client could not talk to the library's own server. A consumer building an
687
+ SPA rejected `createAuthClient` and `AuthProvider` over exactly this and hand-wrote the request
688
+ shapes.
689
+
690
+ All four are now `tenantId?: string`. The defect was type-level rather than on the wire —
691
+ `JSON.stringify` already dropped an `undefined` property — which is why the guard is that the
692
+ client suite now calls `login`/`register`/`forgotPassword`/`resetPassword` **without** a tenant
693
+ and would stop compiling if the field went back to required.
694
+
695
+ The JSDoc was the worse half. It read _"`tenantId` is required because the server-side
696
+ `LoginDto` enforces it with `@IsNotEmpty()`"_ — and that was never true: `@IsNotEmpty()` sits
697
+ under `@IsOptional()`, so it rejects an empty string when the field is present and says nothing
698
+ about absence. `LoginDto.tenantId` has been optional since **1.3.0**; the comment misread its own
699
+ decorator stack and survived three minors, because a comment is checked by nobody. The
700
+ replacements state the consequence and name where the mechanism is asserted, rather than
701
+ restating decorators they cannot see.
702
+
703
+ - **Draining the response body deadlocked under request interception.**
704
+ `await response.body?.cancel()` in `createAuthFetch` and `createAuthClient`. Under MSW or
705
+ undici-in-jsdom the promise never settles, so every call whose response carries a body hung.
706
+ `/auth/refresh` carries one on success as well as on failure, which put it on the happy path at
707
+ every token rotation.
708
+
709
+ **Production was never affected, and that is measured rather than assumed** — a real browser
710
+ cancels the stream cleanly, confirmed under Playwright by deleting only the `access_token`
711
+ cookie and watching a reload produce exactly one `POST /auth/refresh`, status 200, with no
712
+ bounce to sign-in. So this is a **testing defect**, and the cost is precise: every consumer
713
+ using request interception cannot test refresh-and-retry at all, and it is the _success_ path
714
+ that is untestable. A four-way probe established the body's construction is irrelevant —
715
+ `HttpResponse.json`, a raw string and a hand-built `ReadableStream` all hang while `.json()` on
716
+ the same response resolves — so it is the interceptor's stream teardown, and dropping the
717
+ `await` fixes it for every consumer without MSW changing anything.
718
+
719
+ The drain is no longer awaited; nothing downstream needs it to have completed, the status has
720
+ already been read. Regression test: a response whose `cancel()` never settles.
721
+
722
+ - **`refreshEndpoint` was undocumented, and its default 404s in a plain SPA.**
723
+ It defaults to `/api/auth/client-refresh`, a Next.js proxy route, and a Vite/CRA app serves
724
+ nothing there — refresh silently fails and every access-token expiry presents as a session bug.
725
+ The README now covers it, with the symptom: _if every expiry logs the user out, check
726
+ `refreshEndpoint` before looking at cookies._
727
+
728
+ **Apply to a derived backend.** Nothing changes server-side. Frontends on a non-Next stack
729
+ should set `refreshEndpoint` explicitly, and frontends on a resolver deployment should now stop
730
+ passing `tenantId` — the client no longer forces them to.
731
+
732
+ ## [1.4.2] - 2026-08-13
733
+
734
+ Closes the two findings that came out of auditing this library from the outside: every DTO it
735
+ ships published an empty schema, and a request naming a tenant a configured resolver would not
736
+ honour was answered `201` with the account created elsewhere. **One breaking change rides along
737
+ in a patch** — the tenant refusal — so `^1.4.0` and `~1.4.1` both pick it up on a routine update.
738
+ Read the `Apply to a derived backend` note before upgrading.
739
+
740
+ ### Added
741
+
742
+ - **Request-body schemas, generated from the DTOs' own decorators**
743
+ ([`conformance/openapi-request-schemas.json`](conformance/openapi-request-schemas.json)).
744
+ OpenAPI 3.0 for all 22 DTOs, derived from class-validator metadata and regenerated by
745
+ `pnpm gen:openapi-schemas`. It closes a gap a consumer's OpenAPI audit found: because the
746
+ `@nestjs/swagger` CLI plugin does not run over precompiled `node_modules`, every DTO this
747
+ library ships published as `{"type":"object","properties":{}}`, and the real contracts were
748
+ discoverable only by triggering validation errors.
749
+
750
+ The artifact is data rather than code so `rust-auth` can assert the same file, and it is
751
+ **generated, not hand-written**: the suite regenerates and fails on drift, so a decorator
752
+ change nobody mirrored is a red test in the repository that caused it. Three guards make the
753
+ gate mean what it says — the committed copy must equal the regeneration, the set of validators
754
+ the derivation understands is pinned by name (an unmapped decorator is silent, so a new one
755
+ must fail rather than thin the schema), and the DTO list is asserted so a DTO added later
756
+ cannot be quietly uncovered.
757
+
758
+ A regex carrying flags is **refused** rather than rendered: `pattern` is the ECMA 262 dialect
759
+ with no flags slot (JSON Schema Wright Draft 00 §5.2.3) and ECMA 262 has no inline modifier to
760
+ rewrite them into, so emitting `.source` would publish a stricter pattern than the server
761
+ enforces, silently.
762
+
763
+ - **Normalisation descriptions, each carrying the probe that verifies it**
764
+ ([`conformance/openapi-request-descriptions.json`](conformance/openapi-request-descriptions.json)).
765
+ Twelve e-mail fields are trimmed and lowercased before validation — a fact a client needs and
766
+ no schema keyword expresses. A generator cannot derive it, because `@Transform` runs an opaque
767
+ lambda, so the prose is written by hand and every entry ships an `{ input, expected }` probe the
768
+ suite runs through `plainToInstance`. The probe is the sentence's operational meaning rather
769
+ than a test beside it, so prose and behaviour cannot drift.
770
+
771
+ The opposite direction is covered by a canary sweep: one rich input through every string
772
+ property of all 22 DTOs, failing when a property transforms without a declared entry. Stated
773
+ limit, in the artifact itself: a future transform that is the identity on that canary escapes
774
+ both checks. The rejected alternative — reading class-transformer's `cjs/storage` internals —
775
+ has no type declarations and is an unpublished path that can move between minors.
776
+
777
+ ### Fixed
778
+
779
+ - **BREAKING: a request body naming `tenantId` is now refused when the deployment configures a
780
+ `tenantIdResolver`**, instead of being accepted and silently discarded. A security audit of a
781
+ derived backend found `POST /register` answering `201` for
782
+ `{"tenantId": "attacker-chosen-tenant", ...}` while creating the account under the resolved
783
+ tenant — the caller's belief about which tenant it registered into diverging from server state,
784
+ on the boundary the resolver exists to defend, with nothing in the response saying so. No
785
+ privilege crossed, and that is why it survived: accept-and-ignore is the worst of the three
786
+ available answers precisely because it looks like success.
787
+
788
+ The refusal is **conditional, and the asymmetry is the point**. Without a resolver the field is
789
+ the only thing that can name a tenant — `resolveTenantId` already answers `400` when it is
790
+ absent — so rejecting it outright would break every deployment that relies on it. With a
791
+ resolver configured it does not participate at all, and whitelist validation already refuses
792
+ `role` and `status` on exactly that principle. This makes the principle config-aware rather
793
+ than carving an exception out of it.
794
+
795
+ `null` and an omitted field are not refused: the caller asserted nothing, so there is nothing
796
+ to contradict.
797
+
798
+ **Apply to a derived backend:** if you configure `tenantIdResolver`, stop sending `tenantId` on
799
+ the nine endpoints that accept it. Eight read it from the **request body** — `register`,
800
+ `login`, `verify-email`, `resend-verification`, `forgot-password`, `reset-password`,
801
+ `verify-otp`, `resend-otp` — and one reads it from the **query string**:
802
+ `GET /oauth/:provider?tenantId=…`, so dropping a body field is not the change to make there.
803
+ All nine answered `201`/`200` while discarding the value and now answer `400 auth.validation`
804
+ with `field: "tenantId"`. Deployments without a resolver are unaffected — the field remains
805
+ required there.
806
+
19
807
  ## [1.4.1] - 2026-08-12
20
808
 
21
809
  Aligns every HTTP status with `rust-auth` and makes the pairing structural rather than
@@ -1468,7 +2256,9 @@ ever installable.
1468
2256
  - 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
1469
2257
  - 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
1470
2258
 
1471
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.1...HEAD
2259
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...HEAD
2260
+ [1.4.3]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...v1.4.3
2261
+ [1.4.2]: https://github.com/bymaxone/nest-auth/compare/v1.4.1...v1.4.2
1472
2262
  [1.4.1]: https://github.com/bymaxone/nest-auth/compare/v1.4.0...v1.4.1
1473
2263
  [1.4.0]: https://github.com/bymaxone/nest-auth/compare/v1.3.2...v1.4.0
1474
2264
  [1.3.2]: https://github.com/bymaxone/nest-auth/compare/v1.3.1...v1.3.2