@bymax-one/nest-auth 1.4.6 → 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/CHANGELOG.md CHANGED
@@ -18,6 +18,95 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.8] - 2026-10-31
22
+
23
+ ### Apply to a derived backend
24
+
25
+ What a backend built on this library does about the changes below. The first item is a
26
+ compile-time change to the resolver's parameter type; the rest change behaviour or add opt-in
27
+ surface.
28
+
29
+ - **`tenantIdResolver` is now typed `(req: TenantResolverRequest) => ...`, not `(req: Request) => ...`.**
30
+ `TenantResolverRequest` is a new exported type with `headers`, `url` and `hostname`. A resolver
31
+ annotated `(req: Request)` must be re-annotated to `TenantResolverRequest` or left to infer; one
32
+ that reads `cookies`, `ip` or `ips` no longer compiles, so move that data into a header or the
33
+ hostname. An Express request still satisfies the type, so HTTP behaviour is unchanged.
34
+ - **`enforceTenantBinding` now holds on WebSockets.** `WsJwtGuard` previously never consulted it, so
35
+ a ticket or token minted for tenant A opened a socket resolved to tenant B even though the HTTP
36
+ guard refused the same credential. It now calls your `tenantIdResolver` on both credential
37
+ channels and answers `auth.token_invalid` on a mismatch. No option changes. **Read your
38
+ resolver:** an upgrade has no Express request, so it receives a request-like object with only
39
+ `headers` (lowercased), `url` and `hostname` (from `Host`, port cut). `cookies`, `ip`, `ips` and
40
+ trust-proxy behaviour are absent, and a resolver that throws on their absence, or returns another
41
+ tenant, **refuses** the connection rather than binding it wrongly. A resolver that
42
+ reads a cookie or `req.ip` and still compiles (an untyped one) will refuse every socket until it
43
+ resolves from `headers` or `hostname`. Nothing changes when `enforceTenantBinding` is off.
44
+ - **`AuthTokenVerifierService.verifyAccessToken` takes an optional `request`.** Pass the
45
+ handshake (or any object with `headers` and `url`, an Express request included) and, with
46
+ `enforceTenantBinding` on, the dashboard plane applies the same resolver check as `WsJwtGuard`,
47
+ with the same limited request and the same refusal (`auth.token_invalid`). Existing callers are
48
+ not broken: without `request` the token verifies as before, and with the binding on one warning
49
+ per service instance says it was not applied. To close the gap, pass `request: socket.handshake`.
50
+ - **Service API keys (new, opt-in).** To authenticate a machine caller, set `apiKeys` in the
51
+ factory (`enabled`, `pepper`, `scopes`) and provide `BYMAX_AUTH_API_KEY_REPOSITORY` in
52
+ `extraProviders`; either one alone fails at startup. Implement `IApiKeyRepository`, protect a
53
+ route with `@ServiceKey('read')`, and read the caller with `@CurrentApiKey()`. A backend that
54
+ keeps its own interim guard can delete it once its keys are re-issued (digests are not
55
+ portable across peppers) and its route-gate tests pass against `ApiKeyGuard`.
56
+ - **Three new error codes** in the catalog and in `AUTH_ERROR_CODES` of both subpaths:
57
+ `auth.api_key_invalid` (401), `auth.api_key_scope_insufficient` (403) and
58
+ `auth.api_key_not_found` (404). A client that switches on `error.code` need not handle them
59
+ unless it calls routes behind `@ServiceKey`.
60
+ - **`rust-auth` is to mirror the key format, the digest, the scope rules, the audit event and the
61
+ three codes.** They are pinned in the new `apiKeys` section of `conformance/wire-contract.json`,
62
+ with a digest vector, so the two libraries cannot drift unnoticed.
63
+ - **An OAuth sign-in now records the last login and runs `afterLogin`.** Until now only a password
64
+ login did. If your `afterLogin` hook sends a notification or writes an audit row, OAuth sign-ins
65
+ will now reach it; if you read `lastLoginAt`, OAuth sign-ins now move it. An account with MFA
66
+ gets both when the challenge completes, for password and OAuth sign-ins alike, on the dashboard
67
+ and the platform plane: before, an MFA account's last login never changed.
68
+ - **The default `onOAuthLogin` no longer keeps a link when the provider has not verified the
69
+ address.** It answers `reject` (`Email not verified`) instead of `link`. Nothing changes if you
70
+ supply your own `onOAuthLogin`. The `existingUser` it receives was always the user already
71
+ linked to the provider identity, found by provider id, not by email; the documentation said the
72
+ latter and is corrected.
73
+
74
+ ### Security
75
+
76
+ - `WsJwtGuard` enforces `enforceTenantBinding` on the bearer-header and ticket paths, and `verifyAccessToken` can now enforce it when given the request.
77
+
78
+ ### Fixed
79
+
80
+ - **An MFA account's last login was never recorded.** The password step stopped at the challenge
81
+ and the challenge completion did not write it, so `lastLoginAt` never moved for a password
82
+ account with MFA, on the dashboard or the platform plane. Completing the challenge now records
83
+ it and runs `afterLogin`, for password and OAuth sign-ins alike.
84
+ - **A host `afterLogin` hook that threw synchronously could fail an MFA sign-in that had already
85
+ passed.** Completing the challenge now runs the hook detached, so neither a throw nor a
86
+ rejection changes the outcome, and the log line carries a label and the error's shape only.
87
+
88
+ ### Added
89
+
90
+ - **Scoped service API keys for machine callers.** `ApiKeyGuard` and the `@ServiceKey(...scopes)`
91
+ decorator (scopes, the user-JWT bypass and the guard in one), `@ApiKeyScopes`, `@CurrentApiKey`,
92
+ `ApiKeyService` (`issue`, `revoke`, `rotate`), `IApiKeyRepository` and the
93
+ `onApiKeyRequest` audit hook.
94
+ - Keys are stored only as `HMAC-SHA-256(pepper, secret)`; the plaintext is returned once.
95
+ - Every key takes the same verification steps (a dummy row and digest stand in for a missing
96
+ one) and every bad credential answers the same `401`.
97
+ - Scopes are route metadata; a bound route with no declaration is refused. A key must hold all
98
+ declared scopes, with no hierarchy and no wildcard.
99
+ - Several active keys may share a label, which is what an overlapping rotation uses.
100
+ - Last-used tracking is coalesced in memory and flushed in batches, so a verified request costs
101
+ no store write. With N instances a key is written up to N times per window.
102
+ - The hook receives the label, the route pattern and the outcome of every guarded request,
103
+ refusals included. `apiKeys.auditMode: 'required'` awaits it and denies the request if it
104
+ throws.
105
+ - A scope that is not in `apiKeys.scopes` stops the application at startup.
106
+ - `issue`, `revoke` and `rotate` emit no hook: they run inside the host's own admin route.
107
+ - Rate limiting is not built in; the README shows `@nestjs/throttler` keyed on the verified key
108
+ id, and an end-to-end test exercises that example.
109
+
21
110
  ## [1.4.6] - 2026-10-31
