@bymax-one/nest-auth 1.4.4 → 1.4.6

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/README.md CHANGED
@@ -726,6 +726,13 @@ export const config = {
726
726
  }
727
727
  ```
728
728
 
729
+ How the route lists match a path: an entry matches the path that equals it and anything under
730
+ it (`'/auth'` covers `/auth/login`), and takes no wildcards (`'/auth/*'` matches nothing). An
731
+ entry ending in `/` is a plain prefix, so `'/'` matches every path. In `publicRoutes` that is
732
+ harmless: `protectedRoutes` are tried first, and a path no list names is already let through. In
733
+ `publicRoutesRedirectIfAuthenticated` it sends a signed-in user to their dashboard from every page
734
+ that is not protected, so list the login and register pages there, never `'/'`.
735
+
729
736
  ```typescript
730
737
  // app/api/auth/silent-refresh/route.ts
731
738
  import { createSilentRefreshHandler } from '@bymax-one/nest-auth/nextjs'
@@ -786,14 +793,27 @@ const { ticket, expiresIn } = await fetch('/auth/ws-ticket', {
786
793
  const socket = new WebSocket(`wss://api.example.com/socket?ticket=${ticket}`)
787
794
  ```
788
795
 
789
- The ticket is opaque, 32 bytes of CSPRNG output, and lives 30 seconds. Only `sha256(ticket)` is
790
- ever a Redis key, and the stored value is a verified-identity **snapshot** — no `jti`, no
791
- signature, no expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned
792
- back into a session. Minting requires an authenticated session in good standing that has already
796
+ The ticket is opaque, 32 bytes of CSPRNG output, and lives at most 30 seconds, ending a second before the access
797
+ token that minted it does at the latest: `expiresIn` in the response is that capped lifetime in seconds, so a client
798
+ schedules its upgrade by it, and a token with no life left mints nothing. Only `sha256(ticket)` is
799
+ ever a Redis key, and the stored value is a verified-identity **snapshot** — no signature, no
800
+ expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned back into a
801
+ session. It carries the `jti` and `epoch` of the access token that minted it, the two keys the
802
+ revocation channels are read by, and redemption is refused when that token has been blacklisted by
803
+ a logout or stamped below the user's current epoch (sign-out-everywhere, password change, MFA
804
+ reset): a ticket does not outlive the session that asked for it. A logout blacklists only
805
+ the access token it was given and does not move the epoch, so a ticket minted from an access token
806
+ that a refresh had already replaced is not refused after that logout, as a bearer token of that
807
+ kind is not; it is refused only after a later epoch bump (a password reset or change, an MFA
808
+ enable, disable or reset, or revoking another session or all of them). Minting requires an authenticated session in good standing that has already
793
809
  satisfied MFA, so a ticket never carries more authority than the request that asked for it.
794
810
 
795
811
  Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
796
- both channels are accepted, and a ticket wins when both are present.
812
+ both channels are accepted, and a ticket wins when both are present. `WsJwtGuard` checks
813
+ signature, token type and revocation on the Bearer path but not account status or MFA; where the
814
+ socket must also refuse a blocked account or an unfinished second factor, authorize with
815
+ `AuthTokenVerifierService.verifyAccessToken` (see
816
+ [Authorising a long-lived transport](#authorising-a-long-lived-transport--authtokenverifierservice)).
797
817
 
798
818
  Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
799
819
  `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
@@ -813,11 +833,12 @@ All options are configurable via `registerAsync()`. Here are the key configurati
813
833
  | Group | Key Options | Default |
814
834
  | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
815
835
  | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, `30d` cap, `HS256`, both off |
836
+ | **identifierKey** | Top-level secret the Redis account identifiers and MFA recovery-code digests derive from; pin it before rotating `jwt.secret` | `jwt.secret` |
816
837
  | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
817
838
  | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
818
839
  | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
819
840
  | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
820
- | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
841
+ | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | `totpWindow` `1`, `recoveryCodeCount` `8` |
821
842
  | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
822
843
  | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
823
844
  | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
@@ -828,10 +849,10 @@ All options are configurable via `registerAsync()`. Here are the key configurati
828
849
  | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
829
850
  | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
830
851
  | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
831
- | **controllers** | Toggle individual controllers on/off | `auth`, `passwordReset` on; rest opt-in |
852
+ | **controllers** | Toggle individual controllers on/off — passed to `registerAsync()` itself, never returned from `useFactory` (which refuses it at startup) | `auth`, `passwordReset` on; rest opt-in |
832
853
 
833
854
  > [!NOTE]
834
- > When a feature is not configured (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead.
855
+ > When a feature is not enabled (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead. A feature is enabled by `controllers.<name>: true` on the `registerAsync()` call together with its configuration group (`mfa.encryptionKey` and `mfa.issuer`, `sessions.enabled`, `platform.enabled`); either half alone leaves it unregistered or fails at startup.
835
856
 
836
857
  > [!IMPORTANT]
837
858
  > **`environment` is how the module decides whether this is production, and it defaults to
@@ -897,6 +918,29 @@ All options are configurable via `registerAsync()`. Here are the key configurati
897
918
  > rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has
898
919
  > expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
899
920
  > way, through its own list — see below.
921
+ >
922
+ > **Pin `identifierKey` before you rotate.** Every Redis name that identifies an account — the
923
+ > session index, the token epoch, the MFA keys, the recent-authentication marker, and the OTP and
924
+ > rate-limit identifiers — is an HMAC under a key derived from `jwt.secret` unless you set
925
+ > `identifierKey`, and so are the stored MFA recovery-code digests. Rotate `jwt.secret` alone and
926
+ > all of them are renamed: live sessions lose their index, every token epoch reads zero, so a token
927
+ > that a password reset or a revoke-all had refused is accepted again until it expires, and
928
+ > recovery codes stop verifying unless the old secret is listed in `jwt.previousSecrets`. `identifierKey` is a secret of its own for those names and
929
+ > digests; it is validated like `jwt.secret` and never signs or verifies a token. The value is
930
+ > simply the secret you want them to keep deriving from — there is nothing to compute.
931
+ >
932
+ > | | Routine rotation — keep sessions, epochs and recovery codes | Rotation after a compromise — cut the link |
933
+ > | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
934
+ > | Before rotating | Once, set `identifierKey` to the value `jwt.secret` has **now** and deploy. Nothing moves: the derivation is unchanged. Later rotations leave it as it is. | Revoke what has to be revoked while the session index can still find it; afterwards nothing can be revoked through it, and refresh tokens, which are looked up by their own hash, keep working. Do not list the compromised secret in `jwt.previousSecrets`. |
935
+ > | Rotating | Put the new secret in `jwt.secret` and the old one in `jwt.previousSecrets`; keep `identifierKey` as it is. | Put the new secret in `jwt.secret` **and** choose a new `identifierKey`. |
936
+ > | Names | Unchanged. | Moved: sessions lose their index until they next refresh (meanwhile they are missing from the session list and cannot be revoked through it, and their refresh tokens still work until they expire), every epoch reads zero, MFA set-up state and lockout counters start empty, and stored recovery-code digests stop verifying. |
937
+ > | Revoked tokens | Stay revoked. | Tokens signed under the old secret no longer verify. A token signed under a secret that stays in `previousSecrets` and had been refused by an epoch is accepted again, because the epoch is renamed with the rest and revoking first does not carry it across: remove retired secrets from `previousSecrets` or wait out `jwt.accessExpiresIn`. |
938
+ > | Afterwards | Drop the old secret from `previousSecrets` once its last token has expired. | Users with MFA need new recovery codes: an old code is refused like any wrong code, and sign-in with the authenticator app is unaffected. A signed-in user replaces them with `POST /mfa/recovery-codes` (`POST /platform/mfa/recovery-codes` for an admin), proving a fresh OTP; the library does not regenerate them at the next sign-in or notify anyone, so your application prompts for it. Listing the secret the digests were keyed from (the old `identifierKey` value) in `previousSecrets` would keep the old codes working, and would keep tokens signed with it verifying if it was also a signing secret: that is the trade-off. |
939
+ >
940
+ > Pinning to the old secret leaves the derived Redis names computable by anyone who knows that
941
+ > secret. They are names, not signing material, and using one still needs access to your Redis;
942
+ > if cutting that link matters more than keeping sessions, take the second column. Without
943
+ > `identifierKey` a rotation moves the names as the second column does, whether or not you wanted them to.
900
944
 
901
945
  > [!TIP]
902
946
  > **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
@@ -954,7 +998,9 @@ All options are configurable via `registerAsync()`. Here are the key configurati
954
998
  > claim _usually_ wrong instead of _reliably_ empty, which is the failure mode that survives
955
999
  > testing.
956
1000
  >
957
- > Status is resolved per request or not at all: mount `UserStatusGuard` on the route, and for
1001
+ > Status is resolved per request or not at all: mount `UserStatusGuard` on the route (on a
1002
+ > WebSocket, SSE stream or message consumer, call `AuthTokenVerifierService.verifyAccessToken`,
1003
+ > which resolves status through the same cache before it applies the MFA policy), and for
958
1004
  > anything richer read the account **tenant-scoped**, the way that guard does —
959
1005
  > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is required by the
960
1006
  > port and cannot be dropped: ids may collide across tenants, so a lookup by bare id can resolve
@@ -965,10 +1011,13 @@ All options are configurable via `registerAsync()`. Here are the key configurati
965
1011
  >
966
1012
  > One consequence worth planning for: the guard reads a status cache with a
967
1013
  > `userStatusCacheTtlSeconds` window (default **60**), so a suspension takes up to that long to
968
- > bite on a guarded route, and a reactivation the same to restore. Nothing exported invalidates
969
- > that key for one user today — the only immediate lever is `bumpUserTokenEpoch`, which ends
970
- > every session the user has rather than refreshing one cached string. Lower the TTL if a faster
971
- > answer matters more than the repository reads it costs.
1014
+ > bite on a guarded route, and a reactivation the same to restore. Call
1015
+ > `AccountStatusService.invalidate({ userId, tenantId })` after persisting a status change to drop
1016
+ > that account's cached status immediately; a request already resolving can still write the old
1017
+ > value back, so the window narrows to one repository read rather than to zero (see
1018
+ > [Invalidating the account cache](#invalidating-the-account-cache--accountstatusserviceinvalidate)).
1019
+ > `bumpUserTokenEpoch` is the heavier lever: it ends every session the user has. Lower
1020
+ > `userStatusCacheTtlSeconds` if a faster answer matters more than the repository reads it costs.
972
1021
 
973
1022
  `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
974
1023
  **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
@@ -1113,7 +1162,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1113
1162
  | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
1114
1163
  | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
1115
1164
  | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), path-scoped |
1116
- | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
1165
+ | Brute-Force | Redis atomic counters per HMAC(email, identifier key) |
1117
1166
  | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
1118
1167
  | Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
1119
1168
  | Cross-Site Writes | `Origin` / `Sec-Fetch-Site` check on cookie-authenticated writes — the gap `SameSite=None` leaves open |
@@ -1135,7 +1184,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1135
1184
  <img src="https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white" alt="Next.js" />
1136
1185
  <img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
1137
1186
  <img src="https://img.shields.io/badge/Redis-7%2B-DC382D?style=flat-square&logo=redis&logoColor=white" alt="Redis" />
1138
- <img src="https://img.shields.io/badge/Jest-29-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
1187
+ <img src="https://img.shields.io/badge/Jest-30-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
1139
1188
  </p>
1140
1189
 
1141
1190
  ---
@@ -1145,9 +1194,9 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1145
1194
  Authentication is critical infrastructure, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
1146
1195
 
1147
1196
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
1148
- - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 5,333 seeded faults detected (5,311 killed, 22 timed out), **no survivors and nothing left uncovered**, against a `break` threshold of 100 ([measured cold on 2026-08-15](./docs/mutation_testing_results.md#re-measured-cold--2026-08-15))
1149
- - ✅ **3,971 tests** — 3,721 unit and 250 end-to-end, spanning all five subpaths
1150
- - ✅ **Every equivalent mutant documented** — the 367 mutants that no test can kill (a redundant guard, a dependency array of stable references) each carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
1197
+ - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/) against a `break` threshold of 100, **no survivors and nothing left uncovered** (the latest cold measurement is in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md))
1198
+ - ✅ **Thousands of tests** — unit and end-to-end, spanning all five subpaths
1199
+ - ✅ **Every equivalent mutant documented** — each mutant that no test can kill (a redundant guard, a dependency array of stable references) carries an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
1151
1200
 
1152
1201
  ```bash
1153
1202
  pnpm test # unit suite
@@ -1173,18 +1222,18 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
1173
1222
  | POST | `/logout` | Public (reads both credentials) | Revoke the session; blacklists the access token it is given |
1174
1223
  | POST | `/refresh` | Public (refresh cookie or body) | Rotate refresh token, issue new access token |
1175
1224
  | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
1176
- | POST | `/ws-ticket` | `JwtAuthGuard` | Mint a single-use ticket for a WebSocket upgrade |
1225
+ | POST | `/ws-ticket` | `JwtAuthGuard`, `UserStatusGuard` | Mint a single-use ticket for a WebSocket upgrade |
1177
1226
  | POST | `/verify-email` | Public | Verify email with OTP |
1178
1227
  | POST | `/resend-verification` | Public | Resend email-verification OTP |
1179
1228
  | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
1180
1229
  | POST | `/password/reset-password` | Public | Submit new password with reset token |
1181
1230
  | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
1182
1231
  | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
1183
- | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
1184
- | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
1232
+ | POST | `/mfa/setup` | `JwtAuthGuard`, `UserStatusGuard` | Generate TOTP secret and recovery codes |
1233
+ | POST | `/mfa/verify-enable` | `JwtAuthGuard`, `UserStatusGuard` | Confirm setup and enable MFA |
1185
1234
  | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
1186
- | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
1187
- | POST | `/mfa/recovery-codes` | `JwtAuthGuard` | Replace the recovery codes, proving a fresh OTP |
1235
+ | POST | `/mfa/disable` | `JwtAuthGuard`, `UserStatusGuard` | Disable MFA for the current user |
1236
+ | POST | `/mfa/recovery-codes` | `JwtAuthGuard`, `UserStatusGuard` | Replace the recovery codes, proving a fresh OTP |
1188
1237
  | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
1189
1238
  | POST | `/sessions/revoke-all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke every session except the caller's |
1190
1239
  | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
@@ -1337,6 +1386,30 @@ const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
1337
1386
  > whether this library is new enough to contribute them at all, and only then your nest-core
1338
1387
  > version. The two states look identical from the document.
1339
1388
 
1389
+ #### On `@bymax-one/nest-core` 1.6.1 or later, the request bodies are described too
1390
+
1391
+ The same contributor offers the request-body schema of every DTO that the controllers your
1392
+ deployment mounted take (`LoginDto`, `RegisterDto`, `ResetPasswordDto` and the rest), derived from
1393
+ their `class-validator` decorators. Without a contribution `@nestjs/swagger` registers each of them as
1394
+ `{"type":"object","properties":{}}`, because this package is built without its CLI plugin, and a
1395
+ client generated from the document types every request body as `{}`.
1396
+
1397
+ > **Request schemas appear with `@bymax-one/nest-core` ≥ 1.6.1; older versions ignore the
1398
+ > contribution without a signal.** Through 1.6.0 an empty placeholder counts as a declaration, so
1399
+ > the schema offered here is dropped and the document renders exactly as before: no error, no
1400
+ > warning, and no `discarded` field on what `applyBymaxOpenApi` returns. From 1.6.1 the
1401
+ > placeholder is filled from the contribution. A schema of the same name that carries properties
1402
+ > of its own is a declaration and wins, and `applyBymaxOpenApi` reports the contribution that
1403
+ > lost in `discarded`. Components are keyed by the DTO's class name, so a DTO of your own that
1404
+ > shares a name with one of this library's (a `LoginDto`, say) and is itself an empty placeholder
1405
+ > is filled with this library's schema: name your own classes differently.
1406
+
1407
+ Two limits, so a missing field is not mistaken for a bug. The OAuth endpoints take their input as
1408
+ query parameters, which the builder describes as operation parameters rather than as a component,
1409
+ so no schema is offered for those two DTOs. And what a decorator cannot express (which proof
1410
+ `ResetPasswordDto` accepts for the configured `passwordReset.method`, the deployment's
1411
+ `password.minLength`) is not in the schema and is not described elsewhere in the served document.
1412
+
1340
1413
  **If you already wrote these by hand, delete them** — not because they are wrong. They are what
1341
1414
  makes your document correct today; the deletion is what hands the job to the library, and it is
1342
1415
  needed precisely because they were doing it. Precedence, read from nest-core's
@@ -1620,10 +1693,10 @@ mean inventing an authorization model ("who is an admin?") that this library doe
1620
1693
  your application already does. Call them from your own admin surface, where the caller is
1621
1694
  already authorized.
1622
1695
 
1623
- | Method | Answers |
1624
- | ------------------------------------------ | --------------------------------------------------- |
1625
- | `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
1626
- | `MfaService.resetMfa(userId, context?)` | "I lost my authenticator **and** my recovery codes" |
1696
+ | Method | Answers |
1697
+ | -------------------------------------------------- | --------------------------------------------------- |
1698
+ | `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
1699
+ | `MfaService.resetMfa(userId, context?, tenantId?)` | "I lost my authenticator **and** my recovery codes" |
1627
1700
 
1628
1701
  **`unlockAccount`** clears the brute-force lockout. It grants no access: the password, the
1629
1702
  status gate, the verification gate and MFA all still apply — it restores the ability to _try_.
@@ -1640,12 +1713,154 @@ epoch, so access tokens carrying `mfaVerified: true` die with the factor; it **n
1640
1713
  account holder** through the same channel a self-service disable uses; and it logs at `warn`
1641
1714
  under its own prefix. The notification is not optional: an administrative reset the owner
1642
1715
  cannot see is an account-takeover path, and it is what makes the event detectable and
1643
- disputable. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
1716
+ disputable. `tenantId` is required when `context` is `'dashboard'` (the default) and ignored for
1717
+ `'platform'`. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
1644
1718
  "done".
1645
1719
 
1646
1720
  > `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
1647
1721
  > otherwise add it to `extraProviders` to inject it.
1648
1722
 
1723
+ ### Checking revocation outside a guard — `AuthRevocationService`
1724
+
1725
+ The three JWT guards do not decide revocation themselves; they delegate to one service, and that
1726
+ service is exported so **you can consult the same two channels from a transport the guards never
1727
+ see** — a WebSocket, an SSE stream, a message consumer. Without it there is no way to ask the
1728
+ question at all outside an HTTP request: a connection whose user logs out keeps its stream until
1729
+ the access token expires, while that user's HTTP calls are refused at once.
1730
+
1731
+ ```ts
1732
+ import { AuthRevocationService } from '@bymax-one/nest-auth'
1733
+
1734
+ const revoked = await this.revocation.isAccessTokenRevoked(
1735
+ { jti: payload.jti, sub: payload.sub, epoch: payload.epoch, tenantId: payload.tenantId },
1736
+ 'dashboard'
1737
+ )
1738
+ ```
1739
+
1740
+ It is registered and exported unconditionally, so it is injectable wherever `BymaxAuthModule` is
1741
+ imported — no `extraProviders` entry and no controller flag to turn on.
1742
+
1743
+ > [!IMPORTANT]
1744
+ > **On the dashboard plane you must forward `tenantId` from the verified token.** It is optional
1745
+ > on `RevocableTokenPayload` because the platform plane genuinely has none — its admins are
1746
+ > cross-tenant — so **`tsc` will not catch the omission**, and a dashboard payload without it is
1747
+ > treated as **revoked** without a store read, with a `warn` naming the missing field.
1748
+ >
1749
+ > Failing closed is deliberate. The epoch key derives from the tenant-scoped subject, so an absent
1750
+ > tenant names a keyspace belonging to no tenant, where nothing has ever been bumped: the read
1751
+ > would answer `0`, `stamped < 0` is false for every token, and a bulk-revoked token would be
1752
+ > reported **valid**. A revocation check that fails open on malformed input is worse than no check.
1753
+ >
1754
+ > **Recognise the symptom, because it does not look like an auth bug.** The refusal answers the
1755
+ > same `true` a genuinely revoked token answers, throws nothing and emits no event — so a
1756
+ > transport that gates a stream on it simply registers nothing. Measured on a consumer's realtime
1757
+ > bridge: the SSE handshake answered `200` and the connection registry stayed at `count: 0`.
1758
+ > Declaring the tenant **required** on your own port type is the stronger fix, because it turns the
1759
+ > next occurrence into a compile error rather than a log line.
1760
+
1761
+ **What this method is and is not.** It answers two channels at the moment you call it: the
1762
+ per-token blacklist and the user's token epoch. It reads no `exp`, holds no subscription, emits no
1763
+ event, and knows nothing about account status, roles, tenant binding or the identity plane. It is
1764
+ therefore **one check among the many a guarded HTTP route performs**, and not a substitute for
1765
+ them.
1766
+
1767
+ Using it to authorise a long-lived transport takes more than this method. Use
1768
+ `AuthTokenVerifierService` for that, below.
1769
+
1770
+ ### Authorising a long-lived transport — `AuthTokenVerifierService`
1771
+
1772
+ A guarded HTTP route establishes seven things before a handler runs. A WebSocket, an SSE stream or
1773
+ a message consumer has no guard in front of it, so it must establish the same seven itself — and on
1774
+ a cadence, because a connection outlives the request that opened it. Assembling that from the
1775
+ exported parts is where it goes wrong: a bridge that calls `isAccessTokenRevoked` alone has checked
1776
+ a signature and a blacklist while checking neither the token's **type**, nor its **`exp`**, nor
1777
+ whether the **account** behind it still exists.
1778
+
1779
+ `AuthTokenVerifierService.verifyAccessToken` is all seven in one call:
1780
+
1781
+ ```ts
1782
+ import { AuthTokenVerifierService } from '@bymax-one/nest-auth'
1783
+
1784
+ const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
1785
+ registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
1786
+ ```
1787
+
1788
+ | It checks | So that |
1789
+ | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1790
+ | Signature, pinned algorithm, `issuer`/`audience`, and any secret retired by a rotation | `alg: none` and a token carrying no binding claim are refused, and a rotation drains instead of disconnecting everyone |
1791
+ | `exp` | A revocation check answers "was this withdrawn", never "is this still current" — `isAccessTokenRevoked` reads no `exp` at all |
1792
+ | `jti` a UUID v4; `sub` and (dashboard) `tenantId` bounded non-empty strings | A malformed claim cannot build a Redis key nobody intended |
1793
+ | Token `type`, against the plane **you** name | An `mfa_challenge` token — signed with the same secret, half a credential — cannot read as a session |
1794
+ | Both revocation channels | A logout's `jti` blacklist AND the epoch a password reset or revoke-all advances |
1795
+ | Account status (`checkStatus`, default on) | Runs before the MFA decision. A suspension landing between two reconnects is seen, and so is an unverified email on the dashboard plane (`auth.email_not_verified`) — the token's own `status` claim is a snapshot taken at issuance |
1796
+ | MFA policy (`requireMfa`, default on) | Runs after the account-status check, so a blocked account is refused with its own code even while a challenge is pending. A refresh mints `mfaEnabled: true, mfaVerified: false`; the type alone does not imply the second factor was completed. A token whose `mfaEnabled` claim is missing or not a boolean is refused `auth.token_invalid` before the account lookup |
1797
+
1798
+ On the dashboard plane that last row reads a cache, and **its freshness is bounded by
1799
+ `userStatusCacheTtlSeconds` (default 60 s), not by how often you call**: a stream re-verifying every
1800
+ five seconds still serves a banned account until the entry expires. What shortens that is
1801
+ [`AccountStatusService.invalidate`](#invalidating-the-account-cache--accountstatusserviceinvalidate)
1802
+ — call it wherever you change a status, and read the caveat under that method: a request already
1803
+ resolving when you invalidate can write the old value back, so the window narrows to one repository
1804
+ read rather than to zero. Failing that, lower the TTL. The platform plane is uncached and genuinely current, at one repository read per call.
1805
+
1806
+ The plane is **yours to declare**, never inferred from the token. Inferring it would make the plane
1807
+ attacker-chosen: a platform token would open a dashboard stream by saying it is one. Passing a
1808
+ value that is neither throws a `TypeError` rather than refusing quietly — the fall-through would
1809
+ otherwise be the cross-tenant platform arm.
1810
+
1811
+ Every refusal is an `AuthException`, and each mirrors the code the equivalent guard already
1812
+ answers. Most answer `auth.token_invalid` so a caller cannot tell "valid but revoked" from "never
1813
+ valid"; `auth.mfa_required`, the `ACCOUNT_*` codes, `auth.email_not_verified` (dashboard plane) and — on
1814
+ the platform plane only — `auth.platform_auth_required` name themselves, because a legitimate
1815
+ client acts on each differently. The account codes are answered whether or not an MFA challenge
1816
+ is pending; `auth.mfa_required` is answered only for a usable account.
1817
+
1818
+ > [!IMPORTANT]
1819
+ > **Three things it still does not do.** Route **authorization** is yours — this answers who the
1820
+ > caller is, never what they may do, so your `@Roles()` equivalent belongs on every message a
1821
+ > stream carries, not only on the handshake. **Tenant binding** (`enforceTenantBinding`) needs the
1822
+ > request its resolver reads, which a redeemed ticket no longer has. And it holds **no
1823
+ > subscription**: it answers at the moment you call it, so a stream that calls it once at connect
1824
+ > is authorized for the lifetime of the token rather than of the session. Call it again on a
1825
+ > cadence and treat a rejection as a disconnect.
1826
+
1827
+ `AccountStatusService` is exported alongside it for the narrower case: you already hold a verified
1828
+ payload and want to re-ask only the one question whose answer changes while a stream is open.
1829
+
1830
+ ### Invalidating the account cache — `AccountStatusService.invalidate`
1831
+
1832
+ Account status is read through a Redis cache with a `userStatusCacheTtlSeconds` lifetime (60 s by
1833
+ default), so a change made **outside** this library is not seen until the entry expires. Suspend a
1834
+ user through your own admin surface and they keep reaching protected routes for up to a minute.
1835
+
1836
+ ```ts
1837
+ import { AccountStatusService } from '@bymax-one/nest-auth'
1838
+
1839
+ await this.accountStatus.invalidate({ userId, tenantId })
1840
+ ```
1841
+
1842
+ Call it whenever you change an account's status yourself. It drops both cached facts — the status
1843
+ and the email-verified flag — and is idempotent, so you need not know whether the account was
1844
+ cached. The tenant is required: a repository id is unique only within one, so a bare id would name
1845
+ another tenant's entry. An empty or blank `userId` or `tenantId` throws a `TypeError` rather than
1846
+ deleting nothing and resolving.
1847
+
1848
+ **Persist the status change first, then invalidate.** The read path fills the cache in two steps —
1849
+ resolve from the repository, then write — so a request that resolved the old value just before your
1850
+ update lands will write it back afterwards, with a full TTL, however promptly you call this. The
1851
+ window is one repository read wide rather than one TTL, which is the improvement; it is not zero.
1852
+ Writing first means any request whose read starts after your write already sees the new value, and
1853
+ only genuinely concurrent ones can lose the race. Closing it entirely would need the fill to be
1854
+ conditional on nothing having invalidated in between, which this service does not do today.
1855
+
1856
+ > [!IMPORTANT]
1857
+ > **Do not delete the cache keys yourself**, even though the `<namespace>:*` prefix is yours to
1858
+ > read. Their format is this library's to change — it already changed once, in v1.3.2, which added
1859
+ > the tenant segment — and a delete that stops matching **fails silently**: no error, no event, just
1860
+ > a status change that takes a full TTL to land. That is a security control degrading quietly. This
1861
+ > method is the supported way to ask, and it is the only thing that stays correct when the format
1862
+ > moves.
1863
+
1649
1864
  ### Server Guards
1650
1865
 
1651
1866
  | Guard | Decorator | Purpose |
@@ -1801,10 +2016,12 @@ went one release stated and unenforced.
1801
2016
  > internally for logs and control flow — branching on them client-side is the same dead branch as
1802
2017
  > an invented code, for a subtler reason.
1803
2018
 
1804
- > **Anti-enumeration reads through the status too.** `POST /forgot-password` answers `200` and
1805
- > `POST /verify-email` / the resend endpoints answer `204` **whether or not the address exists**.
2019
+ > **Anti-enumeration reads through the status too.** `POST /password/forgot-password` and
2020
+ > `POST /password/resend-otp` answer `200`, and `POST /verify-email` and
2021
+ > `POST /resend-verification` answer `204`, **whether or not the address exists**.
1806
2022
  > A `200` there does not mean an email was sent, and treating it as confirmation re-introduces
1807
- > the account enumeration the endpoints exist to prevent. For the same reason the OTP failures
2023
+ > the account enumeration the endpoints exist to prevent. `POST /password/verify-otp` answers `200`
2024
+ > only for a correct code; for the same reason the OTP failures
1808
2025
  > collapse: a wrong code, a record that expired, and an exhausted attempt ceiling are one code
1809
2026
  > (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
1810
2027
  > registered, since only a record that exists can reach one.
@@ -296,18 +296,16 @@ declare function getSetCookieHeaders(headers: HeadersLike): string[];
296
296
  * API (`globalThis.crypto.subtle`) for signature verification and
297
297
  * never import from `node:crypto` or `@nestjs/jwt`.
298
298
  *
299
- * Two modes are supported:
300
- *
301
- * - **Verify mode**: when a `JWT_SECRET` is provided we call
302
- * {@link verifyJwtToken} which performs HS256 signature
303
- * verification and expiry validation. This is the production path.
304
- *
305
- * - **Decode-only mode**: when no secret is available (e.g., during
306
- * local development or in a proxy that delegates signature
307
- * verification to the upstream API) we fall back to
308
- * {@link decodeJwtToken} which parses the payload without
309
- * verifying the signature. Decode-only mode is explicit — the
310
- * caller must pass `undefined`/`null` as the secret.
299
+ * Two functions, and a missing secret never selects between them:
300
+ *
301
+ * - {@link verifyJwtToken} performs HS256 signature verification and
302
+ * expiry validation. It fails closed: a missing or empty secret
303
+ * returns an empty, invalid result rather than a decoded payload.
304
+ * This is the production path.
305
+ *
306
+ * - {@link decodeJwtToken} parses the payload without verifying the
307
+ * signature. It is called explicitly, for non-authoritative claims
308
+ * such as UI hints, and never as a fallback for a missing secret.
311
309
  *
312
310
  * SECURITY — algorithm pinning:
313
311
  *
@@ -296,18 +296,16 @@ declare function getSetCookieHeaders(headers: HeadersLike): string[];
296
296
  * API (`globalThis.crypto.subtle`) for signature verification and
297
297
  * never import from `node:crypto` or `@nestjs/jwt`.
298
298
  *
299
- * Two modes are supported:
300
- *
301
- * - **Verify mode**: when a `JWT_SECRET` is provided we call
302
- * {@link verifyJwtToken} which performs HS256 signature
303
- * verification and expiry validation. This is the production path.
304
- *
305
- * - **Decode-only mode**: when no secret is available (e.g., during
306
- * local development or in a proxy that delegates signature
307
- * verification to the upstream API) we fall back to
308
- * {@link decodeJwtToken} which parses the payload without
309
- * verifying the signature. Decode-only mode is explicit — the
310
- * caller must pass `undefined`/`null` as the secret.
299
+ * Two functions, and a missing secret never selects between them:
300
+ *
301
+ * - {@link verifyJwtToken} performs HS256 signature verification and
302
+ * expiry validation. It fails closed: a missing or empty secret
303
+ * returns an empty, invalid result rather than a decoded payload.
304
+ * This is the production path.
305
+ *
306
+ * - {@link decodeJwtToken} parses the payload without verifying the
307
+ * signature. It is called explicitly, for non-authoritative claims
308
+ * such as UI hints, and never as a fallback for a missing secret.
311
309
  *
312
310
  * SECURITY — algorithm pinning:
313
311
  *
@@ -13,7 +13,6 @@ var AuthContext = React.createContext(null);
13
13
 
14
14
  // src/react/AuthProvider.tsx
15
15
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
16
- var DEFAULT_TENANT_ID = "default";
17
16
  var INITIAL_STATE = {
18
17
  user: null,
19
18
  status: "loading",
@@ -138,7 +137,6 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
138
137
  revalidateInterval
139
138
  ]);
140
139
  const login = React.useCallback(async (email, password, options) => {
141
- const tenantId = options?.tenantId ?? DEFAULT_TENANT_ID;
142
140
  syncedDispatch({
143
141
  type: "SET_LOADING"
144
142
  });
@@ -146,7 +144,9 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
146
144
  const result = await clientRef.current.login({
147
145
  email,
148
146
  password,
149
- tenantId
147
+ ...options?.tenantId !== void 0 ? {
148
+ tenantId: options.tenantId
149
+ } : {}
150
150
  });
151
151
  if ("mfaRequired" in result) {
152
152
  sessionGenerationRef.current = {};
@@ -216,7 +216,7 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
216
216
  ]);
217
217
  const forgotPassword = React.useCallback(
218
218
  async (email, tenantId) => {
219
- await clientRef.current.forgotPassword(email, tenantId ?? DEFAULT_TENANT_ID);
219
+ await clientRef.current.forgotPassword(email, tenantId);
220
220
  },
221
221
  // Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
222
222
  []
@@ -101,8 +101,12 @@ interface AuthContextValue {
101
101
  *
102
102
  * @param email User's primary email address.
103
103
  * @param password Plaintext password — the server hashes on receipt.
104
- * @param options Optional metadata. `tenantId` defaults to `'default'`
105
- * when omitted so single-tenant apps can skip it.
104
+ * @param options Optional metadata. `tenantId` is forwarded exactly as
105
+ * given: omit it and the request body carries no tenant
106
+ * at all. Which of the two a deployment wants is the
107
+ * server's answer, not this signature's — one configuring
108
+ * `tenantIdResolver` refuses a body that names a tenant,
109
+ * and one without a resolver requires it.
106
110
  *
107
111
  * @returns The discriminated {@link LoginResult} — branch on
108
112
  * `'mfaRequired' in result` to handle the MFA challenge case.
@@ -154,6 +158,10 @@ interface AuthContextValue {
154
158
  * Initiate a password reset. The server returns 200 regardless of
155
159
  * whether the email is registered (anti-enumeration) — treat a
156
160
  * resolved Promise as "request accepted", not "email known".
161
+ *
162
+ * `tenantId` is forwarded exactly as given, under the same rule
163
+ * {@link AuthContextValue.login} documents: an omitted tenant reaches
164
+ * the server as an absent field rather than a default one.
157
165
  */
158
166
  forgotPassword: (email: string, tenantId?: string) => Promise<void>;
159
167
  /**
@@ -267,6 +275,11 @@ type UseAuthResult = Pick<AuthContextValue, 'login' | 'register' | 'logout' | 'f
267
275
  * surfacing as an undefined-method runtime failure inside a
268
276
  * component handler.
269
277
  *
278
+ * The example omits `tenantId`, which is correct for a deployment configuring
279
+ * `tenantIdResolver` — there the server decides the tenant and REFUSES a body that
280
+ * names one. Without a resolver the server requires it, so pass
281
+ * `{ tenantId }` as the third argument. See {@link AuthContextValue.login}.
282
+ *
270
283
  * @example
271
284
  * ```tsx
272
285
  * function LoginForm(): ReactNode {
@@ -101,8 +101,12 @@ interface AuthContextValue {
101
101
  *
102
102
  * @param email User's primary email address.
103
103
  * @param password Plaintext password — the server hashes on receipt.
104
- * @param options Optional metadata. `tenantId` defaults to `'default'`
105
- * when omitted so single-tenant apps can skip it.
104
+ * @param options Optional metadata. `tenantId` is forwarded exactly as
105
+ * given: omit it and the request body carries no tenant
106
+ * at all. Which of the two a deployment wants is the
107
+ * server's answer, not this signature's — one configuring
108
+ * `tenantIdResolver` refuses a body that names a tenant,
109
+ * and one without a resolver requires it.
106
110
  *
107
111
  * @returns The discriminated {@link LoginResult} — branch on
108
112
  * `'mfaRequired' in result` to handle the MFA challenge case.
@@ -154,6 +158,10 @@ interface AuthContextValue {
154
158
  * Initiate a password reset. The server returns 200 regardless of
155
159
  * whether the email is registered (anti-enumeration) — treat a
156
160
  * resolved Promise as "request accepted", not "email known".
161
+ *
162
+ * `tenantId` is forwarded exactly as given, under the same rule
163
+ * {@link AuthContextValue.login} documents: an omitted tenant reaches
164
+ * the server as an absent field rather than a default one.
157
165
  */
158
166
  forgotPassword: (email: string, tenantId?: string) => Promise<void>;
159
167
  /**
@@ -267,6 +275,11 @@ type UseAuthResult = Pick<AuthContextValue, 'login' | 'register' | 'logout' | 'f
267
275
  * surfacing as an undefined-method runtime failure inside a
268
276
  * component handler.
269
277
  *
278
+ * The example omits `tenantId`, which is correct for a deployment configuring
279
+ * `tenantIdResolver` — there the server decides the tenant and REFUSES a body that
280
+ * names one. Without a resolver the server requires it, so pass
281
+ * `{ tenantId }` as the third argument. See {@link AuthContextValue.login}.
282
+ *
270
283
  * @example
271
284
  * ```tsx
272
285
  * function LoginForm(): ReactNode {