@bymax-one/nest-auth 1.0.11 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,366 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.1.0] - 2026-08-03
11
+
12
+ The API changes marked **Breaking** below are breaking against `1.0.11`. They are
13
+ released as a minor because the package has no consumers yet — it is published but
14
+ not in use anywhere. The marks stay because the changelog records what changed, not
15
+ who it reached.
16
+
17
+ This cycle closes the divergences between this library and its Rust counterpart
18
+ [`bymaxone/rust-auth`](https://github.com/bymaxone/rust-auth) — the two can back the same
19
+ deployment over one Redis, so keys, stored record shapes, JWT claims and Lua scripts are a
20
+ contract between them — and then ships five security items that came out of auditing both
21
+ against `better-auth`. Every change here has a matching change on the Rust side, and
22
+ `conformance/wire-contract.json` is held byte-identical in both repositories.
23
+
24
+ ### Added
25
+
26
+ - **`pnpm check:exports`** runs `attw --profile strict` against the tarball this
27
+ package would publish. Its absence is why both resolution defects above went
28
+ unnoticed: a source-level typecheck compiles `src` and never resolves through the
29
+ `exports` map. The gate packs the tarball itself rather than letting `attw --pack`
30
+ do it, because `npm publish --dry-run` exports `npm_config_dry_run`, a nested pack
31
+ inherits it, and a dry pack writes no file — so the gate could not otherwise run
32
+ from inside `prepublishOnly`, which is the one place standing between a manual
33
+ `npm publish` and the registry.
34
+ - **`pnpm check:runtime`** packs the tarball, lays it out the way npm would, and
35
+ loads every subpath from it in ESM _and_ CommonJS. `./nextjs` is excluded by
36
+ design — it reaches `next/server`, which Next ships without an `exports` map, so
37
+ a bare ESM specifier cannot resolve it outside a bundler, and under CommonJS it
38
+ trips Next's own Server-Component guard. Both are Next's behaviour, not this
39
+ package's.
40
+
41
+ - **Refresh-token reuse detection by family lineage** ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts), [`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts)). A login opens a family; every rotation inherits it; replaying a consumed token past its grace window revokes that lineage — and only that lineage. Previously a theft signed the user out of every device they owned. Platform rotation gains the same detection, which it never had.
42
+ - **Bulk access-token revocation by epoch** ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)). A per-user generation counter replaces the `utc:` cutoff timestamp. The counter has no clock semantics — a token issued in the same second as a password reset was previously indistinguishable from one issued just before it — and does not depend on the token carrying a well-formed `iat`.
43
+ - **Cross-site request refusal** ([`src/server/guards/trusted-origin.guard.ts`](src/server/guards/trusted-origin.guard.ts)). `Origin` / `Sec-Fetch-Site` verification on cookie-authenticated writes. `SameSite` covers this for `lax`/`strict`; it does not for `SameSite=None`, which this library allows and which sends the session cookie cross-site. On by default; `cookies.trustedOrigins` is required as soon as `cookies.sameSite: 'none'` is set.
44
+ - **Breached-password refusal** ([`src/server/providers/hibp-breach-checker.provider.ts`](src/server/providers/hibp-breach-checker.provider.ts)). `IPasswordBreachChecker` with an opt-in `HibpBreachChecker` using Have I Been Pwned k-anonymity ranges: only a 5-character SHA-1 prefix leaves the process. Fails **open** by contract — an unreachable corpus must never stop someone changing their password. Off by default (`AllowAllBreachChecker`): it is the only part of the credential path that reaches the network.
45
+ - **Per-IP rate limiting enforced by the library** ([`src/server/guards/auth-rate-limit.guard.ts`](src/server/guards/auth-rate-limit.guard.ts), [`src/server/decorators/auth-rate-limit.decorator.ts`](src/server/decorators/auth-rate-limit.decorator.ts)). `AUTH_THROTTLE_CONFIGS` existed but was advisory: the numbers only applied if the host wired `ThrottlerModule`, and nothing said so. The refusal is now the library's own `auth.too_many_requests` envelope with `Retry-After`, matching what `rust-auth` already returned. On by default (`rateLimit.enabled`).
46
+ - **Absolute session lifetime** ([`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts)). `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation. `refreshExpiresInDays` bounds a single token, not a session — a client rotating every fifteen minutes renews it forever. Off by default: switching it on ends sessions already older than the cap.
47
+ - **Startup validation of `jwt.accessExpiresIn` against the token-epoch retention window** ([`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts), [`src/server/constants/token-epoch.ts`](src/server/constants/token-epoch.ts)). The epoch is what makes a stateless access token revocable, and it only holds while the bumped value is still readable. An access token allowed to outlive the 30-day record sat past that: the lookup falls back to `0`, the staleness check stops firing, and a token a password reset had revoked verified again. The Redis TTL now derives from the same constant the validation reads, so the bound enforced and the bound honoured cannot drift. An unreadable time string or a non-positive lifetime is refused here too, rather than at the first token issued. `rust-auth` enforces the identical rule.
48
+ - **`server-only` guard on the Next.js JWT helper** ([`src/nextjs/helpers/jwt.ts`](src/nextjs/helpers/jwt.ts)). The module receives the HS256 secret; importing it from a Client Component is now a build error rather than a secret published to every visitor. Declared as an **optional peer dependency**, so the zero-direct-dependency rule holds and a consumer not using `./nextjs` installs nothing — install it alongside `next` if you do. `rust-auth`'s Next.js package guards its verifier the same way.
49
+
50
+ - **Single-use WebSocket upgrade tickets** ([`src/server/services/ws-ticket.service.ts`](src/server/services/ws-ticket.service.ts), [`POST {prefix}/ws-ticket`](src/server/controllers/auth.controller.ts)). The browser `WebSocket` API cannot set handshake headers, and `WsJwtGuard` refuses a token in the query string — correctly, since that writes a long-lived credential into access logs, browser history and proxy caches. Between the two, browser clients had no supported path, which in practice means the consumer writes the query-string token themselves. A ticket is the alternative: opaque, 30 seconds, consumed by the first redemption, and stored as a verified-identity snapshot with no `jti`, no signature and no expiry of its own — so it authorizes a socket and cannot be turned back into a session. Minting requires an authenticated session in good standing with its second factor already satisfied. `rust-auth` has authenticated its upgrades this way from the start; this closes the gap.
51
+
52
+ - **`rateLimit.clientIpSource`** (`'peer'` | `'trusted-proxy'`, **required** when rate limiting is enabled — `rateLimit` itself is now a required, discriminated option group, so the omission is a compile error and not only a startup one). The limiter keyed on `req.ip`, which honours Express's `trust proxy` setting: with it enabled — the usual configuration behind a proxy — `req.ip` is whatever the client wrote in `X-Forwarded-For` unless the hop count is exactly right, and a caller who chooses their own key is not limited at all. Reading the socket address instead is not a safe default either: behind any proxy it is the proxy's address for every client, so all of them share one bucket and a single caller sending a handful of logins locks out the whole user base, with no credential. Each value is a working limiter in one deployment and no limiter at all in the other, both look like a working limiter at runtime, and nothing detects the mismatch — so the deployment states which shape it is, or the module refuses to start. Pass `rateLimit.enabled: false` if the limits are enforced at the edge. `rust-auth` draws the same distinction (`ClientIpSource`) and requires it too.
53
+ - **`jwt.previousSecrets`** — secrets retired by a rotation, accepted for verification only. Rotating `jwt.secret` used to sign every user out at once **and** invalidate every stored recovery-code digest, which is keyed by an HMAC derived from that secret: users would lose the codes they printed and filed, and find out at the moment they most need them. Both stay readable while the old tokens drain. Signing always uses the current secret, so a rotation is one-way.
54
+ - **`mfa.previousEncryptionKeys`** ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts)) — AES-256 keys retired by a rotation of `mfa.encryptionKey`. The stored ciphertext carries no key identifier, so changing that key made every enrolled user's TOTP secret undecryptable at once, with no way back: the authenticator they set up simply stops matching, and nothing in the library could tell them why. A secret that opens under a retired key is now re-encrypted under the current one on the next successful challenge, so the rotation drains instead of requiring the retired key to stay configured forever — a key that still opens every stored secret is not retired. Every entry is held to the same bar as the current key at startup (base64, exactly 32 bytes, never equal to the current key or to another entry), because a malformed one would otherwise surface at a user's first challenge. Same option on both sides.
55
+
56
+ - **Startup bounds on the parameters that carry a control's strength** ([`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). `mfa.totpWindow` (`0..=10`), `mfa.recoveryCodeCount` (`1..=50`), `password.blockSize` (`>= 8`) and `password.parallelization` (`>= 1`) had no validation while every sibling parameter did. The window counts 30-second steps on _either_ side of now, so `2n + 1` codes are valid at once: at 60 that is 121, and a six-digit code becomes a hundred times easier to guess while the configuration still reads as "MFA enabled". Zero recovery codes enrols an account with no way back if the authenticator is lost. And scrypt's memory cost is `128 * N * r`, so a block size below 8 divides the hardness that `password.costFactor`'s floor exists to guarantee — invisibly, because the parameter that _is_ bounded stays intact. `rust-auth` enforces the identical ranges.
57
+
58
+ - **`tenantIdResolver` is now honoured by every tenant-scoped flow** ([`src/server/utils/resolve-tenant-id.ts`](src/server/utils/resolve-tenant-id.ts)). The option documents itself as ignoring the body's `tenantId` when a resolver is configured, "to prevent tenant spoofing" — but only `login` and `register` called it. Password reset (all four steps) and email verification (both) read the caller's value verbatim, so on a deployment that derives the tenant from the request, a caller on one tenant could drive reset and verification mail at accounts in another, and a reset started under the resolved tenant could never be completed because the two steps derived different identifiers. **Breaking:** `PasswordResetService`'s four methods and `AuthService.verifyEmail` / `resendVerificationEmail` now take the request as their final argument; the library's own controllers pass it. The resolution itself moved out of `AuthService` into a shared helper — one rule with two implementations is how the gap opened. `rust-auth` takes the same change as `&RequestContext`.
59
+
60
+ - **`POST /auth/logout` no longer requires a live access token** ([`src/server/controllers/auth.controller.ts`](src/server/controllers/auth.controller.ts)). The route sat behind `JwtAuthGuard`, so the overwhelmingly common case — a user returning after the 15-minute access token expired and clicking "sign out" — answered 401 and `logout` never ran: the refresh session, the long-lived credential logout exists to kill, stayed live for its full seven days on a device the user had just signed out. The refresh token is what authorizes the operation now, and the session's owner is read from the stored record rather than from the token's claims. The access token is still _verified_ (signature + pinned algorithm) before its `jti` is blacklisted, waiving only the expiry check — reading it unverified would let a caller blacklist a token they do not own by naming its id. **Breaking:** `AuthService.logout` drops its `userId` parameter and returns the revoked session's owner. `rust-auth` takes the same change.
61
+
62
+ - **MFA enrolment re-authenticates against the account password** ([`src/server/dto/mfa-setup.dto.ts`](src/server/dto/mfa-setup.dto.ts), [`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts)). `POST /mfa/setup` and `/platform/mfa/setup` were guarded by the access token alone, so a token lifted by XSS or from a shared machine could enrol an authenticator the attacker holds — and the enable then revokes every session and bumps the epoch, locking the real owner out of an account they still know the password to, with the recovery codes displayed only to the attacker. ASVS requires re-authentication before an authentication factor changes; `disable` already demanded a TOTP code. Gating `setup` rather than `verify-enable` means the attacker cannot even obtain a secret they control, at the cost of one prompt at the natural moment. An account provisioned purely through OAuth has no local password and is exempt — its credential belongs to the provider, which this library cannot re-verify inline. **Breaking:** `MfaService.setup` takes the password as a third argument and the two `setup` endpoints accept a `password` body field. `rust-auth` takes the same change.
63
+
64
+ - **The OAuth `state` is bound to the browser that started the flow** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts), [`src/server/constants/oauth-state-cookie.ts`](src/server/constants/oauth-state-cookie.ts)). The `state` nonce was validated against Redis alone, which proves only that _somebody_ started a flow. An attacker could run their own authorization, complete consent at the provider, capture the resulting `?code=…&state=…` callback URL without visiting it, and lure the victim there: the victim's browser then received the attacker's session, and everything they did next — a payment method, an uploaded document, a linked account — landed in the attacker's hands. PKCE does not cover this, because the verifier is held server-side and replayed for whoever presents the state. `initiateOAuth` now plants the raw state as an HttpOnly cookie and the callback refuses any request that does not carry it back, as RFC 6749 §10.12 requires. The cookie is `SameSite=Lax` regardless of `cookies.sameSite` — the provider's callback is a cross-site top-level GET, and `strict` would withhold the cookie on exactly that hop — and the check runs _before_ the state is consumed, so a lured victim cannot burn a state the legitimate browser is still entitled to spend. **Consumers must mount `cookie-parser`** for the OAuth routes; without it every callback is refused. `rust-auth` takes the same change.
65
+
66
+ - **Session cookies are host-only unless `cookies.resolveDomains` says otherwise** ([`src/server/services/token-delivery.service.ts`](src/server/services/token-delivery.service.ts)). With no resolver configured the library derived the `Domain` attribute from the request host, and a cookie carrying `Domain=app.example.com` is sent to **every subdomain** of that name (RFC 6265 §5.2.3) — so the session was readable by a marketing site, a user-content host, or a stale DNS record someone else now answers for, on a deployment that never asked for any of that. The default is now no `Domain` attribute at all; sharing across subdomains stays available and is what `resolveDomains` is for. The logout clear follows the same rule, since a browser matches a deletion on name, domain and path. `rust-auth` is host-only by default too, and now actually honours its `resolve_domains` resolver, which it had been ignoring.
67
+
68
+ - **Six documented defaults corrected** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [README](README.md)). `bruteForce.maxAttempts` documented `10` against a real `5`; `passwordReset.tokenTtlSeconds` documented `3600` against a real `600`; `emailVerification.required` documented `false` against a real `true`; and `controllers.sessions` / `.platform` / `.invitations` claimed to default on "when the feature is enabled" when all three are opt-in and refuse to mount without an explicit `true`. A consumer reading the JSDoc — the only place most of these are described — would size a lockout window, a reset window, and a login gate wrongly, and would wait for endpoints that were never going to appear.
69
+
70
+ - **The Next.js proxy refuses a token that is not an access token** ([`src/nextjs/internal/tokenState.ts`](src/nextjs/internal/tokenState.ts)). A valid signature was the only question asked, but the server signs several kinds of token with one key — including the short-lived `mfa_challenge` temp token, issued to a user who has proven their password and **not** their second factor. Moving that value into the access cookie walked past every proxy-protected page, which is precisely the state the second factor exists to stop. The upstream API rejected it all along, because its guards check `type`; the gap was the edge, where the page renders. The proxy now admits `dashboard` and `platform` and nothing else, matching `rust-auth`'s `ACCESS_TOKEN_TYPES`, which had this gate from the start.
71
+
72
+ - **`isSafeSameOriginPath` rejects every C0 control and DEL** ([`src/nextjs/helpers/routeHandlerUtils.ts`](src/nextjs/helpers/routeHandlerUtils.ts)), not just the CR / LF / NUL trio. Those three are the ones that smuggle a header; the others have no business in a path either, and enumerating the dangerous characters is the kind of allowlist-by-omission that only looks complete until someone finds the character nobody thought of.
73
+
74
+ - **The provider's error callback reaches the OAuth error handling instead of the `ValidationPipe`** ([`src/server/dto/oauth-callback-query.dto.ts`](src/server/dto/oauth-callback-query.dto.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts)). RFC 6749 §4.1.2.1 defines a callback carrying `error` and no `code` — the response a provider sends when the user declines consent. The DTO required `code`, so a user who simply clicked "Cancel" got a raw validation envelope rather than the configured error redirect. `code` is now optional and the controller refuses a callback carrying neither it nor `error` on the same path. The provider's value is logged and never echoed: it is provider-chosen text that would otherwise land in a URL the browser follows, and `oauth_failed` already says everything the library is willing to vouch for. `rust-auth` takes the same change.
75
+
76
+ - **A second token-epoch bump extends the record's lifetime** ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)). `bumpUserTokenEpoch` was built on the rate-limiter's `incrWithFixedTtl`, which applies the expiry only on the first increment — correct for a fixed window, wrong here. It anchored the 30-day retention to the _first_ bump a user ever took: a password reset on day 0 and a "sign out everywhere" on day 29 shared one expiry, the key vanished on day 30 while the tokens the second bump revoked were still inside their lifetime, and `getUserTokenEpoch` then answered `0` — under which `stamped < epoch` is false for every token and the revocation quietly stopped applying. `rust-auth` has always issued the unconditional `EXPIRE`; a shared Redis cannot have the two libraries disagree about when the key dies.
77
+
78
+ - **`initiateReset` shares the resend cooldown** ([`src/server/services/password-reset.service.ts`](src/server/services/password-reset.service.ts)). `resendOtp` was throttled and `initiateReset` was not, which made the throttle decorative — a caller just used the other door. It also made the OTP's 5-attempt ceiling per-issuance rather than per-account, because every issuance rewrites the record with `attempts: 0`: an attacker who knew an address could loop "initiate, guess five times" at a six-digit code indefinitely, mailing the victim once per lap. Both entry points now claim one budget under one key. `rust-auth` takes the same change.
79
+
80
+ - **The absolute session-lifetime cap is enforced on the grace-recovery path** ([`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts)). The check ran against the seed, and on that path the seed is the placeholder used when the live key is already gone — its `familyCreatedAt` is `now`, so the check compared `now - now` and always passed. A lineage that had just passed its cap could still mint a fresh access token and a full-length refresh session by presenting a token inside its grace window: the cap ended normal rotation and left the one remaining door open. `rust-auth` takes the same check on both planes.
81
+
82
+ - **`POST /auth/logout` and `POST /auth/ws-ticket` are rate-limited** (20/60s each, pinned in `conformance/wire-contract.json`). Logout became public in this cycle by necessity — a user whose access token expired has to be able to sign out — but public and unlimited are different things, and each call costs a SHA-256 and several Redis round trips for an unknown caller. `ws-ticket` is authenticated but writes a fresh single-use key per call.
83
+
84
+ - **The Next.js proxy strips the caller's identity headers on `/api/auth/*` too** ([`src/nextjs/createAuthProxy.ts`](src/nextjs/createAuthProxy.ts)). That arm returned before sanitisation ran, so a client-forged `x-user-id: admin` reached whatever the consumer mounts there — in direct contradiction of the module's own promise that a forged header cannot reach a server component via _any_ response path. `rust-auth`'s proxy had the same gap on its public-path arm and takes the same fix.
85
+
86
+ - **The OAuth state cookie is cleared only when the browser sent it** ([`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts)). The callback is a `GET`, so `SameSite=Lax` withholds the cookie from a cross-site subresource — an `<img src=…/callback>` carries none — but a `Set-Cookie` deleting it took effect anyway. Any page could therefore kill an OAuth login that was still at the consent screen, repeatably. The provider's `error` and the `provider` path segment are also no longer interpolated into a log line verbatim: both are attacker-controlled, and a newline in either forges whole log records.
87
+
88
+ - **Refresh re-reads the account and re-applies the status and email-verification gates** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). Rotation worked entirely from the Redis record, so nothing on that path ever looked at the user again — and rotation is the door a signed-in caller actually uses. Two consequences, both in the default configuration. A banned or suspended account renewed its access token every fifteen minutes for the refresh token's whole seven days, because the ban closes only the login door (ASVS v5 §7.4.2 requires disabling an account to terminate its sessions). And an address that was never verified held an authenticated session **indefinitely**: `register` issues a session deliberately, this library's own specification bounds that window at one access-token lifetime, and rotation is what un-bounded it. Both gates now run on refresh, and a blocked account that touches the system has every session revoked and its epoch bumped in the same breath. The account is returned with the rotation, so the caller does not pay a second repository read.
89
+
90
+ - **`AuthService.revokeAllSessions(userId)`** — the dashboard twin of `PlatformAuthService.revokeAllPlatformSessions`. A library cannot see the moment a host suspends, bans, or deletes an account, so the host needs a supported way to say so; `SessionService.revokeAllExceptCurrent` could not serve, because it wants the hash of a session to keep and an administrator banning somebody else has none.
91
+
92
+ - **`POST /platform/logout` no longer requires a live access token** ([`src/server/controllers/platform-auth.controller.ts`](src/server/controllers/platform-auth.controller.ts)). The route sat behind `JwtPlatformGuard`, which refuses an expired token — so an operator who stepped away for longer than the fifteen-minute access lifetime could not sign out at all, and the seven-day refresh session of the highest-privilege identity in the system stayed live on a console they believed they had left. This is the same fix the dashboard plane took earlier in this cycle; the platform plane kept the old shape. The owner is now read from the stored record instead of the token's claims, and the access token is still verified — signature and pinned algorithm — before its `jti` is blacklisted. **Breaking:** `PlatformAuthService.logout` takes `(accessToken, rawRefreshToken)` and returns the revoked session's owner.
93
+
94
+ - **The absolute session-lifetime cap now covers the platform grace path too** ([`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts)). The check was added to the dashboard twin earlier in this cycle and not to its platform counterpart, which left the higher-privilege identity with the hole the dashboard one had just closed: the pre-script check runs against the seed, and on the grace path the seed is the placeholder used when the live key is gone — its `familyCreatedAt` is `now`, so the cap compared `now - now`.
95
+
96
+ - **`POST {prefix}/password/change` — authenticated password change** ([`src/server/controllers/password-reset.controller.ts`](src/server/controllers/password-reset.controller.ts), [`src/server/dto/change-password.dto.ts`](src/server/dto/change-password.dto.ts)). ASVS v5 §6.2.2 and §6.2.3 require it at **Level 1** — "users can change their password", and the change "requires the user's current and new password" — and it was the one credential operation this library did not own. Without it a consumer either sent users through the _unauthenticated_ recovery flow to rotate a password they already knew, or rebuilt the operation against a hash format the README forbids them to touch. The current password is what makes it safe: a session alone is not proof of identity, so a token lifted by XSS or from a shared machine could otherwise rotate the credential, lock the real owner out of an account they still know the password to, and keep the attacker in. Every other session ends on success and the token epoch is bumped (§7.4.3), while the caller's own session survives when the request carries its refresh token — so the device that made the change stays signed in.
97
+
98
+ - **`@Authenticated()`** ([`src/server/decorators/authenticated.decorator.ts`](src/server/decorators/authenticated.decorator.ts)) — un-exempts a single handler from a class-level `@Public()`. Until now that exemption was irreversible: the guards resolve the flag with `getAllAndOverride([handler, class])` and only `true` was ever written, so adding `@UseGuards(JwtAuthGuard)` to a method of a public controller changed nothing. The route mounted, the guard ran, and everyone was let through — a silent failure, and the reason the new change endpoint could not simply be added to the password controller.
99
+
100
+ - **`CommonPasswordChecker` is the default password screen** ([`src/server/providers/common-password-checker.provider.ts`](src/server/providers/common-password-checker.provider.ts)). NIST SP 800-63B §3.1.1.2 states a verifier **SHALL** compare a prospective secret against a blocklist of commonly used values, and ASVS v5 §6.2.4 asks for it at **Level 1**. The previous default, `AllowAllBreachChecker`, approved everything: a deployment on defaults accepted `password1` and `12345678`, and the brute-force machinery never fired, because a spraying campaign that tries one password across ten thousand accounts never crosses any single account's threshold. The new default is offline — no network call, so it can be on by default where the HIBP checker could not. It refuses the base words behind the bulk of real-world weak passwords, keyboard walks, repeats, sequential runs, and any _decorated_ form of those: `Password1`, `P@ssw0rd`, and `PASSWORD123!` all reduce to the same base, which is why a few hundred entries stand in for a list many times longer. It is a floor, not a corpus — `password.blocklist` adds the deployment's own context words (§6.2.11), and `HibpBreachChecker` remains the opt-in upgrade to a real breach corpus. `AllowAllBreachChecker` is still exported for a deployment with a deliberate reason to screen nothing.
101
+
102
+ - **Password-change notification** ([`src/server/interfaces/email-provider.interface.ts`](src/server/interfaces/email-provider.interface.ts)). `IEmailProvider` gains an optional `sendPasswordChangedNotification`, fired after both a completed change and a completed reset. NIST SP 800-63B §4.6 requires the subscriber to be notified through a channel independent of the transaction that bound the new credential, and this was the one credential change the interface stayed silent about while announcing every MFA change unprompted. The classic takeover starts with a compromised mailbox — trigger a reset, complete it, delete the mail — so the notice is what turns "the victim finds out days later, at a failed login" into "the victim finds out now". Optional, so an existing provider keeps compiling; delivery failures never fail the password change.
103
+
104
+ - **An invitation is re-validated against its inviter at redemption** ([`src/server/services/invitation.service.ts`](src/server/services/invitation.service.ts)). The inviter's authority was checked when the link was minted and never again, so for the token's whole 48-hour life the invitation outlived the person behind it: an admin could send one, be banned and stripped of their role, and the invitee would still arrive as an admin of that tenant with a live session. That is a clean way to keep a foothold across the account kill switch, which makes the switch advisory. The inviter must now still exist, still be in good standing, still belong to the tenant, and still out-rank the role being granted. `POST /invitations` also gains `UserStatusGuard`, closing the window in which a just-suspended admin could still mint one. `rust-auth` takes the same change.
105
+
106
+ - **A completed password change or reset invalidates the reset tokens issued beside it** ([`src/server/services/password-reset.service.ts`](src/server/services/password-reset.service.ts)). Each `forgot-password` writes its own `pw_reset:` key, so several can be alive at once — a 60-second cooldown against a 600-second TTL allows up to ten. Completing a reset with one left the others valid, which is the wrong end state precisely when it matters: a victim who resets _because_ an attacker read a link from their mailbox had not closed the link the attacker read, and the attacker could set the password again for the rest of the TTL. Each token now carries `passwordFingerprint` — a digest of the password hash in force when it was minted — and is refused once that no longer matches. The hash itself never leaves the repository. An absent field reads as "no binding" and is accepted, so a rolling deploy does not break the resets already in flight.
107
+
108
+ - **Revoking a named session cuts its access token too** ([`src/server/services/session.service.ts`](src/server/services/session.service.ts)). `DELETE /sessions/:id` deleted the refresh session, which stops rotation but says nothing about the stateless access token that device is already carrying — and that token kept working until it expired, up to whatever `jwt.accessExpiresIn` allows. Someone who opens their session list and revokes a device does so because they think it is compromised: a decision about _right now_. The new `SessionService.revokeOtherSession` bumps the token epoch, which is the only lever available since a session hash names no `jti`. The collateral is that the account's other devices re-mint their access token on the next rotation, which the shipped client does silently. `logout` deliberately keeps the plain `revokeSession`: it blacklists its own `jti` by name, and ending one session must not reach every other device.
109
+
110
+ - **Failure-side hooks: `onLoginFailed`, `onLockout`, `onRefreshTokenReuseDetected`** ([`src/server/interfaces/auth-hooks.interface.ts`](src/server/interfaces/auth-hooks.interface.ts)). Every one of the fourteen existing hooks fired on a success path, which left the failure side of authentication with no structured seam at all: a burst of wrong passwords, an account tripping its lockout, and a stolen refresh token being replayed existed only as English log lines whose wording is not a contract and whose change is not semver-visible. ASVS v5 §16.3.1 expects authentication operations to be logged with their outcome and §6.1.1 an _adaptive_ response, which needs a signal to adapt to. `onLoginFailed` carries the reason and — only when the account resolved — the user id, so a consumer can tell "someone is guessing at this account" from "someone is spraying addresses". `onLockout` fires on the attempt that _crosses_ the threshold, not the next one, because an attacker who trips the lock and walks away would otherwise never produce the event. `onRefreshTokenReuseDetected` is the strongest evidence of compromise the library produces: a token already exchanged has been presented again, so one of its two holders is not the owner.
111
+
112
+ - **Reuse detection can finally name its victim, and fires on the platform plane too**
113
+ ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)).
114
+ `revokeFamily` now returns `{ removed, ownerId }` instead of a bare count. The owner could
115
+ not be read any other way: the replayed token's own `rt:` key is deleted the moment it is
116
+ rotated, so the previous lookup — `readSessionOwner('rt:' + sha256(oldRefresh))` — was
117
+ reading a key that reuse detection guarantees is gone, and `onRefreshTokenReuseDetected`
118
+ would have been skipped every time in production. The family index is the last surviving
119
+ link between a replayed token and an account, and the revocation already reads a member
120
+ record to find the session index it prunes. The platform rotation now emits the hook as
121
+ well: an operator watching for account takeover cares about a replayed platform token at
122
+ least as much as a dashboard one.
123
+
124
+ - **`POST /invitations/revoke` — withdrawing a pending invitation**
125
+ ([`src/server/controllers/invitation.controller.ts`](src/server/controllers/invitation.controller.ts)).
126
+ `controllers.invitations` has always been documented as "send, accept, **revoke** invitations"
127
+ and there was no revoke: an invitation provisions an account, at a role, inside a tenant, to
128
+ whoever holds the link — a credential in every sense — and once sent it stayed redeemable for
129
+ its whole TTL with nothing an operator could do about it. A link sent to the wrong address was
130
+ simply unrecoverable. ASVS v5 §6.1.1 expects an administrative path to invalidate a credential
131
+ that should no longer work.
132
+
133
+ The record is keyed by the hash of a token only the invitee's mailbox ever held, so nothing on
134
+ the issuing side could _name_ a pending invitation. A new `invidx:{tenantId}:{sha256(email)}`
135
+ index carries the invitation's TTL and points at its record; the email is hashed so a dump of
136
+ the keyspace does not enumerate who a tenant has been inviting. Re-inviting an address now
137
+ supersedes the previous invitation through that index rather than adding a second live token —
138
+ two tokens for one invitee is two chances for an intercepted link, and a revoke would only ever
139
+ have reached the newest. The revoker is held to the same bar as the issuer (in the tenant, in
140
+ good standing, out-ranking the granted role), and the endpoint answers `204` whether or not
141
+ anything was pending, so it cannot be used as an oracle for which addresses have invitations.
142
+
143
+ - **`AuthService.unlockAccount(email, tenantId)` — clearing a brute-force lockout**
144
+ ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). A lockout is
145
+ a denial of service the library imposes on its own users, and it could only be waited out:
146
+ the counter is keyed by an HMAC of `{tenantId}:{email}` under the library's own `hmacKey`,
147
+ which no consumer can derive, so a support desk facing "I am locked out and I need in now"
148
+ had nothing to offer. The lockout is also the lever an attacker pulls to deny service to one
149
+ specific account, which makes the ability to undo it part of the defence rather than a
150
+ convenience (ASVS v5 §6.1.1). It grants no access — the password, the status gate, the
151
+ verification gate and MFA all still apply; it restores the ability to _try_. No route ships
152
+ with it, because who may unlock whom is a decision only the host application can make.
153
+ `BruteForceService` is now exported for consumers building their own lockout tooling.
154
+
155
+ - **The session index is maintained by the rotation script, not after it**
156
+ ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)).
157
+ `rotateRefreshSession` now takes the owner and does the `sess:{userId}` bookkeeping inside
158
+ the Lua. Doing it in the service afterwards left a window between the atomic consume and the
159
+ `SADD` in which "log out everywhere" could sweep the index without seeing the session the
160
+ rotation had just minted: that session survived a revocation the user was told had happened,
161
+ and went on rotating — re-stamping a fresh access token under every later epoch, so the token
162
+ epoch did not contain it either. The window is attacker-aimable: a thief holding a stolen
163
+ refresh token and refreshing in a loop is most likely to be mid-rotation exactly when a
164
+ password reset is trying to evict them. Inside the script the two operations serialize —
165
+ either the sweep sees the new member and revokes it, or the rotation runs after the sweep and
166
+ finds no live key to rotate. Held byte-compatible with rust-auth, which rotates the same
167
+ sessions.
168
+
169
+ The grace-recovery path still writes its session after the script (the recovered identity is
170
+ only known once the script has answered), so it keeps a much narrower version of this window.
171
+ Unlike the primary path it cannot be summoned on demand — it is reachable only by a client
172
+ retrying a rotation whose response it lost, inside a grace window measured in seconds.
173
+
174
+ - **A recovery code is claimed before it is accepted**
175
+ ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts)). Consuming a
176
+ recovery code is a read-modify-write against the consumer's user repository: the challenge
177
+ reads the whole array, removes one entry, and writes the rest back. Two challenges landing
178
+ together both read the array containing the code, both match it, and both write — one code
179
+ minting two sessions, which is the one property a recovery code has. The library cannot make
180
+ the consumer's repository atomic, because that repository is theirs and its atomicity is
181
+ theirs to define; it can be atomic in the store it owns. A `SET NX` over
182
+ `rcu:{hmac(plane:userId:code)}` claims the code, and the losing challenge reads as an invalid
183
+ code — which is what a code already spent is. Same construction as the TOTP anti-replay
184
+ marker, for the same reason: the key discloses neither the user nor the code, and binding the
185
+ plane stops a dashboard user and a platform admin sharing an id from burning each other's
186
+ codes. The marker is deliberately short-lived (5 minutes): it serializes a race, it is not
187
+ the durable record of consumption, and outliving the repository write would turn a failed
188
+ write into a code the account can see but can never use.
189
+
190
+ - **`jwt.issuer` and `jwt.audience` — binding tokens to who minted them and who they are for**
191
+ ([`src/server/utils/verify-with-rotation.ts`](src/server/utils/verify-with-rotation.ts)).
192
+ Optional and absent by default, so an existing deployment is unchanged. When set, the value
193
+ is stamped on every token the backend mints — access, platform and MFA challenge alike — and
194
+ **required** on every token it verifies: one carrying a different value, or none at all, is
195
+ rejected. Accepting an unstamped token would give an attacker a way to opt out of the check
196
+ simply by omitting the claim.
197
+
198
+ This matters here specifically because HS256 means the verifier can also sign. Every service
199
+ holding the secret to check a token can mint one, so audience binding is what stops a token
200
+ minted for one service being replayed at another that trusts the same secret. It is opt-in
201
+ because both backends of a shared deployment must carry the same pair or they stop accepting
202
+ each other's tokens, and because turning it on invalidates the access tokens already in
203
+ flight — a window of one access-token lifetime, which clients close by refreshing, since the
204
+ refresh token is opaque and carries no claims.
205
+
206
+ An empty string reads as unconfigured rather than as "require the empty issuer", so a
207
+ consumer threading an unset environment variable through does not silently turn the check on
208
+ and start minting tokens their own verifier rejects.
209
+
210
+ - **`createAuthValidationPipe` and `auth.validation`** ([`src/server/pipes/auth-validation.pipe.ts`](src/server/pipes/auth-validation.pipe.ts)). Nest's default rejection is `{ statusCode, message, error }`, while everything else this library throws answers `{ error: { code, message, details } }` — so a client parsing `error.code` needed a second parser, and the one shape it could not read was the one that says which field to fix. Every auth controller now mounts the shared pipe, which raises `auth.validation` with the per-field failures as `[{ field, message }]` under `error.details`. Same code and same shape `rust-auth` emits.
211
+ - **`AuthExceptionFilter` and `auth.internal`** ([`src/server/filters/auth-exception.filter.ts`](src/server/filters/auth-exception.filter.ts)). Opt-in, because a library does not get to decide how an application answers failures it did not raise. Registered, it gives every failure the library envelope: an `AuthException` passes through with its `details` intact, a body already in the envelope is left alone, any other `HttpException` keeps the status the application chose, and an unhandled throw answers `auth.internal` with the generic message — never the thrown one, which is the one path where a stack detail or a connection string would reach a response body. `rust-auth` answered `auth.internal` in its own envelope already.
212
+ - **`PlatformAuthService`, `InvitationService` and `EmailChangeService` are exported** ([`src/server/index.ts`](src/server/index.ts)). Every other service already was, for consumers driving a custom route; these three had the same reason to be.
213
+ - **`identifierPreimages`, `requestFieldBounds` and `errorCatalog` in the shared contract** ([`conformance/wire-contract.json`](conformance/wire-contract.json)). The preimages each backend HMACs, the length bounds every request DTO applies, and the full `auth.*` vocabulary with the codes that must never reach a client. Both conformance tiers assert against them by exercising the real derivations and the real validators, not by reading the numbers back to themselves. Writing the catalog down immediately found that `rust-auth`'s own catalog test was missing three codes it does emit.
214
+
215
+ ### Changed
216
+
217
+ - **The release publishes with `npm publish` rather than `pnpm publish`.** pnpm 11
218
+ does not send the registry's `readme` field; every package in this family
219
+ published under it carries an empty one, which renders the npm page with no
220
+ documentation. It already cost this family two corrective patch releases.
221
+ - **Dependabot groups the `github/codeql-action/*` bumps.** Split one per
222
+ sub-action, merging any single one leaves the default branch with mismatched
223
+ versions — `init` writes a config that `analyze` refuses to read back.
224
+
225
+ - **The stored password hash records the parameters it was written under** ([`src/server/services/password.service.ts`](src/server/services/password.service.ts)). The format is now `scrypt:{N}:{r}:{p}:{salt}:{derived}`. Without this a verify can only assume the cost configured today, which made `password.costFactor` unchangeable: raise it and every stored hash becomes unreproducible — every user locked out, irreversibly, because the value they were derived under is gone. No test could see it, because a suite that writes and reads inside one configuration never represents "written yesterday, read today under a new setting". `rust-auth` has always carried its parameters (PHC strings); this is the same guarantee.
226
+ - **Rehash on verify** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). A hash written under weaker parameters is re-derived at the current cost after a successful login and stored, fire-and-forget. This is what makes raising the cost factor a migration rather than a mass invalidation — `rust-auth` had it, this side did not.
227
+ - **`mfaEnabled` is required on a stored session record.** It used to default to `false` when absent, which turns a truncated or corrupt record into a silent second-factor bypass: the gate refuses only a token whose claims say `mfaEnabled && !mfaVerified`, so a missing field reads as "no second factor here" and the rotated token clears every MFA-gated route. Refusing the record costs the holder a login; defaulting it costs the account. Same change on both sides.
228
+ - **The decoy derivation no longer reads a stored hash.** With parameters recorded per hash, a constant decoy would carry whatever they were the day it was generated, and the moment a deployment configured a different cost it would stop taking the same time as a real verify — reopening the timing oracle it exists to close. It derives under the configured parameters instead.
229
+
230
+ - **`OAuthProfile.emailVerified` is now required** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts)). `createWithOAuth` was called with `emailVerified: true` unconditionally. There is no bug today — the one shipped plugin is Google's, and it refuses an unverified profile before building one — but the roadmap opens `oauth.plugins` for GitHub, Microsoft and Apple, and GitHub hands back unverified addresses. The field cannot be defaulted to `true` without reintroducing exactly that assumption. **Breaking** for anyone implementing a custom OAuth plugin.
231
+ - **`cookies.sameSite: 'none'` now requires `cookies.trustedOrigins`**, and the allowlist is refused only where it genuinely cannot be consulted ([`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). `'none'` with no list rejects every cross-site call, so that half is required. The inverse holds only for a single host: `lax` withholds the cookie cross-**site**, not cross-**origin**, so a deployment serving `app.example.com` and `api.example.com` from one `.example.com` cookie is same-site and the browser does send it — while `Sec-Fetch-Site: same-site` is not proof the request came from the app itself, so the guard falls through to the origin check. The list is therefore accepted whenever `cookies.resolveDomains` is configured, and still refused without one. **Breaking** for a deployment already on `SameSite=None`.
232
+ - **Signing out other devices now advances the token epoch** ([`src/server/services/session.service.ts`](src/server/services/session.service.ts)). Deleting a refresh session stops that device rotating, but its already-issued access token is stateless and kept verifying for the rest of its lifetime — up to `jwt.accessExpiresIn` of continued access on a device the user had just revoked. Someone doing that because they believe a device is compromised means now. The caller's own access token is invalidated too, and the caller is the one party who recovers instantly: their refresh session is the one deliberately preserved. **Behavioural** for a client without silent refresh, which sees one 401 after the call.
233
+ - **The default scrypt cost is `131072` (2¹⁷)**, OWASP's recommended minimum at `r=8, p=1`, up from `32768`. **Behavioural**: roughly 128 MiB and ~100 ms per hash. Lower `password.costFactor` deliberately if the memory is not there.
234
+ - **A duplicate registration now spends the same derivation as a new one** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). Skipping it was cheaper and leaked: a taken address answered in single-digit milliseconds against ~100 ms for a free one, which enumerates accounts by clock regardless of the status code.
235
+ - **`revokeAllUserTokens` is removed** ([`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts)). The password reset names its two steps directly. **Breaking** for a consumer calling it.
236
+
237
+ - **Every OTP failure answers `auth.otp_invalid`, in the same time.** `forgot-password` answers the same whether or not the address exists — but it only writes an OTP record when it does, so `auth.otp_expired` for an absent record and `auth.otp_invalid` for a wrong code turned that uniform answer definitive after one extra request. `auth.otp_max_attempts` said the same thing more slowly, since only a record that exists can reach a ceiling. Both sentinels stay in the catalog as internal, diagnostic codes — the treatment `auth.token_expired` and `auth.token_revoked` already get. `rust-auth` collapses them the same way, and now derives the HTTP status from the wire code so the oracle does not survive as 429-vs-401.
238
+ - **The reset and verification flows canonicalize the address** ([`src/server/services/password-reset.service.ts`](src/server/services/password-reset.service.ts), [`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). Every control on them is keyed on `hmac(tenantId:email)` — the OTP record, its five-attempt ceiling, the resend cooldown — so a change of case was a change of key: the same six-digit code could be guessed five times per spelling, and one send per minute became one send per spelling. `login` and `register` had always canonicalized; the four reset doors and both verification doors had not. `rust-auth` normalizes on all of them, which is what made this a disparity rather than a shared blind spot.
239
+ - **The invitee index is keyed by an HMAC of the address** ([`src/server/services/invitation.service.ts`](src/server/services/invitation.service.ts)). It used a bare SHA-256, which an address carries far too little entropy to survive — and this key is the one handle anyone reading a keyspace dump has on who a tenant has been inviting, which is the reason every other identifier here is an HMAC. **Breaking for the keyspace:** invitations pending across the upgrade stay redeemable but can no longer be superseded or withdrawn by address. Same change on both sides, pinned by the contract.
240
+ - **OAuth runs the configured `tenantIdResolver`, and tells `onOAuthLogin` what it resolved** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts)). Every other entry point already did, on the stated principle that a deployment deriving the tenant from the request has said the caller's value is not to be trusted — and this is the door that decides which tenant an account gets provisioned into. The resolved value goes into the state record, so the callback cannot be talked into a different one. The hook context now carries that tenant and the verified address: `onOAuthLogin` is the only place a deployment can enforce tenant membership, and it was being asked to decide without being told which tenant. **Breaking:** `initiateOAuth` takes the request as its third argument.
241
+ - **The new password is judged before any reset proof is spent** ([`src/server/services/password-reset.service.ts`](src/server/services/password-reset.service.ts)). Every proof is single-use and consumed atomically, so a breach-list rejection that arrived afterwards burned it: the caller was told their password was unacceptable and, in the same breath, that the credential they needed to fix it was gone. Same change on both sides.
242
+ - **`revokeInvitation` answers an outranked revoker exactly as it answers an address with nothing pending** ([`src/server/services/invitation.service.ts`](src/server/services/invitation.service.ts)). The caller names an address and nothing else, so `INSUFFICIENT_ROLE` said "there is a pending invitation here, at a role above yours" while `204` said "there is none" — an oracle any member could walk an address list through, and precisely the disclosure hashing the address into the index exists to prevent. The revoker's own standing is a fact about the caller, so it still refuses out loud, and now does so before any lookup.
243
+ - **The platform login password floors at 1, not 12** ([`src/server/dto/platform-login.dto.ts`](src/server/dto/platform-login.dto.ts)). A policy floor on a door that _proves_ a credential refuses an operator whose password predates the current policy — with a validation error rather than an authentication one — and tells an unauthenticated caller what the policy is before any key derivation runs. The dashboard login always floored at 1 and `rust-auth` bounds the field the same way. Blank is still refused.
244
+ - **Request bounds are held identical to `rust-auth`'s** and pinned by `requestFieldBounds`. The email-verification OTP is exactly six digits on both sides, which is the only length either backend issues.
245
+ - **`controllers` returned from `useFactory` is now a startup error** ([`src/server/bymax-auth.module.ts`](src/server/bymax-auth.module.ts)). Nest decides a module's shape before any factory runs, so the flags were read by nothing: the endpoints they were meant to enable were simply absent, surfacing as a 404 whose cause lives in a different object from the one the developer edited. It had been documented for as long as it existed; documentation is not a control.
246
+
247
+ ### Removed
248
+
249
+ - **Every legacy-compatibility path in the credential surface.** The libraries are new and
250
+ unreleased into production, so a parsing allowance for a corpus that does not exist is a
251
+ widened input for nothing — and each of these sat in the credential-verification core, which
252
+ is exactly where an unused branch is most expensive:
253
+ - the parameterless `scrypt:{salt}:{hash}` password form,
254
+ - the `scrypt:`-prefixed recovery-code digest, which cost one key derivation **per stored
255
+ code** on every wrong submission — an amplifier reachable by anyone holding a temp token,
256
+ - the UUID-v4 refresh-token shape,
257
+ - and the corresponding `refreshTokenLegacy` / `recoveryCodeDigestLegacy` contract entries.
258
+
259
+ - **Five error codes nothing could emit.** `SESSION_EXPIRED` and `SESSION_LIMIT_REACHED` describe behaviours the library chose not to have — rotation answers `REFRESH_TOKEN_INVALID`, and the session cap evicts rather than refuses. `RECOVERY_CODE_INVALID` is unreachable on purpose: a wrong recovery code answers `MFA_INVALID_CODE`, so a caller cannot learn which kind of credential they guessed wrong. `PASSWORD_TOO_WEAK` is the DTO's job, and `PASSWORD_RESET_TOKEN_EXPIRED` was documented as unreachable by design. A code nothing can emit is a client branch that never fires. **Breaking** for a consumer switching on them; gone from both libraries.
260
+ - **`AuthRedisModule`** ([`src/server/redis/auth-redis.module.ts`](src/server/redis/auth-redis.module.ts)). It documented itself as imported by `BymaxAuthModule`, which registers `AuthRedisService` directly instead — reachable from nothing, and its own docblock said otherwise.
261
+ - **`sessions.evictionStrategy`.** A union of one value: a knob that configures nothing while looking like a choice. Eviction is still FIFO, and the caveat the option carried — that it is silent, so an attacker opening a session pushes a legitimate one out with no signal — moves onto the limit it actually describes.
262
+ - **The unreachable platform branches in the dashboard MFA controller** ([`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts)). `JwtAuthGuard` runs `assertTokenType(payload, 'dashboard')`, so a platform token never reaches it — the platform surface has its own controller. The tests that covered the arm were feeding the methods a payload the guard would have refused, which is how a branch stays at 100% while being unreachable.
263
+
264
+ ### Fixed
265
+
266
+ - **CommonJS consumers resolved ESM type declarations, on every subpath.** The
267
+ `exports` map declared a single `types` condition, so `require()` landed on
268
+ `.d.ts` instead of the `.d.cts` that was being built all along — `attw` reports
269
+ it as _Masquerading as ESM_ on all five subpaths of the published `1.0.11`.
270
+ - **`node10` type resolution failed outright**, the manifest carrying no `main`,
271
+ `module`, `types` or `typesVersions`. A resolver that does not read the
272
+ `exports` map found nothing at all. Each `typesVersions` entry lists the
273
+ CommonJS declaration first and the ESM one as a fallback: a resolver old enough
274
+ to ignore the `exports` map may also be old enough not to load a `.d.cts`, and
275
+ would then find no declarations at all — the state `typesVersions` exists to
276
+ prevent. TypeScript takes the first path that resolves, so nothing changes for a
277
+ toolchain that understands `.d.cts`. `@types/react` 19 ships the same shape for
278
+ TypeScript 5.0 and below. The package root is covered too, keyed on the path in
279
+ `types` rather than on `"."` — TypeScript matches `typesVersions` patterns against
280
+ the value of the `types` field, so a `"."` entry never fires.
281
+ - **Four README examples did not compile against the package they document.** The
282
+ module-registration example omitted `rateLimit`, which is a required option group;
283
+ the client example omitted `baseUrl` and a comment claimed it was needed only
284
+ cross-origin, when `AuthClientConfig` requires it (a relative `'/api'` is what
285
+ routes through the Next.js proxy); a component read `user.name` after checking
286
+ `status`, which does not narrow the separate `user` field away from `null`; and the
287
+ proxy example passed `process.env.JWT_SECRET` into an optional property, which
288
+ `exactOptionalPropertyTypes` refuses. Every one of them is a type error the moment
289
+ a reader pastes it. `pnpm check:published` compiles the README's snippets against
290
+ `dist/`, and it was not run before.
291
+ - **`check:published` collected links from inside fenced code blocks.** An
292
+ `<a href="${url}">` in an example email template is a string the example builds at
293
+ runtime, not a link a reader can click, and the checker tried to resolve the
294
+ placeholder as a repository path. It now reads the prose, as the anchor check
295
+ already did.
296
+
297
+ - **The platform guard never read the token epoch back** ([`src/server/guards/jwt-platform.guard.ts`](src/server/guards/jwt-platform.guard.ts)). Platform access tokens have carried an `epoch` stamp since they were introduced — issuing reads `pep:{sub}` — but the guard never consulted it, so a platform epoch bump revoked nothing: the mechanism existed on the wire and was dead on the door. `rust-auth`'s verify has always enforced the admin epoch; the guard now mirrors `JwtAuthGuard` with the platform key.
298
+ - **An auth-state change now revokes the outstanding access tokens too** ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts), [`src/server/services/platform-auth.service.ts`](src/server/services/platform-auth.service.ts)). Enabling or disabling MFA, and the platform "log out everywhere", invalidated the refresh sessions but left every access token working to expiry. For MFA enable that is the worst possible window: every pre-enable token is stamped `mfaEnabled: false`, and the MFA gate refuses only `mfaEnabled && !mfaVerified` — so a stolen token kept clearing every MFA-gated route at the exact moment the user enabled a second factor because they suspected that theft. All three flows now advance the plane-scoped token epoch alongside the session sweep, the same rule the password-reset flow already applied. ASVS requires stateless tokens relied on for access control to be revocable on an auth-state change; same change on both sides.
299
+ - **Every auth response is stamped `Cache-Control: no-store`** ([`src/server/interceptors/no-store.interceptor.ts`](src/server/interceptors/no-store.interceptor.ts)). RFC 6749 §5.1 requires it on any response carrying a token, and a CDN or corporate proxy that caches a login response serves one user's tokens to the next caller. The Next.js proxy layer already set it on its own responses; nothing set it for consumers reaching the NestJS API directly. Applied per-controller via an interceptor (with `Pragma: no-cache` for HTTP/1.0 intermediaries) and pinned by a test that fails if a future controller forgets it. `rust-auth` stamps the identical headers via router middleware.
300
+ - **A grace pointer could resurrect a revoked lineage** ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)). Reuse detection only proves the _replayed_ token's own pointer expired; a pointer planted by an earlier rotation of the same lineage can still be live, and recovering from it handed the thief back the family the revocation had just killed. A recovery now requires its family index to still exist. Red-checked: the test needs a three-token lineage to fail without the fix.
301
+ - **The MFA challenge did not re-check account status** ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts)). A temp token stays valid for its whole TTL, so an account blocked between the password step and the second factor could still complete the challenge.
302
+ - **Platform sessions shared the dashboard's Redis index** ([`src/server/redis/auth-redis.service.ts`](src/server/redis/auth-redis.service.ts)), so "sign out everywhere" on one plane could reach the other.
303
+ - **Recovery-code verification amplified CPU** ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts)) by running the KDF once per stored code; refresh tokens widened to the documented entropy.
304
+ - **The client parsed its own error shape rather than the server's envelope** ([`src/client/createAuthClient.ts`](src/client/createAuthClient.ts)), so `code` and `details` were lost on every failure.
305
+ - **Logout left the rotation grace pointer behind** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). It deleted `rt:{hash}` but not `rp:{hash}`, so a refresh token that had already rotated and was still inside its grace window could recover into a fresh session _after_ the user logged out — logout was final only for a token that had not yet rotated. The platform plane already cleared its `prp:` twin.
306
+ - **An OAuth `create` onto an address that was already taken surfaced as a 500** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts)). `findByOAuthId` cannot see an account that owns the address without being linked to this OAuth identity — a local registration, or a link to another provider — so the insert hit the repository's uniqueness constraint and became an opaque error. It is a conflict and it is actionable (sign in and link instead), so it answers **409 `auth.oauth_email_mismatch`**, the code and status `rust-auth` already returned. The concurrent case still reaches the constraint: `IUserRepository` is host-implemented and its errors are untyped.
307
+
308
+ - **Both login doors answered before proving the password** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts), [`src/server/services/platform-auth.service.ts`](src/server/services/platform-auth.service.ts)). The status and email-verification gates ran ahead of the KDF, so a caller who never held the credential learned an account's moderation state from the error code alone — and learned it in single-digit milliseconds, because the derivation was skipped. A wrong password now answers `INVALID_CREDENTIALS` whatever the account's state is, and only the password holder is told why they still cannot sign in. Same change on both sides.
309
+ - **A tenant named `platform` shared the platform lockout counter.** The brute-force identifier was written out by hand at four call sites as `dashboard:${tenantId}:${email}`, while the platform door builds `platform:${email}` — and `tenantId` comes from the request body whenever no resolver is configured, which is the default. Nothing stopped the two preimages colliding, so five unauthenticated dashboard logins against an operator's address could lock that operator out of the console, repeatably, without the platform surface being touched — and a successful one cleared their lockout mid-attack. Both planes now derive through a single private helper, and the three preimages are pinned by the contract.
310
+ - **Platform rotation never re-read the admin** ([`src/server/services/platform-auth.service.ts`](src/server/services/platform-auth.service.ts)). It worked entirely from the session record, so blocking an administrator closed only the login door: they kept minting access tokens for the refresh token's whole lifetime, which ASVS v5 §7.4.2 asks a disable to end. A blocked or deleted admin now loses every platform session, including the one just minted.
311
+ - **Rotation froze the role and the tenant** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). Claims were built from the session record written at login and inherited unchanged through every later rotation, so demoting an ADMIN to MEMBER, or moving a user between tenants, had no effect on a live session for up to seven days — while every role guard reads that claim. The gates above already re-read the account; the current authority was sitting there, unused. It is re-stamped now, and only when it differs.
312
+ - **The WebSocket guard leaked `TOKEN_REVOKED`** ([`src/server/guards/ws-jwt.guard.ts`](src/server/guards/ws-jwt.guard.ts)). `JwtAuthGuard` deliberately collapses a revoked token into `TOKEN_INVALID` so a caller cannot distinguish "valid until someone logged it out" from "never valid". The upgrade handshake is a cheaper place to ask that question, not a more private one.
313
+
314
+ ### Tests
315
+
316
+ - **`responseBodies` joins the contract, and it caught a real one.** The tier covered stored
317
+ records, claims and prefixes but never the client-facing payloads — the shapes a consumer's
318
+ TypeScript actually describes. `rust-auth`'s generated type named the platform account `user`
319
+ while its own adapter emitted `admin`, so a consumer reading `result.user` got `undefined` at
320
+ runtime. Both sides now assert the login body per delivery mode, the platform body, the
321
+ challenge and the ws-ticket against what each serializes. The cookie-mode entry is the
322
+ load-bearing one: the tokens are in `Set-Cookie` so script cannot read them, and a refresh
323
+ token repeated in the JSON body would make the HttpOnly flag decorative.
324
+ - **The conformance tier now covers every section of the shared contract.**
325
+ `credentialFormats` was read as prose — the assertions checked that the agreement still said
326
+ what it said, which a drift in the implementation leaves green — and `errorEnvelope` was not
327
+ asserted at all. Both are now pinned against what the code actually does: a minted refresh
328
+ token, a TOTP secret prepared the way `MfaService` prepares it, and a real serialized
329
+ exception. The envelope assertion is what surfaced a live divergence: `rust-auth` was omitting
330
+ `error.details` where this library sends `null`, so a client reading both backends saw two
331
+ shapes for one meaning.
332
+
333
+ - **100% mutation score** ([docs/mutation_testing_results.md](docs/mutation_testing_results.md)) — 3,474 seeded faults killed, no survivors and nothing left uncovered, against a `break` threshold of 95. The pass closed 57 open mutants across 19 files; not one was a bug in the library, and every one was a test that could not see its own subject.
334
+ - **2,458 tests** at 100% coverage on all four metrics, including a conformance tier that reads `conformance/wire-contract.json` — the same file `rust-auth` reads — and an adversarial suite for the credential paths.
335
+
336
+ ### Security
337
+
338
+ - **Secrets are no longer disclosed when an injected provider is serialized.** The signing
339
+ secret, its rotation predecessors, the HMAC keys derived from them and each configured
340
+ OAuth `clientSecret` were plain fields on the resolved options, and `AuthRedisService`
341
+ held its ioredis client — which carries `options.password` — in a TypeScript `private`
342
+ property, which is erased at runtime. The resolved options are injected into roughly a
343
+ dozen guards, controllers and services, so `JSON.stringify`, object spread and
344
+ `util.inspect` on any of them emitted key material in plaintext. That is what a
345
+ structured logger does when it renders its arguments, and what an error reporter does
346
+ when it captures the scope of a throw. Every one of those fields is now a
347
+ non-enumerable accessor or an ECMAScript private field, withheld from `showHidden` as
348
+ well. Reads are unchanged, no public type moved, and the consumer's own options object
349
+ is never rewritten — the OAuth provider configs are copied before being adjusted.
350
+
351
+ - **Peer floors raised to exclude known-vulnerable versions.** Three declared
352
+ ranges admitted versions carrying published advisories:
353
+
354
+ | Peer | Was | Now | Advisories cleared |
355
+ | ---------------- | --------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
356
+ | `@nestjs/common` | `^11.0.0` | `^11.0.16` | [GHSA-cj7v-w2c7-cp7c](https://github.com/advisories/GHSA-cj7v-w2c7-cp7c) — remote code execution via the `Content-Type` header |
357
+ | `@nestjs/core` | `^11.0.0` | `^11.1.18` | [GHSA-36xv-jgw5-4q75](https://github.com/advisories/GHSA-36xv-jgw5-4q75) — improper neutralization of special elements in downstream output |
358
+ | `next` | `^16.0.0` | `^16.2.11` | 37 advisories, worst high — SSRF in Server Actions and in rewrites, middleware/proxy bypasses, several DoS paths |
359
+
360
+ A peer range is a statement about which versions this library supports. A floor
361
+ below a published advisory tells a consumer that a vulnerable install is a
362
+ supported one, and nothing in their tooling contradicts it — the install
363
+ resolves cleanly and silently. Dependabot does not catch this: it audits what
364
+ is installed in this repository, never what the package declares it supports.
365
+
366
+ Each new floor is the highest first-patched version among the advisories that
367
+ range admitted, which is what clears every one of them at once. No runtime
368
+ behaviour changed.
369
+
10
370
  ## [1.0.11] - 2026-05-30
11
371
 
12
372
  ### Security
@@ -308,7 +668,12 @@ The full e2e count goes from **9 suites / 59 tests** to **14 suites / 89 tests**
308
668
  - React subpath specs cover the `loading → authenticated / unauthenticated` state machine, revalidation loop, `onSessionExpired` firing policy (transition-only, not on mount or explicit logout), MFA challenge short-circuit, and the three hook selectors
309
669
  - Existing `error-codes.spec.ts` drift guard between `server` and `shared` `AUTH_ERROR_CODES`
310
670
 
311
- ## [1.0.0] - 2026-04-16
671
+ ## Pre-release development — 2026-04-16
672
+
673
+ This section predates the first publish. `1.0.0` reached npm on 2026-05-25 and is
674
+ the section above; what follows is the scaffold-and-foundation work that led to it,
675
+ kept for history and deliberately not labelled as a release — no such version was
676
+ ever installable.
312
677
 
313
678
  ### Added
314
679
 
@@ -648,3 +1013,18 @@ The full e2e count goes from **9 suites / 59 tests** to **14 suites / 89 tests**
648
1013
  - Phase 4 session tests cover: `createSession` FIFO eviction, `listSessions` `isCurrent` marking, `revokeSession` ownership check, `revokeAllExceptCurrent` current-session preservation, `rotateSession` atomic rename, and stale member cleanup
649
1014
  - 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
650
1015
  - 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
1016
+
1017
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.1.0...HEAD
1018
+ [1.1.0]: https://github.com/bymaxone/nest-auth/compare/v1.0.11...v1.1.0
1019
+ [1.0.11]: https://github.com/bymaxone/nest-auth/compare/v1.0.10...v1.0.11
1020
+ [1.0.10]: https://github.com/bymaxone/nest-auth/compare/v1.0.9...v1.0.10
1021
+ [1.0.9]: https://github.com/bymaxone/nest-auth/compare/v1.0.8...v1.0.9
1022
+ [1.0.8]: https://github.com/bymaxone/nest-auth/compare/v1.0.7...v1.0.8
1023
+ [1.0.7]: https://github.com/bymaxone/nest-auth/compare/v1.0.6...v1.0.7
1024
+ [1.0.6]: https://github.com/bymaxone/nest-auth/compare/v1.0.5...v1.0.6
1025
+ [1.0.5]: https://github.com/bymaxone/nest-auth/compare/v1.0.4...v1.0.5
1026
+ [1.0.4]: https://github.com/bymaxone/nest-auth/compare/v1.0.3...v1.0.4
1027
+ [1.0.3]: https://github.com/bymaxone/nest-auth/compare/v1.0.2...v1.0.3
1028
+ [1.0.2]: https://github.com/bymaxone/nest-auth/compare/v1.0.1...v1.0.2
1029
+ [1.0.1]: https://github.com/bymaxone/nest-auth/compare/v1.0.0...v1.0.1
1030
+ [1.0.0]: https://github.com/bymaxone/nest-auth/releases/tag/v1.0.0