@bymax-one/nest-auth 1.4.5 → 1.4.8

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,47 @@ 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)).
817
+
818
+ **Tenant binding on the socket.** With `enforceTenantBinding` on, `WsJwtGuard` re-resolves the
819
+ tenant of the upgrade and refuses (`auth.token_invalid`, the same code HTTP answers) a ticket or
820
+ token minted for another tenant, as `JwtAuthGuard` does on a mismatch. An upgrade has no Express request,
821
+ so your `tenantIdResolver` is handed a request-like object with **only** these fields:
822
+
823
+ | Field | Value |
824
+ | ---------- | ------------------------------------------------------------------------------------------------- |
825
+ | `headers` | The handshake headers, names lowercased |
826
+ | `url` | The upgrade URL, `''` when the transport exposes none |
827
+ | `hostname` | The `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets), `''` if absent |
828
+
829
+ There is **no** `cookies` (the `Cookie` header is present in `headers`, but nothing parses it the way
830
+ `cookie-parser` does on HTTP), no `ip` or `ips`, and no trust-proxy behaviour: `hostname` is the
831
+ `Host` as received, never `X-Forwarded-Host`. The resolver's parameter is typed
832
+ `TenantResolverRequest` (exported), so a resolver that reads one of the absent fields does not
833
+ compile. If a resolver still throws at runtime, or returns anything other than the credential's
834
+ tenant, the connection is **refused**, never bound to the wrong tenant. Resolve from `headers` or
835
+ `hostname` so one resolver
836
+ serves both HTTP and sockets.
797
837
 
798
838
  Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
799
839
  `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
@@ -810,28 +850,30 @@ refusal to reach the client as anything but `Internal server error` — see
810
850
 
811
851
  All options are configurable via `registerAsync()`. Here are the key configuration groups:
812
852
 
