@bymax-one/nest-auth 1.4.3 → 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 +1128 -1
- package/README.md +355 -34
- package/dist/client/index.cjs +85 -34
- package/dist/client/index.d.cts +60 -1
- package/dist/client/index.d.ts +60 -1
- package/dist/client/index.mjs +86 -35
- package/dist/server/index.cjs +1196 -364
- package/dist/server/index.d.cts +945 -130
- package/dist/server/index.d.ts +945 -130
- package/dist/server/index.mjs +1191 -365
- package/dist/shared/index.cjs +41 -0
- package/dist/shared/index.d.cts +17 -1
- package/dist/shared/index.d.ts +17 -1
- package/dist/shared/index.mjs +41 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -18,6 +18,1081 @@ 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
|
+
|
|
21
1096
|
## [1.4.3] - 2026-08-15
|
|
22
1097
|
|
|
23
1098
|
### Changed
|
|
@@ -264,6 +1339,57 @@ what moves, and that note is the compatibility contract until strict SemVer begi
|
|
|
264
1339
|
it, so nothing downstream will remind you. Delete the literals, update whatever pins the
|
|
265
1340
|
document to the four-name vocabulary, rebuild, and regenerate any typed client.
|
|
266
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
|
+
|
|
267
1393
|
**Not in this change:** per-operation error responses (the `4xx` set each operation can answer,
|
|
268
1394
|
read from `errorCatalog.statuses`) and the DTO request schemas. Both are additive to the same
|
|
269
1395
|
contributor and are next; the security posture is the half a consumer asserts today.
|
|
@@ -2256,7 +3382,8 @@ ever installable.
|
|
|
2256
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
|
|
2257
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
|
|
2258
3384
|
|
|
2259
|
-
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.
|
|
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
|
|
2260
3387
|
[1.4.3]: https://github.com/bymaxone/nest-auth/compare/v1.4.2...v1.4.3
|
|
2261
3388
|
[1.4.2]: https://github.com/bymaxone/nest-auth/compare/v1.4.1...v1.4.2
|
|
2262
3389
|
[1.4.1]: https://github.com/bymaxone/nest-auth/compare/v1.4.0...v1.4.1
|