@bymax-one/nest-auth 1.4.2 → 1.4.4

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,1843 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.4] - 2026-08-19
22
+
23
+ ### Changed
24
+
25
+ - **`SessionInfo` now names the shape `GET /sessions` returns.** (#156) Two interfaces answered to
26
+ that name — the session listing in `SessionService`, and the contextual payload sent in
27
+ new-login alert emails — and the barrel exported the **email** one under the plain name, with
28
+ the listing type exported as `ActiveSessionInfo`. That is backwards: a consumer typing a session
29
+ listing imports `SessionInfo`, receives `device` and `ip` with no `id` — and a `sessionHash` that
30
+ means something different. On the alert type it is the TRUNCATED display value; on the listing it
31
+ is the full 64-hex hash. Same field name, same type, different value, and the truncated one is
32
+ precisely what `DELETE /sessions/:id` refuses.
33
+
34
+ It does. Two consumer sessions disagreed for a day over exactly that — one read the wire and saw
35
+ an `id`, the other read the published type and did not. Neither was careless; the name resolved
36
+ to the wrong shape.
37
+
38
+ **Apply to a derived backend.** The email-alert type is now `SessionAlertInfo`, named for what
39
+ it is. If you implement `IEmailProvider`, rename the parameter type on `sendNewSessionAlert` —
40
+ the fields are unchanged. If you imported `ActiveSessionInfo` to type a session listing, import
41
+ `SessionInfo` instead: same shape, correct name. No runtime behaviour moves.
42
+
43
+ - **A malformed `sessionHash` answers `VALIDATION`, not `SESSION_NOT_FOUND`.** (#156) The two were
44
+ deliberately indistinguishable, on the argument that telling them apart would let a caller
45
+ enumerate valid hash formats. The format is not a secret: it is 64 hex characters,
46
+ `SessionInfo.sessionHash` publishes it on every listed session, and the route documents it. So
47
+ the pairing protected nothing and cost something real — a consumer sending a malformed hash got
48
+ the same answer as one sending an already-revoked session, and read a UI bug as a race between
49
+ the session list and the click. Twenty minutes chasing a race that cannot happen.
50
+
51
+ A well-formed hash that names nothing still answers `SESSION_NOT_FOUND`. That is where the
52
+ no-enumeration argument does apply, because that answer really would say whether a session
53
+ exists.
54
+
55
+ **Apply to a derived backend.** If you branch on `auth.session_not_found` to mean "bad input",
56
+ branch on `auth.validation` for that case; the payload names `sessionHash` in `details`.
57
+
58
+ ### Fixed
59
+
60
+ - **`DELETE /sessions/:id` documented a prefix it has always refused.** (#156) The controller
61
+ described the parameter as accepting "its hash prefix (display id) **or** full 64-character
62
+ SHA-256 session hash". The handler has only ever accepted the full hash — and until the change
63
+ above, a prefix was refused with the same error as a session that no longer exists, which is
64
+ what made it read as a race rather than as a rejected input.
65
+
66
+ The prefix will **not** be made to work: `SessionInfo.id` is the first 8 characters of the hash
67
+ and is not unique by construction, so resolving one on a revocation could revoke a different
68
+ session than the one the user clicked. The documentation now says so and names the display value
69
+ as display-only.
70
+
71
+ - **`mergeHeaders` sent every header twice when the caller's key case differed from the default,
72
+ which broke every authenticated call carrying a body.** (#156)
73
+
74
+ Header names are case-insensitive; plain object keys are not. `DEFAULT_HEADERS` keys
75
+ `Content-Type`, `Headers.prototype.forEach` yields lowercase names, and both survived into the
76
+ merged record — so `fetch` joined them on the wire:
77
+
78
+ ```
79
+ content-type: application/json, application/json
80
+ ```
81
+
82
+ Legal HTTP, so nothing rejects it. The backend simply stops parsing the body and answers
83
+ `400 "role is required"` naming a field that IS present, which reads as a caller bug while the
84
+ caller is correct. The header is the last place anyone looks.
85
+
86
+ **Both reports put arrays in the safe column, and that is one notch too narrow.** Measured
87
+ against the shipped function, the rule is only _"the key case differs from the default"_ — the
88
+ `HeadersInit` shape does not enter into it. A record written `content-type`, the spelling the
89
+ platform itself uses, duplicates just as surely as a `Headers` instance does, and so does an
90
+ array of pairs written lowercase. `Headers` merely makes it unavoidable, because `forEach`
91
+ lowercases for you. "We do not pass `Headers`" was not the reassurance it looked like.
92
+
93
+ **A second site neither report reached:** the factory built its defaults with the same
94
+ case-sensitive spread, so overriding the content type through the documented
95
+ `defaultHeaders` option also duplicated it — set up once, poisoning every request, far from
96
+ the call anyone is debugging.
97
+
98
+ Fixed by letting `Headers` own the semantics on both paths: names normalise per the spec, and
99
+ `set` replaces rather than appends, which is the intent the old code expressed and did not
100
+ achieve. `mergeHeaders` now returns a `Headers` rather than a record, because handing back a
101
+ record hands back a structure in which `Content-Type` and `content-type` are two different
102
+ things — the shape the defect grew in.
103
+
104
+ Three `eslint-disable security/detect-object-injection` comments and one Stryker disable went
105
+ with it: a `Headers` has no prototype to pollute, so the guard is no longer working against the
106
+ type it is written on. The unsafe-name drop is kept as observable behaviour, and now also
107
+ covers the factory defaults, which the previous spread never guarded.
108
+
109
+ **The class, for anyone auditing the rest of the client surface:** case-insensitive header
110
+ semantics implemented with case-sensitive object keys. Anywhere this library keys a header by
111
+ string, the same latent duplicate exists.
112
+
113
+ The regression test asserts what the wire carries rather than what the record contains, and the
114
+ distinction is the whole reason this survived: the previous tests read ONE case-sensitive key
115
+ off the raw record, which held the default's value, while the caller's lowercase twin sat beside
116
+ it unread. Nothing ever asserted against the joined value, so nothing failed. A mock server does
117
+ not help either — it accepts the duplicate without complaint, because the request is well-formed
118
+ and wrong.
119
+
120
+ ### Added
121
+
122
+ - **`AuthService.isAccountLockedOut()` and `getAccountLockoutSeconds()` — read the lockout, not
123
+ just clear it.** (#157)
124
+
125
+ `unlockAccount` was already public, so a host could **clear** a dashboard lockout. There was no
126
+ public way to **read** one, so a console could offer an Unlock button and could not tell anyone
127
+ whether it had anything to do. The write side was exposed and the read side was not.
128
+
129
+ The primitives existed — `BruteForceService.isLockedOut` and `getRemainingLockoutSeconds` are
130
+ both public — but the identifier was out of reach. It is an HMAC of
131
+ `dashboard:{tenantId}:{email}` under the library's own derived `hmacKey`, which a consumer does
132
+ not have, and reproducing that preimage is exactly what keeping the derivation in one place
133
+ prevents: a third copy in a consumer repository is a third chance to drift, and a drifted key
134
+ reads a record that never exists. That reports **"not locked out" for every account, including
135
+ locked ones** — a false negative on a security indicator, delivered confidently and silently.
136
+
137
+ The second method matters more than it looks. A bare flag with no horizon is the interface that
138
+ invites the support call the indicator was meant to prevent: it can say an account is locked and
139
+ cannot say for how long, so the only honest advice left is "try again later".
140
+
141
+ **Cheap enough for every row of a directory listing — issue them concurrently.** The reporter
142
+ measured twenty of these against a local Redis over ioredis: `0.39 ms` issued concurrently
143
+ against `0.33 ms` for a single one, and `6.25 ms` awaited one at a time in a loop. Concurrency is
144
+ what buys that, by overlapping the round trips; use `Promise.all` and not `await` inside a loop.
145
+
146
+ Those numbers are one environment's, not a guarantee this library makes. Each call is its own
147
+ Redis command, the ioredis client is the host's, and whether the commands are also **batched**
148
+ into a single write depends on `enableAutoPipelining`, which ioredis leaves off by default.
149
+
150
+ `getAccountLockoutSeconds` reads the threshold before the TTL. The underlying counter is created
151
+ on the FIRST failed attempt, so its raw TTL is positive long before the lockout exists —
152
+ returned unchecked it would show "locked for 14 minutes" beside an account whose next attempt
153
+ would succeed, with the two reads contradicting each other on the same account.
154
+
155
+ Argument order mirrors `unlockAccount(email, tenantId)` so the three read as a set, and a test
156
+ asserts all three address the SAME record rather than pinning three copies of the preimage.
157
+
158
+ - **`authDocumentSecurity()` — the document-level default, derived instead of copied.** An OpenAPI
159
+ contributor carries operations and components, never the document root, so the top-level
160
+ `security` that covers a consumer's OWN routes stays theirs to set. But the scheme it has to
161
+ name, and whether that scheme exists at all, are decided by THIS library's configuration. The
162
+ consumer was left writing a name they do not control.
163
+
164
+ Exporting `AUTH_SECURITY_SCHEMES` narrowed that and did not close it: a correct spelling read
165
+ off a constant still leaves "which of the four applies to my deployment" unanswered, and the
166
+ answer takes the guard family and `tokenDelivery` together. Every consumer setting a default was
167
+ re-deriving it by reading this package's source.
168
+
169
+ ```ts
170
+ import { authDocumentSecurity } from '@bymax-one/nest-auth'
171
+
172
+ security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
173
+ ```
174
+
175
+ **Pass the option exactly as you wrote it, `undefined` included.** `tokenDelivery` is optional
176
+ on the module, so a deployment relying on the documented `'cookie'` default has nothing to
177
+ forward — and requiring a narrowed value here would have forced `options.tokenDelivery ?? 'cookie'`
178
+ at the call site, putting a library decision back into consumer code one line further out.
179
+ Omission resolves through the same constant the module resolves it with.
180
+
181
+ It also settles the part a hand-written default usually gets wrong. Under `tokenDelivery: 'both'`
182
+ the result is a two-entry **list** — OpenAPI reads that as OR, either transport satisfies it.
183
+ Merged into one entry with two schemes it would mean AND, describing a server that demands the
184
+ same credential twice.
185
+
186
+ **Reported from a live failure, not from review.** A consumer whose `tokenDelivery` is a
187
+ validated environment enum kept a hard-coded cookie scheme in their document default. Setting
188
+ that variable to `bearer` stopped the process from booting: no cookie scheme is declared in that
189
+ mode, and `assertSchemesDeclared` refuses a default naming one rather than serving a dangling
190
+ reference. Reachable by configuration alone, with no code change and no warning.
191
+
192
+ What it does **not** answer is what you mounted — the dashboard schemes are declared only where
193
+ a dashboard controller is registered, and an OAuth-only or platform-only deployment declares
194
+ neither. That row of the README's table is still yours, and the JSDoc says so rather than
195
+ implying the call is sufficient.
196
+
197
+ A conformance test now asserts that every scheme this function names is one the contributor
198
+ declares for the same delivery mode. The two derive independently — the requirement from the
199
+ guard family and the mode, the definitions from the resolved options and the registration — so
200
+ nothing but that assertion makes them agree.
201
+
202
+ ### Fixed
203
+
204
+ - **The sink's own documentation routed consumers into the wiring that drops
205
+ `containsCredential`.** `AuthEmailSink` said `@bymax-one/nest-notification`'s
206
+ `EmailService.send` "satisfies it structurally". True of the shape and false of the semantics:
207
+ passed in directly, as that sentence invites, `containsCredential: true` lands in a property
208
+ that library does not read, while its own switch — `publishProviderText` — stays at its
209
+ default. A relay answering `550` with the offending body quoted then puts a reset code in an
210
+ audit record, from a `send` call that looked correctly wired.
211
+
212
+ The JSDoc now states that structural fit is not enough, that an implementation owes a
213
+ **translation** of the flag into whatever its channel calls the same thing, and it names that
214
+ library as both the worked example and the trap, with the adapter to copy. Nothing about the
215
+ types changed; the field was always emitted. What changed is that the documentation stops
216
+ pointing at the one configuration where it is ignored.
217
+
218
+ Raised by the `nest-notification` seat, which is taking the symmetric half on its side. Emitting
219
+ `publishProviderText` from here was considered and rejected: it would put another contract's
220
+ vocabulary into this package's published surface, and that field has a rename open upstream.
221
+
222
+ - **The reuse-detection hook reported a compromise and no way to act on it.**
223
+ `onRefreshTokenReuseDetected` fires on the strongest evidence this library produces — a refresh
224
+ token presented after it was already exchanged, so one of its two holders is not the owner — and
225
+ it received a context whose `ip` and `userAgent` were **empty strings**. `HookContext` declares
226
+ both as required `string`, so the type promised a value the path did not deliver.
227
+
228
+ The values were never unavailable: `reissueTokens(oldRefresh, ip, userAgent)` and its platform
229
+ twin have both in scope as their own parameters, and the emit built
230
+ `createEmptyHookContext()` anyway. `userId` says whose account the family belongs to; `ip` and
231
+ `userAgent` are the only description of **who presented** the token. A report carrying the first
232
+ and not the second names a victim and says nothing about the party holding a credential that
233
+ should not exist.
234
+
235
+ Both planes now carry them. `sanitizedHeaders` stays `{}` deliberately — the rotation path
236
+ receives the address and the agent, never the header map, so there is nothing to sanitize and an
237
+ invented value would be worse than an empty object a consumer can see is empty.
238
+
239
+ Found by a consumer wiring the hook into a real backend and reading the emitted record, not by a
240
+ test: the two specs covering this hook asserted the context as `expect.anything()`, which cannot
241
+ distinguish a populated context from an empty one. Both now pin it exactly.
242
+
243
+ ### Added
244
+
245
+ - **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, and `AUTH_ERROR_STATUS` now
246
+ also from `./shared`. Two different defects, worth keeping apart: `AUTH_SECURITY_SCHEMES` was
247
+ declared and never re-exported, so there was nowhere to import it from at all;
248
+ `AUTH_ERROR_STATUS` shipped from the server entry and only from there, so reaching it meant
249
+ pulling the NestJS peer dependencies — which the three cases the README points at (a typed
250
+ client, an API document, a browser test) are precisely the ones that must not.
251
+
252
+ The scheme names are stable identifiers — renaming one is a break a generated client feels —
253
+ while their DEFINITIONS are derived from configuration, which is why the names are worth
254
+ exporting and the definitions are not. A platform-only deployment guarding its own routes with
255
+ `JwtAuthGuard` has to declare the dashboard access scheme itself, because `schemesFor` gates
256
+ dashboard schemes on `dashboardMounted`; before this it was told to write
257
+ `bymaxAuthAccessCookie` by hand, with nothing checking the spelling, in a section whose whole
258
+ subject is that literals drift from configuration.
259
+
260
+ The 1.4.3 entry and the README both said the constant was not public and to use string
261
+ literals. **That advice is now wrong**; the 1.4.3 section is left as written, because it was
262
+ true when it shipped, and this entry is the correction. The README paragraph is rewritten.
263
+
264
+ ### Security
265
+
266
+ - **The tenant-scoped user port did not bind, and a stale implementation destroyed the password
267
+ hash.** `IUserRepository`'s ten account-naming methods took the tenant as a positional
268
+ `string`. TypeScript accepts an implementation with FEWER parameters, so a consumer who
269
+ upgraded and did not touch their repository still type-checked — proven, not argued:
270
+
271
+ ```
272
+ $ tsc --noEmit --strict # a pre-upgrade implementation against the shipped port
273
+ exit code: 0
274
+ ```
275
+
276
+ Two consequences. Their `findById(id)` ignored the tenant, so the cross-tenant read the entry
277
+ below closes stayed open on a clean build, with no error and no warning. And the library calls
278
+ `updatePassword(userId, tenantId, hash)`: a stale two-parameter implementation bound
279
+ `passwordHash = tenantId` and wrote the tenant id into the credential column.
280
+
281
+ **Every one of those methods now takes a single object.** An object parameter is structurally
282
+ incompatible with the old positional shape, so the same implementation fails to compile instead
283
+ of failing in production. `TenantScopedUserRef` and the eight params types are exported from the
284
+ package entry, because a consumer implements this port and needs to name what it receives.
285
+
286
+ **Apply to a derived backend.** Every `IUserRepository` method that names an account takes ONE
287
+ object now — `findById`, `findByEmail`, `updatePassword`, `updateMfa`, `updateLastLogin`,
288
+ `updateStatus`, `updateEmailVerified`, `updateEmail`, `findByOAuthId` and `linkOAuth`. Destructure
289
+ it and keep filtering on the tenant. **Eight of the ten are keyed by `id`.** Seven of those are
290
+ writes: on Prisma they are still `updateMany({ where: { id, tenantId } })` rather than
291
+ `update({ where: { id } })`, because `update` takes a unique clause and cannot carry the pair.
292
+ The eighth, `findById`, is a **read** — it filters on the same pair through `findFirst`, because
293
+ `findUnique` by id alone can answer with another tenant's row. **The other two are not keyed by
294
+ `id` at all:** `findByEmail` receives `{ email, tenantId }` and `findByOAuthId` receives
295
+ `{ provider, providerId, tenantId }`, and each filters on its own lookup key plus the tenant.
296
+
297
+ ```ts
298
+ // before → after, for every signature that changed
299
+ findById(id, tenantId)
300
+ findById({ id, tenantId })
301
+
302
+ findByEmail(email, tenantId)
303
+ findByEmail({ email, tenantId })
304
+
305
+ updatePassword(id, tenantId, passwordHash)
306
+ updatePassword({ id, tenantId, passwordHash })
307
+
308
+ updateMfa(id, tenantId, data)
309
+ updateMfa({ id, tenantId, data })
310
+
311
+ updateLastLogin(id, tenantId)
312
+ updateLastLogin({ id, tenantId })
313
+
314
+ updateStatus(id, tenantId, status)
315
+ updateStatus({ id, tenantId, status })
316
+
317
+ updateEmailVerified(id, tenantId, verified)
318
+ updateEmailVerified({ id, tenantId, verified })
319
+
320
+ updateEmail(id, tenantId, email)
321
+ updateEmail({ id, tenantId, email })
322
+
323
+ findByOAuthId(provider, providerId, tenantId)
324
+ findByOAuthId({ provider, providerId, tenantId })
325
+
326
+ linkOAuth(userId, tenantId, provider, providerId)
327
+ linkOAuth({ id, tenantId, provider, providerId })
328
+ ```
329
+
330
+ **This supersedes the note in the tenant-scoping entry below**, which told you to take `tenantId`
331
+ as the _second argument_. Follow that note today and the implementation does not compile:
332
+ `findById(id: string, tenantId: string)` is rejected against `findById(params: TenantScopedUserRef)`
333
+ with `TS2416 — Target signature provides too few arguments`. That loud failure is the entire point
334
+ of the shape.
335
+
336
+ What still passes silently is narrower, and worth stating exactly rather than overstating:
337
+ TypeScript accepts an implementation declaring FEWER parameters than the signature, so one taking
338
+ no parameters at all compiles — and so does one that takes the object and never reads `tenantId`
339
+ off it. The compiler rules out a value bound into the wrong slot. It cannot rule out a body that
340
+ ignores the tenant, which is why every method documents the scoping as a MUST.
341
+
342
+ The `AuthService` guidance in that note is unaffected:
343
+ `getMe(userId, tenantId)` and `issueTokensForUserId(userId, tenantId, ip, userAgent)` are
344
+ unchanged. The README's example implementation shows the whole shape.
345
+
346
+ ```ts
347
+ // before
348
+ await repo.updatePassword(userId, tenantId, hash)
349
+ // after
350
+ await repo.updatePassword({ id: userId, tenantId, passwordHash: hash })
351
+ ```
352
+
353
+ The property is pinned by a type test that compiles a stale implementation against the real port
354
+ and requires `tsc` to refuse it, with a positive twin that compiles the current shape — a
355
+ negative test that cannot pass for the wrong reason. Nothing else in the suite can see this:
356
+ every other check reads the declaration, and a positional signature reads as correct in all of
357
+ them. One residual hole is stated rather than hidden: TypeScript always accepts an
358
+ implementation taking NO parameters, which cannot put a value in the wrong slot.
359
+
360
+ - **Two re-authentication counters were tenant-blind.** `changePassword` and `requestChange`
361
+ scoped their account read and then derived the brute-force identifier from
362
+ `reauth:{flow}:{userId}` — the bare id. A repository id is unique only within a tenant, so
363
+ failures against `t1/u1` spent `t2/u1`'s budget and locked that account out of changing its own
364
+ password or address without any credential, and a success on either side cleared the other's
365
+ count. Both now derive from the injective `userSubject`, and the tests assert the separation
366
+ rather than pinning a digest — a pinned hex string is satisfied by any preimage that produces
367
+ it, so updating the constant after a preimage change keeps the test green with its rule gone.
368
+
369
+ - **Two tenants could share one session index, one token epoch and one recovery-code claim.**
370
+ The subject every user-derived key is HMACed over was `dashboard:{tenantId}:{userId}`, and a
371
+ bare `:` between two free-form components is not injective. Both halves may legitimately
372
+ contain it — the DTO charset deliberately admits a tenant id like `acme.eu-west-1:prod`, and a
373
+ composite `tenant:user` subject is a documented `sub` shape — so:
374
+
375
+ ```
376
+ tenantId 'acme:prod' + userId 'u1' -> dashboard:acme:prod:u1
377
+ tenantId 'acme' + userId 'prod:u1' -> dashboard:acme:prod:u1 <- same preimage, same HMAC
378
+ ```
379
+
380
+ Two unrelated tenants then shared every key derived from it: the session index, the token
381
+ epoch, the five MFA store keys, the three MFA failure counters, the recent-authentication
382
+ marker and — worst — `rcu:`, the claim that stops a recovery code being spent twice. Revoking
383
+ one tenant's sessions swept the other's, and one tenant could spend the other's recovery code.
384
+ That is precisely the cross-tenant revocation the entry below removes, reintroduced through the
385
+ delimiter.
386
+
387
+ **Whether a given deployment could reach that collision depends on its user ids, and the two
388
+ halves are not equally exposed.** The `tenantId` half is attacker-chosen by default: it arrives
389
+ in the request body, validated only for length and control characters, and a deployment only
390
+ takes that away by configuring `tenantIdResolver`. The `userId` half comes from
391
+ `IUserRepository`, and the **scheme** is the host's — but the resulting value is not
392
+ automatically outside the caller's reach, because `CreateUserData` carries `email` and `name`
393
+ straight from the registration request. `name` in particular is validated for length and
394
+ nothing else: no charset constraint, so `:` passes. A host that derives its id from either
395
+ field has handed the caller influence over both halves.
396
+
397
+ The arithmetic makes the user id the gate. For `{t1}:{u1}` and `{t2}:{u2}` to render the same
398
+ string with `(t1,u1) ≠ (t2,u2)`, one of the two **user ids** must itself contain a `:` — there
399
+ is no way to move the boundary otherwise. Three tiers follow, and they are not the same risk:
400
+
401
+ - **Host-generated ids with no colon** (UUID, a sequence): unreachable. The preimage is
402
+ ambiguous in principle and no input can exercise it.
403
+ - **Composite host-assigned ids** (`dept:1234`, a stored `tenant:user` subject): reachable by
404
+ accident. Two unrelated accounts can collide with nobody trying.
405
+ - **Ids derived from caller-supplied input in a way that PRESERVES the delimiter** (the display
406
+ name stored verbatim; a `{name}:{n}` disambiguator): reachable **on purpose**. The attacker
407
+ picks the tenant, then picks a value that splits the preimage where they want, and both
408
+ halves are theirs. `name` is the field that carries this: `@IsString`, `@MinLength(2)`,
409
+ `@MaxLength(128)` and **no charset rule**, so a `:` passes.
410
+
411
+ The address is the instructive near-miss. `@IsEmail` does accept a colon —
412
+ `"ana:silva"@x.com` is a valid addr-spec with a quoted local part, and class-validator
413
+ takes it. What saves the scheme is the second half of the condition below: splitting there
414
+ leaves `silva"@x.com`, and that is not a valid address, so no second account can hold it.
415
+ The colon is present and the suffix pair still cannot be formed.
416
+
417
+ The qualifier carries the tier, and it is a property of the **sets of values the two sides
418
+ admit**, not of one id and not of the transform that made it. A colon in the id is necessary
419
+ and not sufficient. Both halves have to cooperate:
420
+
421
+ > can the id scheme produce two valid ids `u1` and `u2` with `u1 = p + ":" + u2`, **and** is
422
+ > `t + ":" + p` still a valid tenant for some tenant `t` the caller can send?
423
+
424
+ Only then does moving the boundary turn one pair into the other. The tenant clause is not
425
+ decoration: a body-supplied tenant is non-empty, at most 128 characters and control-free, so
426
+ a scheme whose only suffix pair needs a 200-character or control-bearing `p` satisfies the
427
+ first clause and is still unreachable.
428
+
429
+ A worked pair that clears every validator this library applies:
430
+
431
+ ```
432
+ name 'ana:silva' -> id 'ana:silva' tenant 'acme' -> dashboard:acme:ana:silva
433
+ name 'silva' -> id 'silva' tenant 'acme:ana' -> dashboard:acme:ana:silva
434
+ ```
435
+
436
+ And the case that does **not** qualify despite carrying a colon: a fixed-width
437
+ `sha256:{64 hex}` id. Every id in that scheme is the same length, so none is a proper suffix
438
+ of another, and no tenant makes `t1:u1` equal `t2:u2`. Slugging to `[a-z0-9-]`, or rendering
439
+ a digest as bare hex or base64url, removes the delimiter and settles it a step earlier.
440
+
441
+ Read the value sets you can actually store — not the provenance of the input, not the
442
+ transform's reputation, and not one example id in isolation.
443
+
444
+ That third tier is the reason the previous wording mattered: it read as though the user id were
445
+ always the host's to control, which would have left this the mildest of the three. The tier is
446
+ narrow on purpose — a note that over-warns gets discounted the same way one that under-warns
447
+ gets ignored, and only one of those failures is visible to whoever wrote it.
448
+
449
+ That does not make the fix conditional. A library may not assume the shape of ids its consumers
450
+ assign — it is the same assumption `findById` taking a tenant already refuses to make — and a
451
+ preimage that is injective only for well-behaved input is not injective. But an operator
452
+ reading this entry should be able to tell which side of that line they are on, and the previous
453
+ wording did not let them.
454
+
455
+ **This predates the release.** The same preimage shipped in 1.4.3 as `mfaSubject`, backing the
456
+ MFA keyspace; renaming it to `userSubject` and extending it to `sess:`/`ep:` widened the blast
457
+ radius rather than creating it.
458
+
459
+ The dashboard arm now carries a length prefix —
460
+ `dashboard:{utf8ByteLength(tenantId)}:{tenantId}:{userId}` — which makes the split unambiguous
461
+ while rejecting no identifier, and the charset is deliberately permissive. The platform arm has
462
+ one component after the plane and is unchanged.
463
+
464
+ **The prefix counts UTF-8 bytes, not characters**, and the contract says so: JavaScript's
465
+ `String.length` counts UTF-16 code units while Rust's `str::len()` counts bytes, so `açaí` is 4
466
+ by one measure and 6 by the other. A character count would agree for ASCII and derive different
467
+ keys on the first accented tenant id — a split between the paired libraries that shows up only
468
+ in production, in one locale.
469
+
470
+ **Apply to a derived backend.** The MFA keyspace relocates too, on top of the session and epoch
471
+ migration described below, under the same first rule — copy state forward, never drop it — but
472
+ **not** under the same fan-out. Those keys already carried the tenant, so the remap is 1:1 for
473
+ every pair, with one exception that is the entire point of this entry: a pair that was
474
+ **colliding** shared one old key, and that key has to be written to each of the pairs that shared
475
+ it. There is no way to tell from the old key which of them last wrote it, so copy it to all of
476
+ them and let the safe direction win — for `rcu:`, a claim present on a code that was never spent
477
+ costs one unusable recovery code, while a claim missing on a code that WAS spent makes it usable
478
+ again. The MFA keys are where dropping is least acceptable for exactly that reason.
479
+
480
+ - **Suspending one tenant's user revoked another tenant's.** The session index and the token
481
+ epoch were keyed on the bare user id — `sess:{userId}` and `ep:{userId}` — while the status
482
+ cache beside them had been tenant-scoped for releases. `IUserRepository.findById` takes a
483
+ `tenantId` precisely because ids may not be unique across tenants, so on a deployment that
484
+ numbers users per tenant, deleting or suspending `t1/u1` swept the sessions and bumped the
485
+ token epoch of `t2/u1`. A **credential-free cross-tenant revocation**, reachable by anyone who
486
+ can get an account suspended in their own tenant.
487
+
488
+ Both keys now derive the way every other account-naming key in this library already did:
489
+ `{prefix}:{hmac_sha256(hmacKey, userSubject)}`. The **derivation** was not invented here — it is
490
+ what the five MFA store keys, the three MFA failure counters and the recent-authentication
491
+ marker have used since they were fixed for the same reason, and the wire contract already
492
+ carried its argument. The two joining it close the gap between what `recentAuthKey`'s own
493
+ documentation claimed — _"keyed by HMAC rather than the raw id, like every other user-derived
494
+ key in this library"_ — and what was true.
495
+
496
+ The **subject** those keys are derived from does change in this release, and the entry above is
497
+ why: it is now `dashboard:{utf8ByteLength(tenantId)}:{tenantId}:{userId}` on the dashboard plane
498
+ and `platform:{userId}` on the platform one. The form it inherited from the MFA keyspace —
499
+ `dashboard:{tenantId}:{userId}`, without the length prefix — is the one that was not injective.
500
+
501
+ The HMAC is the second half and it matters on its own: rust-auth reads this keyspace, so a
502
+ bare id there was an account identifier in the clear to anyone with store access. A user id
503
+ carries too little entropy for a plain digest to hide, which is why the identifier preimages
504
+ are HMACed rather than merely hashed.
505
+
506
+ The platform plane keeps no tenant segment. Its admins are cross-tenant and have none, exactly
507
+ as `userSubject`'s platform arm has always said.
508
+
509
+ **Apply to a derived backend.** The five `SessionService` methods —
510
+ `createSession`, `listSessions`, `revokeSession`, `revokeOtherSession`,
511
+ `revokeAllExceptCurrent` — now take a **single object** instead of positional arguments:
512
+
513
+ ```ts
514
+ // before
515
+ await sessions.listSessions(user.sub, currentHash)
516
+ // after
517
+ await sessions.listSessions({ userId: user.sub, tenantId: user.tenantId, currentSessionHash })
518
+ ```
519
+
520
+ The object is the point, not a style preference. Threading the tenant through positionally put
521
+ a second `string` beside `userId`, and the old two-argument call **still compiled** against the
522
+ new signature — binding the session hash to `tenantId` and returning an empty listing that is
523
+ indistinguishable from "this user has no sessions". On `revokeSession` the same transposition
524
+ is a revocation that silently reaches nothing. A named field cannot be transposed; the worst it
525
+ can be is misspelled, which the compiler catches. `CreateSessionParams`, `ListSessionsParams`,
526
+ `RevokeSessionParams` and `RevokeAllExceptCurrentParams` are exported from the package entry so
527
+ a caller can name the shape.
528
+
529
+ `AuthService.revokeAllSessions` takes the same treatment and for the same reason — two
530
+ unconstrained strings side by side, where `revokeAllSessions(user.tenantId, user.id)` compiled,
531
+ derived an unrelated subject and returned normally:
532
+
533
+ ```ts
534
+ await auth.revokeAllSessions({ userId: user.sub, tenantId: user.tenantId })
535
+ ```
536
+
537
+ Also taking the tenant they always needed: the three
538
+ `AuthRedisService` entry points (`invalidateUserSessions`, `getUserTokenEpoch`,
539
+ `bumpUserTokenEpoch`), whose `kind` argument also **loses its default** — a positional tenant
540
+ next to a positional plane is a transposition nobody notices, and the two call sites that
541
+ passed `'platform'` in what became the tenant slot compiled silently until the default was
542
+ gone. If you call any of these, pass `user.tenantId`; on the platform plane pass `undefined`
543
+ and name the plane.
544
+
545
+ `readSessionOwner` now answers `{ userId, tenantId }`. Logout takes both off the record the
546
+ refresh token just proved possession of, rather than from a caller who could aim the
547
+ revocation at a colliding id. A record written before this carries no tenant: the index revoke
548
+ is skipped rather than guessed, and the session still dies because `rt:{hash}` is deleted
549
+ either way.
550
+
551
+ **This is a paired wire change and it has no compatibility path.** `sess` and `ep` are pinned
552
+ in `conformance/wire-contract.json` and byte-shared with `@bymax-one/rust-auth`; a backend on
553
+ the old shape writes `sess:{userId}` while one on the new shape reads `sess:{hmac}`, so
554
+ sessions survive a revoke-all that never saw them. **Both libraries must ship this in the same
555
+ release.**
556
+
557
+ **Three paths now fail closed on a dashboard subject with no tenant**, because an absent
558
+ tenant interpolates as the literal text `undefined`, so `userSubject` builds
559
+ `dashboard:9:undefined:{userId}` — a keyspace belonging to no tenant, in which nothing has ever
560
+ been written. The MFA flows already refused a blank tenant for exactly this reason; these three did
561
+ not.
562
+
563
+ - `AuthRevocationService.isAccessTokenRevoked` **failed open**: it read the epoch under
564
+ `dashboard:9:undefined:{sub}`, got `0`, and reported a bulk-revoked token as valid. It is
565
+ exported for callers that never pass a guard — a realtime bridge checking a socket — and its
566
+ payload type marks `tenantId` optional, so the omission is a shape a caller can produce. A
567
+ dashboard payload without a tenant is now treated as **revoked**, without touching the store.
568
+ - `reissueTokens` accepted a **pre-upgrade record**: `parseSession` validates `userId`, `role`
569
+ and `mfaEnabled` but never `tenantId`, so a session written before this change rotated into
570
+ `dashboard:9:undefined:{userId}` and minted an access token with no tenant claim — one every
571
+ dashboard guard then refuses. The caller held a session that could be neither used nor
572
+ revoked. Both the primary and the grace-recovery path now refuse it as
573
+ `REFRESH_TOKEN_INVALID`; the platform plane is exempt, its subject carries no tenant segment.
574
+ - `revokeFamily` derived an index for such a record and pruned a key nobody writes while the
575
+ real index kept every member. It now omits the index, exactly as logout already did.
576
+
577
+ **Deploy this as a cutover, not a rolling upgrade.** Drain the pods on the old release before
578
+ the new ones serve. The MFA keyspace is where this bites hardest: `mutate`'s transition lock,
579
+ which serializes the read-modify-write on the recovery-code list, is keyed by the same subject
580
+ as everything else — so two pods that disagree about the subject take **different locks and do
581
+ not exclude each other at all**, and the `rcu:` claim that stops a code being spent twice splits
582
+ the same way. The library carries a fallback for the _pre-tenant_ preimage but deliberately none
583
+ for the tenant-scoped one this release replaces: a fallback is compatibility weight for a
584
+ deployment shape the cutover removes the need for.
585
+
586
+ **A live keyspace must be migrated, not dropped.** Deleting the old keys is unsafe in both
587
+ directions, and each direction is a hole rather than an inconvenience.
588
+
589
+ **On the dashboard plane the migration is a fan-out: one old key becomes N new ones.** The old
590
+ keys are tenant-blind — `ep:{userId}` and `sess:{userId}` name a bare user id — which is the
591
+ defect this release removes, so a single old key served **every** tenant that has a user with
592
+ that id, and each of those pairs derives its own key now. Copying an old key to one derived key
593
+ and dropping it migrates one tenant and silently resets all the others: for them it is not a
594
+ partial migration, it is exactly the deletion described below. Enumerate the tenants that user
595
+ id appears in and write every one of them. On the platform plane the mapping is 1:1 — that
596
+ subject carries no tenant — so the fan-out is a dashboard-only obligation.
597
+
598
+ Deleting an old `ep:{userId}` does not expire the tokens it revoked. `getUserTokenEpoch` answers
599
+ `0` for an absent key — `Number(null)` is `0`, and that is deliberately the "never bumped"
600
+ default — and under `0` the `stamped < epoch` test is false for **every** token. A password
601
+ reset, an MFA reset or a sign-out-everywhere that had already invalidated an access token is
602
+ undone by the migration, and that token works again for the rest of its lifetime. Epochs must be
603
+ **copied to every derived key the old one served**, each with at least the old value and at
604
+ least the remainder of its TTL, and only then dropped. An epoch may never move backwards.
605
+
606
+ Deleting an old `sess:{userId}` does not end the sessions it listed. Its `rt:`/`rp:` members
607
+ outlive the index and become unreachable: a later revoke-all reads the new, empty index, finds
608
+ nothing to delete, and reports success while those refresh tokens keep rotating. Either re-add
609
+ the members under the derived index keys, or delete the member keys and their `sd:` details
610
+ **before** dropping the index. The second costs a forced re-login and is the safer of the two;
611
+ the first preserves sessions and must be done atomically per user.
612
+
613
+ Re-adding is where the fan-out bites hardest, because the old index **mixes tenants**: its
614
+ members are the sessions of every tenant's user with that id, so emptying it into one derived
615
+ index would hand that tenant another's live sessions — worse than the collision being fixed,
616
+ because it turns a shared keyspace into a listable, revocable cross-tenant handle. Partition
617
+ instead: every member names an `rt:`/`rp:` record carrying its **own** `tenantId`, so read the
618
+ record, derive that pair's index, and place the member there. A member whose record is already
619
+ gone is a dead session and is dropped rather than guessed at.
620
+
621
+ **Both obligations apply to the PLATFORM twins, `pep:{userId}` and `psess:{userId}`, which this
622
+ release relocates identically.** They are the easier pair to forget and the worse pair to get
623
+ wrong: a platform epoch left behind revalidates previously revoked **admin** JWTs, and a
624
+ platform index left behind hides an admin's live refresh sessions from revoke-all. The platform
625
+ subject carries no tenant segment — `platform:{userId}` — but the HMAC relocates the key just as
626
+ it does on the dashboard plane, so "we have no tenants" is not a reason to skip either step.
627
+
628
+ - **The dashboard user port let every account read and write skip the tenant.** The sibling half
629
+ of the entry above, on the layer the keyspace fix cannot reach. `IUserRepository` documented the
630
+ rule — _"ids may not be unique across tenants"_ — and then declined to enforce it, in three
631
+ shapes that hid one another because they sat on adjacent lines:
632
+
633
+ - `findById(id, tenantId?)` took the tenant as **optional**, for _"internal admin flows where
634
+ cross-tenant access is intentional"_. All twelve of this library's own call sites omitted it,
635
+ and not one was such a flow: `getMe`, `changePassword`, the email-change request and confirm,
636
+ the three invitation authority checks, the OAuth re-fetch, the session-limit resolver, the
637
+ WebSocket ticket snapshot and the password-reset fingerprint all read the account by bare id.
638
+ On a host that numbers users per tenant, each of those could resolve **another tenant's row**
639
+ — and then decide status, role, MFA state or a password change against it.
640
+ - Six mutators — `updatePassword`, `updateLastLogin`, `updateStatus`, `updateEmailVerified`,
641
+ `updateEmail`, `linkOAuth` — took **no tenant at all**, under JSDoc telling implementations
642
+ they MUST scope the write. An obligation the signature does not permit fulfilling is not a
643
+ contract; the implementation has nothing to scope by.
644
+ - `updateMfa` typed its tenant `string | undefined` beneath a sentence promising it was _"never
645
+ omitted for a dashboard account"_.
646
+
647
+ Every method now requires `tenantId: string`, positioned immediately after the account id, and
648
+ the library passes it everywhere. `MfaService` gained `assertDashboardTenant`, an assertion
649
+ signature splitting the dashboard half out of the existing `assertPlaneTenant` so the guard the
650
+ entry points already ran narrows the type instead of only throwing.
651
+
652
+ **The rule is now a test, not a paragraph.** `test/e2e/tenant-scoped-port.e2e-spec.ts` reads the
653
+ port's TypeScript AST and fails when a method can name an account without a tenant, when the
654
+ tenant is typed anything but `string`, when it does not follow the id, or when
655
+ `IPlatformUserRepository` — whose admins belong to no tenant — grows one. It also compares the
656
+ README's example `PrismaUserRepository` signature-for-signature against the port: that example
657
+ is what a consumer pastes in, and it had drifted to `update({ where: { id } })` on six mutators,
658
+ a query that crosses tenants by construction. Prose does not close by grep.
659
+
660
+ **Apply to a derived backend.** **Superseded — see the object-parameter entry above.** The
661
+ positional shape described here no longer compiles against the port: written as this note
662
+ describes it, the implementation is rejected with `TS2416`. Kept as written because this entry
663
+ describes the release it shipped in; the note above is the one to follow.
664
+
665
+ Your `IUserRepository` implementation must take `tenantId` as
666
+ the second argument of `findById`, `updatePassword`, `updateMfa`, `updateLastLogin`,
667
+ `updateStatus`, `updateEmailVerified`, `updateEmail` and `linkOAuth`, and must filter on it. On
668
+ Prisma that means `updateMany({ where: { id, tenantId } })` rather than
669
+ `update({ where: { id } })` — `update` takes a unique clause and so cannot carry the pair. Two
670
+ service methods take the tenant too: `AuthService.getMe(userId, tenantId)` and
671
+ `AuthService.issueTokensForUserId(userId, tenantId, ip, userAgent)`; pass `user.tenantId` from
672
+ the verified claims. The README's example implementation shows the whole shape.
673
+
674
+ ### Fixed
675
+
676
+ - **The compromise line left `userId` empty on repeat attack traffic.** `revokeFamily` resolves
677
+ the owner by reading the first LIVE member of the token family. On the second and later replay
678
+ of an already-revoked family there is none — the consumed marker outlives the sessions it points
679
+ at, so reuse is detected again while every record that could name the owner is gone — and the
680
+ line read `userId= familyId=…`.
681
+
682
+ That is an empty field on what this library's own documentation calls the strongest evidence of
683
+ compromise it produces, and `userId` is the only field an on-call can act on. It emptied
684
+ precisely on **repeat** attack traffic, which is the traffic worth reading.
685
+
686
+ The line now says what is unknown and what was measured:
687
+ `userId=<unknown: no live session remains in this family to name it>`. An empty field reads as a
688
+ defect in the logger and makes a reader distrust the tool instead of the event; a family with no
689
+ readable member is itself the fact worth seeing. The `familyId` is still named, because it is
690
+ the only handle left on the lineage.
691
+
692
+ It names the observation and not a cause on purpose. `readFamilyOwner` answers with nothing for
693
+ three different reasons — every member record gone, a member whose JSON will not parse, a member
694
+ carrying no `userId` — and only the first is the already-revoked case, which even then cannot be
695
+ told apart from ordinary TTL expiry. A line asserting "already revoked" would send an on-call
696
+ looking for a revocation during what may be store corruption.
697
+
698
+ Reported by the `@bymax-one/bymax-one` seat from a measured audit against real Postgres and
699
+ Redis — two runs of the same path, one populated and one not. The cause was traced rather than
700
+ guessed, and it also explains their second observation: a `revoked` line with no `detected` line
701
+ before it is the same repeat replay.
702
+
703
+ - **The README's own contract test could not fail for a name mentioned anywhere in a barrel.**
704
+ It searched the barrel's SOURCE TEXT for the identifier, so a name in a comment, a JSDoc
705
+ paragraph or an internal import satisfied it without being exported. `src/client/index.ts`
706
+ carries the sharpest instance — a comment reading _"Constants like `AUTH_ERROR_CODES` and
707
+ `AUTH_ROUTES` stay [in shared]"_ — so a README documenting either import FROM `/client` passed
708
+ on the strength of the very sentence saying it does not export them. Measured: across the five
709
+ barrels, 77 capitalised tokens appear in text without being exports.
710
+
711
+ It now reads the barrel's export DECLARATIONS from the TypeScript AST, and four arms joined it:
712
+ no barrel may `export *` (which would name nothing and make the check under-report); the README
713
+ may not call a symbol non-public that a barrel exports (the contradiction this release ships the
714
+ fix for); the documented subpaths are checked against **`package.json#exports`** rather than the
715
+ suite's own hand-kept map, which agreed with the manifest only for as long as somebody kept both
716
+ in step; and every published subpath must have a source barrel mapped, because an unmapped one
717
+ was skipped silently by the arms above.
718
+
719
+ The scheme-table check had the same defect in a second form: it searched the **whole README** for
720
+ each scheme name, so deleting the `controllers.platform` row still passed — the name appears
721
+ three more times below the table. That table had already lost a row twice, under a check that
722
+ was running the whole time. Completeness is now asked of the table alone; invention is still
723
+ asked of the whole document, because a name the prose made up is wrong wherever it sits.
724
+
725
+ And the claim that `AUTH_ERROR_STATUS` ships from `/shared` was prose, which this suite does not
726
+ read — removing the export left it green. It is shown as an import now, which the suite does
727
+ read.
728
+
729
+ - **A rate-limited refresh signed the user out of a session that was still valid.**
730
+ `createAuthFetch`'s refresh reduced the response to `response.ok`, so `429`, `401`, `503` and a
731
+ `404` from a mistyped `routePrefix` arrived at the caller as one indistinguishable `false` — and
732
+ the caller treats `false` as expiry. Measured by a consumer against a real browser round; twelve
733
+ browser specs passed on both runs that produced the finding, so no green suite covered it.
734
+
735
+ `performRefresh` now returns a `RefreshOutcome`: `{ ok: true }`, or `{ ok: false, reason, status }`
736
+ where `reason` is `'rejected'` (a 401, **or a 403 whose error code names a terminal account
737
+ state** — the server looked at the credential and refused it, so `rejected.status` is `401` or
738
+ `403`), `'unavailable'` (it answered, but not with a session) or `'unreachable'` (no answer at
739
+ all).
740
+ **`onSessionExpired` now fires only on `'rejected'`.**
741
+
742
+ 403 is decided by the error **code**, because the route answers it for two unrelated reasons.
743
+ `TrustedOriginGuard` covers `/refresh` and answers `auth.untrusted_origin` with 403 — reading
744
+ that as expiry would sign out every user of a deployment whose `trustedOrigins` is wrong. But
745
+ `refresh` also revokes every session before rethrowing a blocked-account status
746
+ (`auth.account_suspended`, `auth.account_banned`, `auth.account_inactive`,
747
+ `auth.pending_approval`), and there the session really is over. The wrapper reads the code
748
+ itself, since it drains the refresh body and the caller only ever sees the original response.
749
+
750
+ A new `onRefreshFailed?: (failure: RefreshFailure) => void` reports **every** failure with its
751
+ reason and status, before the expiry decision. That is what makes the answer to _why_ usable: a
752
+ rate limit deserves "retrying", a dropped connection deserves "you appear to be offline", and
753
+ only a refused credential deserves the sign-in screen.
754
+
755
+ A `429` branch was offered and declined by the consumer who found it: _"the refresh needs to
756
+ report why it failed, not whether"_. A boolean with one carve-out reproduces the same defect for
757
+ whichever status matters next.
758
+
759
+ **Behaviour change for consumers.** Before, any refresh failure invoked `onSessionExpired`. Now a
760
+ dropped connection, a rate limit or a server fault does not — the caller still receives the
761
+ original `401`, so a failed request stays failed, but it no longer receives a claim that the
762
+ session is over. If you relied on the callback to mean "the refresh did not succeed", read the
763
+ `reason` instead: `RefreshOutcome` and `RefreshFailureReason` are exported from
764
+ `@bymax-one/nest-auth/client`.
765
+
766
+ ### Security
767
+
768
+ - **No error object reaches the logger any more.** Twenty-seven log sites passed the thrown value
769
+ as Nest's second `Logger` argument, which prints its `stack`. On every one of those paths the
770
+ thrower is code this library does not own: a hook, an OAuth plugin, the consumer's repository,
771
+ a Redis client — and in `AuthExceptionFilter`'s case, literally anything the surrounding
772
+ application threw. None of them hands the logger an error object any more, and on the twenty
773
+ sites where the caller could not name what the thrower held, **nothing the thrower authored is
774
+ published at all** — `describeChannelStatus` reports the shape of the failure (that a throw
775
+ happened, and how many links its `cause` chain has) and reads neither `message` nor `name` nor
776
+ `stack`. Where the caller CAN name the values it passed in, `describeError` still publishes the
777
+ text with those removed.
778
+
779
+ **An empty redaction list is the shape that looked safe and was not.** `describeError(err, [])`
780
+ publishes the thrower's `name` and `message` with an empty list asserting there is nothing to
781
+ remove — an assertion none of these call sites can make, because every thrower on them is
782
+ consumer code: a repository handed `findByEmail(dto.email, tenantId)`, a hook handed the IP and
783
+ user agent, a `maxSessionsResolver` handed the full `AuthUser` including the password hash, a
784
+ repository call carrying re-encrypted MFA material. A consumer error that quotes its own input
785
+ put those in the log. The empty list did not make the line safe; it removed the only defence
786
+ being attempted while reading like one. The form is now banned outright and the guard suite
787
+ enforces it.
788
+
789
+ **A partial list is the same defect with a longer sleeve.** Seven more sites named one to three
790
+ fields while the thrower had been handed a whole object: every `afterRegister`, `afterLogin`,
791
+ `afterEmailVerified`, `afterPasswordReset`, `afterInvitationAccepted` and `onNewSession` hook
792
+ receives the complete `SafeAuthUser`, so a hook throwing `new Error(user.name)` published a name
793
+ that no list mentioned. Those are opaque now too. What survives is the rule the list was always
794
+ meant to express — **name the values the thrower actually received** — which three sites can
795
+ still satisfy honestly, because they hand a repository or a hook exactly one identifier and
796
+ name exactly that.
797
+
798
+ Those three also had the list naming the wrong string: `describeError(err, [logSafe(user.id)])`
799
+ redacted the SANITISED id, and `logSafe` returns `<malformed>` for precisely the ids worth
800
+ worrying about — so the value the repository was handed was not in the list at all. They name
801
+ the value as passed now, and the guard rejects any redaction list containing a call.
802
+
803
+ **The highest-value site was not in the original report.** `OAuthService.handleCallback` wraps
804
+ `plugin.exchangeCode(code, codeVerifier)` and `plugin.fetchProfile(accessToken)`. The plugin is
805
+ consumer code that RECEIVED all three, and an HTTP client attaching its request config to the
806
+ error is the ordinary case rather than an exotic one — axios does it by default. A live access
807
+ token could reach the operator's pipeline through a rejection this library then logged in full.
808
+ The handler publishes nothing the plugin wrote. Naming the three values was the first fix and it
809
+ was the weaker half by its own reasoning: redaction is a substring match, so it holds for a token
810
+ the plugin echoed as given and not for one it re-encoded — and a token inside a base64 or
811
+ URL-encoded request body is not present as written. The test drives exactly that: the plugin
812
+ echoes the token base64url-encoded, and the line contains neither form.
813
+
814
+ The second was found by the guard rather than by reading: `AuthExceptionFilter`, whose parameter
815
+ is called `exception`, not `err`. It is the branch a re-thrown mail-channel error lands in under
816
+ `onDeliveryError: 'rethrow'` — this library's own documentation says so — so it is the most
817
+ exposed log site of the set, and a name-based sweep walked straight past it.
818
+
819
+ **What you lose:** the stack trace for a hook, plugin or repository failure. That stack belongs
820
+ to the consumer's own code, which can log it where the audience is known; a library's log line
821
+ reaches a wider one. Same argument that took the recipient address out of the delivery-failure
822
+ line. On the twenty opaque sites you also lose the message and the error's class; what remains
823
+ is that a failure happened, where, and how deep its `cause` chain ran.
824
+
825
+ `redactSecrets` was hardened in the process. It read `.length` off each element, so a single
826
+ `undefined` in the list threw a `TypeError` — out of a `catch` block, turning a failure the
827
+ caller meant to absorb into an unhandled rejection with no log line at all, which is worse than
828
+ the leak it exists to prevent. It is exported, so a consumer reaches that edge from plain
829
+ JavaScript. Found when a caller named a field the compiler believed was a `string`; the suite
830
+ did not fail an assertion, it crashed the worker.
831
+
832
+ - **A consumer-supplied identifier could forge a second record in the log.** Every value this
833
+ library interpolates into a log template now passes a guard: `logSafe` for identifiers,
834
+ `maskEmail` for addresses, `describeError` for a rejection's own text. Forty-eight
835
+ interpolations did not, across nine files.
836
+
837
+ `IUserRepository` places no character constraint on `id`, `role` or `tenantId` — `role` is a
838
+ bare `string` in the interface — so a value carrying CR/LF closes the log record and opens one
839
+ the reader attributes to this library. That is the attack `logSafe` was written for.
840
+
841
+ **The convention already existed and had been applied to `tenantId` at fourteen sites.** It was
842
+ never extended to anything else, and the omission was invisible because it sat on the SAME
843
+ LINES: `userId=${user.id} tenantId=${logSafe(tenantId)}` reads as deliberate until you ask why
844
+ one half is wrapped and the other is not.
845
+
846
+ Two sites went further and stringified a rejection straight into the line
847
+ (`logout: session cleanup failed — ${String(err)}`). `String()` strips nothing and bounds
848
+ nothing; those now go through `describeError`, which does both. The rejection is Redis's rather
849
+ than a mail channel's, so no credential is implied — but the failing key it names embeds the
850
+ consumer's user id.
851
+
852
+ A guard suite (`test/e2e/log-injection-guard.e2e-spec.ts`) now walks every `this.logger.*` call
853
+ in `src/` and fails on any interpolation that is neither guarded nor named in an explicit
854
+ allowlist of values this library authors. It fails **closed**: a new interpolation breaks the
855
+ build until somebody decides which it is. The guard call must BE the whole expression —
856
+ `${logSafe(a) || attackerValue}` is rejected, as are a concatenation, a ternary arm, and a
857
+ helper whose name merely starts with a guard's.
858
+
859
+ It reads the **TypeScript AST**, not the text. Three hand-rolled scanners preceded it and each
860
+ was fooled by ordinary punctuation: a comma inside a message read as an argument separator, a
861
+ `)` inside a template's literal text ended the call early, and a guard's name matched anywhere
862
+ in the expression. Parentheses and quotes inside string literals defeat every version of that
863
+ approach, and a gate whose parser can be fooled by punctuation is not a gate. It caught the two `String(err)` sites on its first
864
+ run, which is the argument for it — forty-eight had drifted silently under a convention that
865
+ lived only in reviewers' heads.
866
+
867
+ Two corrections to the walker itself, both held by synthetic fixtures because `src/` has no
868
+ example of either. It now knows `fatal`, the sixth level Nest 11's `Logger` exposes — a level
869
+ list has to be complete rather than sufficient, and the first `this.logger.fatal(...)` anyone
870
+ wrote would otherwise have been invisible to a gate claiming to walk them all. And it no longer
871
+ descends into a guard's argument: what reaches the record is the guard's OUTPUT, so
872
+ ``logSafe(`id=${user.id}`)`` was being reported twice, once as guarded and once as bare, failing
873
+ a line that cannot carry a control character. A false positive on correct code is how a gate
874
+ gets weakened by whoever hits it next.
875
+
876
+ Requires no action from a consumer: `logSafe` returns an ordinary identifier unchanged, so log
877
+ lines are byte-identical unless a value actually carried a control character, in which case the
878
+ field is replaced with `<malformed>` and the record stays one record.
879
+
880
+ **`maskEmail` was one of those guards and did not enforce the boundary.** It preserves the
881
+ domain verbatim to keep the line useful to an operator, so `a@example.com\nforged` masked to
882
+ `a***@example.com\nforged`: the address was hidden and the injection was not, and being on the
883
+ allowlist meant the gate reported those sites as safe. Masking and record safety are two
884
+ separate duties and the helper owed both; it now passes its result through `logSafe`. The
885
+ addresses reaching those lines are not all DTO-validated — `profile.email` is whatever an OAuth
886
+ provider's userinfo response contained and `oldEmail` is whatever the host's repository stored,
887
+ so `@IsEmail()` saw neither. The allowlist's claim is now a test rather than a sentence: every
888
+ name on it is fed a value carrying LF, CR, NEL and both Unicode separators, and must return
889
+ something that cannot end a record. `safeLogLine` was removed from the allowlist in the same
890
+ pass — it is a check on a fully composed line, not a field guard (`safeLogLine(raw, [])` is
891
+ `raw`), and it appears inside no interpolation in `src/`.
892
+
893
+ - **`onDeliveryError` takes a per-message map, so an opt-in stops being all-or-nothing.** It was one
894
+ switch for all ten messages. A deployment sets `'rethrow'` for a specific benefit — deleting an
895
+ undelivered reset token early, not recording "verification sent" for a send that failed — and the
896
+ same setting then handed it the channel's **original, unlaundered** error on every other path.
897
+ Five messages render a credential, and those two flows are two of the five — so the bare form
898
+ reached three further credential-bearing paths that neither flow asked for.
899
+
900
+ ```typescript
901
+ new DefaultAuthEmailProvider(sink, {
902
+ onDeliveryError: { passwordResetToken: 'rethrow', emailChangeVerification: 'rethrow' }
903
+ })
904
+ ```
905
+
906
+ A message left out keeps `'swallow'`, so the safe value is what you get by saying nothing and
907
+ widening the opt-in is always explicit. A bare `'swallow' | 'rethrow'` still works and still
908
+ applies to all ten. A key the catalogue does not know is dropped — a typo leaves the message
909
+ swallowing, never exposed. The resolved policy is read from a `Map` and built by iterating the
910
+ deployment's own entries, so no lookup walks a prototype chain.
911
+
912
+ `AUTH_EMAIL_KINDS`, `AuthEmailKind` and `DeliveryErrorPolicyMap` are exported. A catalogue entry
913
+ added without a matching kind fails to compile.
914
+
915
+ - **`AuthEmailSink.send` now states which message it is carrying and whether it holds a live
916
+ credential** — anywhere in the rendered message, subject included, since all three fields reach
917
+ the sink. `kind` and `containsCredential` are always set. The obligation is in the port's own
918
+ documentation, where an implementer meets it: **a sink must not publish the content of a message
919
+ flagged `containsCredential`** — not in an error it throws, not in a log line, not in an audit
920
+ record that outlives delivery.
921
+
922
+ This is a statement of fact, **not** protection, and the docs say so plainly. Once the body leaves
923
+ `send`, what happens to it belongs to the sink. It is delivered at the only moment a sink could
924
+ act on it.
925
+
926
+ **A rendering can declare a credential its kind does not imply.** `AuthEmailMessage` gained an
927
+ optional `containsCredential`, OR-ed with the kind's baseline. `messages` replaces a renderer
928
+ outright, so a product whose own `mfaEnabled` copy hands the user recovery codes has turned a
929
+ notice into a credential-bearing message while its kind still reads `mfaEnabled` — and the sink
930
+ would have been told `false` about a body carrying a live secret. That is the flag being _wrong_,
931
+ which is worse than the flag being merely non-protective. The combination is one-way: a renderer
932
+ can only add. Returning `containsCredential: false` from an override of `passwordResetOtp`
933
+ changes nothing, because a consumer does not get to switch off a statement this library makes
934
+ about its own messages.
935
+
936
+ Why a flag and not a list of values to redact: that was measured and rejected. Redaction is a
937
+ substring match, so it holds for a value quoted as written and not for the same bytes re-encoded —
938
+ a relay may answer with the body in base64, and then no list matches. A categorical "publish none
939
+ of this message" has to find nothing, which is the only shape that survives an encoding it cannot
940
+ predict. The same reasoning took every channel-authored byte out of this library's own log lines.
941
+
942
+ Adding fields to the input is not breaking for a sink: an implementation taking fewer properties
943
+ still satisfies the port.
944
+
945
+ - **A one-time code could reach the operator's log in clear text when the mail relay rejected the
946
+ message.** `DefaultAuthEmailProvider` logged the raw error object on a delivery failure. The
947
+ comment justifying it read "the error is the channel's own, not the rendered body" — and a
948
+ measurement against a real relay disproved exactly that premise. A policy, DLP or anti-spam
949
+ relay answering `550` **quotes the offending content**, so the channel's error _is_ the rendered
950
+ body, and for this provider that body carries a live password-reset OTP, an email-verification
951
+ OTP, a reset token, an email-change token or an invitation token. The credential landed in the
952
+ log pipeline valid until it expired. Reported by the `@bymax-one/nest-notification` seat from a
953
+ run measured on a real relay, where the code captured from the SMTP `DATA` appeared verbatim in
954
+ the consumer's error entry under the same request id.
955
+
956
+ **The rule that came out of it, after four weaker ones failed: this library publishes nothing a
957
+ mail channel authored.** Not the error's `message`, not its `name`, not the rendered subject —
958
+ and not on "credential paths" only, but on every path. What a delivery failure logs is the
959
+ message's own label and, per link of the error's cause chain, an opaque stand-in:
960
+
961
+ ```
962
+ delivery failed sending passwordResetOtp: <error>
963
+ ```
964
+
965
+ Every part of that line is text this library wrote. The guarantee is simpler to hold than any
966
+ amount of stripping, and it is what the four earlier attempts each failed to reach.
967
+
968
+ **Why redaction is not enough.** It is a substring match, so it assumes the credential reaches
969
+ the error the way this library wrote it. A relay is free to quote what it rejected in transfer
970
+ encoding instead, and base64 is the ordinary case. Measured: the whole reset-code body is 96
971
+ base64 characters, and the first 200 characters of the line decode straight back to the OTP.
972
+
973
+ **Why a length cap is not enough either.** The encoding runs from the body's FIRST byte, so the
974
+ code sits in the first sentence, well inside any cap that leaves enough text to decode. A bound
975
+ on volume was never a bound on disclosure, and this changelog described it as a second lock
976
+ before the measurement above.
977
+
978
+ **Why validating the `name` by shape is not enough.** Closing only `message` moves the leak one
979
+ field over: an error class built around a relay reply is a normal thing for a mail client to do.
980
+ Requiring the name to look like an identifier excludes a quoted body and does **not** exclude an
981
+ encoded one — `MTIzNDU2` is the base64 of the OTP `123456`, eight characters, alphanumeric,
982
+ leading letter, a valid identifier by any such rule, and reversible by anyone reading the log.
983
+
984
+ **Why redacting the rendered subject is not enough.** A subject comes from the `messages`
985
+ catalogue, which a consumer may override with arbitrary code. Redaction only ever covered a
986
+ subject that reproduced a value verbatim, and `Code 123-456` for the OTP `123456` is a
987
+ reasonable-looking thing to write. The line carries a fixed label instead, which also identifies
988
+ the message more stably for anyone parsing it.
989
+
990
+ **Nothing is kept.** The line carries the message's label and, when the chain has one, the
991
+ `<error>` stand-in per link — no status, no name, no message. A parsed SMTP status survived
992
+ several rounds on the reasoning that a value rebuilt from a validated grammar cannot carry body
993
+ content, and the test that finally settled it is whether the output DEPENDS on the secret. It
994
+ does: an OTP of `424242` grouped as `424-242` at the head of a quoted body publishes `424`, and a
995
+ different code publishes different digits. That is derivation, not the coincidence that `550
996
+ 5.7.1` reassembling into `550571` turned out to be — and no grammar separates a reply from body
997
+ text shaped like one, because a reply code and a grouped credential prefix are the same three
998
+ digits and a separator.
999
+
1000
+ What an operator loses is the transient-versus-permanent split, which their mail provider's own
1001
+ dashboard carries. What they keep is which message failed, which is the half this library is the
1002
+ only source for.
1003
+
1004
+ **The same defect was one port over, in the breach checker.** `IPasswordBreachChecker.isBreached`
1005
+ receives the PLAINTEXT PASSWORD by contract, so an error it raises is a place the plaintext can
1006
+ be — an HTTP client that echoes the request it failed on is the ordinary shape. The fail-open
1007
+ handler passed that error straight to `logger.error(msg, err)`, publishing it with its stack and
1008
+ whatever the client hung on it, under a comment claiming the plaintext never reached the logger.
1009
+ **Nothing** from that error reaches the line now — not the object, not a description, not a status
1010
+ parsed off its front. The first fix described it with `describeChannelStatus` and was wrong in a
1011
+ way worth recording: that helper validates the SMTP reply grammar, and a breach checker is not an
1012
+ SMTP channel. A password of `424 Correct Horse!` echoed back parses as the reply `424` and
1013
+ publishes the first three characters of the credential. Right tool, wrong port. No status is lost
1014
+ by dropping it, because an HTTP checker's own code would have to come from a structured field the
1015
+ interface does not expose.
1016
+
1017
+ Two DTO comments carried the same over-claim (`RegisterDto.password`,
1018
+ `AcceptInvitationDto.password`: _"never logged or persisted in plaintext"_) and now say **by this
1019
+ library**, pointing at the ceiling. Found by sweeping for the CLAIM rather than for the wording
1020
+ already corrected — the method comes from the `@bymax-one/nest-notification` seat, who found two
1021
+ more in their own README the same way. A sweep by phrase misses the siblings written in other
1022
+ words, and the most scannable claim in a file is rarely worded like the one you just fixed.
1023
+
1024
+ **What still needs you: `onDeliveryError: 'rethrow'`.** What the provider re-throws is the
1025
+ channel's original error, deliberately unaltered — a caller that opted into that policy did so to
1026
+ branch on the channel's codes, and handing it a laundered replacement would take those away. So
1027
+ the quoted body travels with it. Whatever catches it must not log it raw, and must not merely
1028
+ redact it either: describe it with **`describeChannelStatus`**, which is exported for exactly
1029
+ this. Deployments on the default `'swallow'` policy need no action.
1030
+
1031
+ **Apply to a derived backend:** nothing to change for the fix itself — it is internal to the
1032
+ provider. **Three** things to check.
1033
+
1034
+ If you parse the log line, it changed from `delivery failed for "<subject>"` with the error
1035
+ attached as a second argument to a single string, `delivery failed sending <label>: <error>`,
1036
+ with `<-` between cause links and no status anywhere in it; `<label>` is a fixed name this
1037
+ library owns (`passwordResetOtp`, `mfaEnabled`, …) and the rendered subject is gone.
1038
+
1039
+ If you run `onDeliveryError: 'rethrow'`, audit what your handler does with the error, per the
1040
+ paragraph above.
1041
+
1042
+ And **the three MFA notices no longer reject the operation that triggered them** — enabling a
1043
+ factor, disabling one, and resetting one now send detached, with the failure logged instead. A
1044
+ deployment on `'rethrow'` that relied on an undelivered MFA notice failing the request will stop
1045
+ seeing that failure. The change is deliberate: by the time the notice is sent, the factor is
1046
+ already enabled or removed, and answering the caller with an error reports a change that HAPPENED
1047
+ as one that did not. The other seven messages are unaffected — `'rethrow'` still surfaces their
1048
+ failures, which is the whole reason the two flows that react to a throw opt in.
1049
+
1050
+ One more, if you catch errors from `EmailChangeService.requestChange` or
1051
+ `InvitationService.invite`: **what they throw is now laundered.** Both awaited the provider with
1052
+ no handler, so a rejection travelled to your code carrying the channel's own error — its
1053
+ `message`, its `name`, whatever fields your mailer attached. They now throw
1054
+ `new Error(describeChannelStatus(err))`, whose message is the opaque description and nothing
1055
+ else. This is not about `'rethrow'`: a custom `IEmailProvider` that throws is laundered here too.
1056
+ The reason is that on these two paths the caller **is this library** — the rejection reaches
1057
+ `AuthExceptionFilter`'s unknown-exception branch, which logs it — so propagating the original
1058
+ publishes the credential through this library's own filter, with no consumer given a chance to
1059
+ contain it. The HTTP response is unchanged: that branch answered `auth.internal` with the generic
1060
+ message before and does now.
1061
+
1062
+ Not exploitable by an unauthenticated caller on its own — it requires a relay configured to
1063
+ quote rejected content — but it needs no attacker at all where such a relay is in the path, and
1064
+ the value exposed is a working credential.
1065
+
1066
+ ### Changed
1067
+
1068
+ - **Stryker deletes its sandbox even when the run fails (`cleanTempDir: "always"`).** `true` — the
1069
+ previous value, and the default — deletes `.stryker-tmp` only after a run that PASSED, and a run
1070
+ that fails the 100 threshold is the normal state while iterating, so a 45 MB copy of `src/` was
1071
+ left behind on every failed run. Wanted on its own terms: `jest.coverage.config.ts` has to name
1072
+ it in `modulePathIgnorePatterns` precisely because a second copy of `src/` in the tree is
1073
+ hazardous, and the cheapest way to hold that is for it not to be there. Contributor-facing only;
1074
+ nothing ships differently.
1075
+
1076
+ ### Added
1077
+
1078
+ - **A table key must now name a route handler, not merely a method that exists.** The conformance
1079
+ spec already checked both directions between the operations table and the controllers — every
1080
+ route handler described, every described key naming a real method — so the second half was
1081
+ looser than it read: `typeof === 'function'` accepts a method carrying no verb decorator, and
1082
+ the lookup resolves through the **prototype chain**, so `toString`, `valueOf` and
1083
+ `hasOwnProperty` answer `'function'` on any class. A typo landing on an inherited member passed
1084
+ here and would have failed in a consumer's document build instead, which is the wrong
1085
+ repository to find out in. It is the same prototype-chain reach that once let a catalog lookup
1086
+ hand a **function** to `HttpException` as a status.
1087
+
1088
+ Both halves falsified before the change was trusted: `'AuthController.toString'` and
1089
+ `'AuthController.onModuleInit'` are now red, and were not.
1090
+
1091
+ Recorded because the first draft of this entry claimed the table could fall behind the
1092
+ controllers unnoticed. It could not — that direction has been covered since the contributor
1093
+ shipped, and removing `AuthController.wsTicket` from the table already failed the conformance
1094
+ spec. Caught in review, verified by running it.
1095
+
1096
+ ## [1.4.3] - 2026-08-15
1097
+
1098
+ ### Changed
1099
+
1100
+ - **BREAKING — the bulk session revocation moved to `POST {prefix}/sessions/revoke-all`.** It was
1101
+ `DELETE {prefix}/sessions/all`, and the verb was the defect. The handler reads the refresh token
1102
+ that names the caller's own session — the one session it must NOT revoke — and under
1103
+ `tokenDelivery: 'bearer'` that token arrives in the request body. OpenAPI 3.0.3 defers to
1104
+ RFC 7231 there: a payload on DELETE has no defined semantics, so `requestBody` on it **SHALL be
1105
+ ignored by consumers**. A generated client therefore sent no body, the server found no refresh
1106
+ token, and every call answered `auth.session_not_found` — an operation the document could not
1107
+ describe and a generated client could not reach, in the delivery mode a mobile or cross-origin
1108
+ consumer runs. POST is the method whose body semantics are defined.
1109
+
1110
+ Found in review of the contributed OpenAPI fragment rather than by a failing test, which is the
1111
+ uncomfortable part: the e2e suite drove the endpoint with a hand-written request that DID carry
1112
+ a body, so it passed throughout. The suite proved the server works; nothing proved a client
1113
+ built from the document could reach it.
1114
+
1115
+ Two smaller truths came out of the same reading. `GET {prefix}/sessions` reads the same token to
1116
+ mark which session is the caller's, and a GET has no body either — so on a bearer-only
1117
+ deployment the cookie is its only channel, the fragment no longer contributes a body it would
1118
+ never receive, and the listing simply marks nothing as current. And `test/e2e` now asserts, from
1119
+ the router Nest actually built, that no contributed `requestBody` lands on a method without
1120
+ payload semantics; the rule is enforced rather than remembered.
1121
+
1122
+ **Apply to a derived backend.** Change `DELETE {prefix}/sessions/all` to
1123
+ `POST {prefix}/sessions/revoke-all` wherever a client calls it — or read it from
1124
+ `AUTH_ROUTES.sessions.revokeAll`, which is what that constant is for. The request body,
1125
+ response (`204`), guards, rate limit and error codes are unchanged; only the method and the last
1126
+ path segment move. `DELETE {prefix}/sessions/:id` is untouched, and no longer has to out-rank a
1127
+ static sibling in routing.
1128
+
1129
+ ### Added
1130
+
1131
+ - **Nine routes this library serves were missing from `AUTH_ROUTES`,** which is the map a client
1132
+ composes URLs with — so a consumer reaching any of them had to hardcode the path the constants
1133
+ exist to spare them, and would keep it hardcoded through a rename. Added:
1134
+ `AUTH_DASHBOARD_ROUTES.wsTicket`, `AUTH_MFA_ROUTES.recoveryCodes`,
1135
+ `AUTH_PASSWORD_ROUTES.changePassword`, the whole `AUTH_PLATFORM_MFA_ROUTES` family (setup,
1136
+ verify-enable, disable, recovery-codes) and `AUTH_OAUTH_ROUTES` (initiate, callback).
1137
+ `AUTH_EMAIL_CHANGE_ROUTES` and the two new families are exported from `./shared` by name, the
1138
+ way every other family already was.
1139
+
1140
+ A test now compares the map against `PATH_METADATA` on the controllers — the same metadata Nest
1141
+ routes with — in **both** directions: no route served without a constant, and no constant
1142
+ pointing at a route nobody serves. It is worth saying how the platform MFA family was found,
1143
+ because it is the failure mode this test exists for: a manual sweep reported those four paths as
1144
+ present, because they appear elsewhere in the same file (in the refresh skip list) and a grep
1145
+ for the literal cannot tell one list from another. The test reads the map, not the file.
1146
+
1147
+ ### Fixed
1148
+
1149
+ - **A wrong password no longer spends a refresh — and ten of them no longer sign the user out.**
1150
+ `createAuthFetch` treated every 401 outside its path skip list as an expired session. A consumer
1151
+ measured what that costs on a live instance: a wrong `currentPassword` on
1152
+ `POST {prefix}/password/change` answers `401 auth.invalid_credentials`, the client refreshed,
1153
+ and the retry then surfaced the real error — one refresh per typo. Ten typos inside a minute
1154
+ exhaust the refresh limiter (`429 auth.too_many_requests`), the client read **that** as an
1155
+ irrecoverable expiry and called `onSessionExpired`.
1156
+
1157
+ The session was never revoked: `GET {prefix}/me` answered `200` throughout. The sign-out was
1158
+ entirely client-side — the wrapper discarding a session the server still honoured, triggered by
1159
+ a rate limit that exists for something else. Behind a proxy with `clientIpSource: 'peer'` the
1160
+ bucket is shared, so the ten are the whole deployment's.
1161
+
1162
+ **The skip list could not fix it, which is the finding under the finding.** That route is behind
1163
+ the JWT guard: an expired token 401s there too. One path, two meanings — so the decision moved
1164
+ to the error **code**, the only thing that separates them. `auth.token_invalid` is the expiry
1165
+ (every guard collapses expired, revoked, malformed and absent onto it deliberately); every other
1166
+ code is the server answering about something else, and a new token would not change its mind.
1167
+
1168
+ Measured across the family rather than fixing the one route reported: `password/change`,
1169
+ `mfa/recovery-codes` and `email/change` all answer a non-expiry 401 and none was on the list,
1170
+ while `mfa/setup` and `mfa/disable` answer the same codes and were. The list was three entries
1171
+ short, not one — which is why the mechanism changed instead of the data.
1172
+
1173
+ **And the whole platform surface joined it.** The list carried five platform routes and left
1174
+ out `platform/me` and all four `platform/mfa/*` — every one of them JWT-**platform**-guarded, so
1175
+ an expired platform token answers `auth.token_invalid`, the code that means "refresh me" on the
1176
+ dashboard plane. A dashboard refresh cannot fix another plane's credential: it spends the
1177
+ budget and can call `onSessionExpired` for a session that is perfectly healthy. Found in review
1178
+ of the paragraph claiming the list already covered the plane.
1179
+
1180
+ **Three routes left the path skip list**: `mfa/setup`, `mfa/verify-enable` and `mfa/disable`.
1181
+ They were there because a wrong password or a wrong TOTP code 401s from them — which the code
1182
+ check now recognises — but all three are **JWT-guarded**, so an expired token 401s from them
1183
+ too, and skipping the refresh would have left the exact inverse of the defect above: a client
1184
+ refusing to refresh a session that only needed refreshing. Found in review, and it is the same
1185
+ one-path-two-meanings shape as `password/change`.
1186
+
1187
+ What remains on the list is the narrower set where a refresh cannot help **whatever** the code
1188
+ says: the token endpoints themselves (recursion), the credential-issuing endpoints (no session
1189
+ to refresh yet), and the **platform** surface — a dashboard refresh cannot fix a platform
1190
+ credential, so attempting one spends the refresh budget and can call `onSessionExpired` for a
1191
+ dashboard session that is perfectly healthy.
1192
+
1193
+ **The classification is time-bounded.** Reading the error body waits at most two seconds; on
1194
+ expiry the pre-existing behaviour applies and a refresh is attempted. The request itself has
1195
+ already completed and its timeout has already been cleared, so an unbounded read would hang the
1196
+ wrapper on a 401 whose body never terminates — including on deployments that disable `timeout`
1197
+ for long-polling. This step may narrow what refreshes; it may never suspend the wrapper.
1198
+
1199
+ **A 401 the client cannot read still refreshes.** No envelope, an empty body, a non-JSON body, a
1200
+ code that is not a string — every one behaves exactly as before, so this wrapper stays usable as
1201
+ a general fetch against an application's own API. Both envelope shapes are read: this library's
1202
+ `{error: {code}}` and the flat `{statusCode, code, …}` a `@bymax-one/nest-core` backend answers
1203
+ with. The body is read from a **clone**, so the caller still receives an unconsumed response —
1204
+ otherwise every consumer parsing the error body would meet `TypeError: body already used`.
1205
+
1206
+ **Apply to a derived backend.** No server change. If your frontend relied on the old behaviour —
1207
+ a 401 from any endpoint eventually reaching `onSessionExpired` — note that only
1208
+ `auth.token_invalid` does now. A 401 your own API answers with no auth envelope is unaffected.
1209
+
1210
+ - **Two internal-only error codes now say so in the shared catalogue.** `auth.token_expired` and
1211
+ `auth.token_revoked` are never on the wire — both implementations collapse them onto
1212
+ `auth.token_invalid`, deliberately, because telling a caller "expired" rather than "invalid"
1213
+ separates a token that WAS valid from one that never was, which is what an attacker holding a
1214
+ captured value wants to learn. `rust-auth` maps them through `AuthErrorCode::to_wire`; this
1215
+ library never throws them at all.
1216
+
1217
+ Three of the five internal-only codes already carried that note (`auth.token_missing`,
1218
+ `auth.otp_expired`, `auth.otp_max_attempts`) and these two did not — so a reader concluded,
1219
+ reasonably, that the unmarked ones do appear. A consumer seat did exactly that while reviewing
1220
+ the refresh fix above, and asked whether it had a hole for `auth.token_expired`. It does not,
1221
+ and now the catalogue answers the question without anyone reading the emit sites. **A code in a
1222
+ published catalogue is something a consumer will write a branch for**, so an unreachable one has
1223
+ to say it is unreachable.
1224
+
1225
+ ### Added
1226
+
1227
+ - **The OpenAPI security posture is contributed at the consumer's boot, not shipped as a file.**
1228
+ A deployment building its document with `@bymax-one/nest-core` >= 1.4.0 now gets this library's
1229
+ operations described automatically: which schemes exist, which operation requires which, and
1230
+ which are reachable unauthenticated. The module registers a contributor; nest-core discovers it
1231
+ while building the document. Nothing to enable, nothing to import.
1232
+
1233
+ It cannot be a static file, and that is the whole reason the contract exists. The same build
1234
+ serves `/auth/login` here and `/api/v2/identity/login` there, with the credential in a cookie
1235
+ on one deployment and an `Authorization` header on the next, under cookie names the consumer
1236
+ chose. So the fragment is derived from the options that actually resolved, and keyed by handler
1237
+ identity — which survives every prefix, version and mount point.
1238
+
1239
+ | resolved options | contributed |
1240
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1241
+ | `tokenDelivery: 'cookie'` | `bymaxAuthAccessCookie`, `bymaxAuthRefreshCookie`, carrying the configured cookie names |
1242
+ | `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 |
1243
+ | `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 |
1244
+ | `controllers.platform: true` | `bymaxPlatformAccessBearer`, in every mode — platform credentials are header-read whatever `tokenDelivery` says. The registration switch decides, not `platform.enabled` |
1245
+ | a controller not mounted | no operation, and no scheme only it would have referenced |
1246
+
1247
+ **Two operations need two credentials at once, and the document says so.** Found in review of
1248
+ this PR, against the controllers rather than against the guard stack: `revokeAllSessions` is
1249
+ JWT-guarded AND reads the refresh token, because it revokes every session except the caller's
1250
+ and cannot spare a session it cannot name — without one it answers `auth.session_not_found`.
1251
+ `listSessions` and `changePassword` read the same token and succeed without it, with a lesser
1252
+ answer (`isCurrent` false everywhere; every session ended, the caller's included). Describing
1253
+ all three as access-only told a bearer-mode client to send no body to an endpoint that refuses
1254
+ without one, and a cookie-mode client that the refresh cookie was not read.
1255
+
1256
+ OpenAPI writes AND as one requirement entry carrying both schemes, so that is what they get —
1257
+ and under `'both'` the list is the product of the two channels: each access form, once with the
1258
+ refresh cookie beside it and once without, the second being the body-borne token that `security`
1259
+ cannot name. The required and the optional case produce the same document in that mode, which is
1260
+ a property of OpenAPI rather than a shortcut: once a body-borne alternative exists, no
1261
+ requirement list can insist on a credential that might be arriving in the body.
1262
+
1263
+ **The fragment also carries one sentence of prose, and it is there because a document cannot
1264
+ say this any other way.** `logout` requires nothing — an operator whose access token expired
1265
+ must still be able to sign out — so `security` renders "requires none" and "accepts and acts on
1266
+ whichever arrives" identically to anyone skimming. A consumer read the `@Public()` decorator,
1267
+ simplified to `security: []`, and measured what that produced: a logout called with no
1268
+ credential answers `204` and revokes **nothing**, with the same access token still getting `200`
1269
+ from `/me` afterwards. The user clicks sign out, sees success, and stays signed in, and no layer
1270
+ reports a failure. Under `tokenDelivery: 'bearer'` the refresh token in the body is the only
1271
+ channel there is, so omitting it is exactly that silent no-op. The operation therefore carries a
1272
+ `description` saying so. It is contributed the way everything else is — nest-core merges a
1273
+ fragment member only where the scan produced none, so a consumer who wrote their own
1274
+ `@ApiOperation` keeps it.
1275
+
1276
+ **And `logout` names the access token it revokes.** Also found in review, and the one with a
1277
+ security consequence rather than an ergonomic one: `logout` is `@Public()` — deliberately, so a
1278
+ user whose 15-minute access token expired can still sign out — but it READS that token and
1279
+ blacklists its `jti` for whatever life it has left. Described as refresh-only, a generated
1280
+ client sent no `Authorization` header, so the refresh session was revoked while a valid access
1281
+ token stayed usable until it expired. Every form it reads is now an alternative, richest first,
1282
+ with the empty entry last saying that nothing is required. Its platform twin already worked this
1283
+ way (`[{platformBearer}, {}]`), which is what made the dashboard side look like the oversight it
1284
+ was.
1285
+
1286
+ The refresh-cookie scheme is now defined when **any** of the three controllers that reference it
1287
+ is mounted, not only `auth` — a deployment mounting the session surface alone was referencing a
1288
+ scheme its own document never declared.
1289
+
1290
+ **A scheme the options cannot satisfy is absent**, never defined-and-unreferenced: nest-core
1291
+ fails a boot on a requirement naming an undefined scheme, and a document defining a credential
1292
+ the server will not read tells a generated client to offer it. Both directions are asserted —
1293
+ no dangling reference, and no unreferenced definition — under all three delivery modes.
1294
+
1295
+ **No coupling at all** — not a dependency, not a peer, not a devDependency, and no import even
1296
+ in tests. The contributor class is unexported, the contract revision is inlined and the marker
1297
+ is the documented string literal, so nothing published or unpublished names
1298
+ `@bymax-one/nest-core`. A conformance gate walks the whole tree and fails on an import of any
1299
+ other `@bymax-one/*` package, this package's own subpaths excepted; falsified from both a
1300
+ production file and a test file.
1301
+
1302
+ An earlier draft of this work took nest-core as a devDependency so the conformance suite could
1303
+ compare its constants as values, on the reasoning that test files do not ship. That reasoning
1304
+ is true and beside the point: **a library does not take a dependency on its consumers' stack in
1305
+ order to assert a composition** — the rule this repository already applies to
1306
+ `AuthExceptionFilter`. The check moves to the consumer, who can make it better anyway, because
1307
+ their suite runs both packages at the versions they installed. The README carries the two
1308
+ expectations to write, and says which of the two failures is silent.
1309
+
1310
+ Two acceptance checks run in both directions over the handler table: every declared key names a
1311
+ method that exists on the controller it names, and every route handler on every controller is
1312
+ declared. The first matters because a key nest-core cannot resolve **fails a consumer's
1313
+ document build** — a renamed handler here would break their repository on upgrade, not ours.
1314
+ The second is what stops the table falling quietly behind: a new endpoint that nobody described
1315
+ would inherit the consumer's document-level default, which is the wrong answer for a public
1316
+ route and an unenforced promise for a protected one.
1317
+
1318
+ **On nest-core older than 1.4.0 the fragments are silently ignored** — no contributor lane, so
1319
+ the document renders exactly as before with no error and no warning. Documented symptom-first
1320
+ in the README, with the diagnosis order, because "the contributor has not shipped yet" and "the
1321
+ nest-core version is too old" are indistinguishable from the document.
1322
+
1323
+ **Apply to a derived backend.** If you wrote `securitySchemes` or `openapi.operationSecurity`
1324
+ entries for this library's routes by hand, **delete them** — and note what that sentence is
1325
+ not saying. Those entries are not stale and not wrong: they are what makes the document correct
1326
+ today, and a maintainer told to remove "incorrect config" will go looking for a defect and find
1327
+ none. The accurate instruction is _delete the entries that currently do this job correctly,
1328
+ because the library now does it_ — the deletion is what transfers the work, and it is needed
1329
+ exactly because the entries were doing it. Precedence — read from nest-core's
1330
+ `augmentOperation`, not summarised — is: the generated operation's own `security`, then your
1331
+ override, then this library's fragment. So the stale vocabulary keeps winning and the
1332
+ contributed one never lands.
1333
+
1334
+ **And your own document test will not catch it.** A consumer seat measured their case: ten
1335
+ `operationSecurity` entries, all for this library's routes, and a suite asserting the
1336
+ operation-to-posture map with `toEqual`. On adoption every fragment loses to those entries, the
1337
+ old scheme names survive, and the suite stays **green** — it is asserting the old answer that is
1338
+ still being served. A test that pins your document confirms the staleness instead of finding
1339
+ it, so nothing downstream will remind you. Delete the literals, update whatever pins the
1340
+ document to the four-name vocabulary, rebuild, and regenerate any typed client.
1341
+
1342
+ **Delete the entries for THIS library's routes. Keep your document-level `security`.** Reported
1343
+ after publication by the consumer who ran the comparison this note asks for, and it is the one
1344
+ way following this instruction makes a document **worse**: the two usually live in the same
1345
+ options block, and removing the block removes the default. In `augmentOperation`, an operation
1346
+ with no requirement of its own, no override and no fragment falls through to `ownRouteSecurity`,
1347
+ which answers `undefined` for anything that is not a health or metrics route — so a backend's
1348
+ **own** guarded routes carry no requirement and inherit the document default. Take the default
1349
+ away and every one of those routes reads as public. The condition travels with the claim: this
1350
+ reaches routes that state nothing of their own — no decorator feeding the scanned operation, no
1351
+ `operationSecurity` entry, not a health or metrics route a policy answers for. Anything carrying
1352
+ its own requirement outranks the default and is untouched, which is why the fix works at all. A
1353
+ backend that annotates every guarded route individually is unaffected; the reason this bit two
1354
+ consumers is that annotating each route is what a document-level default exists to avoid. The
1355
+ health probes do move, losing their explicit `[]`, since `ownRouteSecurity` returns it only
1356
+ while `openapi.security.length > 0`.
1357
+
1358
+ On nest-core below 1.5.0 nothing reports it: no error, no unmatched key, no failing build. The
1359
+ document just stops asking for credentials on those routes — the ones the backend owns.
1360
+ nest-core 1.5.0 warns on this shape and names the bare operations, which makes
1361
+ it visible rather than impossible. Keep the default, and **derive it instead of writing a
1362
+ literal** — from the guard your own routes use, your `tokenDelivery`, and the controllers you
1363
+ registered, all three. A literal goes wrong in two distinct ways: where the named scheme is not
1364
+ declared, nest-core's `assertSchemesDeclared` throws the build; under `both`, where both access
1365
+ schemes exist, nothing throws and the default is merely incomplete, describing one of the two
1366
+ channels the routes accept. Loud in one place, quiet in the other. Two cases a delivery-only
1367
+ recipe gets wrong: `schemesFor` gates both dashboard schemes on a dashboard controller being
1368
+ registered — and `oauth` is not one of them, since its operations are public — so **any
1369
+ deployment with no dashboard surface declares neither and throws under `cookie` too**,
1370
+ platform-only and OAuth-only alike;
1371
+ and a route behind `JwtPlatformGuard` always wants `bymaxPlatformAccessBearer`, since
1372
+ `extractPlatformAccessToken` reads the `Authorization` header whatever the mode says. A backend
1373
+ guarding different routes with both families needs per-operation `security` for one of them —
1374
+ not because the default holds only one entry, but because its entries are alternatives applied
1375
+ to every inheriting operation, so listing both would document each credential as valid for
1376
+ either family.
1377
+
1378
+ The no-dashboard case gets a remedy rather than only a diagnosis, because those deployments are
1379
+ legitimate: `JwtAuthGuard` is registered and exported unconditionally, so mounting no dashboard
1380
+ controller does not stop a backend from guarding its own routes with a dashboard access token.
1381
+ Deriving correctly there answers "the scheme does not exist", which is true and unusable — so
1382
+ that deployment **declares the scheme itself** in `openapi.securitySchemes`. Which scheme is
1383
+ still a function of delivery, not a fixed recipe: `cookie` needs the `apiKey`-in-cookie
1384
+ definition carrying the configured `cookies.accessTokenName`; `bearer` needs the HTTP bearer
1385
+ definition and has no cookie name to carry; `both` needs **both**, or the document is incomplete
1386
+ in the same quiet way described above. `AUTH_SECURITY_SCHEMES` is not public API today, so the
1387
+ names are written as literals for now; exporting them is tracked.
1388
+
1389
+ Per-operation beats document-level, so the default cannot reach this library's operations.
1390
+ Verified on a real adoption: thirteen contributed operations render byte-identical with and
1391
+ without it.
1392
+
1393
+ **Not in this change:** per-operation error responses (the `4xx` set each operation can answer,
1394
+ read from `errorCatalog.statuses`) and the DTO request schemas. Both are additive to the same
1395
+ contributor and are next; the security posture is the half a consumer asserts today.
1396
+
1397
+ - **`WsJwtGuard` is now driven by a real WebSocket handshake.** 228 lines at **0% e2e coverage**:
1398
+ every other guard here is reached by an HTTP request, this one by a socket upgrade, and no
1399
+ suite spoke that protocol — so its only proof was unit tests handing it an `ExecutionContext`
1400
+ whose `switchToWs()` returned an object literal. That proves the code runs; it cannot prove a
1401
+ real handshake presents the credential where the guard looks for it, which is the entire
1402
+ question about a guard fed by a transport.
1403
+
1404
+ The alternative was to exclude it from the e2e-only rule with the residual risk written down.
1405
+ The devDependency was taken instead — `@nestjs/platform-socket.io`, `socket.io` and
1406
+ `socket.io-client`, dev-only, none of them in the published bundle. Statements 0% → **90.16%**,
1407
+ branches → **81.25%**, functions → **100%**, from a gateway declared in the test module the way
1408
+ a consumer declares one.
1409
+
1410
+ Both credential channels are exercised: the single-use ticket in the upgrade query (the only
1411
+ path a browser has, since the `WebSocket` API cannot set handshake headers) and the
1412
+ `Authorization` header. So are the refusals that matter — a replayed ticket, a token this
1413
+ deployment never signed, a token killed by a logout, a token killed by an epoch bump, one
1414
+ carrying no `jti`, and a ticket redeeming to a snapshot with **no tenant**, which is the shape
1415
+ `rust-auth` writes for a platform ticket into the `wst:` keyspace both libraries share.
1416
+
1417
+ **A second finding, from taking a review question seriously enough to measure it: the guard
1418
+ crashed the socket on the native `ws` adapter.** `WsJwtGuard` reads both credential channels
1419
+ from `client.handshake`, and `@nestjs/platform-ws` hands a gateway the raw `ws` socket, which
1420
+ has none — so the first property access threw a `TypeError`. Not an `AuthException`, so no
1421
+ filter could answer it: the connection dropped with no close frame and the caller learned
1422
+ nothing at all. It now **refuses** with `auth.token_invalid`, the same code a missing
1423
+ credential gets, and the filter delivers it. The guard still cannot authenticate on that
1424
+ adapter — `ws` does not retain the upgrade request — and the README says so where a consumer
1425
+ chooses an adapter.
1426
+
1427
+ **The finding this surfaced, and its fix — `WsAuthExceptionFilter`, exported.** The library's
1428
+ error catalogue did not reach the socket: `WsJwtGuard` throws `AuthException`, which extends
1429
+ `HttpException`, and Nest's WebSocket exception layer understands only `WsException` — so a
1430
+ refused client received `{status: 'error', message: 'Internal server error'}`. The refusal was
1431
+ correct (the handler never runs); what was lost is everything the client could act on. A
1432
+ reconnect policy cannot tell a dead credential from a crashed handler, and the sensible default
1433
+ for an unknown error is to retry, so an expired token became a reconnect loop against an
1434
+ endpoint that will refuse it forever.
1435
+
1436
+ Register it on a gateway that applies the guard (`@UseFilters(new WsAuthExceptionFilter())`) and
1437
+ the client reads `error.code` instead. `status: 'error'` is kept — the field Nest itself sets
1438
+ and the one socket.io clients branch on — with the envelope added beside it. The
1439
+ `AuthException` travels whole, so a `details` payload survives.
1440
+
1441
+ **Scoped to `AuthException`, and answering both transports.** An argument-less `@Catch()` would
1442
+ claim every exception the gateway raises, so a `WsException` an unrelated handler throws — a
1443
+ domain error with its own contract — would come back as an `auth.*` code: following the README
1444
+ would silently rewrite errors a consumer already ships. Everything that is not this library's
1445
+ refusal keeps travelling through Nest's own layer. And a native `ws` client is written to with
1446
+ `send`, not emitted on: it extends `EventEmitter`, so `emit` succeeds, dispatches a local event
1447
+ and sends the peer nothing — a filter that only emits is inert on exactly the transport whose
1448
+ refusal this fix exists to deliver.
1449
+
1450
+ Opt-in, like its HTTP twin: a library does not get to decide how an application answers
1451
+ failures it did not raise. It imports neither `socket.io` nor `@nestjs/websockets` — the client
1452
+ is typed structurally — so it costs a consumer with no gateway nothing. The e2e runs **two
1453
+ gateways under one application**, one filtered and one not, because the claim is that the two
1454
+ answer a refused client differently and one gateway can only show one of the two answers.
1455
+
1456
+ Three branches remain unreachable through this transport and say so in the suite: the
1457
+ missing-`@nestjs/websockets` arm of `onModuleInit`, `assertDashboardSnapshot`'s non-string
1458
+ `sub` (`redeemWsTicket` refuses such a record before it becomes a snapshot), and
1459
+ `readUpgradeTicket`'s unparseable-URL arm (Socket.IO builds the URL itself).
1460
+
1461
+ - **`AuthService.refresh` read the account without its tenant.** `findById(session.userId)` with
1462
+ no tenant argument, in the path that re-validates the account on every rotation — while the
1463
+ interface documents that ids may collide across tenants, and `UserStatusGuard` passes both for
1464
+ that reason. On a deployment whose ids are per-tenant, a homonym in another tenant could pass
1465
+ the status gate on the caller's behalf, and the re-stamp path a line below would sign **that
1466
+ account's tenant and role** into the token handed back. Now scoped to the tenant the session
1467
+ already carries, with a test that goes red without it.
1468
+
1469
+ Found in review of the documentation change below, which was recommending tenant-scoped reads
1470
+ to consumers while the library's own refresh path did not do one.
1471
+
1472
+ - **The access token's `status` claim is documented as point-in-time and never authoritative.**
1473
+ Three states, and a client can tell them apart from nothing: minted at login it carries the
1474
+ account's value _at that moment_; an ordinary refresh rotation stamps an **empty string**,
1475
+ because the session record holds no live status; and a refresh that re-signs — which
1476
+ `AuthService.refresh` does when `role`, `tenantId` or `mfaEnabled` changed — stamps the value
1477
+ read during _that_ request. `rust-auth` stamps the same empty string on its rotation path, with
1478
+ a test pinning it, so the middle state is a shared contract rather than a defect in either
1479
+ library.
1480
+
1481
+ Reported by a consumer seat that measured it on a live boot: `"pending"` before the first
1482
+ refresh, `""` after. Nothing in this library's own enforcement reads the claim — `UserStatusGuard`
1483
+ resolves status from the cache and the repository — so it is not a bypass. The exposure is a
1484
+ derived backend reading `request.user.status`, which is wrong in **both** directions:
1485
+ `!== 'active'` refuses everyone once a session has been refreshed, `=== 'suspended'` refuses
1486
+ nobody, ever. Both fail quietly, hours from the code that caused them.
1487
+
1488
+ Every populated value is stale the instant the account changes, because nothing re-stamps a live
1489
+ token — so the exceptional re-stamp is the worst of the three for a reader, not the best: it
1490
+ makes the claim _usually_ wrong rather than reliably empty. That is also why backfilling the
1491
+ rotation path was considered and rejected: it would extend the failure mode that survives
1492
+ testing. The empty string is the one state that cannot be mistaken for an answer.
1493
+
1494
+ Stated in the README as a three-row table and at the call site, with `mfaVerified: false` on
1495
+ rotation beside it, and the `userStatusCacheTtlSeconds` window (default 60) that decides how
1496
+ quickly a suspension bites.
1497
+
1498
+ **Apply to a derived backend.** Read status per request — `UserStatusGuard` on the route, and
1499
+ for anything richer `findById(request.user.sub, request.user.tenantId)`, **tenant-scoped**, the
1500
+ way that guard reads it — and never from the token. The tenant argument matters: ids may collide
1501
+ across tenants and `findById` accepts an absent tenant only for deliberately cross-tenant flows,
1502
+ so an unscoped read can resolve another tenant's account. If you already gate
1503
+ on the claim, that gate is either refusing everyone or nobody depending on which way you wrote
1504
+ the comparison.
1505
+
1506
+ - **The controller layer is now measured by the suite that goes through the framework.** E2E-only
1507
+ branch coverage of `src/server/controllers` was **75%**, and the shortfall was mostly whole
1508
+ endpoints nobody drove over HTTP. It is now **87%**, and everything still uncovered is named
1509
+ below rather than left as a number.
1510
+
1511
+ What had no e2e at all: the **address-change flow** (`EmailChangeController` sat at 0%
1512
+ functions — request, mail, confirm, replay, and the boot-time refusal when the provider cannot
1513
+ deliver the token), **invitation revocation**, the **two challenge routes crossed** (a platform
1514
+ temp token on the dashboard route and a dashboard one on the platform route — the branches that
1515
+ stop a credential from one surface becoming a session on the other), **logout and refresh with
1516
+ no credential at all** on both surfaces, and a **host that never mounted a cookie parser**,
1517
+ which is a supported deployment this library takes no dependency on.
1518
+
1519
+ Two of those found real defects: the MFA one is under _Fixed_ below, and the invitation case
1520
+ corrected the test rather than the code — revocation is by **rank**, not admin-only, and an
1521
+ outranked revoke answers the same `204` a permitted one does, on purpose. Asserting the two
1522
+ responses **against each other** is what makes that an anti-enumeration property instead of two
1523
+ endpoints agreeing because nothing happened in either; the effect is then read where the
1524
+ invitee's token is spent.
1525
+
1526
+ **What remains, and why it stays uncovered:** eight occurrences of `req.ip ?? ''` and one
1527
+ `err instanceof AuthException` fallback. Express sets `req.ip` for every request with a live
1528
+ socket, so the fallback needs a socket that is already gone — real, and not producible over
1529
+ supertest. They are one duplication rather than nine independent gaps, and folding them into a
1530
+ single helper (which would also fix the User-Agent bound being applied by `OAuthController` and
1531
+ by nobody else) is its own change.
1532
+
1533
+ - **The five guards this library exports and never mounts are now driven from a host's own
1534
+ controller.** `RolesGuard`, `PlatformRolesGuard`, `MfaRequiredGuard`, `OptionalAuthGuard` and
1535
+ `SelfOrAdminGuard` exist for a consumer to apply to their routes, and nothing here applied them
1536
+ — so their only proof was unit tests handing each guard an `ExecutionContext` no middleware
1537
+ would build. E2E-only branch coverage of `src/server/guards` was **34.19%**; it is now
1538
+ **65.16%**, and the five are at 100% apart from two branches named below.
1539
+
1540
+ The fixture controller is declared in the **test module**, not inside `BymaxAuthModule`, and
1541
+ that is the point: `@UseGuards(...)` re-instantiates a guard in the declaring module's injector,
1542
+ so it resolves only what this library actually **exports**. The module's export list has carried
1543
+ comments claiming that works — `AuthRedisService`, `AuthRevocationService`,
1544
+ `BYMAX_AUTH_USER_REPOSITORY`, `WsTicketService` and `JwtModule` are all exported for exactly
1545
+ this reason — and nothing exercised the claim until now. It holds: every one of the five mounts
1546
+ and runs from a consumer's controller.
1547
+
1548
+ Three of them are proven by falsification rather than by watching green: admitting a
1549
+ user-less request in `RolesGuard`, swallowing an invalid token in `OptionalAuthGuard`, and
1550
+ dropping the `mfaEnabled` type check in `MfaRequiredGuard` each turn exactly the case that
1551
+ names them red.
1552
+
1553
+ With the wildcard route and the literal-`admin` deployment both driven, `SelfOrAdminGuard`
1554
+ reaches **100% on every axis from e2e alone**, and `RolesGuard`, `OptionalAuthGuard` and
1555
+ `MfaRequiredGuard` were already there.
1556
+
1557
+ **`SelfOrAdminGuard`'s array-valued param is reachable, and is now driven.** The first draft of
1558
+ this work called it impossible — Express builds `req.params` from the path, where a name cannot
1559
+ repeat — and that was wrong: Express 5 (path-to-regexp 8) fills a **named wildcard**'s param
1560
+ with an array of segments, `['abc']` even for a single one. Any consumer writing
1561
+ `@Get('files/*path')` behind the guard reaches it on every request, including the URLs that
1562
+ look exactly like a plain param. Measured, then covered: the fixture declares a wildcard route
1563
+ and the suite drives one segment and three. Refusing is deliberate — picking an element would
1564
+ compare an identity against one segment of a caller-chosen path and admit the rest unlooked-at.
1565
+
1566
+ **One branch is out of reach of the compositions this library supports**, and says so in its own
1567
+ source rather than being quietly missing from the report: `PlatformRolesGuard`'s missing
1568
+ `platformHierarchy`. Reaching it needs `JwtPlatformGuard`, which needs `platform.enabled`, which
1569
+ `resolveOptions` refuses without that map — so nothing this library mounts gets there, while a
1570
+ consumer's own guard populating `request.user` does, over HTTP, which is what the arm defends.
1571
+ Covered by its unit spec.
1572
+
1573
+ - **The shared wire contract is pinned by hash, so it cannot change unnoticed.**
1574
+ `conformance/wire-contract.json` is the one artifact `rust-auth` and this library are supposed
1575
+ to hold **byte-identically** — it is the source on both sides rather than a derivation of one.
1576
+ Nothing asserted it had not moved. The conformance suite now pins its SHA-256.
1577
+
1578
+ **What it catches:** an _unaccompanied_ byte change — an edit that forgets to advance the
1579
+ constant, a formatter rewriting the file, a merge resolving it differently. Falsified by
1580
+ re-serialising the file with identical data and different bytes.
1581
+
1582
+ **What it does not catch, stated because the first draft of this note claimed otherwise:**
1583
+ cross-implementation divergence. Changing the file _and_ the constant in one commit leaves this
1584
+ suite green while `rust-auth`'s untouched pair leaves theirs green too — both green, bytes
1585
+ divergent. Two independent local hashes cannot enforce agreement between two repositories,
1586
+ because neither reads the other. Closing that needs a real cross-repository comparison (one
1587
+ side fetching the other's committed blob in CI, or both consuming an immutable versioned
1588
+ artifact); it is proposed and unbuilt.
1589
+
1590
+ - **The E2E config was the one place the OOM bounds from #41 were never applied.**
1591
+ `jest.config.ts` and `jest.coverage.config.ts` both carry `maxWorkers: '50%'` and
1592
+ `workerIdleMemoryLimit: '1GB'` — added in #41, _"bound mutation and jest memory to stop OOM
1593
+ restarts"_ — and `jest.e2e.config.ts` carried neither. E2E is where they matter most: every spec
1594
+ boots a full Nest application with its own `ioredis-mock`, so per-worker memory grows with the
1595
+ number of spec **files**, not with the number of tests.
1596
+
1597
+ Found by adding spec files. Three unrelated suites began failing intermittently — password
1598
+ reset, platform MFA, refresh-token reuse — alongside `Test suite failed to run`, which is a
1599
+ worker dying rather than a test disagreeing. Which suites break depends on how Jest distributes
1600
+ files across workers, so it presents as a flake in whatever spec was added last, and the first
1601
+ diagnosis is always the new spec.
1602
+
1603
+ - **The cookie flags are pinned, and the half no server-side suite can reach is stated as a
1604
+ consumer contract.** Cookie delivery exists for one guarantee — the tokens are never readable
1605
+ from JavaScript — and a leak into JS-readable storage is invisible from the server: the API
1606
+ answers identically, the wire looks correct, and every test here passes. Only a browser
1607
+ observes it.
1608
+
1609
+ This suite now asserts **its half**: `access_token` and `refresh_token` carry `HttpOnly` and
1610
+ `Secure`, the refresh cookie is path-scoped to the auth prefix rather than origin-wide, and the
1611
+ set of cookies is pinned so a new credential-bearing one cannot appear outside those checks.
1612
+ Asserted **per cookie**, not as a blanket rule, because `has_session` is deliberately
1613
+ JS-readable — it carries no credential and is what lets a SPA know a session probably exists
1614
+ without touching a token. A blanket "everything is HttpOnly" assertion would fail on it, and the
1615
+ obvious fix for that would remove the feature silently.
1616
+
1617
+ The README now states the other half as the consumer's: assert in a browser suite that
1618
+ `localStorage` and `sessionStorage` are empty and that `document.cookie` carries neither token.
1619
+
1620
+ - **The framework-fed layers are now proven by a suite that goes through the framework.**
1621
+ Per-layer measurement, which the aggregate 100% hides: filters were at **0%** e2e coverage and
1622
+ guards at **30.4% of branches**. A unit test on a controller, guard or filter _invents_ its
1623
+ input — it proves the code runs, never that it is reachable.
1624
+
1625
+ `AuthExceptionFilter` reached 100% on every axis, and was found never to have been registered in
1626
+ the harness at all while three specs carried comments crediting it for envelopes it was not
1627
+ producing. The guard work drove the **refusals** — every prior e2e exercised guards admitting a
1628
+ valid caller on the way somewhere else — including every refusal branch of the CSRF guard, a
1629
+ token whose account was deleted after issue, and `/ws-ticket`, which had no e2e of its own.
1630
+
1631
+ ### Changed
1632
+
1633
+ - **An OAuth callback carrying neither `code` nor `error` now answers `401 auth.oauth_failed`
1634
+ instead of `400 auth.validation`.** Wire change, and the one place this library and `rust-auth`
1635
+ still disagreed on the same request.
1636
+
1637
+ `OAuthCallbackQueryDto.code` no longer carries a requirement: it is validated when it is present
1638
+ and `error` is not, so its bounds are unchanged and an empty or oversized `code` is still the
1639
+ pipe's to refuse, naming the field. What moved is the **absent** case. The handler already
1640
+ carried the answer — `if (query.code === undefined) return this.handleCallbackFailure(...)`,
1641
+ written when the "user clicked Cancel" path was fixed — and the DTO's conditional requirement
1642
+ made that branch **unreachable over HTTP**: the pipe refused the request first, every time. The
1643
+ branch nonetheless read as covered, by a unit test handing the controller a query object the
1644
+ HTTP surface could not produce (`{ state } as never`). A test that invents its input proves the
1645
+ code runs, never that it is reachable.
1646
+
1647
+ A codeless callback is a failed authorization, not a malformed request, and both libraries now
1648
+ say so in the same code. Under `oauth.errorRedirectUrl` it takes the same `?error=oauth_failed`
1649
+ redirect every other OAuth failure takes, rather than escaping the redirect as a validation
1650
+ envelope.
1651
+
1652
+ `conformance/openapi-declared-structures.json` follows the behaviour: the `anyOf` over
1653
+ `code | error` was a request structure while the pipe enforced it, and is now a handler refusal
1654
+ (`OAuthController.callback#codelessCallback`) with probes both layers answer — the pipe half
1655
+ read where the pipe answers, the HTTP half over a bootstrapped application. Falsified by putting
1656
+ the requirement back: exactly one case goes red in each suite, and it is the codeless callback
1657
+ in both.
1658
+
1659
+ **Apply to a derived backend.** No code change. If you match on the response to a malformed
1660
+ OAuth callback — an error page keyed by `code`, a log alert, an e2e assertion — a callback with
1661
+ no `code` and no `error` now arrives as `401 auth.oauth_failed` with no `details` array, where
1662
+ it used to arrive as `400 auth.validation` with `details[0].field === 'code'`. The provider's
1663
+ own error callback (`?error=access_denied`) is unaffected; it already answered
1664
+ `auth.oauth_failed`.
1665
+
1666
+ ### Fixed
1667
+
1668
+ - **A malformed `mfaTempToken` answered `500 auth.internal` instead of `401
1669
+ auth.mfa_temp_token_invalid`.** `TokenManagerService.verifyMfaTempToken` let the verifier's own
1670
+ error propagate — its JSDoc said so — and nothing above catches it, so any garbage in the body's
1671
+ `mfaTempToken` or in the `mfa_temp_token` cookie an OAuth callback plants produced a 5xx. Every
1672
+ other failure in that method already answered `MFA_TEMP_TOKEN_INVALID`; the verification failure
1673
+ now says the same thing.
1674
+
1675
+ Three consequences, none visible from a unit test that only ever passed it a token it had just
1676
+ minted: an attacker-controlled input produced a 5xx (free noise in an operator's error budget,
1677
+ and cover for the 500s that mean something); `MfaController` clears the temp cookie only for an
1678
+ `AuthException` it recognises, so a browser holding a malformed cookie was never told to drop
1679
+ it and replayed the same dead value on every attempt; and **`rust-auth` maps the same failure to
1680
+ `MfaTempTokenInvalid`** (`token_manager.rs`,
1681
+ `verify_rotating(...).map_err(|_| AuthError::MfaTempTokenInvalid)`), so the two backends
1682
+ answered one request differently. Found by driving the cookie path over HTTP for the first
1683
+ time.
1684
+
1685
+ **Apply to a derived backend.** No code change. A request that used to come back `500` now
1686
+ comes back `401 auth.mfa_temp_token_invalid`. If you alert on 5xx from `/auth/mfa/challenge`,
1687
+ that alert was firing on client input and will now go quiet.
1688
+
1689
+ - **`AuthExceptionFilter` silently displaces `@bymax-one/nest-core`'s envelope filter.**
1690
+ Documented rather than code-changed: the behaviour is correct and only the advice was
1691
+ incomplete. **Nothing in this repository verifies it** — doing so would mean depending on
1692
+ `@bymax-one/nest-core`, and this library does not depend on its consumers' stack. The
1693
+ measurement below was taken once, deliberately, and then the dependency was removed; a consumer
1694
+ composing both libraries owns the standing assertion. `useGlobalFilters` binds ahead of an `APP_FILTER` provider and this filter is
1695
+ `@Catch()` with no argument, so registering it in a nest-core application means nest-core's
1696
+ never runs. Measured — the same request answers `{error: {code, message, details}}` with it and
1697
+ the flat `{statusCode, code, message, timestamp, path, details}` without it.
1698
+
1699
+ **Apply to a derived backend.** Building on `@bymax-one/nest-core`? **Do not register
1700
+ `AuthExceptionFilter`.** Take theirs — it already recognises this library's envelope and passes
1701
+ the code, message and per-field details through unchanged. Registering both loses `statusCode`,
1702
+ `timestamp`, `path` and the correlation id, which is the opposite of what adding a filter looks
1703
+ like it should do. The symptom is a body nested under `error` where your other endpoints answer
1704
+ flat.
1705
+
1706
+ - **The declared structural overlay**
1707
+ ([`conformance/openapi-declared-structures.json`](conformance/openapi-declared-structures.json)).
1708
+ The 1.4.2 schema artifact named three contracts in its own header that it could not express,
1709
+ plus the anti-enumeration semantics that are a property of two responses rather than of either
1710
+ one. They are now **structure** — `oneOf` for `reset-password`'s exactly-one-of proof set,
1711
+ `required` + `anyOf` for the OAuth callback's conditional requirement — and executable probes
1712
+ for the two that are not structural at all: the 8-vs-15 password floor and the four endpoints
1713
+ that answer identically for an address with no account.
1714
+
1715
+ Kept honest by three rules. The evaluator understands `required`, `oneOf` and `anyOf` and
1716
+ nothing else, and a structure using `allOf` or `not` — both valid OpenAPI 3.0 — is **refused at
1717
+ load** rather than skipped, because a keyword nothing evaluates publishes a claim nothing
1718
+ checks. Every entry ships probes, split across the two suites that can actually answer them:
1719
+ the unit suite evaluates each body against its own structure and enforces the pipe-refused
1720
+ ones, the e2e suite answers the service-enforced and response-level ones against a real
1721
+ application. And each entry must **discriminate** — a probe set that all expected the same
1722
+ refusal would be satisfied by a server that refuses everything, so at least one accepted body
1723
+ must be answered differently.
1724
+
1725
+ Presence, for `required`, means present **and not `null`** — this server's rule rather than
1726
+ JSON Schema's. Measured, not assumed: `@IsOptional()` registers a conditional whose predicate is
1727
+ `value !== null && value !== undefined`, so `{"token": null, "otp": "…"}` carries one proof, not
1728
+ two. The probes carrying an explicit `null` are what prove it.
1729
+
1730
+ One correction to how the exactly-one-of had been described, including in the 1.4.2 header: it
1731
+ is **necessary but not sufficient**. Which of `token`, `otp`, `verifiedToken` is eligible
1732
+ depends on the deployment's `passwordReset.method`, and an ineligible proof is refused with the
1733
+ same `auth.password_reset_token_invalid` a structural violation gets — indistinguishable to the
1734
+ client, and inexpressible in any committed document because it is option-derived. It is declared
1735
+ with its own probes, under its own name, so a reader is not left inferring a symmetry that is
1736
+ not there.
1737
+
1738
+ - **`POST {prefix}/password/change` refused the `refreshToken` it reads.**
1739
+ The handler takes the caller's own refresh token through
1740
+ `TokenDeliveryService.extractRefreshToken`, which reads **the request body** under
1741
+ `tokenDelivery: 'bearer'` and body-after-cookie under `'both'` — but `ChangePasswordDto` never
1742
+ declared the field, and the controller pipe runs `forbidNonWhitelisted: true`. So a bearer-mode
1743
+ caller sending it was answered `auth.validation` naming `refreshToken`, and the only way to
1744
+ change a password was to lose every other session. `refreshToken?: string` is now declared, and
1745
+ appears in the generated request schema.
1746
+
1747
+ **A `tokenDelivery: 'cookie'` deployment was never affected** — the credential arrives in the
1748
+ cookie and no body field exists — which is why this survived: the default hides it. Confirmed
1749
+ live on a derived backend against the published 1.4.2, in both modes: `bearer` answers
1750
+ `400 auth.validation` with `details: [{ field: 'refreshToken', message: 'property refreshToken
1751
+ should not exist' }]`, and the same call without the field answers `204` while ending every
1752
+ other session; `cookie` answers `204` clean.
1753
+
1754
+ Found by the harness fix below: the global `ValidationPipe` stripped the property before the
1755
+ controller's own pipe could refuse it, so every E2E exercised a request production never sees.
1756
+
1757
+ The README's request-body table is updated in the same release: it had listed the old body, so
1758
+ the documentation shipped in the tarball was stale about the very field this fixes. `tenantId`
1759
+ aside, the table now names `refreshToken` and says what both answers mean — send it and the
1760
+ calling device stays signed in, omit it and every session ends. `check:published` cannot catch
1761
+ that class: it compares exported types against the docs and does not see a prose table drift
1762
+ from a DTO.
1763
+
1764
+ - **The E2E harness shadowed the library's own validation pipe, so no E2E had ever seen
1765
+ `auth.validation`.** `test/e2e/setup.ts` installed a global `ValidationPipe`, and global pipes
1766
+ run **before** the controller-scoped `@UsePipes(createAuthValidationPipe())` every auth
1767
+ controller declares. A DTO failure therefore answered with the framework's
1768
+ `{ statusCode, message, error }` instead of `{ error: { code: 'auth.validation', details:
1769
+ [{ field, message }] } }` — measured: a seven-character `newPassword` came back as
1770
+ `{"message":["newPassword must be longer than or equal to 8 characters"],"error":"Bad
1771
+ Request","statusCode":400}`.
1772
+
1773
+ The suite would have stayed green if `createAuthValidationPipe` had stopped producing the
1774
+ envelope entirely. The one E2E touching the path asserted `status === 400`, which the
1775
+ framework's shape satisfies exactly as well as the library's — the same range-assertion
1776
+ blindness that let thirteen wrong statuses survive.
1777
+
1778
+ The harness now installs **no** global pipe at all, so each auth controller's own runs first.
1779
+ Installing the library's pipe globally was not enough: with `whitelist: true` it strips unknown
1780
+ properties before the controller's `forbidNonWhitelisted: true` can refuse them, so the harness
1781
+ still would not have exercised the production contract — which is how the `refreshToken` defect
1782
+ above stayed invisible. That assertion now names the code and the field.
1783
+
1784
+ **Apply to a derived backend.** This is a test-harness fix, but it names a real deployment
1785
+ hazard: **if your application registers `app.useGlobalPipes(new ValidationPipe(...))`, it
1786
+ shadows this library's pipe on every auth route.** DTO failures then answer the framework's
1787
+ shape rather than `auth.validation`, and a client switching on `error.code` never sees it. With
1788
+ `@bymax-one/nest-core`'s envelope filter in front, the failure is re-shaped again and surfaces
1789
+ as `BYMAX_VALIDATION_FAILED` with `details: [{ issue }]` — a different code **and** a different
1790
+ details shape from the `auth.validation` / `[{ field, message }]` this library and `rust-auth`
1791
+ both document.
1792
+
1793
+ **How to tell in one query:** you have it if a DTO failure on an auth route answers
1794
+ `BYMAX_VALIDATION_FAILED` with `details[].issue`; you do not if it answers `auth.validation`
1795
+ with `details[].field`. Grep your own error logs for the first pair rather than auditing where
1796
+ pipes are registered.
1797
+
1798
+ **The fix:** scope your global pipe away from the auth routes, or build it with
1799
+ `createAuthValidationPipe()`, which is exported for exactly this.
1800
+
1801
+ **The durable guard — assert the composed envelope in your application's E2E**, because neither
1802
+ library can. This library's suite sees its own pipe; `nest-core`'s suite sees its own filter;
1803
+ the shape a client actually receives exists only where the two are wired together, which is your
1804
+ application. A consumer who fixes the pipe today and adds a global one next quarter is back here
1805
+ otherwise. One scenario is enough: drive a real request that fails validation and shape-match
1806
+ both `code: 'auth.validation'` and `details: [{ field, … }]`.
1807
+
1808
+ - **`/client` required a `tenantId` the server refuses, so a consumer had to bypass it.**
1809
+ `LoginInput`, `RegisterInput`, `ResetPasswordInput` and `forgotPassword(email, tenantId)` all
1810
+ demanded the field. On a deployment with a configured `tenantIdResolver` — the case 1.4.2 made
1811
+ breaking — sending it answers `400 auth.validation` with a `tenantId` field detail, so the
1812
+ library's own typed client could not talk to the library's own server. A consumer building an
1813
+ SPA rejected `createAuthClient` and `AuthProvider` over exactly this and hand-wrote the request
1814
+ shapes.
1815
+
1816
+ All four are now `tenantId?: string`. The defect was type-level rather than on the wire —
1817
+ `JSON.stringify` already dropped an `undefined` property — which is why the guard is that the
1818
+ client suite now calls `login`/`register`/`forgotPassword`/`resetPassword` **without** a tenant
1819
+ and would stop compiling if the field went back to required.
1820
+
1821
+ The JSDoc was the worse half. It read _"`tenantId` is required because the server-side
1822
+ `LoginDto` enforces it with `@IsNotEmpty()`"_ — and that was never true: `@IsNotEmpty()` sits
1823
+ under `@IsOptional()`, so it rejects an empty string when the field is present and says nothing
1824
+ about absence. `LoginDto.tenantId` has been optional since **1.3.0**; the comment misread its own
1825
+ decorator stack and survived three minors, because a comment is checked by nobody. The
1826
+ replacements state the consequence and name where the mechanism is asserted, rather than
1827
+ restating decorators they cannot see.
1828
+
1829
+ - **Draining the response body deadlocked under request interception.**
1830
+ `await response.body?.cancel()` in `createAuthFetch` and `createAuthClient`. Under MSW or
1831
+ undici-in-jsdom the promise never settles, so every call whose response carries a body hung.
1832
+ `/auth/refresh` carries one on success as well as on failure, which put it on the happy path at
1833
+ every token rotation.
1834
+
1835
+ **Production was never affected, and that is measured rather than assumed** — a real browser
1836
+ cancels the stream cleanly, confirmed under Playwright by deleting only the `access_token`
1837
+ cookie and watching a reload produce exactly one `POST /auth/refresh`, status 200, with no
1838
+ bounce to sign-in. So this is a **testing defect**, and the cost is precise: every consumer
1839
+ using request interception cannot test refresh-and-retry at all, and it is the _success_ path
1840
+ that is untestable. A four-way probe established the body's construction is irrelevant —
1841
+ `HttpResponse.json`, a raw string and a hand-built `ReadableStream` all hang while `.json()` on
1842
+ the same response resolves — so it is the interceptor's stream teardown, and dropping the
1843
+ `await` fixes it for every consumer without MSW changing anything.
1844
+
1845
+ The drain is no longer awaited; nothing downstream needs it to have completed, the status has
1846
+ already been read. Regression test: a response whose `cancel()` never settles.
1847
+
1848
+ - **`refreshEndpoint` was undocumented, and its default 404s in a plain SPA.**
1849
+ It defaults to `/api/auth/client-refresh`, a Next.js proxy route, and a Vite/CRA app serves
1850
+ nothing there — refresh silently fails and every access-token expiry presents as a session bug.
1851
+ The README now covers it, with the symptom: _if every expiry logs the user out, check
1852
+ `refreshEndpoint` before looking at cookies._
1853
+
1854
+ **Apply to a derived backend.** Nothing changes server-side. Frontends on a non-Next stack
1855
+ should set `refreshEndpoint` explicitly, and frontends on a resolver deployment should now stop
1856
+ passing `tenantId` — the client no longer forces them to.
1857
+
21
1858
  ## [1.4.2] - 2026-08-13
22
1859
 
23
1860
  Closes the two findings that came out of auditing this library from the outside: every DTO it
@@ -1545,7 +3382,9 @@ ever installable.
1545
3382
  - 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
1546
3383
  - 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
1547
3384
 
1548
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...HEAD
3385
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.4...HEAD
3386
+ [1.4.4]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...v1.4.4
3387
+ [1.4.3]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...v1.4.3
1549
3388
  [1.4.2]: https://github.com/bymaxone/nest-auth/compare/v1.4.1...v1.4.2
1550
3389
  [1.4.1]: https://github.com/bymaxone/nest-auth/compare/v1.4.0...v1.4.1
1551
3390
  [1.4.0]: https://github.com/bymaxone/nest-auth/compare/v1.3.2...v1.4.0