@bymax-one/nest-auth 1.4.3 → 1.4.5

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,1147 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.5] - 2026-08-29
22
+
23
+ ### Added
24
+
25
+ - **`AuthRevocationService` now warns when it refuses a dashboard token for carrying no tenant.**
26
+ 1.4.4 made that case fail closed, which was the right call and is unchanged. What it did not do
27
+ is say so: the refusal answers the same `true` a genuinely revoked token answers, reads nothing,
28
+ throws nothing and emits no event, so it is indistinguishable from a revocation that worked.
29
+
30
+ Measured on the caller the 1.4.4 entry names. A consumer's realtime bridge called
31
+ `isAccessTokenRevoked({ jti, sub, epoch }, 'dashboard')` without the tenant; the SSE handshake
32
+ answered `200` and then registered nothing, and the connection registry sat at `count: 0` while
33
+ every stream was silently refused. It reads as a realtime bug rather than an auth one, and every
34
+ gate agreed with that reading: `tsc` passes because `tenantId` is optional on
35
+ `RevocableTokenPayload`, and a unit suite passes at 100% mutation score while asserting the
36
+ forwarded payload is exactly `{ jti, sub, epoch }` — a faithful test of a contract that had moved
37
+ underneath it. Twenty minutes of bisecting, ended by a log line that costs two.
38
+
39
+ The message names the missing field and the remedy, and says the refusal is deliberate so it is
40
+ not filed as a library bug. No identifier is logged: `sub` names an account and `jti` a live
41
+ token, and neither is needed to act on it.
42
+
43
+ **The tenant check also moved ahead of the per-token blacklist read**, which validates the input
44
+ before consulting a channel. The answer is unchanged — `true` either way, indistinguishable to a
45
+ caller — but behind the blacklist read the warn fired only for a token that happened not to be
46
+ blacklisted, so a bridge calling this wrongly on every request could go on doing so unheard, the
47
+ diagnostic coming and going with unrelated state. It also spares a Redis round trip on a request
48
+ that is already refused, and makes "without a store read" true of the path rather than nearly
49
+ true.
50
+
51
+ **A distinct error code was considered and rejected.** `isAccessTokenRevoked` returns a boolean
52
+ and the three guards turn it into a refusal, so giving this case its own `AuthErrorCode` means
53
+ widening the return of an exported service and threading it through all three — and an `auth.*`
54
+ code is wire vocabulary, so it would answer an unauthenticated client with a detail about the
55
+ deployment's own wiring that today's refusal does not leak. The operator's log is the one place
56
+ that can act on it.
57
+
58
+ **Apply to a derived backend.** Nothing to do — behaviour is unchanged, and the only new output
59
+ is a `warn` on a path that was already refusing. If it appears in your logs, a caller is reaching
60
+ the service without the tenant from its verified token; fix the caller rather than the log, and
61
+ consider typing the tenant as REQUIRED on your own port so the omission cannot recur.
62
+
63
+ - **`AuthRevocationService` is documented in the README**, under the API reference. It has been a
64
+ public export since it was extracted from the three JWT guards, and the README never mentioned it
65
+ — so the one thing a caller outside a guard has to know, that a dashboard check must forward
66
+ `tenantId` from the verified token, was reachable only from the JSDoc or from this changelog.
67
+ That is the omission the entry above was measured on. The new section names both revocation
68
+ channels, states the tenant obligation as a requirement rather than a note, and describes the
69
+ symptom to recognise — `true` with nothing thrown, a stream that registers nothing — because it
70
+ does not read as an auth bug from the transport side.
71
+
72
+ It also says what the method is **not**: it answers two channels at the moment it is called, and
73
+ reads no `exp`, holds no subscription, emits no event, and knows nothing about account status,
74
+ roles, tenant binding or the identity plane. It is one check among the many a guarded route
75
+ performs, not a way to authorise a stream.
76
+
77
+ **Guidance on doing that safely was drafted and withdrawn**, and the reasoning is worth recording
78
+ because it is a statement about the library rather than about the prose. Seven successive drafts
79
+ were each found wrong by review — a recipe that would have admitted a pre-MFA token, a bare-id
80
+ fan-out reintroducing the cross-tenant defect 1.4.4 removed, a reconnect that carries neither
81
+ route authorization nor `enforceTenantBinding`, and mitigations that cannot reach a
82
+ ticket-authenticated platform socket at all. The through-line is that this library does not
83
+ export the pieces a consumer would need, so the documentation was describing a hand-rolled
84
+ reproduction of a security chain that has no supported form. That belongs in an issue with the
85
+ gaps named, not in a release: [#172](https://github.com/bymaxone/nest-auth/issues/172).
86
+
87
+ ## [1.4.4] - 2026-08-19
88
+
89
+ ### Changed
90
+
91
+ - **`SessionInfo` now names the shape `GET /sessions` returns.** (#156) Two interfaces answered to
92
+ that name — the session listing in `SessionService`, and the contextual payload sent in
93
+ new-login alert emails — and the barrel exported the **email** one under the plain name, with
94
+ the listing type exported as `ActiveSessionInfo`. That is backwards: a consumer typing a session
95
+ listing imports `SessionInfo`, receives `device` and `ip` with no `id` — and a `sessionHash` that
96
+ means something different. On the alert type it is the TRUNCATED display value; on the listing it
97
+ is the full 64-hex hash. Same field name, same type, different value, and the truncated one is
98
+ precisely what `DELETE /sessions/:id` refuses.
99
+
100
+ It does. Two consumer sessions disagreed for a day over exactly that — one read the wire and saw
101
+ an `id`, the other read the published type and did not. Neither was careless; the name resolved
102
+ to the wrong shape.
103
+
104
+ **Apply to a derived backend.** The email-alert type is now `SessionAlertInfo`, named for what
105
+ it is. If you implement `IEmailProvider`, rename the parameter type on `sendNewSessionAlert` —
106
+ the fields are unchanged. If you imported `ActiveSessionInfo` to type a session listing, import
107
+ `SessionInfo` instead: same shape, correct name. No runtime behaviour moves.
108
+
109
+ - **A malformed `sessionHash` answers `VALIDATION`, not `SESSION_NOT_FOUND`.** (#156) The two were
110
+ deliberately indistinguishable, on the argument that telling them apart would let a caller
111
+ enumerate valid hash formats. The format is not a secret: it is 64 hex characters,
112
+ `SessionInfo.sessionHash` publishes it on every listed session, and the route documents it. So
113
+ the pairing protected nothing and cost something real — a consumer sending a malformed hash got
114
+ the same answer as one sending an already-revoked session, and read a UI bug as a race between
115
+ the session list and the click. Twenty minutes chasing a race that cannot happen.
116
+
117
+ A well-formed hash that names nothing still answers `SESSION_NOT_FOUND`. That is where the
118
+ no-enumeration argument does apply, because that answer really would say whether a session
119
+ exists.
120
+
121
+ **Apply to a derived backend.** If you branch on `auth.session_not_found` to mean "bad input",
122
+ branch on `auth.validation` for that case; the payload names `sessionHash` in `details`.
123
+
124
+ ### Fixed
125
+
126
+ - **`DELETE /sessions/:id` documented a prefix it has always refused.** (#156) The controller
127
+ described the parameter as accepting "its hash prefix (display id) **or** full 64-character
128
+ SHA-256 session hash". The handler has only ever accepted the full hash — and until the change
129
+ above, a prefix was refused with the same error as a session that no longer exists, which is
130
+ what made it read as a race rather than as a rejected input.
131
+
132
+ The prefix will **not** be made to work: `SessionInfo.id` is the first 8 characters of the hash
133
+ and is not unique by construction, so resolving one on a revocation could revoke a different
134
+ session than the one the user clicked. The documentation now says so and names the display value
135
+ as display-only.
136
+
137
+ - **`mergeHeaders` sent every header twice when the caller's key case differed from the default,
138
+ which broke every authenticated call carrying a body.** (#156)
139
+
140
+ Header names are case-insensitive; plain object keys are not. `DEFAULT_HEADERS` keys
141
+ `Content-Type`, `Headers.prototype.forEach` yields lowercase names, and both survived into the
142
+ merged record — so `fetch` joined them on the wire:
143
+
144
+ ```
145
+ content-type: application/json, application/json
146
+ ```
147
+
148
+ Legal HTTP, so nothing rejects it. The backend simply stops parsing the body and answers
149
+ `400 "role is required"` naming a field that IS present, which reads as a caller bug while the
150
+ caller is correct. The header is the last place anyone looks.
151
+
152
+ **Both reports put arrays in the safe column, and that is one notch too narrow.** Measured
153
+ against the shipped function, the rule is only _"the key case differs from the default"_ — the
154
+ `HeadersInit` shape does not enter into it. A record written `content-type`, the spelling the
155
+ platform itself uses, duplicates just as surely as a `Headers` instance does, and so does an
156
+ array of pairs written lowercase. `Headers` merely makes it unavoidable, because `forEach`
157
+ lowercases for you. "We do not pass `Headers`" was not the reassurance it looked like.
158
+
159
+ **A second site neither report reached:** the factory built its defaults with the same
160
+ case-sensitive spread, so overriding the content type through the documented
161
+ `defaultHeaders` option also duplicated it — set up once, poisoning every request, far from
162
+ the call anyone is debugging.
163
+
164
+ Fixed by letting `Headers` own the semantics on both paths: names normalise per the spec, and
165
+ `set` replaces rather than appends, which is the intent the old code expressed and did not
166
+ achieve. `mergeHeaders` now returns a `Headers` rather than a record, because handing back a
167
+ record hands back a structure in which `Content-Type` and `content-type` are two different
168
+ things — the shape the defect grew in.
169
+
170
+ Three `eslint-disable security/detect-object-injection` comments and one Stryker disable went
171
+ with it: a `Headers` has no prototype to pollute, so the guard is no longer working against the
172
+ type it is written on. The unsafe-name drop is kept as observable behaviour, and now also
173
+ covers the factory defaults, which the previous spread never guarded.
174
+
175
+ **The class, for anyone auditing the rest of the client surface:** case-insensitive header
176
+ semantics implemented with case-sensitive object keys. Anywhere this library keys a header by
177
+ string, the same latent duplicate exists.
178
+
179
+ The regression test asserts what the wire carries rather than what the record contains, and the
180
+ distinction is the whole reason this survived: the previous tests read ONE case-sensitive key
181
+ off the raw record, which held the default's value, while the caller's lowercase twin sat beside
182
+ it unread. Nothing ever asserted against the joined value, so nothing failed. A mock server does
183
+ not help either — it accepts the duplicate without complaint, because the request is well-formed
184
+ and wrong.
185
+
186
+ ### Added
187
+
188
+ - **`AuthService.isAccountLockedOut()` and `getAccountLockoutSeconds()` — read the lockout, not
189
+ just clear it.** (#157)
190
+
191
+ `unlockAccount` was already public, so a host could **clear** a dashboard lockout. There was no
192
+ public way to **read** one, so a console could offer an Unlock button and could not tell anyone
193
+ whether it had anything to do. The write side was exposed and the read side was not.
194
+
195
+ The primitives existed — `BruteForceService.isLockedOut` and `getRemainingLockoutSeconds` are
196
+ both public — but the identifier was out of reach. It is an HMAC of
197
+ `dashboard:{tenantId}:{email}` under the library's own derived `hmacKey`, which a consumer does
198
+ not have, and reproducing that preimage is exactly what keeping the derivation in one place
199
+ prevents: a third copy in a consumer repository is a third chance to drift, and a drifted key
200
+ reads a record that never exists. That reports **"not locked out" for every account, including
201
+ locked ones** — a false negative on a security indicator, delivered confidently and silently.
202
+
203
+ The second method matters more than it looks. A bare flag with no horizon is the interface that
204
+ invites the support call the indicator was meant to prevent: it can say an account is locked and
205
+ cannot say for how long, so the only honest advice left is "try again later".
206
+
207
+ **Cheap enough for every row of a directory listing — issue them concurrently.** The reporter
208
+ measured twenty of these against a local Redis over ioredis: `0.39 ms` issued concurrently
209
+ against `0.33 ms` for a single one, and `6.25 ms` awaited one at a time in a loop. Concurrency is
210
+ what buys that, by overlapping the round trips; use `Promise.all` and not `await` inside a loop.
211
+
212
+ Those numbers are one environment's, not a guarantee this library makes. Each call is its own
213
+ Redis command, the ioredis client is the host's, and whether the commands are also **batched**
214
+ into a single write depends on `enableAutoPipelining`, which ioredis leaves off by default.
215
+
216
+ `getAccountLockoutSeconds` reads the threshold before the TTL. The underlying counter is created
217
+ on the FIRST failed attempt, so its raw TTL is positive long before the lockout exists —
218
+ returned unchecked it would show "locked for 14 minutes" beside an account whose next attempt
219
+ would succeed, with the two reads contradicting each other on the same account.
220
+
221
+ Argument order mirrors `unlockAccount(email, tenantId)` so the three read as a set, and a test
222
+ asserts all three address the SAME record rather than pinning three copies of the preimage.
223
+
224
+ - **`authDocumentSecurity()` — the document-level default, derived instead of copied.** An OpenAPI
225
+ contributor carries operations and components, never the document root, so the top-level
226
+ `security` that covers a consumer's OWN routes stays theirs to set. But the scheme it has to
227
+ name, and whether that scheme exists at all, are decided by THIS library's configuration. The
228
+ consumer was left writing a name they do not control.
229
+
230
+ Exporting `AUTH_SECURITY_SCHEMES` narrowed that and did not close it: a correct spelling read
231
+ off a constant still leaves "which of the four applies to my deployment" unanswered, and the
232
+ answer takes the guard family and `tokenDelivery` together. Every consumer setting a default was
233
+ re-deriving it by reading this package's source.
234
+
235
+ ```ts
236
+ import { authDocumentSecurity } from '@bymax-one/nest-auth'
237
+
238
+ security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
239
+ ```
240
+
241
+ **Pass the option exactly as you wrote it, `undefined` included.** `tokenDelivery` is optional
242
+ on the module, so a deployment relying on the documented `'cookie'` default has nothing to
243
+ forward — and requiring a narrowed value here would have forced `options.tokenDelivery ?? 'cookie'`
244
+ at the call site, putting a library decision back into consumer code one line further out.
245
+ Omission resolves through the same constant the module resolves it with.
246
+
247
+ It also settles the part a hand-written default usually gets wrong. Under `tokenDelivery: 'both'`
248
+ the result is a two-entry **list** — OpenAPI reads that as OR, either transport satisfies it.
249
+ Merged into one entry with two schemes it would mean AND, describing a server that demands the
250
+ same credential twice.
251
+
252
+ **Reported from a live failure, not from review.** A consumer whose `tokenDelivery` is a
253
+ validated environment enum kept a hard-coded cookie scheme in their document default. Setting
254
+ that variable to `bearer` stopped the process from booting: no cookie scheme is declared in that
255
+ mode, and `assertSchemesDeclared` refuses a default naming one rather than serving a dangling
256
+ reference. Reachable by configuration alone, with no code change and no warning.
257
+
258
+ What it does **not** answer is what you mounted — the dashboard schemes are declared only where
259
+ a dashboard controller is registered, and an OAuth-only or platform-only deployment declares
260
+ neither. That row of the README's table is still yours, and the JSDoc says so rather than
261
+ implying the call is sufficient.
262
+
263
+ A conformance test now asserts that every scheme this function names is one the contributor
264
+ declares for the same delivery mode. The two derive independently — the requirement from the
265
+ guard family and the mode, the definitions from the resolved options and the registration — so
266
+ nothing but that assertion makes them agree.
267
+
268
+ ### Fixed
269
+
270
+ - **The sink's own documentation routed consumers into the wiring that drops
271
+ `containsCredential`.** `AuthEmailSink` said `@bymax-one/nest-notification`'s
272
+ `EmailService.send` "satisfies it structurally". True of the shape and false of the semantics:
273
+ passed in directly, as that sentence invites, `containsCredential: true` lands in a property
274
+ that library does not read, while its own switch — `publishProviderText` — stays at its
275
+ default. A relay answering `550` with the offending body quoted then puts a reset code in an
276
+ audit record, from a `send` call that looked correctly wired.
277
+
278
+ The JSDoc now states that structural fit is not enough, that an implementation owes a
279
+ **translation** of the flag into whatever its channel calls the same thing, and it names that
280
+ library as both the worked example and the trap, with the adapter to copy. Nothing about the
281
+ types changed; the field was always emitted. What changed is that the documentation stops
282
+ pointing at the one configuration where it is ignored.
283
+
284
+ Raised by the `nest-notification` seat, which is taking the symmetric half on its side. Emitting
285
+ `publishProviderText` from here was considered and rejected: it would put another contract's
286
+ vocabulary into this package's published surface, and that field has a rename open upstream.
287
+
288
+ - **The reuse-detection hook reported a compromise and no way to act on it.**
289
+ `onRefreshTokenReuseDetected` fires on the strongest evidence this library produces — a refresh
290
+ token presented after it was already exchanged, so one of its two holders is not the owner — and
291
+ it received a context whose `ip` and `userAgent` were **empty strings**. `HookContext` declares
292
+ both as required `string`, so the type promised a value the path did not deliver.
293
+
294
+ The values were never unavailable: `reissueTokens(oldRefresh, ip, userAgent)` and its platform
295
+ twin have both in scope as their own parameters, and the emit built
296
+ `createEmptyHookContext()` anyway. `userId` says whose account the family belongs to; `ip` and
297
+ `userAgent` are the only description of **who presented** the token. A report carrying the first
298
+ and not the second names a victim and says nothing about the party holding a credential that
299
+ should not exist.
300
+
301
+ Both planes now carry them. `sanitizedHeaders` stays `{}` deliberately — the rotation path
302
+ receives the address and the agent, never the header map, so there is nothing to sanitize and an
303
+ invented value would be worse than an empty object a consumer can see is empty.
304
+
305
+ Found by a consumer wiring the hook into a real backend and reading the emitted record, not by a
306
+ test: the two specs covering this hook asserted the context as `expect.anything()`, which cannot
307
+ distinguish a populated context from an empty one. Both now pin it exactly.
308
+
309
+ ### Added
310
+
311
+ - **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, and `AUTH_ERROR_STATUS` now
312
+ also from `./shared`. Two different defects, worth keeping apart: `AUTH_SECURITY_SCHEMES` was
313
+ declared and never re-exported, so there was nowhere to import it from at all;
314
+ `AUTH_ERROR_STATUS` shipped from the server entry and only from there, so reaching it meant
315
+ pulling the NestJS peer dependencies — which the three cases the README points at (a typed
316
+ client, an API document, a browser test) are precisely the ones that must not.
317
+
318
+ The scheme names are stable identifiers — renaming one is a break a generated client feels —
319
+ while their DEFINITIONS are derived from configuration, which is why the names are worth
320
+ exporting and the definitions are not. A platform-only deployment guarding its own routes with
321
+ `JwtAuthGuard` has to declare the dashboard access scheme itself, because `schemesFor` gates
322
+ dashboard schemes on `dashboardMounted`; before this it was told to write
323
+ `bymaxAuthAccessCookie` by hand, with nothing checking the spelling, in a section whose whole
324
+ subject is that literals drift from configuration.
325
+
326
+ The 1.4.3 entry and the README both said the constant was not public and to use string
327
+ literals. **That advice is now wrong**; the 1.4.3 section is left as written, because it was
328
+ true when it shipped, and this entry is the correction. The README paragraph is rewritten.
329
+
330
+ ### Security
331
+
332
+ - **The tenant-scoped user port did not bind, and a stale implementation destroyed the password
333
+ hash.** `IUserRepository`'s ten account-naming methods took the tenant as a positional
334
+ `string`. TypeScript accepts an implementation with FEWER parameters, so a consumer who
335
+ upgraded and did not touch their repository still type-checked — proven, not argued:
336
+
337
+ ```
338
+ $ tsc --noEmit --strict # a pre-upgrade implementation against the shipped port
339
+ exit code: 0
340
+ ```
341
+
342
+ Two consequences. Their `findById(id)` ignored the tenant, so the cross-tenant read the entry
343
+ below closes stayed open on a clean build, with no error and no warning. And the library calls
344
+ `updatePassword(userId, tenantId, hash)`: a stale two-parameter implementation bound
345
+ `passwordHash = tenantId` and wrote the tenant id into the credential column.
346
+
347
+ **Every one of those methods now takes a single object.** An object parameter is structurally
348
+ incompatible with the old positional shape, so the same implementation fails to compile instead
349
+ of failing in production. `TenantScopedUserRef` and the eight params types are exported from the
350
+ package entry, because a consumer implements this port and needs to name what it receives.
351
+
352
+ **Apply to a derived backend.** Every `IUserRepository` method that names an account takes ONE
353
+ object now — `findById`, `findByEmail`, `updatePassword`, `updateMfa`, `updateLastLogin`,
354
+ `updateStatus`, `updateEmailVerified`, `updateEmail`, `findByOAuthId` and `linkOAuth`. Destructure
355
+ it and keep filtering on the tenant. **Eight of the ten are keyed by `id`.** Seven of those are
356
+ writes: on Prisma they are still `updateMany({ where: { id, tenantId } })` rather than
357
+ `update({ where: { id } })`, because `update` takes a unique clause and cannot carry the pair.
358
+ The eighth, `findById`, is a **read** — it filters on the same pair through `findFirst`, because
359
+ `findUnique` by id alone can answer with another tenant's row. **The other two are not keyed by
360
+ `id` at all:** `findByEmail` receives `{ email, tenantId }` and `findByOAuthId` receives
361
+ `{ provider, providerId, tenantId }`, and each filters on its own lookup key plus the tenant.
362
+
363
+ ```ts
364
+ // before → after, for every signature that changed
365
+ findById(id, tenantId)
366
+ findById({ id, tenantId })
367
+
368
+ findByEmail(email, tenantId)
369
+ findByEmail({ email, tenantId })
370
+
371
+ updatePassword(id, tenantId, passwordHash)
372
+ updatePassword({ id, tenantId, passwordHash })
373
+
374
+ updateMfa(id, tenantId, data)
375
+ updateMfa({ id, tenantId, data })
376
+
377
+ updateLastLogin(id, tenantId)
378
+ updateLastLogin({ id, tenantId })
379
+
380
+ updateStatus(id, tenantId, status)
381
+ updateStatus({ id, tenantId, status })
382
+
383
+ updateEmailVerified(id, tenantId, verified)
384
+ updateEmailVerified({ id, tenantId, verified })
385
+
386
+ updateEmail(id, tenantId, email)
387
+ updateEmail({ id, tenantId, email })
388
+
389
+ findByOAuthId(provider, providerId, tenantId)
390
+ findByOAuthId({ provider, providerId, tenantId })
391
+
392
+ linkOAuth(userId, tenantId, provider, providerId)
393
+ linkOAuth({ id, tenantId, provider, providerId })
394
+ ```
395
+
396
+ **This supersedes the note in the tenant-scoping entry below**, which told you to take `tenantId`
397
+ as the _second argument_. Follow that note today and the implementation does not compile:
398
+ `findById(id: string, tenantId: string)` is rejected against `findById(params: TenantScopedUserRef)`
399
+ with `TS2416 — Target signature provides too few arguments`. That loud failure is the entire point
400
+ of the shape.
401
+
402
+ What still passes silently is narrower, and worth stating exactly rather than overstating:
403
+ TypeScript accepts an implementation declaring FEWER parameters than the signature, so one taking
404
+ no parameters at all compiles — and so does one that takes the object and never reads `tenantId`
405
+ off it. The compiler rules out a value bound into the wrong slot. It cannot rule out a body that
406
+ ignores the tenant, which is why every method documents the scoping as a MUST.
407
+
408
+ The `AuthService` guidance in that note is unaffected:
409
+ `getMe(userId, tenantId)` and `issueTokensForUserId(userId, tenantId, ip, userAgent)` are
410
+ unchanged. The README's example implementation shows the whole shape.
411
+
412
+ ```ts
413
+ // before
414
+ await repo.updatePassword(userId, tenantId, hash)
415
+ // after
416
+ await repo.updatePassword({ id: userId, tenantId, passwordHash: hash })
417
+ ```
418
+
419
+ The property is pinned by a type test that compiles a stale implementation against the real port
420
+ and requires `tsc` to refuse it, with a positive twin that compiles the current shape — a
421
+ negative test that cannot pass for the wrong reason. Nothing else in the suite can see this:
422
+ every other check reads the declaration, and a positional signature reads as correct in all of
423
+ them. One residual hole is stated rather than hidden: TypeScript always accepts an
424
+ implementation taking NO parameters, which cannot put a value in the wrong slot.
425
+
426
+ - **Two re-authentication counters were tenant-blind.** `changePassword` and `requestChange`
427
+ scoped their account read and then derived the brute-force identifier from
428
+ `reauth:{flow}:{userId}` — the bare id. A repository id is unique only within a tenant, so
429
+ failures against `t1/u1` spent `t2/u1`'s budget and locked that account out of changing its own
430
+ password or address without any credential, and a success on either side cleared the other's
431
+ count. Both now derive from the injective `userSubject`, and the tests assert the separation
432
+ rather than pinning a digest — a pinned hex string is satisfied by any preimage that produces
433
+ it, so updating the constant after a preimage change keeps the test green with its rule gone.
434
+
435
+ - **Two tenants could share one session index, one token epoch and one recovery-code claim.**
436
+ The subject every user-derived key is HMACed over was `dashboard:{tenantId}:{userId}`, and a
437
+ bare `:` between two free-form components is not injective. Both halves may legitimately
438
+ contain it — the DTO charset deliberately admits a tenant id like `acme.eu-west-1:prod`, and a
439
+ composite `tenant:user` subject is a documented `sub` shape — so:
440
+
441
+ ```
442
+ tenantId 'acme:prod' + userId 'u1' -> dashboard:acme:prod:u1
443
+ tenantId 'acme' + userId 'prod:u1' -> dashboard:acme:prod:u1 <- same preimage, same HMAC
444
+ ```
445
+
446
+ Two unrelated tenants then shared every key derived from it: the session index, the token
447
+ epoch, the five MFA store keys, the three MFA failure counters, the recent-authentication
448
+ marker and — worst — `rcu:`, the claim that stops a recovery code being spent twice. Revoking
449
+ one tenant's sessions swept the other's, and one tenant could spend the other's recovery code.
450
+ That is precisely the cross-tenant revocation the entry below removes, reintroduced through the
451
+ delimiter.
452
+
453
+ **Whether a given deployment could reach that collision depends on its user ids, and the two
454
+ halves are not equally exposed.** The `tenantId` half is attacker-chosen by default: it arrives
455
+ in the request body, validated only for length and control characters, and a deployment only
456
+ takes that away by configuring `tenantIdResolver`. The `userId` half comes from
457
+ `IUserRepository`, and the **scheme** is the host's — but the resulting value is not
458
+ automatically outside the caller's reach, because `CreateUserData` carries `email` and `name`
459
+ straight from the registration request. `name` in particular is validated for length and
460
+ nothing else: no charset constraint, so `:` passes. A host that derives its id from either
461
+ field has handed the caller influence over both halves.
462
+
463
+ The arithmetic makes the user id the gate. For `{t1}:{u1}` and `{t2}:{u2}` to render the same
464
+ string with `(t1,u1) ≠ (t2,u2)`, one of the two **user ids** must itself contain a `:` — there
465
+ is no way to move the boundary otherwise. Three tiers follow, and they are not the same risk:
466
+
467
+ - **Host-generated ids with no colon** (UUID, a sequence): unreachable. The preimage is
468
+ ambiguous in principle and no input can exercise it.
469
+ - **Composite host-assigned ids** (`dept:1234`, a stored `tenant:user` subject): reachable by
470
+ accident. Two unrelated accounts can collide with nobody trying.
471
+ - **Ids derived from caller-supplied input in a way that PRESERVES the delimiter** (the display
472
+ name stored verbatim; a `{name}:{n}` disambiguator): reachable **on purpose**. The attacker
473
+ picks the tenant, then picks a value that splits the preimage where they want, and both
474
+ halves are theirs. `name` is the field that carries this: `@IsString`, `@MinLength(2)`,
475
+ `@MaxLength(128)` and **no charset rule**, so a `:` passes.
476
+
477
+ The address is the instructive near-miss. `@IsEmail` does accept a colon —
478
+ `"ana:silva"@x.com` is a valid addr-spec with a quoted local part, and class-validator
479
+ takes it. What saves the scheme is the second half of the condition below: splitting there
480
+ leaves `silva"@x.com`, and that is not a valid address, so no second account can hold it.
481
+ The colon is present and the suffix pair still cannot be formed.
482
+
483
+ The qualifier carries the tier, and it is a property of the **sets of values the two sides
484
+ admit**, not of one id and not of the transform that made it. A colon in the id is necessary
485
+ and not sufficient. Both halves have to cooperate:
486
+
487
+ > can the id scheme produce two valid ids `u1` and `u2` with `u1 = p + ":" + u2`, **and** is
488
+ > `t + ":" + p` still a valid tenant for some tenant `t` the caller can send?
489
+
490
+ Only then does moving the boundary turn one pair into the other. The tenant clause is not
491
+ decoration: a body-supplied tenant is non-empty, at most 128 characters and control-free, so
492
+ a scheme whose only suffix pair needs a 200-character or control-bearing `p` satisfies the
493
+ first clause and is still unreachable.
494
+
495
+ A worked pair that clears every validator this library applies:
496
+
497
+ ```
498
+ name 'ana:silva' -> id 'ana:silva' tenant 'acme' -> dashboard:acme:ana:silva
499
+ name 'silva' -> id 'silva' tenant 'acme:ana' -> dashboard:acme:ana:silva
500
+ ```
501
+
502
+ And the case that does **not** qualify despite carrying a colon: a fixed-width
503
+ `sha256:{64 hex}` id. Every id in that scheme is the same length, so none is a proper suffix
504
+ of another, and no tenant makes `t1:u1` equal `t2:u2`. Slugging to `[a-z0-9-]`, or rendering
505
+ a digest as bare hex or base64url, removes the delimiter and settles it a step earlier.
506
+
507
+ Read the value sets you can actually store — not the provenance of the input, not the
508
+ transform's reputation, and not one example id in isolation.
509
+
510
+ That third tier is the reason the previous wording mattered: it read as though the user id were
511
+ always the host's to control, which would have left this the mildest of the three. The tier is
512
+ narrow on purpose — a note that over-warns gets discounted the same way one that under-warns
513
+ gets ignored, and only one of those failures is visible to whoever wrote it.
514
+
515
+ That does not make the fix conditional. A library may not assume the shape of ids its consumers
516
+ assign — it is the same assumption `findById` taking a tenant already refuses to make — and a
517
+ preimage that is injective only for well-behaved input is not injective. But an operator
518
+ reading this entry should be able to tell which side of that line they are on, and the previous
519
+ wording did not let them.
520
+
521
+ **This predates the release.** The same preimage shipped in 1.4.3 as `mfaSubject`, backing the
522
+ MFA keyspace; renaming it to `userSubject` and extending it to `sess:`/`ep:` widened the blast
523
+ radius rather than creating it.
524
+
525
+ The dashboard arm now carries a length prefix —
526
+ `dashboard:{utf8ByteLength(tenantId)}:{tenantId}:{userId}` — which makes the split unambiguous
527
+ while rejecting no identifier, and the charset is deliberately permissive. The platform arm has
528
+ one component after the plane and is unchanged.
529
+
530
+ **The prefix counts UTF-8 bytes, not characters**, and the contract says so: JavaScript's
531
+ `String.length` counts UTF-16 code units while Rust's `str::len()` counts bytes, so `açaí` is 4
532
+ by one measure and 6 by the other. A character count would agree for ASCII and derive different
533
+ keys on the first accented tenant id — a split between the paired libraries that shows up only
534
+ in production, in one locale.
535
+
536
+ **Apply to a derived backend.** The MFA keyspace relocates too, on top of the session and epoch
537
+ migration described below, under the same first rule — copy state forward, never drop it — but
538
+ **not** under the same fan-out. Those keys already carried the tenant, so the remap is 1:1 for
539
+ every pair, with one exception that is the entire point of this entry: a pair that was
540
+ **colliding** shared one old key, and that key has to be written to each of the pairs that shared
541
+ it. There is no way to tell from the old key which of them last wrote it, so copy it to all of
542
+ them and let the safe direction win — for `rcu:`, a claim present on a code that was never spent
543
+ costs one unusable recovery code, while a claim missing on a code that WAS spent makes it usable
544
+ again. The MFA keys are where dropping is least acceptable for exactly that reason.
545
+
546
+ - **Suspending one tenant's user revoked another tenant's.** The session index and the token
547
+ epoch were keyed on the bare user id — `sess:{userId}` and `ep:{userId}` — while the status
548
+ cache beside them had been tenant-scoped for releases. `IUserRepository.findById` takes a
549
+ `tenantId` precisely because ids may not be unique across tenants, so on a deployment that
550
+ numbers users per tenant, deleting or suspending `t1/u1` swept the sessions and bumped the
551
+ token epoch of `t2/u1`. A **credential-free cross-tenant revocation**, reachable by anyone who
552
+ can get an account suspended in their own tenant.
553
+
554
+ Both keys now derive the way every other account-naming key in this library already did:
555
+ `{prefix}:{hmac_sha256(hmacKey, userSubject)}`. The **derivation** was not invented here — it is
556
+ what the five MFA store keys, the three MFA failure counters and the recent-authentication
557
+ marker have used since they were fixed for the same reason, and the wire contract already
558
+ carried its argument. The two joining it close the gap between what `recentAuthKey`'s own
559
+ documentation claimed — _"keyed by HMAC rather than the raw id, like every other user-derived
560
+ key in this library"_ — and what was true.
561
+
562
+ The **subject** those keys are derived from does change in this release, and the entry above is
563
+ why: it is now `dashboard:{utf8ByteLength(tenantId)}:{tenantId}:{userId}` on the dashboard plane
564
+ and `platform:{userId}` on the platform one. The form it inherited from the MFA keyspace —
565
+ `dashboard:{tenantId}:{userId}`, without the length prefix — is the one that was not injective.
566
+
567
+ The HMAC is the second half and it matters on its own: rust-auth reads this keyspace, so a
568
+ bare id there was an account identifier in the clear to anyone with store access. A user id
569
+ carries too little entropy for a plain digest to hide, which is why the identifier preimages
570
+ are HMACed rather than merely hashed.
571
+
572
+ The platform plane keeps no tenant segment. Its admins are cross-tenant and have none, exactly
573
+ as `userSubject`'s platform arm has always said.
574
+
575
+ **Apply to a derived backend.** The five `SessionService` methods —
576
+ `createSession`, `listSessions`, `revokeSession`, `revokeOtherSession`,
577
+ `revokeAllExceptCurrent` — now take a **single object** instead of positional arguments:
578
+
579
+ ```ts
580
+ // before
581
+ await sessions.listSessions(user.sub, currentHash)
582
+ // after
583
+ await sessions.listSessions({ userId: user.sub, tenantId: user.tenantId, currentSessionHash })
584
+ ```
585
+
586
+ The object is the point, not a style preference. Threading the tenant through positionally put
587
+ a second `string` beside `userId`, and the old two-argument call **still compiled** against the
588
+ new signature — binding the session hash to `tenantId` and returning an empty listing that is
589
+ indistinguishable from "this user has no sessions". On `revokeSession` the same transposition
590
+ is a revocation that silently reaches nothing. A named field cannot be transposed; the worst it
591
+ can be is misspelled, which the compiler catches. `CreateSessionParams`, `ListSessionsParams`,
592
+ `RevokeSessionParams` and `RevokeAllExceptCurrentParams` are exported from the package entry so
593
+ a caller can name the shape.
594
+
595
+ `AuthService.revokeAllSessions` takes the same treatment and for the same reason — two
596
+ unconstrained strings side by side, where `revokeAllSessions(user.tenantId, user.id)` compiled,
597
+ derived an unrelated subject and returned normally:
598
+
599
+ ```ts
600
+ await auth.revokeAllSessions({ userId: user.sub, tenantId: user.tenantId })
601
+ ```
602
+
603
+ Also taking the tenant they always needed: the three
604
+ `AuthRedisService` entry points (`invalidateUserSessions`, `getUserTokenEpoch`,
605
+ `bumpUserTokenEpoch`), whose `kind` argument also **loses its default** — a positional tenant
606
+ next to a positional plane is a transposition nobody notices, and the two call sites that
607
+ passed `'platform'` in what became the tenant slot compiled silently until the default was
608
+ gone. If you call any of these, pass `user.tenantId`; on the platform plane pass `undefined`
609
+ and name the plane.
610
+
611
+ `readSessionOwner` now answers `{ userId, tenantId }`. Logout takes both off the record the
612
+ refresh token just proved possession of, rather than from a caller who could aim the
613
+ revocation at a colliding id. A record written before this carries no tenant: the index revoke
614
+ is skipped rather than guessed, and the session still dies because `rt:{hash}` is deleted
615
+ either way.
616
+
617
+ **This is a paired wire change and it has no compatibility path.** `sess` and `ep` are pinned
618
+ in `conformance/wire-contract.json` and byte-shared with `@bymax-one/rust-auth`; a backend on
619
+ the old shape writes `sess:{userId}` while one on the new shape reads `sess:{hmac}`, so
620
+ sessions survive a revoke-all that never saw them. **Both libraries must ship this in the same
621
+ release.**
622
+
623
+ **Three paths now fail closed on a dashboard subject with no tenant**, because an absent
624
+ tenant interpolates as the literal text `undefined`, so `userSubject` builds
625
+ `dashboard:9:undefined:{userId}` — a keyspace belonging to no tenant, in which nothing has ever
626
+ been written. The MFA flows already refused a blank tenant for exactly this reason; these three did
627
+ not.
628
+
629
+ - `AuthRevocationService.isAccessTokenRevoked` **failed open**: it read the epoch under
630
+ `dashboard:9:undefined:{sub}`, got `0`, and reported a bulk-revoked token as valid. It is
631
+ exported for callers that never pass a guard — a realtime bridge checking a socket — and its
632
+ payload type marks `tenantId` optional, so the omission is a shape a caller can produce. A
633
+ dashboard payload without a tenant is now treated as **revoked**, without touching the store.
634
+ - `reissueTokens` accepted a **pre-upgrade record**: `parseSession` validates `userId`, `role`
635
+ and `mfaEnabled` but never `tenantId`, so a session written before this change rotated into
636
+ `dashboard:9:undefined:{userId}` and minted an access token with no tenant claim — one every
637
+ dashboard guard then refuses. The caller held a session that could be neither used nor
638
+ revoked. Both the primary and the grace-recovery path now refuse it as
639
+ `REFRESH_TOKEN_INVALID`; the platform plane is exempt, its subject carries no tenant segment.
640
+ - `revokeFamily` derived an index for such a record and pruned a key nobody writes while the
641
+ real index kept every member. It now omits the index, exactly as logout already did.
642
+
643
+ **Deploy this as a cutover, not a rolling upgrade.** Drain the pods on the old release before
644
+ the new ones serve. The MFA keyspace is where this bites hardest: `mutate`'s transition lock,
645
+ which serializes the read-modify-write on the recovery-code list, is keyed by the same subject
646
+ as everything else — so two pods that disagree about the subject take **different locks and do
647
+ not exclude each other at all**, and the `rcu:` claim that stops a code being spent twice splits
648
+ the same way. The library carries a fallback for the _pre-tenant_ preimage but deliberately none
649
+ for the tenant-scoped one this release replaces: a fallback is compatibility weight for a
650
+ deployment shape the cutover removes the need for.
651
+
652
+ **A live keyspace must be migrated, not dropped.** Deleting the old keys is unsafe in both
653
+ directions, and each direction is a hole rather than an inconvenience.
654
+
655
+ **On the dashboard plane the migration is a fan-out: one old key becomes N new ones.** The old
656
+ keys are tenant-blind — `ep:{userId}` and `sess:{userId}` name a bare user id — which is the
657
+ defect this release removes, so a single old key served **every** tenant that has a user with
658
+ that id, and each of those pairs derives its own key now. Copying an old key to one derived key
659
+ and dropping it migrates one tenant and silently resets all the others: for them it is not a
660
+ partial migration, it is exactly the deletion described below. Enumerate the tenants that user
661
+ id appears in and write every one of them. On the platform plane the mapping is 1:1 — that
662
+ subject carries no tenant — so the fan-out is a dashboard-only obligation.
663
+
664
+ Deleting an old `ep:{userId}` does not expire the tokens it revoked. `getUserTokenEpoch` answers
665
+ `0` for an absent key — `Number(null)` is `0`, and that is deliberately the "never bumped"
666
+ default — and under `0` the `stamped < epoch` test is false for **every** token. A password
667
+ reset, an MFA reset or a sign-out-everywhere that had already invalidated an access token is
668
+ undone by the migration, and that token works again for the rest of its lifetime. Epochs must be
669
+ **copied to every derived key the old one served**, each with at least the old value and at
670
+ least the remainder of its TTL, and only then dropped. An epoch may never move backwards.
671
+
672
+ Deleting an old `sess:{userId}` does not end the sessions it listed. Its `rt:`/`rp:` members
673
+ outlive the index and become unreachable: a later revoke-all reads the new, empty index, finds
674
+ nothing to delete, and reports success while those refresh tokens keep rotating. Either re-add
675
+ the members under the derived index keys, or delete the member keys and their `sd:` details
676
+ **before** dropping the index. The second costs a forced re-login and is the safer of the two;
677
+ the first preserves sessions and must be done atomically per user.
678
+
679
+ Re-adding is where the fan-out bites hardest, because the old index **mixes tenants**: its
680
+ members are the sessions of every tenant's user with that id, so emptying it into one derived
681
+ index would hand that tenant another's live sessions — worse than the collision being fixed,
682
+ because it turns a shared keyspace into a listable, revocable cross-tenant handle. Partition
683
+ instead: every member names an `rt:`/`rp:` record carrying its **own** `tenantId`, so read the
684
+ record, derive that pair's index, and place the member there. A member whose record is already
685
+ gone is a dead session and is dropped rather than guessed at.
686
+
687
+ **Both obligations apply to the PLATFORM twins, `pep:{userId}` and `psess:{userId}`, which this
688
+ release relocates identically.** They are the easier pair to forget and the worse pair to get
689
+ wrong: a platform epoch left behind revalidates previously revoked **admin** JWTs, and a
690
+ platform index left behind hides an admin's live refresh sessions from revoke-all. The platform
691
+ subject carries no tenant segment — `platform:{userId}` — but the HMAC relocates the key just as
692
+ it does on the dashboard plane, so "we have no tenants" is not a reason to skip either step.
693
+
694
+ - **The dashboard user port let every account read and write skip the tenant.** The sibling half
695
+ of the entry above, on the layer the keyspace fix cannot reach. `IUserRepository` documented the
696
+ rule — _"ids may not be unique across tenants"_ — and then declined to enforce it, in three
697
+ shapes that hid one another because they sat on adjacent lines:
698
+
699
+ - `findById(id, tenantId?)` took the tenant as **optional**, for _"internal admin flows where
700
+ cross-tenant access is intentional"_. All twelve of this library's own call sites omitted it,
701
+ and not one was such a flow: `getMe`, `changePassword`, the email-change request and confirm,
702
+ the three invitation authority checks, the OAuth re-fetch, the session-limit resolver, the
703
+ WebSocket ticket snapshot and the password-reset fingerprint all read the account by bare id.
704
+ On a host that numbers users per tenant, each of those could resolve **another tenant's row**
705
+ — and then decide status, role, MFA state or a password change against it.
706
+ - Six mutators — `updatePassword`, `updateLastLogin`, `updateStatus`, `updateEmailVerified`,
707
+ `updateEmail`, `linkOAuth` — took **no tenant at all**, under JSDoc telling implementations
708
+ they MUST scope the write. An obligation the signature does not permit fulfilling is not a
709
+ contract; the implementation has nothing to scope by.
710
+ - `updateMfa` typed its tenant `string | undefined` beneath a sentence promising it was _"never
711
+ omitted for a dashboard account"_.
712
+
713
+ Every method now requires `tenantId: string`, positioned immediately after the account id, and
714
+ the library passes it everywhere. `MfaService` gained `assertDashboardTenant`, an assertion
715
+ signature splitting the dashboard half out of the existing `assertPlaneTenant` so the guard the
716
+ entry points already ran narrows the type instead of only throwing.
717
+
718
+ **The rule is now a test, not a paragraph.** `test/e2e/tenant-scoped-port.e2e-spec.ts` reads the
719
+ port's TypeScript AST and fails when a method can name an account without a tenant, when the
720
+ tenant is typed anything but `string`, when it does not follow the id, or when
721
+ `IPlatformUserRepository` — whose admins belong to no tenant — grows one. It also compares the
722
+ README's example `PrismaUserRepository` signature-for-signature against the port: that example
723
+ is what a consumer pastes in, and it had drifted to `update({ where: { id } })` on six mutators,
724
+ a query that crosses tenants by construction. Prose does not close by grep.
725
+
726
+ **Apply to a derived backend.** **Superseded — see the object-parameter entry above.** The
727
+ positional shape described here no longer compiles against the port: written as this note
728
+ describes it, the implementation is rejected with `TS2416`. Kept as written because this entry
729
+ describes the release it shipped in; the note above is the one to follow.
730
+
731
+ Your `IUserRepository` implementation must take `tenantId` as
732
+ the second argument of `findById`, `updatePassword`, `updateMfa`, `updateLastLogin`,
733
+ `updateStatus`, `updateEmailVerified`, `updateEmail` and `linkOAuth`, and must filter on it. On
734
+ Prisma that means `updateMany({ where: { id, tenantId } })` rather than
735
+ `update({ where: { id } })` — `update` takes a unique clause and so cannot carry the pair. Two
736
+ service methods take the tenant too: `AuthService.getMe(userId, tenantId)` and
737
+ `AuthService.issueTokensForUserId(userId, tenantId, ip, userAgent)`; pass `user.tenantId` from
738
+ the verified claims. The README's example implementation shows the whole shape.
739
+
740
+ ### Fixed
741
+
742
+ - **The compromise line left `userId` empty on repeat attack traffic.** `revokeFamily` resolves
743
+ the owner by reading the first LIVE member of the token family. On the second and later replay
744
+ of an already-revoked family there is none — the consumed marker outlives the sessions it points
745
+ at, so reuse is detected again while every record that could name the owner is gone — and the
746
+ line read `userId= familyId=…`.
747
+
748
+ That is an empty field on what this library's own documentation calls the strongest evidence of
749
+ compromise it produces, and `userId` is the only field an on-call can act on. It emptied
750
+ precisely on **repeat** attack traffic, which is the traffic worth reading.
751
+
752
+ The line now says what is unknown and what was measured:
753
+ `userId=<unknown: no live session remains in this family to name it>`. An empty field reads as a
754
+ defect in the logger and makes a reader distrust the tool instead of the event; a family with no
755
+ readable member is itself the fact worth seeing. The `familyId` is still named, because it is
756
+ the only handle left on the lineage.
757
+
758
+ It names the observation and not a cause on purpose. `readFamilyOwner` answers with nothing for
759
+ three different reasons — every member record gone, a member whose JSON will not parse, a member
760
+ carrying no `userId` — and only the first is the already-revoked case, which even then cannot be
761
+ told apart from ordinary TTL expiry. A line asserting "already revoked" would send an on-call
762
+ looking for a revocation during what may be store corruption.
763
+
764
+ Reported by the `@bymax-one/bymax-one` seat from a measured audit against real Postgres and
765
+ Redis — two runs of the same path, one populated and one not. The cause was traced rather than
766
+ guessed, and it also explains their second observation: a `revoked` line with no `detected` line
767
+ before it is the same repeat replay.
768
+
769
+ - **The README's own contract test could not fail for a name mentioned anywhere in a barrel.**
770
+ It searched the barrel's SOURCE TEXT for the identifier, so a name in a comment, a JSDoc
771
+ paragraph or an internal import satisfied it without being exported. `src/client/index.ts`
772
+ carries the sharpest instance — a comment reading _"Constants like `AUTH_ERROR_CODES` and
773
+ `AUTH_ROUTES` stay [in shared]"_ — so a README documenting either import FROM `/client` passed
774
+ on the strength of the very sentence saying it does not export them. Measured: across the five
775
+ barrels, 77 capitalised tokens appear in text without being exports.
776
+
777
+ It now reads the barrel's export DECLARATIONS from the TypeScript AST, and four arms joined it:
778
+ no barrel may `export *` (which would name nothing and make the check under-report); the README
779
+ may not call a symbol non-public that a barrel exports (the contradiction this release ships the
780
+ fix for); the documented subpaths are checked against **`package.json#exports`** rather than the
781
+ suite's own hand-kept map, which agreed with the manifest only for as long as somebody kept both
782
+ in step; and every published subpath must have a source barrel mapped, because an unmapped one
783
+ was skipped silently by the arms above.
784
+
785
+ The scheme-table check had the same defect in a second form: it searched the **whole README** for
786
+ each scheme name, so deleting the `controllers.platform` row still passed — the name appears
787
+ three more times below the table. That table had already lost a row twice, under a check that
788
+ was running the whole time. Completeness is now asked of the table alone; invention is still
789
+ asked of the whole document, because a name the prose made up is wrong wherever it sits.
790
+
791
+ And the claim that `AUTH_ERROR_STATUS` ships from `/shared` was prose, which this suite does not
792
+ read — removing the export left it green. It is shown as an import now, which the suite does
793
+ read.
794
+
795
+ - **A rate-limited refresh signed the user out of a session that was still valid.**
796
+ `createAuthFetch`'s refresh reduced the response to `response.ok`, so `429`, `401`, `503` and a
797
+ `404` from a mistyped `routePrefix` arrived at the caller as one indistinguishable `false` — and
798
+ the caller treats `false` as expiry. Measured by a consumer against a real browser round; twelve
799
+ browser specs passed on both runs that produced the finding, so no green suite covered it.
800
+
801
+ `performRefresh` now returns a `RefreshOutcome`: `{ ok: true }`, or `{ ok: false, reason, status }`
802
+ where `reason` is `'rejected'` (a 401, **or a 403 whose error code names a terminal account
803
+ state** — the server looked at the credential and refused it, so `rejected.status` is `401` or
804
+ `403`), `'unavailable'` (it answered, but not with a session) or `'unreachable'` (no answer at
805
+ all).
806
+ **`onSessionExpired` now fires only on `'rejected'`.**
807
+
808
+ 403 is decided by the error **code**, because the route answers it for two unrelated reasons.
809
+ `TrustedOriginGuard` covers `/refresh` and answers `auth.untrusted_origin` with 403 — reading
810
+ that as expiry would sign out every user of a deployment whose `trustedOrigins` is wrong. But
811
+ `refresh` also revokes every session before rethrowing a blocked-account status
812
+ (`auth.account_suspended`, `auth.account_banned`, `auth.account_inactive`,
813
+ `auth.pending_approval`), and there the session really is over. The wrapper reads the code
814
+ itself, since it drains the refresh body and the caller only ever sees the original response.
815
+
816
+ A new `onRefreshFailed?: (failure: RefreshFailure) => void` reports **every** failure with its
817
+ reason and status, before the expiry decision. That is what makes the answer to _why_ usable: a
818
+ rate limit deserves "retrying", a dropped connection deserves "you appear to be offline", and
819
+ only a refused credential deserves the sign-in screen.
820
+
821
+ A `429` branch was offered and declined by the consumer who found it: _"the refresh needs to
822
+ report why it failed, not whether"_. A boolean with one carve-out reproduces the same defect for
823
+ whichever status matters next.
824
+
825
+ **Behaviour change for consumers.** Before, any refresh failure invoked `onSessionExpired`. Now a
826
+ dropped connection, a rate limit or a server fault does not — the caller still receives the
827
+ original `401`, so a failed request stays failed, but it no longer receives a claim that the
828
+ session is over. If you relied on the callback to mean "the refresh did not succeed", read the
829
+ `reason` instead: `RefreshOutcome` and `RefreshFailureReason` are exported from
830
+ `@bymax-one/nest-auth/client`.
831
+
832
+ ### Security
833
+
834
+ - **No error object reaches the logger any more.** Twenty-seven log sites passed the thrown value
835
+ as Nest's second `Logger` argument, which prints its `stack`. On every one of those paths the
836
+ thrower is code this library does not own: a hook, an OAuth plugin, the consumer's repository,
837
+ a Redis client — and in `AuthExceptionFilter`'s case, literally anything the surrounding
838
+ application threw. None of them hands the logger an error object any more, and on the twenty
839
+ sites where the caller could not name what the thrower held, **nothing the thrower authored is
840
+ published at all** — `describeChannelStatus` reports the shape of the failure (that a throw
841
+ happened, and how many links its `cause` chain has) and reads neither `message` nor `name` nor
842
+ `stack`. Where the caller CAN name the values it passed in, `describeError` still publishes the
843
+ text with those removed.
844
+
845
+ **An empty redaction list is the shape that looked safe and was not.** `describeError(err, [])`
846
+ publishes the thrower's `name` and `message` with an empty list asserting there is nothing to
847
+ remove — an assertion none of these call sites can make, because every thrower on them is
848
+ consumer code: a repository handed `findByEmail(dto.email, tenantId)`, a hook handed the IP and
849
+ user agent, a `maxSessionsResolver` handed the full `AuthUser` including the password hash, a
850
+ repository call carrying re-encrypted MFA material. A consumer error that quotes its own input
851
+ put those in the log. The empty list did not make the line safe; it removed the only defence
852
+ being attempted while reading like one. The form is now banned outright and the guard suite
853
+ enforces it.
854
+
855
+ **A partial list is the same defect with a longer sleeve.** Seven more sites named one to three
856
+ fields while the thrower had been handed a whole object: every `afterRegister`, `afterLogin`,
857
+ `afterEmailVerified`, `afterPasswordReset`, `afterInvitationAccepted` and `onNewSession` hook
858
+ receives the complete `SafeAuthUser`, so a hook throwing `new Error(user.name)` published a name
859
+ that no list mentioned. Those are opaque now too. What survives is the rule the list was always
860
+ meant to express — **name the values the thrower actually received** — which three sites can
861
+ still satisfy honestly, because they hand a repository or a hook exactly one identifier and
862
+ name exactly that.
863
+
864
+ Those three also had the list naming the wrong string: `describeError(err, [logSafe(user.id)])`
865
+ redacted the SANITISED id, and `logSafe` returns `<malformed>` for precisely the ids worth
866
+ worrying about — so the value the repository was handed was not in the list at all. They name
867
+ the value as passed now, and the guard rejects any redaction list containing a call.
868
+
869
+ **The highest-value site was not in the original report.** `OAuthService.handleCallback` wraps
870
+ `plugin.exchangeCode(code, codeVerifier)` and `plugin.fetchProfile(accessToken)`. The plugin is
871
+ consumer code that RECEIVED all three, and an HTTP client attaching its request config to the
872
+ error is the ordinary case rather than an exotic one — axios does it by default. A live access
873
+ token could reach the operator's pipeline through a rejection this library then logged in full.
874
+ The handler publishes nothing the plugin wrote. Naming the three values was the first fix and it
875
+ was the weaker half by its own reasoning: redaction is a substring match, so it holds for a token
876
+ the plugin echoed as given and not for one it re-encoded — and a token inside a base64 or
877
+ URL-encoded request body is not present as written. The test drives exactly that: the plugin
878
+ echoes the token base64url-encoded, and the line contains neither form.
879
+
880
+ The second was found by the guard rather than by reading: `AuthExceptionFilter`, whose parameter
881
+ is called `exception`, not `err`. It is the branch a re-thrown mail-channel error lands in under
882
+ `onDeliveryError: 'rethrow'` — this library's own documentation says so — so it is the most
883
+ exposed log site of the set, and a name-based sweep walked straight past it.
884
+
885
+ **What you lose:** the stack trace for a hook, plugin or repository failure. That stack belongs
886
+ to the consumer's own code, which can log it where the audience is known; a library's log line
887
+ reaches a wider one. Same argument that took the recipient address out of the delivery-failure
888
+ line. On the twenty opaque sites you also lose the message and the error's class; what remains
889
+ is that a failure happened, where, and how deep its `cause` chain ran.
890
+
891
+ `redactSecrets` was hardened in the process. It read `.length` off each element, so a single
892
+ `undefined` in the list threw a `TypeError` — out of a `catch` block, turning a failure the
893
+ caller meant to absorb into an unhandled rejection with no log line at all, which is worse than
894
+ the leak it exists to prevent. It is exported, so a consumer reaches that edge from plain
895
+ JavaScript. Found when a caller named a field the compiler believed was a `string`; the suite
896
+ did not fail an assertion, it crashed the worker.
897
+
898
+ - **A consumer-supplied identifier could forge a second record in the log.** Every value this
899
+ library interpolates into a log template now passes a guard: `logSafe` for identifiers,
900
+ `maskEmail` for addresses, `describeError` for a rejection's own text. Forty-eight
901
+ interpolations did not, across nine files.
902
+
903
+ `IUserRepository` places no character constraint on `id`, `role` or `tenantId` — `role` is a
904
+ bare `string` in the interface — so a value carrying CR/LF closes the log record and opens one
905
+ the reader attributes to this library. That is the attack `logSafe` was written for.
906
+
907
+ **The convention already existed and had been applied to `tenantId` at fourteen sites.** It was
908
+ never extended to anything else, and the omission was invisible because it sat on the SAME
909
+ LINES: `userId=${user.id} tenantId=${logSafe(tenantId)}` reads as deliberate until you ask why
910
+ one half is wrapped and the other is not.
911
+
912
+ Two sites went further and stringified a rejection straight into the line
913
+ (`logout: session cleanup failed — ${String(err)}`). `String()` strips nothing and bounds
914
+ nothing; those now go through `describeError`, which does both. The rejection is Redis's rather
915
+ than a mail channel's, so no credential is implied — but the failing key it names embeds the
916
+ consumer's user id.
917
+
918
+ A guard suite (`test/e2e/log-injection-guard.e2e-spec.ts`) now walks every `this.logger.*` call
919
+ in `src/` and fails on any interpolation that is neither guarded nor named in an explicit
920
+ allowlist of values this library authors. It fails **closed**: a new interpolation breaks the
921
+ build until somebody decides which it is. The guard call must BE the whole expression —
922
+ `${logSafe(a) || attackerValue}` is rejected, as are a concatenation, a ternary arm, and a
923
+ helper whose name merely starts with a guard's.
924
+
925
+ It reads the **TypeScript AST**, not the text. Three hand-rolled scanners preceded it and each
926
+ was fooled by ordinary punctuation: a comma inside a message read as an argument separator, a
927
+ `)` inside a template's literal text ended the call early, and a guard's name matched anywhere
928
+ in the expression. Parentheses and quotes inside string literals defeat every version of that
929
+ 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
930
+ run, which is the argument for it — forty-eight had drifted silently under a convention that
931
+ lived only in reviewers' heads.
932
+
933
+ Two corrections to the walker itself, both held by synthetic fixtures because `src/` has no
934
+ example of either. It now knows `fatal`, the sixth level Nest 11's `Logger` exposes — a level
935
+ list has to be complete rather than sufficient, and the first `this.logger.fatal(...)` anyone
936
+ wrote would otherwise have been invisible to a gate claiming to walk them all. And it no longer
937
+ descends into a guard's argument: what reaches the record is the guard's OUTPUT, so
938
+ ``logSafe(`id=${user.id}`)`` was being reported twice, once as guarded and once as bare, failing
939
+ a line that cannot carry a control character. A false positive on correct code is how a gate
940
+ gets weakened by whoever hits it next.
941
+
942
+ Requires no action from a consumer: `logSafe` returns an ordinary identifier unchanged, so log
943
+ lines are byte-identical unless a value actually carried a control character, in which case the
944
+ field is replaced with `<malformed>` and the record stays one record.
945
+
946
+ **`maskEmail` was one of those guards and did not enforce the boundary.** It preserves the
947
+ domain verbatim to keep the line useful to an operator, so `a@example.com\nforged` masked to
948
+ `a***@example.com\nforged`: the address was hidden and the injection was not, and being on the
949
+ allowlist meant the gate reported those sites as safe. Masking and record safety are two
950
+ separate duties and the helper owed both; it now passes its result through `logSafe`. The
951
+ addresses reaching those lines are not all DTO-validated — `profile.email` is whatever an OAuth
952
+ provider's userinfo response contained and `oldEmail` is whatever the host's repository stored,
953
+ so `@IsEmail()` saw neither. The allowlist's claim is now a test rather than a sentence: every
954
+ name on it is fed a value carrying LF, CR, NEL and both Unicode separators, and must return
955
+ something that cannot end a record. `safeLogLine` was removed from the allowlist in the same
956
+ pass — it is a check on a fully composed line, not a field guard (`safeLogLine(raw, [])` is
957
+ `raw`), and it appears inside no interpolation in `src/`.
958
+
959
+ - **`onDeliveryError` takes a per-message map, so an opt-in stops being all-or-nothing.** It was one
960
+ switch for all ten messages. A deployment sets `'rethrow'` for a specific benefit — deleting an
961
+ undelivered reset token early, not recording "verification sent" for a send that failed — and the
962
+ same setting then handed it the channel's **original, unlaundered** error on every other path.
963
+ Five messages render a credential, and those two flows are two of the five — so the bare form
964
+ reached three further credential-bearing paths that neither flow asked for.
965
+
966
+ ```typescript
967
+ new DefaultAuthEmailProvider(sink, {
968
+ onDeliveryError: { passwordResetToken: 'rethrow', emailChangeVerification: 'rethrow' }
969
+ })
970
+ ```
971
+
972
+ A message left out keeps `'swallow'`, so the safe value is what you get by saying nothing and
973
+ widening the opt-in is always explicit. A bare `'swallow' | 'rethrow'` still works and still
974
+ applies to all ten. A key the catalogue does not know is dropped — a typo leaves the message
975
+ swallowing, never exposed. The resolved policy is read from a `Map` and built by iterating the
976
+ deployment's own entries, so no lookup walks a prototype chain.
977
+
978
+ `AUTH_EMAIL_KINDS`, `AuthEmailKind` and `DeliveryErrorPolicyMap` are exported. A catalogue entry
979
+ added without a matching kind fails to compile.
980
+
981
+ - **`AuthEmailSink.send` now states which message it is carrying and whether it holds a live
982
+ credential** — anywhere in the rendered message, subject included, since all three fields reach
983
+ the sink. `kind` and `containsCredential` are always set. The obligation is in the port's own
984
+ documentation, where an implementer meets it: **a sink must not publish the content of a message
985
+ flagged `containsCredential`** — not in an error it throws, not in a log line, not in an audit
986
+ record that outlives delivery.
987
+
988
+ This is a statement of fact, **not** protection, and the docs say so plainly. Once the body leaves
989
+ `send`, what happens to it belongs to the sink. It is delivered at the only moment a sink could
990
+ act on it.
991
+
992
+ **A rendering can declare a credential its kind does not imply.** `AuthEmailMessage` gained an
993
+ optional `containsCredential`, OR-ed with the kind's baseline. `messages` replaces a renderer
994
+ outright, so a product whose own `mfaEnabled` copy hands the user recovery codes has turned a
995
+ notice into a credential-bearing message while its kind still reads `mfaEnabled` — and the sink
996
+ would have been told `false` about a body carrying a live secret. That is the flag being _wrong_,
997
+ which is worse than the flag being merely non-protective. The combination is one-way: a renderer
998
+ can only add. Returning `containsCredential: false` from an override of `passwordResetOtp`
999
+ changes nothing, because a consumer does not get to switch off a statement this library makes
1000
+ about its own messages.
1001
+
1002
+ Why a flag and not a list of values to redact: that was measured and rejected. Redaction is a
1003
+ substring match, so it holds for a value quoted as written and not for the same bytes re-encoded —
1004
+ a relay may answer with the body in base64, and then no list matches. A categorical "publish none
1005
+ of this message" has to find nothing, which is the only shape that survives an encoding it cannot
1006
+ predict. The same reasoning took every channel-authored byte out of this library's own log lines.
1007
+
1008
+ Adding fields to the input is not breaking for a sink: an implementation taking fewer properties
1009
+ still satisfies the port.
1010
+
1011
+ - **A one-time code could reach the operator's log in clear text when the mail relay rejected the
1012
+ message.** `DefaultAuthEmailProvider` logged the raw error object on a delivery failure. The
1013
+ comment justifying it read "the error is the channel's own, not the rendered body" — and a
1014
+ measurement against a real relay disproved exactly that premise. A policy, DLP or anti-spam
1015
+ relay answering `550` **quotes the offending content**, so the channel's error _is_ the rendered
1016
+ body, and for this provider that body carries a live password-reset OTP, an email-verification
1017
+ OTP, a reset token, an email-change token or an invitation token. The credential landed in the
1018
+ log pipeline valid until it expired. Reported by the `@bymax-one/nest-notification` seat from a
1019
+ run measured on a real relay, where the code captured from the SMTP `DATA` appeared verbatim in
1020
+ the consumer's error entry under the same request id.
1021
+
1022
+ **The rule that came out of it, after four weaker ones failed: this library publishes nothing a
1023
+ mail channel authored.** Not the error's `message`, not its `name`, not the rendered subject —
1024
+ and not on "credential paths" only, but on every path. What a delivery failure logs is the
1025
+ message's own label and, per link of the error's cause chain, an opaque stand-in:
1026
+
1027
+ ```
1028
+ delivery failed sending passwordResetOtp: <error>
1029
+ ```
1030
+
1031
+ Every part of that line is text this library wrote. The guarantee is simpler to hold than any
1032
+ amount of stripping, and it is what the four earlier attempts each failed to reach.
1033
+
1034
+ **Why redaction is not enough.** It is a substring match, so it assumes the credential reaches
1035
+ the error the way this library wrote it. A relay is free to quote what it rejected in transfer
1036
+ encoding instead, and base64 is the ordinary case. Measured: the whole reset-code body is 96
1037
+ base64 characters, and the first 200 characters of the line decode straight back to the OTP.
1038
+
1039
+ **Why a length cap is not enough either.** The encoding runs from the body's FIRST byte, so the
1040
+ code sits in the first sentence, well inside any cap that leaves enough text to decode. A bound
1041
+ on volume was never a bound on disclosure, and this changelog described it as a second lock
1042
+ before the measurement above.
1043
+
1044
+ **Why validating the `name` by shape is not enough.** Closing only `message` moves the leak one
1045
+ field over: an error class built around a relay reply is a normal thing for a mail client to do.
1046
+ Requiring the name to look like an identifier excludes a quoted body and does **not** exclude an
1047
+ encoded one — `MTIzNDU2` is the base64 of the OTP `123456`, eight characters, alphanumeric,
1048
+ leading letter, a valid identifier by any such rule, and reversible by anyone reading the log.
1049
+
1050
+ **Why redacting the rendered subject is not enough.** A subject comes from the `messages`
1051
+ catalogue, which a consumer may override with arbitrary code. Redaction only ever covered a
1052
+ subject that reproduced a value verbatim, and `Code 123-456` for the OTP `123456` is a
1053
+ reasonable-looking thing to write. The line carries a fixed label instead, which also identifies
1054
+ the message more stably for anyone parsing it.
1055
+
1056
+ **Nothing is kept.** The line carries the message's label and, when the chain has one, the
1057
+ `<error>` stand-in per link — no status, no name, no message. A parsed SMTP status survived
1058
+ several rounds on the reasoning that a value rebuilt from a validated grammar cannot carry body
1059
+ content, and the test that finally settled it is whether the output DEPENDS on the secret. It
1060
+ does: an OTP of `424242` grouped as `424-242` at the head of a quoted body publishes `424`, and a
1061
+ different code publishes different digits. That is derivation, not the coincidence that `550
1062
+ 5.7.1` reassembling into `550571` turned out to be — and no grammar separates a reply from body
1063
+ text shaped like one, because a reply code and a grouped credential prefix are the same three
1064
+ digits and a separator.
1065
+
1066
+ What an operator loses is the transient-versus-permanent split, which their mail provider's own
1067
+ dashboard carries. What they keep is which message failed, which is the half this library is the
1068
+ only source for.
1069
+
1070
+ **The same defect was one port over, in the breach checker.** `IPasswordBreachChecker.isBreached`
1071
+ receives the PLAINTEXT PASSWORD by contract, so an error it raises is a place the plaintext can
1072
+ be — an HTTP client that echoes the request it failed on is the ordinary shape. The fail-open
1073
+ handler passed that error straight to `logger.error(msg, err)`, publishing it with its stack and
1074
+ whatever the client hung on it, under a comment claiming the plaintext never reached the logger.
1075
+ **Nothing** from that error reaches the line now — not the object, not a description, not a status
1076
+ parsed off its front. The first fix described it with `describeChannelStatus` and was wrong in a
1077
+ way worth recording: that helper validates the SMTP reply grammar, and a breach checker is not an
1078
+ SMTP channel. A password of `424 Correct Horse!` echoed back parses as the reply `424` and
1079
+ publishes the first three characters of the credential. Right tool, wrong port. No status is lost
1080
+ by dropping it, because an HTTP checker's own code would have to come from a structured field the
1081
+ interface does not expose.
1082
+
1083
+ Two DTO comments carried the same over-claim (`RegisterDto.password`,
1084
+ `AcceptInvitationDto.password`: _"never logged or persisted in plaintext"_) and now say **by this
1085
+ library**, pointing at the ceiling. Found by sweeping for the CLAIM rather than for the wording
1086
+ already corrected — the method comes from the `@bymax-one/nest-notification` seat, who found two
1087
+ more in their own README the same way. A sweep by phrase misses the siblings written in other
1088
+ words, and the most scannable claim in a file is rarely worded like the one you just fixed.
1089
+
1090
+ **What still needs you: `onDeliveryError: 'rethrow'`.** What the provider re-throws is the
1091
+ channel's original error, deliberately unaltered — a caller that opted into that policy did so to
1092
+ branch on the channel's codes, and handing it a laundered replacement would take those away. So
1093
+ the quoted body travels with it. Whatever catches it must not log it raw, and must not merely
1094
+ redact it either: describe it with **`describeChannelStatus`**, which is exported for exactly
1095
+ this. Deployments on the default `'swallow'` policy need no action.
1096
+
1097
+ **Apply to a derived backend:** nothing to change for the fix itself — it is internal to the
1098
+ provider. **Three** things to check.
1099
+
1100
+ If you parse the log line, it changed from `delivery failed for "<subject>"` with the error
1101
+ attached as a second argument to a single string, `delivery failed sending <label>: <error>`,
1102
+ with `<-` between cause links and no status anywhere in it; `<label>` is a fixed name this
1103
+ library owns (`passwordResetOtp`, `mfaEnabled`, …) and the rendered subject is gone.
1104
+
1105
+ If you run `onDeliveryError: 'rethrow'`, audit what your handler does with the error, per the
1106
+ paragraph above.
1107
+
1108
+ And **the three MFA notices no longer reject the operation that triggered them** — enabling a
1109
+ factor, disabling one, and resetting one now send detached, with the failure logged instead. A
1110
+ deployment on `'rethrow'` that relied on an undelivered MFA notice failing the request will stop
1111
+ seeing that failure. The change is deliberate: by the time the notice is sent, the factor is
1112
+ already enabled or removed, and answering the caller with an error reports a change that HAPPENED
1113
+ as one that did not. The other seven messages are unaffected — `'rethrow'` still surfaces their
1114
+ failures, which is the whole reason the two flows that react to a throw opt in.
1115
+
1116
+ One more, if you catch errors from `EmailChangeService.requestChange` or
1117
+ `InvitationService.invite`: **what they throw is now laundered.** Both awaited the provider with
1118
+ no handler, so a rejection travelled to your code carrying the channel's own error — its
1119
+ `message`, its `name`, whatever fields your mailer attached. They now throw
1120
+ `new Error(describeChannelStatus(err))`, whose message is the opaque description and nothing
1121
+ else. This is not about `'rethrow'`: a custom `IEmailProvider` that throws is laundered here too.
1122
+ The reason is that on these two paths the caller **is this library** — the rejection reaches
1123
+ `AuthExceptionFilter`'s unknown-exception branch, which logs it — so propagating the original
1124
+ publishes the credential through this library's own filter, with no consumer given a chance to
1125
+ contain it. The HTTP response is unchanged: that branch answered `auth.internal` with the generic
1126
+ message before and does now.
1127
+
1128
+ Not exploitable by an unauthenticated caller on its own — it requires a relay configured to
1129
+ quote rejected content — but it needs no attacker at all where such a relay is in the path, and
1130
+ the value exposed is a working credential.
1131
+
1132
+ ### Changed
1133
+
1134
+ - **Stryker deletes its sandbox even when the run fails (`cleanTempDir: "always"`).** `true` — the
1135
+ previous value, and the default — deletes `.stryker-tmp` only after a run that PASSED, and a run
1136
+ that fails the 100 threshold is the normal state while iterating, so a 45 MB copy of `src/` was
1137
+ left behind on every failed run. Wanted on its own terms: `jest.coverage.config.ts` has to name
1138
+ it in `modulePathIgnorePatterns` precisely because a second copy of `src/` in the tree is
1139
+ hazardous, and the cheapest way to hold that is for it not to be there. Contributor-facing only;
1140
+ nothing ships differently.
1141
+
1142
+ ### Added
1143
+
1144
+ - **A table key must now name a route handler, not merely a method that exists.** The conformance
1145
+ spec already checked both directions between the operations table and the controllers — every
1146
+ route handler described, every described key naming a real method — so the second half was
1147
+ looser than it read: `typeof === 'function'` accepts a method carrying no verb decorator, and
1148
+ the lookup resolves through the **prototype chain**, so `toString`, `valueOf` and
1149
+ `hasOwnProperty` answer `'function'` on any class. A typo landing on an inherited member passed
1150
+ here and would have failed in a consumer's document build instead, which is the wrong
1151
+ repository to find out in. It is the same prototype-chain reach that once let a catalog lookup
1152
+ hand a **function** to `HttpException` as a status.
1153
+
1154
+ Both halves falsified before the change was trusted: `'AuthController.toString'` and
1155
+ `'AuthController.onModuleInit'` are now red, and were not.
1156
+
1157
+ Recorded because the first draft of this entry claimed the table could fall behind the
1158
+ controllers unnoticed. It could not — that direction has been covered since the contributor
1159
+ shipped, and removing `AuthController.wsTicket` from the table already failed the conformance
1160
+ spec. Caught in review, verified by running it.
1161
+
21
1162
  ## [1.4.3] - 2026-08-15
22
1163
 
23
1164
  ### Changed
@@ -264,6 +1405,57 @@ what moves, and that note is the compatibility contract until strict SemVer begi
264
1405
  it, so nothing downstream will remind you. Delete the literals, update whatever pins the
265
1406
  document to the four-name vocabulary, rebuild, and regenerate any typed client.
266
1407
 
1408
+ **Delete the entries for THIS library's routes. Keep your document-level `security`.** Reported
1409
+ after publication by the consumer who ran the comparison this note asks for, and it is the one
1410
+ way following this instruction makes a document **worse**: the two usually live in the same
1411
+ options block, and removing the block removes the default. In `augmentOperation`, an operation
1412
+ with no requirement of its own, no override and no fragment falls through to `ownRouteSecurity`,
1413
+ which answers `undefined` for anything that is not a health or metrics route — so a backend's
1414
+ **own** guarded routes carry no requirement and inherit the document default. Take the default
1415
+ away and every one of those routes reads as public. The condition travels with the claim: this
1416
+ reaches routes that state nothing of their own — no decorator feeding the scanned operation, no
1417
+ `operationSecurity` entry, not a health or metrics route a policy answers for. Anything carrying
1418
+ its own requirement outranks the default and is untouched, which is why the fix works at all. A
1419
+ backend that annotates every guarded route individually is unaffected; the reason this bit two
1420
+ consumers is that annotating each route is what a document-level default exists to avoid. The
1421
+ health probes do move, losing their explicit `[]`, since `ownRouteSecurity` returns it only
1422
+ while `openapi.security.length > 0`.
1423
+
1424
+ On nest-core below 1.5.0 nothing reports it: no error, no unmatched key, no failing build. The
1425
+ document just stops asking for credentials on those routes — the ones the backend owns.
1426
+ nest-core 1.5.0 warns on this shape and names the bare operations, which makes
1427
+ it visible rather than impossible. Keep the default, and **derive it instead of writing a
1428
+ literal** — from the guard your own routes use, your `tokenDelivery`, and the controllers you
1429
+ registered, all three. A literal goes wrong in two distinct ways: where the named scheme is not
1430
+ declared, nest-core's `assertSchemesDeclared` throws the build; under `both`, where both access
1431
+ schemes exist, nothing throws and the default is merely incomplete, describing one of the two
1432
+ channels the routes accept. Loud in one place, quiet in the other. Two cases a delivery-only
1433
+ recipe gets wrong: `schemesFor` gates both dashboard schemes on a dashboard controller being
1434
+ registered — and `oauth` is not one of them, since its operations are public — so **any
1435
+ deployment with no dashboard surface declares neither and throws under `cookie` too**,
1436
+ platform-only and OAuth-only alike;
1437
+ and a route behind `JwtPlatformGuard` always wants `bymaxPlatformAccessBearer`, since
1438
+ `extractPlatformAccessToken` reads the `Authorization` header whatever the mode says. A backend
1439
+ guarding different routes with both families needs per-operation `security` for one of them —
1440
+ not because the default holds only one entry, but because its entries are alternatives applied
1441
+ to every inheriting operation, so listing both would document each credential as valid for
1442
+ either family.
1443
+
1444
+ The no-dashboard case gets a remedy rather than only a diagnosis, because those deployments are
1445
+ legitimate: `JwtAuthGuard` is registered and exported unconditionally, so mounting no dashboard
1446
+ controller does not stop a backend from guarding its own routes with a dashboard access token.
1447
+ Deriving correctly there answers "the scheme does not exist", which is true and unusable — so
1448
+ that deployment **declares the scheme itself** in `openapi.securitySchemes`. Which scheme is
1449
+ still a function of delivery, not a fixed recipe: `cookie` needs the `apiKey`-in-cookie
1450
+ definition carrying the configured `cookies.accessTokenName`; `bearer` needs the HTTP bearer
1451
+ definition and has no cookie name to carry; `both` needs **both**, or the document is incomplete
1452
+ in the same quiet way described above. `AUTH_SECURITY_SCHEMES` is not public API today, so the
1453
+ names are written as literals for now; exporting them is tracked.
1454
+
1455
+ Per-operation beats document-level, so the default cannot reach this library's operations.
1456
+ Verified on a real adoption: thirteen contributed operations render byte-identical with and
1457
+ without it.
1458
+
267
1459
  **Not in this change:** per-operation error responses (the `4xx` set each operation can answer,
268
1460
  read from `errorCatalog.statuses`) and the DTO request schemas. Both are additive to the same
269
1461
  contributor and are next; the security posture is the half a consumer asserts today.
@@ -2256,7 +3448,9 @@ ever installable.
2256
3448
  - 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
2257
3449
  - 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
2258
3450
 
2259
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...HEAD
3451
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...HEAD
3452
+ [1.4.5]: https://github.com/bymaxone/nest-auth/compare/v1.4.4...v1.4.5
3453
+ [1.4.4]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...v1.4.4
2260
3454
  [1.4.3]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...v1.4.3
2261
3455
  [1.4.2]: https://github.com/bymaxone/nest-auth/compare/v1.4.1...v1.4.2
2262
3456
  [1.4.1]: https://github.com/bymaxone/nest-auth/compare/v1.4.0...v1.4.1