22
111
 
23
112
  ### Apply to a derived backend
@@ -3987,7 +4076,8 @@ ever installable.
3987
4076
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
3988
4077
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
3989
4078
 
3990
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...HEAD
4079
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...HEAD
4080
+ [1.4.8]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...v1.4.8
3991
4081
  [1.4.6]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...v1.4.6
3992
4082
  [1.4.5]: https://github.com/bymaxone/nest-auth/compare/v1.4.4...v1.4.5
3993
4083
  [1.4.4]: https://github.com/bymaxone/nest-auth/compare/v1.4.3...v1.4.4
package/README.md CHANGED
@@ -815,6 +815,26 @@ socket must also refuse a blocked account or an unfinished second factor, author
815
815
  `AuthTokenVerifierService.verifyAccessToken` (see
816
816
  [Authorising a long-lived transport](#authorising-a-long-lived-transport--authtokenverifierservice)).
817
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.
837
+
818
838
  Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
819
839
  `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
820
840
  does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
@@ -830,26 +850,27 @@ refusal to reach the client as anything but `Internal server error` — see
830
850
 
831
851
  All options are configurable via `registerAsync()`. Here are the key configuration groups:
832
852
 
833
- | Group | Key Options | Default |
834
- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
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` |
837
- | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
838
- | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
839
- | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
840
- | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
841
- | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | `totpWindow` `1`, `recoveryCodeCount` `8` |
842
- | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
843
- | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
844
- | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
845
- | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
846
- | **platform** | `enabled` | `false` |
847
- | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
848
- | **roles** | `hierarchy` (required), `platformHierarchy` | — |
849
- | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
850
- | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
851
- | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
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 |
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 |
853
874
 
854
875
  > [!NOTE]
855
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.
@@ -1049,6 +1070,270 @@ BymaxAuthModule.registerAsync({
1049
1070
 
1050
1071
  ---
1051
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
+
1052
1337
  ## 🏗️ Architecture
1053
1338
 
1054
1339
  The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
@@ -1819,7 +2104,9 @@ is pending; `auth.mfa_required` is answered only for a usable account.
1819
2104
  > **Three things it still does not do.** Route **authorization** is yours — this answers who the
1820
2105
  > caller is, never what they may do, so your `@Roles()` equivalent belongs on every message a
1821
2106
  > 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
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
1823
2110
  > subscription**: it answers at the moment you call it, so a stream that calls it once at connect
1824
2111
  > is authorized for the lifetime of the token rather than of the session. Call it again on a
1825
2112
  > cadence and treat a rejection as a disconnect.
@@ -1863,14 +2150,15 @@ conditional on nothing having invalidated in between, which this service does no
1863
2150
 
1864
2151
  ### Server Guards
1865
2152
 
1866
- | Guard | Decorator | Purpose |
1867
- | -------------------- | ------------------------------- | ----------------------------------------------------------- |
1868
- | `JwtAuthGuard` | — | Validates JWT from cookie or `Authorization: Bearer` header |
1869
- | `RolesGuard` | `@Roles('admin')` | Hierarchical role check |
1870
- | `UserStatusGuard` | — | Blocks inactive/banned users (Redis-cached status) |
1871
- | `MfaRequiredGuard` | `@SkipMfa()` | Enforces MFA verification on protected routes |
1872
- | `JwtPlatformGuard` | — | Platform admin JWT validation (Bearer only) |
1873
- | `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 |
1874
2162
 
1875
2163
  > [!NOTE]
1876
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.
@@ -1977,15 +2265,15 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1977
2265
  [`conformance/wire-contract.json`](./conformance/wire-contract.json) under
1978
2266
  `errorCatalog.statuses` and asserted by both suites against that file.
1979
2267
 
1980
- | Status | Codes |
1981
- | -----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1982
- | `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` |
1983
- | `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` |
1984
- | `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` |
1985
- | `404` | `auth.session_not_found` |
1986
- | `409` | `auth.email_already_exists` · `auth.mfa_already_enabled` · `auth.mfa_state_conflict` · `auth.oauth_email_mismatch` |
1987
- | `429` | `auth.account_locked` · `auth.too_many_requests` |
1988
- | `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` |
1989
2277
 
1990
2278
  `AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
1991
2279
  need the mapping at runtime — for a typed client, an API document, or a test that asserts against
@@ -2034,6 +2322,9 @@ went one release stated and unenforced.
2034
2322
  | `@Roles(...roles)` | Set required roles: `@Roles('admin', 'manager')` |
2035
2323
  | `@PlatformRoles(...roles)` | Set required platform roles: `@PlatformRoles('super_admin')` |
2036
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` |
2037
2328
  | `@SkipMfa()` | Skip MFA verification for this route |
2038
2329
 
2039
2330
  ### React Hooks