813
- | Group | Key Options | Default |
814
- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
815
- | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, `30d` cap, `HS256`, both off |
816
- | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
817
- | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
818
- | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
819
- | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
820
- | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
821
- | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
822
- | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
823
- | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
824
- | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
825
- | **platform** | `enabled` | `false` |
826
- | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
827
- | **roles** | `hierarchy` (required), `platformHierarchy` | — |
828
- | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
829
- | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
830
- | **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 |
853
+ | Group | Key Options | Default |
854
+ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ |
855
+ | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, `30d` cap, `HS256`, both off |
856
+ | **identifierKey** | Top-level secret the Redis account identifiers and MFA recovery-code digests derive from; pin it before rotating `jwt.secret` | `jwt.secret` |
857
+ | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
858
+ | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
859
+ | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
860
+ | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
861
+ | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | `totpWindow` `1`, `recoveryCodeCount` `8` |
862
+ | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
863
+ | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
864
+ | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
865
+ | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
866
+ | **platform** | `enabled` | `false` |
867
+ | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
868
+ | **apiKeys** | `enabled`, `pepper` and `scopes` (required when enabled), `header`, `prefix`, `lastUsedFlushSeconds`, `auditMode` — see [Service API keys](#-service-api-keys-machine-callers) | `false`, `'x-api-key'`, `'bak'`, `60`, `'best-effort'` |
869
+ | **roles** | `hierarchy` (required), `platformHierarchy` | — |
870
+ | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
871
+ | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
872
+ | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
873
+ | **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
874
 
833
875
  > [!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.
876
+ > 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
877
 
836
878
  > [!IMPORTANT]
837
879
  > **`environment` is how the module decides whether this is production, and it defaults to
@@ -897,6 +939,29 @@ All options are configurable via `registerAsync()`. Here are the key configurati
897
939
  > rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has
898
940
  > expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
899
941
  > way, through its own list — see below.
942
+ >
943
+ > **Pin `identifierKey` before you rotate.** Every Redis name that identifies an account — the
944
+ > session index, the token epoch, the MFA keys, the recent-authentication marker, and the OTP and
945
+ > rate-limit identifiers — is an HMAC under a key derived from `jwt.secret` unless you set
946
+ > `identifierKey`, and so are the stored MFA recovery-code digests. Rotate `jwt.secret` alone and
947
+ > all of them are renamed: live sessions lose their index, every token epoch reads zero, so a token
948
+ > that a password reset or a revoke-all had refused is accepted again until it expires, and
949
+ > recovery codes stop verifying unless the old secret is listed in `jwt.previousSecrets`. `identifierKey` is a secret of its own for those names and
950
+ > digests; it is validated like `jwt.secret` and never signs or verifies a token. The value is
951
+ > simply the secret you want them to keep deriving from — there is nothing to compute.
952
+ >
953
+ > | | Routine rotation — keep sessions, epochs and recovery codes | Rotation after a compromise — cut the link |
954
+ > | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
955
+ > | 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`. |
956
+ > | 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`. |
957
+ > | 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. |
958
+ > | 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`. |
959
+ > | 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. |
960
+ >
961
+ > Pinning to the old secret leaves the derived Redis names computable by anyone who knows that
962
+ > secret. They are names, not signing material, and using one still needs access to your Redis;
963
+ > if cutting that link matters more than keeping sessions, take the second column. Without
964
+ > `identifierKey` a rotation moves the names as the second column does, whether or not you wanted them to.
900
965
 
901
966
  > [!TIP]
902
967
  > **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
@@ -954,7 +1019,9 @@ All options are configurable via `registerAsync()`. Here are the key configurati
954
1019
  > claim _usually_ wrong instead of _reliably_ empty, which is the failure mode that survives
955
1020
  > testing.
956
1021
  >
957
- > Status is resolved per request or not at all: mount `UserStatusGuard` on the route, and for
1022
+ > Status is resolved per request or not at all: mount `UserStatusGuard` on the route (on a
1023
+ > WebSocket, SSE stream or message consumer, call `AuthTokenVerifierService.verifyAccessToken`,
1024
+ > which resolves status through the same cache before it applies the MFA policy), and for
958
1025
  > anything richer read the account **tenant-scoped**, the way that guard does —
959
1026
  > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is required by the
960
1027
  > port and cannot be dropped: ids may collide across tenants, so a lookup by bare id can resolve
@@ -965,10 +1032,13 @@ All options are configurable via `registerAsync()`. Here are the key configurati
965
1032
  >
966
1033
  > One consequence worth planning for: the guard reads a status cache with a
967
1034
  > `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.
1035
+ > bite on a guarded route, and a reactivation the same to restore. Call
1036
+ > `AccountStatusService.invalidate({ userId, tenantId })` after persisting a status change to drop
1037
+ > that account's cached status immediately; a request already resolving can still write the old
1038
+ > value back, so the window narrows to one repository read rather than to zero (see
1039
+ > [Invalidating the account cache](#invalidating-the-account-cache--accountstatusserviceinvalidate)).
1040
+ > `bumpUserTokenEpoch` is the heavier lever: it ends every session the user has. Lower
1041
+ > `userStatusCacheTtlSeconds` if a faster answer matters more than the repository reads it costs.
972
1042
 
973
1043
  `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
974
1044
  **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
@@ -1000,6 +1070,270 @@ BymaxAuthModule.registerAsync({
1000
1070
 
1001
1071
  ---
1002
1072
 
1073
+ ## 🔑 Service API keys (machine callers)
1074
+
1075
+ For a caller that is a program, not a person: an automation service, a build agent, a partner
1076
+ integration. A key is stored only as a peppered HMAC digest, carries a set of scopes, is checked
1077
+ by a guard that has no dependency on user sessions, and every guarded request — refused ones
1078
+ included — reaches an audit hook. Nothing is registered until you opt in.
1079
+
1080
+ ### Enable it
1081
+
1082
+ ```typescript
1083
+ // app.module.ts
1084
+ import { BYMAX_AUTH_API_KEY_REPOSITORY, BymaxAuthModule } from '@bymax-one/nest-auth'
1085
+
1086
+ BymaxAuthModule.registerAsync({
1087
+ useFactory: () => ({
1088
+ jwt: { secret: process.env.JWT_SECRET ?? '' },
1089
+ roles: { hierarchy: { ADMIN: ['MEMBER'], MEMBER: [] } },
1090
+ rateLimit: { clientIpSource: 'peer' },
1091
+ apiKeys: {
1092
+ enabled: true,
1093
+ // A secret of its own, held apart from the database that stores the digests.
1094
+ pepper: process.env.API_KEY_PEPPER ?? '',
1095
+ // The closed vocabulary: issue() refuses anything else, and so does the startup scan.
1096
+ scopes: ['read', 'operate', 'publish-claim', 'admin']
1097
+ }
1098
+ }),
1099
+ extraProviders: [
1100
+ // …BYMAX_AUTH_USER_REPOSITORY and BYMAX_AUTH_REDIS_CLIENT as usual
1101
+ { provide: BYMAX_AUTH_API_KEY_REPOSITORY, useClass: PrismaApiKeyRepository }
1102
+ ]
1103
+ })
1104
+ ```
1105
+
1106
+ The feature is registered by the repository provider **and** `apiKeys.enabled`. Either one alone
1107
+ fails at startup and says which is missing.
1108
+
1109
+ | Option | Default | Meaning |
1110
+ | ---------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1111
+ | `pepper` | — (required) | The HMAC key every digest is computed under. As strong as `jwt.secret`, and refused if it equals `jwt.secret` (current or retired), `identifierKey` or an MFA key. |
1112
+ | `scopes` | — (required) | The closed vocabulary: letters, digits and `: . _ -`, up to 64 characters each. |
1113
+ | `header` | `'x-api-key'` | Where the key is read from. Never the query string. Lowercased. Never a header the library reads, such as `authorization`, `cookie`, `user-agent`, `origin` or the forwarded-address headers; also avoid one your own `tenantIdResolver` reads. |
1114
+ | `prefix` | `'bak'` | Literal start of every issued key, for secret scanners. Lowercase letters and digits, 2 to 16, no underscore. |
1115
+ | `lastUsedFlushSeconds` | `60` | How often coalesced `lastUsedAt` values are written, in one batch. 1 to 3600. |
1116
+ | `auditMode` | `'best-effort'` | `'required'` awaits the audit hook and **denies** the request if it throws, and startup refuses it when the registered hooks plainly lack `onApiKeyRequest`. See [Audit](#audit). |
1117
+
1118
+ ### Protect a route
1119
+
1120
+ ```typescript
1121
+ // videos.controller.ts
1122
+ import { Controller, Get, Post } from '@nestjs/common'
1123
+ import { CurrentApiKey, ServiceKey } from '@bymax-one/nest-auth'
1124
+ import type { ApiKeyPrincipal } from '@bymax-one/nest-auth'
1125
+
1126
+ @Controller('videos')
1127
+ export class VideosController {
1128
+ @ServiceKey('read')
1129
+ @Get()
1130
+ list(@CurrentApiKey() key: ApiKeyPrincipal) {
1131
+ // key.id, key.label and key.scopes — and nothing secret.
1132
+ return { caller: key.label }
1133
+ }
1134
+
1135
+ @ServiceKey('operate', 'publish-claim')
1136
+ @Post()
1137
+ publish() {
1138
+ // The key must hold BOTH scopes.
1139
+ }
1140
+ }
1141
+ ```
1142
+
1143
+ `@ServiceKey(...scopes)` does three things in one decorator so they cannot be separated by
1144
+ mistake: it declares the scopes, it lets the route past `JwtAuthGuard` and `JwtPlatformGuard`
1145
+ (which skip a route carrying the public marker), and it binds `ApiKeyGuard`. **"Public" here
1146
+ means "not a user route", never "unauthenticated"**: the key guard refuses a missing or invalid
1147
+ key on every request, even with a global `JwtAuthGuard` registered.
1148
+
1149
+ - A key must hold **all** the scopes a route declares. There is no wildcard and no hierarchy:
1150
+ `admin` does not imply `read`, so grant both.
1151
+ - The most specific declaration wins: a method's `@ApiKeyScopes` replaces its class's.
1152
+ - **A route with no scope declaration is refused** (`403 auth.forbidden`) before any credential
1153
+ is read, so a forgotten declaration cannot become an open route. If you bind `ApiKeyGuard`
1154
+ globally, every route without a declaration is refused: that is the strict mode.
1155
+ - A scope outside `apiKeys.scopes` stops the application at startup, not at the first request.
1156
+ - Verification attaches `request.apiKey` and never `request.user`, so no user-session guard can
1157
+ mistake a machine for a person.
1158
+
1159
+ ### Issue, revoke and rotate
1160
+
1161
+ The library mounts no controller: the admin surface is yours, and `ApiKeyService` is the
1162
+ mechanism behind it.
1163
+
1164
+ ```typescript
1165
+ // keys-admin.controller.ts
1166
+ import { Body, Controller, Delete, Param, Post } from '@nestjs/common'
1167
+ import { ApiKeyService, JwtAuthGuard, Roles, RolesGuard } from '@bymax-one/nest-auth'
1168
+ import { UseGuards } from '@nestjs/common'
1169
+
1170
+ @Controller('admin/keys')
1171
+ @UseGuards(JwtAuthGuard, RolesGuard)
1172
+ @Roles('admin')
1173
+ export class KeysAdminController {
1174
+ constructor(private readonly keys: ApiKeyService) {}
1175
+
1176
+ @Post()
1177
+ async issue(@Body() body: { label: string; scopes: string[] }) {
1178
+ const { key, record } = await this.keys.issue(body)
1179
+ // `key` is the plaintext. It is returned this once and cannot be retrieved again.
1180
+ return { key, record }
1181
+ }
1182
+
1183
+ @Post(':id/rotate')
1184
+ rotate(@Param('id') id: string) {
1185
+ // The old key keeps working for an hour so the caller can switch without downtime.
1186
+ return this.keys.rotate(id, { overlapSeconds: 3600 })
1187
+ }
1188
+
1189
+ @Delete(':id')
1190
+ revoke(@Param('id') id: string) {
1191
+ return this.keys.revoke(id)
1192
+ }
1193
+ }
1194
+ ```
1195
+
1196
+ - `issue({ label, scopes, expiresAt? })`: the label is 1 to 128 characters with no control
1197
+ characters, `expiresAt` must be in the future, and every scope must come from the vocabulary.
1198
+ Failures answer `auth.validation`.
1199
+ - Several active keys may share one label. **Rotation is that rule, not a special case**:
1200
+ `rotate(id, { overlapSeconds })` issues a second key with the same label and scopes, then
1201
+ retires the first after the overlap (`0` retires it at once; the maximum is
1202
+ `API_KEY_MAX_OVERLAP_SECONDS`). The new key is issued before the old one is retired,
1203
+ so a failure in between leaves both valid rather than neither. A revoked or expired key is
1204
+ not rotated (`auth.api_key_not_found`): that would re-issue access nobody holds.
1205
+ - `revoke(id)` takes effect on the very next request: the row is read on every request, and
1206
+ there is no verification cache.
1207
+ - **Who did it.** `issue`, `revoke` and `rotate` emit no hook of their own — they run inside
1208
+ your admin route, which already knows the operator, so attribute them there (log or audit it
1209
+ beside the call). The per-request hook below covers requests _made with_ a key. If you want
1210
+ provenance stored with the key, add your own columns: `IApiKeyRepository.create` receives the
1211
+ row and your implementation can persist whatever else it knows. That is why `issue()` takes
1212
+ no `createdBy`.
1213
+
1214
+ ### The repository
1215
+
1216
+ You implement `IApiKeyRepository`, as you do for users. The library supplies the `id` and the
1217
+ `digest`; the store only persists them.
1218
+
1219
+ | Method | Contract |
1220
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1221
+ | `findById(id)` | One primary-key read per request. Return revoked and expired rows too: the library decides validity. |
1222
+ | `create(row)` | Insert `{ id, label, digest, scopes, createdAt, expiresAt }`. Do not make `label` unique. |
1223
+ | `markRevoked(id, at)` | `false` when unknown. Revoking twice is not an error. A row with `revokedAt` set is revoked at once on every instance, whatever instant it holds: a future date is not a schedule, so schedule with `expiresAt`. |
1224
+ | `setExpiry(id, at)` | `false` when unknown. The scheduling field: a key stops verifying at `expiresAt`. Used by rotation to retire the old key after the overlap. |
1225
+ | `touchLastUsed(entries)` | One batch. **Must be monotonic**: `GREATEST(last_used_at, :at)`, never backwards — several instances flush independently. |
1226
+ | `listByLabel(label)` | Every key of a label, for your admin screen. |
1227
+
1228
+ ### How a key is stored and checked
1229
+
1230
+ A key looks like `bak_<keyId>_<secret>`: a literal prefix, the row's UUID (a public handle that
1231
+ makes verification an indexed read), and 43 base64url characters carrying 32 random bytes. Only
1232
+ `HMAC-SHA-256(pepper, secret)` is stored, as lowercase hex. Labels and scopes are not part of the
1233
+ digest, so editing them never invalidates a key. The grammar and the digest are pinned by
1234
+ [`conformance/wire-contract.json`](./conformance/wire-contract.json) with a vector, because
1235
+ `rust-auth` mints and verifies the same keys.
1236
+
1237
+ **Why a fast HMAC rather than a slow password hash.** This is the library's own reasoning, not
1238
+ an OWASP rule: the OWASP Password Storage Cheat Sheet's case against fast hashes is about
1239
+ passwords, which people choose and which can be guessed. A key's secret is 256 bits from the
1240
+ CSPRNG, so the work factor of the hash adds nothing to its resistance, and a per-request scrypt
1241
+ would only hand an attacker a cheap way to burn CPU. The pepper is what the cheat sheet calls
1242
+ the HMAC key: kept apart from the database, so a leaked table of digests cannot be tested
1243
+ offline.
1244
+
1245
+ **Every key takes the same steps.** Parse (substituting a dummy when it does not parse), read a
1246
+ row (always), compute the digest, compare two 32-byte buffers with `timingSafeEqual` (against a
1247
+ dummy digest when there is no row), and only then decide. An unknown, malformed, wrong, revoked
1248
+ or expired key all answer `401 auth.api_key_invalid` with the same body; the operator sees the
1249
+ real reason in the audit event. A key is valid strictly before its `expiresAt`, and not at all once `revokedAt` is set.
1250
+
1251
+ Two things this does _not_ claim. The store round trip costs differently for a present and an
1252
+ absent row, and no library can hide that — put a per-address throttle in front (below). And the
1253
+ fail-closed branch (a bound route with no scopes) intentionally takes different steps: it
1254
+ depends on route configuration, not on the key, so there is nothing for the key to leak.
1255
+
1256
+ **Changing the pepper makes every issued key unverifiable.** Digests are not portable across
1257
+ peppers, so a new pepper means re-issuing every key. There is no pepper rotation in this
1258
+ version.
1259
+
1260
+ ### Audit
1261
+
1262
+ Implement `onApiKeyRequest` on your `IAuthHooks`. It fires once for every guarded request:
1263
+
1264
+ ```typescript
1265
+ import type { ApiKeyAccessEvent, HookContext, IAuthHooks } from '@bymax-one/nest-auth'
1266
+
1267
+ export class AuditHooks implements IAuthHooks {
1268
+ async onApiKeyRequest(event: ApiKeyAccessEvent, context: HookContext): Promise<void> {
1269
+ // event.outcome: 'allowed' | 'denied'
1270
+ // event.reason: null, or missing | malformed | unknown | wrong_secret | revoked | expired
1271
+ // | scope_insufficient | route_undeclared | store_error
1272
+ // event.label, event.keyId, event.method, event.route (the PATTERN, e.g. /videos/:id),
1273
+ // event.requiredScopes, event.ip
1274
+ await this.audit.write({ ...event, userAgent: context.userAgent })
1275
+ }
1276
+ }
1277
+ ```
1278
+
1279
+ Every refused request reaches the hook too, so anonymous traffic can write audit rows: throttle by address before the guard. By default the hook is fired without being awaited and its failure is logged. With `apiKeys.auditMode: 'required'` it is awaited, and **if it throws the request is
1280
+ denied** (`500 auth.internal`): use that when the audit row is a record you must have.
1281
+
1282
+ ### Keep the key out of your logs
1283
+
1284
+ The library never logs, throws or emits the presented key, and strips the key header from the
1285
+ hook's `sanitizedHeaders`. Your HTTP logger sits outside the library, so redact the header
1286
+ there, custom `apiKeys.header` included:
1287
+
1288
+ ```typescript
1289
+ // nest-logger
1290
+ LoggerModule.forRoot({ redactPaths: ['req.headers["x-machine-key"]'] })
1291
+ ```
1292
+
1293
+ ```typescript
1294
+ // plain pino
1295
+ const logger = pino({ redact: ['req.headers["x-api-key"]'] })
1296
+ ```
1297
+
1298
+ ### Rate limiting
1299
+
1300
+ Rate limiting is deliberately not built in. Use `@nestjs/throttler` in two layers: a per-address
1301
+ limit in front of everything, which is the only protection for the pre-verification lookup; and
1302
+ a per-key limit placed **after** `ApiKeyGuard`, keyed on the verified key id:
1303
+
1304
+ ```typescript
1305
+ import { UseGuards, Get } from '@nestjs/common'
1306
+ import { ServiceKey } from '@bymax-one/nest-auth'
1307
+ import type { ApiKeyPrincipal } from '@bymax-one/nest-auth'
1308
+ import { ThrottlerGuard } from '@nestjs/throttler'
1309
+
1310
+ export class KeyThrottlerGuard extends ThrottlerGuard {
1311
+ protected override async getTracker(req: Record<string, unknown>): Promise<string> {
1312
+ const key = req['apiKey'] as ApiKeyPrincipal | undefined
1313
+ return key?.id ?? String(req['ip'])
1314
+ }
1315
+ }
1316
+
1317
+ export class LimitedController {
1318
+ // @UseGuards sits ABOVE @ServiceKey: decorators run bottom-up and the guards run in that
1319
+ // order, so the key guard verifies first and the tracker sees `request.apiKey`.
1320
+ @UseGuards(KeyThrottlerGuard)
1321
+ @ServiceKey('read')
1322
+ @Get('limited')
1323
+ limited() {}
1324
+ }
1325
+ ```
1326
+
1327
+ A request that fails verification never reaches the second guard, so garbage cannot spend a real
1328
+ key's budget. This example is exercised end to end in `test/e2e/api-keys.e2e-spec.ts`.
1329
+
1330
+ ### Last-used tracking, and what it costs
1331
+
1332
+ A verified request does a map write, nothing else; every `lastUsedFlushSeconds` the values are
1333
+ written to your repository in one batch. With **N instances** a key is written up to N times
1334
+ per window instead of once, and a crash loses at most one window of `lastUsedAt`. The field is
1335
+ advisory: authorization never reads it.
1336
+
1003
1337
  ## 🏗️ Architecture
1004
1338
 
1005
1339
  The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
@@ -1113,7 +1447,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1113
1447
  | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
1114
1448
  | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
1115
1449
  | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), path-scoped |
1116
- | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
1450
+ | Brute-Force | Redis atomic counters per HMAC(email, identifier key) |
1117
1451
  | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
1118
1452
  | Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
1119
1453
  | Cross-Site Writes | `Origin` / `Sec-Fetch-Site` check on cookie-authenticated writes — the gap `SameSite=None` leaves open |
@@ -1135,7 +1469,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1135
1469
  <img src="https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white" alt="Next.js" />
1136
1470
  <img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
1137
1471
  <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" />
1472
+ <img src="https://img.shields.io/badge/Jest-30-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
1139
1473
  </p>
1140
1474
 
1141
1475
  ---
@@ -1145,9 +1479,9 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1145
1479
  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
1480
 
1147
1481
  - ✅ **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
1482
+ - ✅ **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))
1483
+ - ✅ **Thousands of tests** — unit and end-to-end, spanning all five subpaths
1484
+ - ✅ **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
1485
 
1152
1486
  ```bash
1153
1487
  pnpm test # unit suite
@@ -1173,18 +1507,18 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
1173
1507
  | POST | `/logout` | Public (reads both credentials) | Revoke the session; blacklists the access token it is given |
1174
1508
  | POST | `/refresh` | Public (refresh cookie or body) | Rotate refresh token, issue new access token |
1175
1509
  | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
1176
- | POST | `/ws-ticket` | `JwtAuthGuard` | Mint a single-use ticket for a WebSocket upgrade |
1510
+ | POST | `/ws-ticket` | `JwtAuthGuard`, `UserStatusGuard` | Mint a single-use ticket for a WebSocket upgrade |
1177
1511
  | POST | `/verify-email` | Public | Verify email with OTP |
1178
1512
  | POST | `/resend-verification` | Public | Resend email-verification OTP |
1179
1513
  | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
1180
1514
  | POST | `/password/reset-password` | Public | Submit new password with reset token |
1181
1515
  | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
1182
1516
  | 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 |
1517
+ | POST | `/mfa/setup` | `JwtAuthGuard`, `UserStatusGuard` | Generate TOTP secret and recovery codes |
1518
+ | POST | `/mfa/verify-enable` | `JwtAuthGuard`, `UserStatusGuard` | Confirm setup and enable MFA |
1185
1519
  | 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 |
1520
+ | POST | `/mfa/disable` | `JwtAuthGuard`, `UserStatusGuard` | Disable MFA for the current user |
1521
+ | POST | `/mfa/recovery-codes` | `JwtAuthGuard`, `UserStatusGuard` | Replace the recovery codes, proving a fresh OTP |
1188
1522
  | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
1189
1523
  | POST | `/sessions/revoke-all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke every session except the caller's |
1190
1524
  | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
@@ -1337,6 +1671,30 @@ const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
1337
1671
  > whether this library is new enough to contribute them at all, and only then your nest-core
1338
1672
  > version. The two states look identical from the document.
1339
1673
 
1674
+ #### On `@bymax-one/nest-core` 1.6.1 or later, the request bodies are described too
1675
+
1676
+ The same contributor offers the request-body schema of every DTO that the controllers your
1677
+ deployment mounted take (`LoginDto`, `RegisterDto`, `ResetPasswordDto` and the rest), derived from
1678
+ their `class-validator` decorators. Without a contribution `@nestjs/swagger` registers each of them as
1679
+ `{"type":"object","properties":{}}`, because this package is built without its CLI plugin, and a
1680
+ client generated from the document types every request body as `{}`.
1681
+
1682
+ > **Request schemas appear with `@bymax-one/nest-core` ≥ 1.6.1; older versions ignore the
1683
+ > contribution without a signal.** Through 1.6.0 an empty placeholder counts as a declaration, so
1684
+ > the schema offered here is dropped and the document renders exactly as before: no error, no
1685
+ > warning, and no `discarded` field on what `applyBymaxOpenApi` returns. From 1.6.1 the
1686
+ > placeholder is filled from the contribution. A schema of the same name that carries properties
1687
+ > of its own is a declaration and wins, and `applyBymaxOpenApi` reports the contribution that
1688
+ > lost in `discarded`. Components are keyed by the DTO's class name, so a DTO of your own that
1689
+ > shares a name with one of this library's (a `LoginDto`, say) and is itself an empty placeholder
1690
+ > is filled with this library's schema: name your own classes differently.
1691
+
1692
+ Two limits, so a missing field is not mistaken for a bug. The OAuth endpoints take their input as
1693
+ query parameters, which the builder describes as operation parameters rather than as a component,
1694
+ so no schema is offered for those two DTOs. And what a decorator cannot express (which proof
1695
+ `ResetPasswordDto` accepts for the configured `passwordReset.method`, the deployment's
1696
+ `password.minLength`) is not in the schema and is not described elsewhere in the served document.
1697
+
1340
1698
  **If you already wrote these by hand, delete them** — not because they are wrong. They are what
1341
1699
  makes your document correct today; the deletion is what hands the job to the library, and it is
1342
1700
  needed precisely because they were doing it. Precedence, read from nest-core's
@@ -1620,10 +1978,10 @@ mean inventing an authorization model ("who is an admin?") that this library doe
1620
1978
  your application already does. Call them from your own admin surface, where the caller is
1621
1979
  already authorized.
1622
1980
 
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" |
1981
+ | Method | Answers |
1982
+ | -------------------------------------------------- | --------------------------------------------------- |
1983
+ | `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
1984
+ | `MfaService.resetMfa(userId, context?, tenantId?)` | "I lost my authenticator **and** my recovery codes" |
1627
1985
 
1628
1986
  **`unlockAccount`** clears the brute-force lockout. It grants no access: the password, the
1629
1987
  status gate, the verification gate and MFA all still apply — it restores the ability to _try_.
@@ -1640,7 +1998,8 @@ epoch, so access tokens carrying `mfaVerified: true` die with the factor; it **n
1640
1998
  account holder** through the same channel a self-service disable uses; and it logs at `warn`
1641
1999
  under its own prefix. The notification is not optional: an administrative reset the owner
1642
2000
  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
2001
+ disputable. `tenantId` is required when `context` is `'dashboard'` (the default) and ignored for
2002
+ `'platform'`. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
1644
2003
  "done".
1645
2004
 
1646
2005
  > `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
@@ -1690,22 +2049,116 @@ event, and knows nothing about account status, roles, tenant binding or the iden
1690
2049
  therefore **one check among the many a guarded HTTP route performs**, and not a substitute for
1691
2050
  them.
1692
2051
 
1693
- Using it to authorise a long-lived transport — a WebSocket, an SSE stream — takes more than this
1694
- method, and this library does not yet export the pieces that would make that safe. See
1695
- [#172](https://github.com/bymaxone/nest-auth/issues/172), which records what a stream must
1696
- establish beyond revocation, the gaps that make each one consumer-built today, and the library
1697
- changes that would close them.
2052
+ Using it to authorise a long-lived transport takes more than this method. Use
2053
+ `AuthTokenVerifierService` for that, below.
2054
+
2055
+ ### Authorising a long-lived transport — `AuthTokenVerifierService`
2056
+
2057
+ A guarded HTTP route establishes seven things before a handler runs. A WebSocket, an SSE stream or
2058
+ a message consumer has no guard in front of it, so it must establish the same seven itself — and on
2059
+ a cadence, because a connection outlives the request that opened it. Assembling that from the
2060
+ exported parts is where it goes wrong: a bridge that calls `isAccessTokenRevoked` alone has checked
2061
+ a signature and a blacklist while checking neither the token's **type**, nor its **`exp`**, nor
2062
+ whether the **account** behind it still exists.
2063
+
2064
+ `AuthTokenVerifierService.verifyAccessToken` is all seven in one call:
2065
+
2066
+ ```ts
2067
+ import { AuthTokenVerifierService } from '@bymax-one/nest-auth'
2068
+
2069
+ const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
2070
+ registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
2071
+ ```
2072
+
2073
+ | It checks | So that |
2074
+ | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2075
+ | 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 |
2076
+ | `exp` | A revocation check answers "was this withdrawn", never "is this still current" — `isAccessTokenRevoked` reads no `exp` at all |
2077
+ | `jti` a UUID v4; `sub` and (dashboard) `tenantId` bounded non-empty strings | A malformed claim cannot build a Redis key nobody intended |
2078
+ | Token `type`, against the plane **you** name | An `mfa_challenge` token — signed with the same secret, half a credential — cannot read as a session |
2079
+ | Both revocation channels | A logout's `jti` blacklist AND the epoch a password reset or revoke-all advances |
2080
+ | 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 |
2081
+ | 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 |
2082
+
2083
+ On the dashboard plane that last row reads a cache, and **its freshness is bounded by
2084
+ `userStatusCacheTtlSeconds` (default 60 s), not by how often you call**: a stream re-verifying every
2085
+ five seconds still serves a banned account until the entry expires. What shortens that is
2086
+ [`AccountStatusService.invalidate`](#invalidating-the-account-cache--accountstatusserviceinvalidate)
2087
+ — call it wherever you change a status, and read the caveat under that method: a request already
2088
+ resolving when you invalidate can write the old value back, so the window narrows to one repository
2089
+ read rather than to zero. Failing that, lower the TTL. The platform plane is uncached and genuinely current, at one repository read per call.
2090
+
2091
+ The plane is **yours to declare**, never inferred from the token. Inferring it would make the plane
2092
+ attacker-chosen: a platform token would open a dashboard stream by saying it is one. Passing a
2093
+ value that is neither throws a `TypeError` rather than refusing quietly — the fall-through would
2094
+ otherwise be the cross-tenant platform arm.
2095
+
2096
+ Every refusal is an `AuthException`, and each mirrors the code the equivalent guard already
2097
+ answers. Most answer `auth.token_invalid` so a caller cannot tell "valid but revoked" from "never
2098
+ valid"; `auth.mfa_required`, the `ACCOUNT_*` codes, `auth.email_not_verified` (dashboard plane) and — on
2099
+ the platform plane only — `auth.platform_auth_required` name themselves, because a legitimate
2100
+ client acts on each differently. The account codes are answered whether or not an MFA challenge
2101
+ is pending; `auth.mfa_required` is answered only for a usable account.
2102
+
2103
+ > [!IMPORTANT]
2104
+ > **Three things it still does not do.** Route **authorization** is yours — this answers who the
2105
+ > caller is, never what they may do, so your `@Roles()` equivalent belongs on every message a
2106
+ > stream carries, not only on the handshake. **Tenant binding** (`enforceTenantBinding`) needs the
2107
+ > request its resolver reads, so pass the handshake as `request` to `verifyAccessToken` (the same
2108
+ > `headers`/`url`/`hostname` request as on `WsJwtGuard`, fail-closed on a resolver that cannot answer);
2109
+ > without it the binding is not applied to that call, and one warning per service instance says so. And it holds **no
2110
+ > subscription**: it answers at the moment you call it, so a stream that calls it once at connect
2111
+ > is authorized for the lifetime of the token rather than of the session. Call it again on a
2112
+ > cadence and treat a rejection as a disconnect.
2113
+
2114
+ `AccountStatusService` is exported alongside it for the narrower case: you already hold a verified
2115
+ payload and want to re-ask only the one question whose answer changes while a stream is open.
2116
+
2117
+ ### Invalidating the account cache — `AccountStatusService.invalidate`
2118
+
2119
+ Account status is read through a Redis cache with a `userStatusCacheTtlSeconds` lifetime (60 s by
2120
+ default), so a change made **outside** this library is not seen until the entry expires. Suspend a
2121
+ user through your own admin surface and they keep reaching protected routes for up to a minute.
2122
+
2123
+ ```ts
2124
+ import { AccountStatusService } from '@bymax-one/nest-auth'
2125
+
2126
+ await this.accountStatus.invalidate({ userId, tenantId })
2127
+ ```
2128
+
2129
+ Call it whenever you change an account's status yourself. It drops both cached facts — the status
2130
+ and the email-verified flag — and is idempotent, so you need not know whether the account was
2131
+ cached. The tenant is required: a repository id is unique only within one, so a bare id would name
2132
+ another tenant's entry. An empty or blank `userId` or `tenantId` throws a `TypeError` rather than
2133
+ deleting nothing and resolving.
2134
+
2135
+ **Persist the status change first, then invalidate.** The read path fills the cache in two steps —
2136
+ resolve from the repository, then write — so a request that resolved the old value just before your
2137
+ update lands will write it back afterwards, with a full TTL, however promptly you call this. The
2138
+ window is one repository read wide rather than one TTL, which is the improvement; it is not zero.
2139
+ Writing first means any request whose read starts after your write already sees the new value, and
2140
+ only genuinely concurrent ones can lose the race. Closing it entirely would need the fill to be
2141
+ conditional on nothing having invalidated in between, which this service does not do today.
2142
+
2143
+ > [!IMPORTANT]
2144
+ > **Do not delete the cache keys yourself**, even though the `<namespace>:*` prefix is yours to
2145
+ > read. Their format is this library's to change — it already changed once, in v1.3.2, which added
2146
+ > the tenant segment — and a delete that stops matching **fails silently**: no error, no event, just
2147
+ > a status change that takes a full TTL to land. That is a security control degrading quietly. This
2148
+ > method is the supported way to ask, and it is the only thing that stays correct when the format
2149
+ > moves.
1698
2150
 
1699
2151
  ### Server Guards
1700
2152
 
1701
- | Guard | Decorator | Purpose |
1702
- | -------------------- | ------------------------------- | ----------------------------------------------------------- |
1703
- | `JwtAuthGuard` | — | Validates JWT from cookie or `Authorization: Bearer` header |
1704
- | `RolesGuard` | `@Roles('admin')` | Hierarchical role check |
1705
- | `UserStatusGuard` | — | Blocks inactive/banned users (Redis-cached status) |
1706
- | `MfaRequiredGuard` | `@SkipMfa()` | Enforces MFA verification on protected routes |
1707
- | `JwtPlatformGuard` | — | Platform admin JWT validation (Bearer only) |
1708
- | `PlatformRolesGuard` | `@PlatformRoles('super_admin')` | Platform role hierarchy enforcement |
2153
+ | Guard | Decorator | Purpose |
2154
+ | -------------------- | ------------------------------- | ---------------------------------------------------------------- |
2155
+ | `JwtAuthGuard` | — | Validates JWT from cookie or `Authorization: Bearer` header |
2156
+ | `RolesGuard` | `@Roles('admin')` | Hierarchical role check |
2157
+ | `UserStatusGuard` | — | Blocks inactive/banned users (Redis-cached status) |
2158
+ | `MfaRequiredGuard` | `@SkipMfa()` | Enforces MFA verification on protected routes |
2159
+ | `JwtPlatformGuard` | — | Platform admin JWT validation (Bearer only) |
2160
+ | `PlatformRolesGuard` | `@PlatformRoles('super_admin')` | Platform role hierarchy enforcement |
2161
+ | `ApiKeyGuard` | `@ServiceKey('read')` | Service API key for machine callers; fails closed without scopes |
1709
2162
 
1710
2163
  > [!NOTE]
1711
2164
  > Three additional guards — `SelfOrAdminGuard` (ownership checks), `OptionalAuthGuard` (routes that behave differently for anonymous vs authenticated users), and `WsJwtGuard` (JWT authentication on WebSocket gateways) — are exported from the public `@bymax-one/nest-auth` barrel. Use them exactly like the core guards above.
@@ -1812,15 +2265,15 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1812
2265
  [`conformance/wire-contract.json`](./conformance/wire-contract.json) under
1813
2266
  `errorCatalog.statuses` and asserted by both suites against that file.
1814
2267
 
1815
- | Status | Codes |
1816
- | -----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1817
- | `400` | `auth.validation` · `auth.password_compromised` · `auth.password_reset_token_invalid` · `auth.email_change_token_invalid` · `auth.invalid_invitation_token` · `auth.mfa_not_enabled` · `auth.mfa_setup_required` |
1818
- | `401` | `auth.invalid_credentials` · `auth.token_invalid` · `auth.refresh_token_invalid` · `auth.mfa_invalid_code` · `auth.mfa_temp_token_invalid` · `auth.otp_invalid` · `auth.oauth_failed` · `auth.platform_auth_required` |
1819
- | `403` | `auth.account_inactive` · `auth.account_suspended` · `auth.account_banned` · `auth.pending_approval` · `auth.email_not_verified` · `auth.mfa_required` · `auth.insufficient_role` · `auth.forbidden` · `auth.untrusted_origin` · `auth.reauthentication_required` |
1820
- | `404` | `auth.session_not_found` |
1821
- | `409` | `auth.email_already_exists` · `auth.mfa_already_enabled` · `auth.mfa_state_conflict` · `auth.oauth_email_mismatch` |
1822
- | `429` | `auth.account_locked` · `auth.too_many_requests` |
1823
- | `500` | `auth.internal` |
2268
+ | Status | Codes |
2269
+ | -----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2270
+ | `400` | `auth.validation` · `auth.password_compromised` · `auth.password_reset_token_invalid` · `auth.email_change_token_invalid` · `auth.invalid_invitation_token` · `auth.mfa_not_enabled` · `auth.mfa_setup_required` |
2271
+ | `401` | `auth.invalid_credentials` · `auth.token_invalid` · `auth.refresh_token_invalid` · `auth.mfa_invalid_code` · `auth.mfa_temp_token_invalid` · `auth.otp_invalid` · `auth.oauth_failed` · `auth.platform_auth_required` · `auth.api_key_invalid` |
2272
+ | `403` | `auth.account_inactive` · `auth.account_suspended` · `auth.account_banned` · `auth.pending_approval` · `auth.email_not_verified` · `auth.mfa_required` · `auth.insufficient_role` · `auth.forbidden` · `auth.untrusted_origin` · `auth.reauthentication_required` · `auth.api_key_scope_insufficient` |
2273
+ | `404` | `auth.session_not_found` · `auth.api_key_not_found` |
2274
+ | `409` | `auth.email_already_exists` · `auth.mfa_already_enabled` · `auth.mfa_state_conflict` · `auth.oauth_email_mismatch` |
2275
+ | `429` | `auth.account_locked` · `auth.too_many_requests` |
2276
+ | `500` | `auth.internal` |
1824
2277
 
1825
2278
  `AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
1826
2279
  need the mapping at runtime — for a typed client, an API document, or a test that asserts against
@@ -1851,10 +2304,12 @@ went one release stated and unenforced.
1851
2304
  > internally for logs and control flow — branching on them client-side is the same dead branch as
1852
2305
  > an invented code, for a subtler reason.
1853
2306
 
1854
- > **Anti-enumeration reads through the status too.** `POST /forgot-password` answers `200` and
1855
- > `POST /verify-email` / the resend endpoints answer `204` **whether or not the address exists**.
2307
+ > **Anti-enumeration reads through the status too.** `POST /password/forgot-password` and
2308
+ > `POST /password/resend-otp` answer `200`, and `POST /verify-email` and
2309
+ > `POST /resend-verification` answer `204`, **whether or not the address exists**.
1856
2310
  > A `200` there does not mean an email was sent, and treating it as confirmation re-introduces
1857
- > the account enumeration the endpoints exist to prevent. For the same reason the OTP failures
2311
+ > the account enumeration the endpoints exist to prevent. `POST /password/verify-otp` answers `200`
2312
+ > only for a correct code; for the same reason the OTP failures
1858
2313
  > collapse: a wrong code, a record that expired, and an exhausted attempt ceiling are one code
1859
2314
  > (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
1860
2315
  > registered, since only a record that exists can reach one.
@@ -1867,6 +2322,9 @@ went one release stated and unenforced.
1867
2322
  | `@Roles(...roles)` | Set required roles: `@Roles('admin', 'manager')` |
1868
2323
  | `@PlatformRoles(...roles)` | Set required platform roles: `@PlatformRoles('super_admin')` |
1869
2324
  | `@Public()` | Mark route as public (skip JWT guard) |
2325
+ | `@ServiceKey(...scopes)` | Machine-caller route: scopes + JWT bypass + `ApiKeyGuard`, in one |
2326
+ | `@ApiKeyScopes(...scopes)` | Declare required scopes only (when binding `ApiKeyGuard` yourself) |
2327
+ | `@CurrentApiKey()` | Inject the verified key: `@CurrentApiKey() key: ApiKeyPrincipal` |
1870
2328
  | `@SkipMfa()` | Skip MFA verification for this route |
1871
2329
 
1872
2330
  ### React Hooks