@bymax-one/nest-auth 1.5.1 → 1.5.3

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
@@ -25,7 +25,7 @@
25
25
  <a href="https://github.com/bymaxone/nest-auth">GitHub</a> ·
26
26
  <a href="https://github.com/bymaxone/nest-auth/issues">Issues</a> ·
27
27
  <a href="#-quick-start">Quick Start</a> ·
28
- <a href="#-subpath-exports">API Reference</a> ·
28
+ <a href="#-api-reference">API Reference</a> ·
29
29
  <a href="https://github.com/bymaxone/nest-auth-example">Example App</a>
30
30
  </p>
31
31
 
@@ -142,7 +142,8 @@ yarn add @bymax-one/nest-auth
142
142
 
143
143
  ```bash
144
144
  # Server subpath (required)
145
- pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/websockets ioredis class-validator class-transformer reflect-metadata
145
+ pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/websockets express ioredis class-validator class-transformer reflect-metadata
146
+ pnpm add -D @types/express
146
147
 
147
148
  # Also needed with `tokenDelivery: 'cookie'` or `'both'` (see step 4): the library reads `req.cookies`
148
149
  pnpm add cookie-parser
@@ -306,70 +307,22 @@ Email delivery is fully delegated to the consumer — the library never imports
306
307
  > Any user-supplied value (display name, tenant name, inviter name) interpolated into HTML email bodies MUST be escaped to prevent stored XSS in notification content. Tokens and OTPs are library-generated and safe, but `inviterName`, `tenantName`, device strings, and any consumer-supplied placeholder are attacker-controllable.
307
308
 
308
309
  > [!CAUTION]
309
- > **Never log the error your transport rejects with — it can contain the code you just sent.**
310
- > A policy, DLP or anti-spam relay answering `550` commonly **quotes the offending message body**,
311
- > so the error your `send()` throws carries the OTP or token this library rendered into it. Logging
312
- > that error, or attaching it as a `cause` to one you log, puts a working credential into your log
313
- > pipeline in clear text until it expires. Measured on a real relay, not hypothesised.
314
- >
315
- > This is your half: the library cannot reach inside your provider implementation.
316
- > **`describeChannelStatus` is exported for it** — the same helper the bundled provider uses on
317
- > every one of its own log lines, so you get the whole treatment rather than just redaction:
318
- >
319
- > ```typescript
320
- > import { describeChannelStatus } from '@bymax-one/nest-auth'
321
- >
322
- > async sendPasswordResetOtp(tenantId: string, email: string, otp: string): Promise<void> {
323
- > try {
324
- > await this.resend.emails.send({ /* ... */ })
325
- > } catch (error: unknown) {
326
- > // Never `logger.error(msg, error)` here, and never `new Error(msg, { cause: error })`
327
- > // into something that logs — both carry the quoted body.
328
- > this.logger.error(`reset OTP delivery failed: ${describeChannelStatus(error)}`)
329
- > throw error
330
- > }
331
- > }
332
- > ```
333
- >
334
- > Two functions, not one with a mode: which one you call IS the decision, and there is no
335
- > permissive default to inherit by forgetting.
336
- >
337
- > **`describeChannelStatus(error)` wherever the body rendered something you would withhold.** It
338
- > takes no secrets, and that is the guarantee rather than an omission — nothing the channel wrote
339
- > is published, so there is nothing to name. Redaction alone does not close this, and neither does
340
- > a length cap. A relay may quote the body it rejected in transfer encoding rather
341
- > than verbatim; base64 is the ordinary case and defeats both at once — substring matching finds
342
- > nothing because the credential's characters are not in the line, and the cap does not help
343
- > because the encoding runs from the body's first byte, so the code is in the first sentence.
344
- > Measured: a reset-code body is 96 base64 characters end to end, and the first 200 characters of
345
- > the line decode straight back to the OTP. Under `describeChannelStatus` NOTHING the channel wrote
346
- > reaches the line — not the message, not the `name`, not a status parsed off the front. Each of
347
- > those was tried and each fell: shape validation admits `MTIzNDU2`, the base64 of OTP `123456`;
348
- > and a status grammar admits `424-242`, an OTP grouped, publishing `424`. What you keep is which
349
- > message failed. What you lose is the transient-versus-permanent split, which your mail provider's
350
- > dashboard has and this library does not.
351
- >
352
- > **`describeError(error, [values])` for errors whose text you have a reason to trust**, where the
353
- > values you name appear the way you wrote them and redaction reaches them. The bundled provider
354
- > uses it nowhere — every one of its paths uses the opaque form, including the notices that
355
- > render nothing secret, because a relay may re-encode whatever it quotes and the recipient address
356
- > is in the message either way. If you can say the same about your channel, prefer
357
- > `describeChannelStatus` and keep this one for strings you built yourself.
358
- >
359
- > Neither reads `stack`, and neither reads the transport's own fields — nodemailer hangs the
360
- > server's full reply on `response`. Beyond that they differ, and the difference is the point:
361
- > `describeError` reads `name` and `message`, strips the values you named, caps the length and
362
- > removes control characters so a relay cannot forge extra records in a line-oriented pipeline.
363
- > `describeChannelStatus` reads **neither** — the only thing it touches is `cause`, walked to count
364
- > the links. Both walk that chain and never throw, whatever the transport's error does.
365
- >
366
- > `redactSecrets(text, [otp])` is exported too, for a string you built yourself and know contains
367
- > the literal value. It is **not** a substitute for either description on a transport's error: a
368
- > substring match cannot see through an encoding, which is the whole reason the bundled provider
369
- > stopped relying on it.
370
- >
371
- > If you use the bundled `DefaultAuthEmailProvider` with `onDeliveryError: 'rethrow'`, the error it
372
- > re-throws is the channel's original and is still yours to contain the same way.
310
+ > **Never log the error your transport rejects with.** A relay that answers `550` commonly quotes the
311
+ > message body, so the error `send()` throws can carry the OTP or token the library rendered into it,
312
+ > and logging it (or attaching it as a `cause`) puts a working credential in your logs. Log
313
+ > `describeChannelStatus(error)` instead: it is exported for exactly this and reads nothing the
314
+ > channel wrote. See [Keeping delivery errors out of your logs](./docs/email-delivery-errors.md).
315
+
316
+ > [!NOTE]
317
+ > The bundled `DefaultAuthEmailProvider` implements every method of `IEmailProvider`, the optional
318
+ > ones included (`sendWorkspaceInvitation` among them), so a host that takes it can enable every
319
+ > controller. It renders a **token**, not a link: the invitation messages say "use this token to
320
+ > accept: ..." and it has no base URL to build one from. To send a link, override the message,
321
+ > `new DefaultAuthEmailProvider(sink, { messages: { invitation, workspaceInvitation } })`, with a
322
+ > renderer that returns your own `html`; the escaping of caller-supplied text, the credential flag
323
+ > and the delivery-error policy still apply to it. A workspace invitation says whether it is for a
324
+ > workspace that exists (`kind: 'member'`) or a platform invitation to set one up and own it
325
+ > (`kind: 'bootstrap'`).
373
326
 
374
327
  ```typescript
375
328
  // email.provider.ts
@@ -757,6 +710,21 @@ export const config = {
757
710
  }
758
711
  ```
759
712
 
713
+ > [!IMPORTANT]
714
+ > **The proxy is a routing hint, not an authorization check.** `jwtSecret` lets the proxy tell
715
+ > whether an access token was minted with your secret and has not expired, which is enough to choose
716
+ > between rendering a page and redirecting to sign-in. It cannot see what the backend sees: a logout,
717
+ > a password reset or a revoke-all, a blocked account, the MFA state, or a workspace membership. A
718
+ > token the proxy lets through may be one the backend refuses on the next call, so a role or a header
719
+ > the proxy sets must never be the access decision for data or an action: the backend verifies every
720
+ > request that reads or changes anything.
721
+ >
722
+ > Set `jwtIssuer`, `jwtAudience` and `jwtPreviousSecrets` to the same values as the backend's
723
+ > `jwt.issuer`, `jwt.audience` and `jwt.previousSecrets`. The backend requires a configured issuer
724
+ > and audience on every token and keeps accepting the retired secrets while a rotation drains, so a
725
+ > proxy without them signs out a session the backend still honours, or admits a token the backend
726
+ > refuses. `verifyJwtToken` takes the same three values as its `options` argument.
727
+
760
728
  How the route lists match a path: an entry matches the path that equals it and anything under
761
729
  it (`'/auth'` covers `/auth/login`), and takes no wildcards (`'/auth/*'` matches nothing). An
762
730
  entry ending in `/` is a plain prefix, so `'/'` matches every path. In `publicRoutes` that is
@@ -802,124 +770,8 @@ export const POST = createLogoutHandler({
802
770
  })
803
771
  ```
804
772
 
805
- ---
806
-
807
- ### WebSocket upgrades
808
-
809
- The browser `WebSocket` API cannot set handshake headers, so a browser client cannot send
810
- `Authorization: Bearer <token>` at the upgrade. The usual workaround puts the access token in the
811
- query string, where it lands in access logs, browser history and proxy caches — a long-lived
812
- credential in plaintext. `WsJwtGuard` refuses it.
813
-
814
- The supported path is a single-use ticket:
815
-
816
- ```typescript
817
- // 1. Mint from an authenticated session (POST, cookies or bearer as usual).
818
- const { ticket, expiresIn } = await fetch('/auth/ws-ticket', {
819
- method: 'POST',
820
- credentials: 'include'
821
- }).then((r) => r.json())
822
-
823
- // 2. Open the socket with it. The ticket is consumed by the first redemption.
824
- const socket = new WebSocket(`wss://api.example.com/socket?ticket=${ticket}`)
825
- ```
826
-
827
- The ticket is opaque, 32 bytes of CSPRNG output, and lives at most 30 seconds, ending a second before the access
828
- token that minted it does at the latest: `expiresIn` in the response is that capped lifetime in seconds, so a client
829
- schedules its upgrade by it, and a token with no life left mints nothing. Only `sha256(ticket)` is
830
- ever a Redis key, and the stored value is a verified-identity **snapshot** — no signature, no
831
- expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned back into a
832
- session. It carries the `jti` and `epoch` of the access token that minted it, the two keys the
833
- revocation channels are read by, and redemption is refused when that token has been blacklisted by
834
- a logout or stamped below the user's current epoch (sign-out-everywhere, password change, MFA
835
- reset): a ticket does not outlive the session that asked for it. A logout blacklists only
836
- the access token it was given and does not move the epoch, so a ticket minted from an access token
837
- that a refresh had already replaced is not refused after that logout, as a bearer token of that
838
- kind is not; it is refused only after a later epoch bump (a password reset or change, an MFA
839
- enable, disable or reset, or revoking another session or all of them). Minting requires an authenticated session in good standing that has already
840
- satisfied MFA, so a ticket never carries more authority than the request that asked for it.
841
-
842
- Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
843
- both channels are accepted, and a ticket wins when both are present. `WsJwtGuard` checks
844
- signature, token type and revocation on the Bearer path but not account status or MFA; where the
845
- socket must also refuse a blocked account or an unfinished second factor, authorize with
846
- `AuthTokenVerifierService.verifyAccessToken` (see
847
- [Authorising a long-lived transport](#authorising-a-long-lived-transport--authtokenverifierservice)).
848
-
849
- **Tenant binding on the socket.** With `enforceTenantBinding` on, `WsJwtGuard` re-resolves the
850
- tenant of the upgrade and refuses (`auth.token_invalid`, the same code HTTP answers) a ticket or
851
- token minted for another tenant, as `JwtAuthGuard` does on a mismatch. An upgrade has no Express request,
852
- so your `tenantIdResolver` is handed a request-like object with **only** these fields:
853
-
854
- | Field | Value |
855
- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------- |
856
- | `headers` | The handshake headers, names lowercased |
857
- | `url` | The upgrade URL, `''` when the transport exposes none |
858
- | `hostname` | The `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets), `''` if absent; see below for `X-Forwarded-Host` |
859
-
860
- There is **no** `cookies` (the `Cookie` header is present in `headers`, but nothing parses it the way
861
- `cookie-parser` does on HTTP) and no `ip` or `ips`. `hostname` is the `Host` as received unless you
862
- set `isTrustedProxy` (below). The resolver's parameter is typed
863
- `TenantResolverRequest` (exported), so a resolver that reads one of the absent fields does not
864
- compile. If a resolver still throws at runtime, or returns anything other than the credential's
865
- tenant, the connection is **refused**, never bound to the wrong tenant. Resolve from `headers` or
866
- `hostname` so one resolver
867
- serves both HTTP and sockets.
868
-
869
- **Behind a proxy that rewrites `Host`.** nginx's default `proxy_set_header Host $proxy_host` presents
870
- the upstream name in `Host` and the public one in `X-Forwarded-Host`. Over HTTP, Express resolves
871
- `req.hostname` from the forwarded header when its `trust proxy` setting trusts the peer; a socket has
872
- no Express request, so without more the resolver sees the upstream host and the binding refuses every
873
- stream. Declare the same trust decision once with `isTrustedProxy`, a function that takes the TCP peer
874
- address and answers a boolean:
875
-
876
- ```typescript
877
- // The module factory runs before the app exists, so it reads the policy per connection.
878
- // Until main.ts fills it in, no peer is trusted.
879
- export const proxyPolicy = { trusts: (_peer: string): boolean => false }
880
-
881
- BymaxAuthModule.registerAsync({
882
- useFactory: () => ({
883
- // ...
884
- enforceTenantBinding: true,
885
- tenantIdResolver: (req) => req.hostname.split('.')[0] ?? '',
886
- isTrustedProxy: (peer) => proxyPolicy.trusts(peer)
887
- })
888
- })
889
-
890
- // main.ts
891
- import { proxyPolicy } from './app.module' // wherever the module is configured
892
-
893
- const app = await NestFactory.create<NestExpressApplication>(AppModule)
894
- const expressApp = app.getHttpAdapter().getInstance()
895
- expressApp.set('trust proxy', 'loopback, 10.0.0.0/8')
896
- proxyPolicy.trusts = (peer) => expressApp.get('trust proxy fn')(peer, 0)
897
- ```
898
-
899
- Read the compiled policy from the **Express instance**, `app.getHttpAdapter().getInstance()`. On a
900
- Nest application, `app.get()` resolves a provider from the container and does not read an Express
901
- setting, so `app.get('trust proxy fn')` looks for a provider of that name and fails.
902
-
903
- The predicate receives the peer **exactly as the transport reported it**, so an IPv4-mapped form such
904
- as `::ffff:10.0.0.1` reaches it unchanged; Express's compiled setting understands that form, which
905
- is why the recipe delegates to it. When it answers `true`, the first element of a single
906
- `X-Forwarded-Host` is used, with the port cut like `Host`. Unset, which is the default,
907
- `X-Forwarded-Host` is never read. Every other case falls back to `Host`: no peer address, a header handed
908
- over as separate values, an empty first element, a predicate that throws or answers anything but
909
- `true`. (Node joins a header repeated on the wire into one comma-separated string, and its first
910
- element is used, as in Express.) Those cases can therefore only make the binding stricter, never
911
- admit a tenant the client chose. The
912
- peer address comes from `WsJwtGuard` itself (Socket.IO's `handshake.address`); a caller of
913
- `AuthTokenVerifierService.verifyAccessToken` passes it as `request.remoteAddress`.
914
-
915
- Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
916
- `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
917
- does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
918
- `auth.token_invalid` instead of crashing on it, but it cannot authenticate anyone on that
919
- adapter. And because `AuthException` extends `HttpException`, which Nest's WebSocket layer does
920
- not recognise, a gateway that applies the guard also needs `WsAuthExceptionFilter` for the
921
- refusal to reach the client as anything but `Internal server error` — see
922
- [On a WebSocket, the envelope needs its own filter](#on-a-websocket-the-envelope-needs-its-own-filter).
773
+ > [!NOTE]
774
+ > Authenticating a WebSocket (single-use upgrade tickets, tenant binding on a socket, a proxy that rewrites `Host`) is covered in [WebSocket upgrades](./docs/websocket-upgrades.md).
923
775
 
924
776
  ---
925
777
 
@@ -955,84 +807,60 @@ All options are configurable via `registerAsync()`. Here are the key configurati
955
807
  > [!IMPORTANT]
956
808
  > **`environment` is how the module decides whether this is production, and it defaults to
957
809
  > saying yes.** It drives cookie `Secure`, the HTTPS requirement on the OAuth `callbackUrl`, and
958
- > three redirect validations. It used to be read from `NODE_ENV`, which failed **open** on every
959
- > near miss — unset, `'staging'`, `'prod'`, or `'production '` with a trailing space each
960
- > silently took the insecure branch, in all six places at once. Whether a deployment is
961
- > production is something the deployer knows and the process environment only hints at, so it is
962
- > passed in. The consequence to plan for: a local or test setup must now say
963
- > `environment: 'development'` (or `'test'`) explicitly, or it will be held to production rules —
964
- > an `http://` callback URL is refused, and cookies are marked `Secure` and never sent over
965
- > plaintext. That failure is loud, which is the point; the old one was silent. Matches
966
- > `Environment` in rust-auth.
810
+ > redirect validations. A local or test setup must say `environment: 'development'` (or
811
+ > `'test'`) explicitly, or it is held to production rules: an `http://` callback URL is refused and
812
+ > cookies are marked `Secure`. It is an explicit option rather than `NODE_ENV` because a near miss
813
+ > (unset, `'staging'`, `'prod'`) would otherwise silently take the insecure branch.
967
814
 
968
815
  > [!NOTE]
969
- > **`password.minLength` defaults to 15, not 8.** The DTOs keep a structural floor of 8 — the
970
- > lowest NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance — and this is the
971
- > deployment's policy on top of it. §3.1.1.1 allows 8 only for a password used as part of
972
- > multi-factor authentication and requires 15 for one used as a single factor; MFA here is
973
- > opt-in per user, so the default deployment **is** single-factor. Configurable to anything in
974
- > `8..=128`, validated at startup: below 8 changes no outcome (the DTOs refuse the request
975
- > first), and above 128 is longer than any password the validation layer accepts. It is checked
976
- > in the service rather than a decorator because a decorator is evaluated when the class is
977
- > defined, before any configuration exists — and it answers the same `auth.validation` code and
978
- > the same `{ field, message }[]` details a length failure already produced, so a client
979
- > handling short passwords sees no new shape.
816
+ > **`password.minLength` defaults to 15, not 8.** The DTOs keep a structural floor of 8, the lowest
817
+ > NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and 15 is the minimum it requires for a
818
+ > password used as a single factor. MFA is opt-in per user, so the default deployment is
819
+ > single-factor. Configurable to anything in `8..=128`, validated at startup. A shorter password
820
+ > answers the same `auth.validation` code and `{ field, message }[]` details as any length failure.
980
821
 
981
822
  > [!IMPORTANT]
982
- > **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled — there is no
983
- > default. The option group is a discriminated union, so TypeScript refuses the omission at
984
- > compile time; the module also refuses to start without it, because the type binds TypeScript
985
- > and nothing else. Set `'peer'` when the application is
986
- > directly exposed: the limit keys on the socket address, read from the connection and never
987
- > from a forwarding header. Set `'trusted-proxy'` when it runs behind a proxy and `trust proxy`
988
- > is configured for the real hop count: the limit keys on `req.ip`, the forwarded client
989
- > address. Neither can be the default, because each is a working limiter in one deployment and
990
- > no limiter at all in the other — `'peer'` behind a proxy puts every client in **one** bucket,
991
- > so a single caller can rate-limit your whole user base with no credential, and
992
- > `'trusted-proxy'` without a proxy lets the caller choose their own key. Both look like a
993
- > working limiter at runtime. Pass `rateLimit.enabled: false` if the limits are enforced at the
994
- > edge instead.
823
+ > **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled; there is no default,
824
+ > and the module refuses to start without it. Set `'peer'` when the application is directly
825
+ > exposed: the limit keys on the socket address, never on a forwarding header. Set
826
+ > `'trusted-proxy'` when it runs behind a proxy and `trust proxy` is configured for the real hop
827
+ > count: the limit keys on `req.ip`. Neither can be the default, because each is a working limiter
828
+ > in one deployment and none in the other: `'peer'` behind a proxy puts every client in **one**
829
+ > bucket, and `'trusted-proxy'` without a proxy lets the caller choose their own key. Pass
830
+ > `rateLimit.enabled: false` if the limits are enforced at the edge instead.
995
831
  >
996
- > `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each
997
- > hop appends the address it saw, so the client is the rightmost entry that is not itself a
998
- > trusted proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client
999
- > choose its address, so a client that varies it gets a fresh budget every time; behind such a hop
1000
- > use `'peer'`, or make the hop append or overwrite the header. An entry that is not an address at
1001
- > all is never a key: the limit is charged to the nearest trusted hop instead.
832
+ > `'trusted-proxy'` is only as honest as the hops in front of the app: the client is the rightmost
833
+ > `X-Forwarded-For` entry that is not itself a trusted proxy. A hop that forwards the client's own
834
+ > header unchanged lets the client choose its address; behind such a hop use `'peer'`, or make the
835
+ > hop append or overwrite the header. An entry that is not an address is never a key; the limit is
836
+ > charged to the nearest trusted hop instead.
1002
837
 
1003
838
  > [!TIP]
1004
839
  > **Binding tokens to an issuer and an audience.** `jwt.issuer` and `jwt.audience` are off by
1005
840
  > default. Set either and its value is stamped on every token this backend mints and **required**
1006
- > on every token it verifies — one carrying a different value, or none at all, is rejected.
1007
- > That matters with HS256, where the verifier can also sign: every service holding the secret to
1008
- > check a token can mint one, so audience binding is what stops a token minted for one service
1009
- > being replayed at another that trusts the same secret.
1010
- >
1011
- > Two things to know before switching it on. Both backends of a shared deployment must carry the
1012
- > same pair, or they stop accepting each other's tokens. And enabling it invalidates the access
1013
- > tokens already in flight, since those were minted without the claims — a window of one
1014
- > access-token lifetime, which clients close by refreshing. An empty string reads as unconfigured
1015
- > rather than as "require the empty issuer", so an unset environment variable cannot turn the
1016
- > check on by accident.
841
+ > on every token it verifies. With HS256 every service holding the secret can mint a token, so
842
+ > audience binding is what stops a token minted for one service being replayed at another that
843
+ > trusts the same secret. Both backends of a shared deployment must carry the same pair, and
844
+ > enabling it invalidates access tokens already in flight (one access-token lifetime, closed by a
845
+ > refresh). An empty string reads as unconfigured, so an unset environment variable cannot turn the
846
+ > check on.
1017
847
 
1018
848
  > **Rotating the signing secret.** `jwt.previousSecrets` lists secrets retired by a rotation,
1019
- > accepted for verification only. Without it, changing `jwt.secret` signs every user out the
1020
- > moment the new configuration rolls out **and** invalidates every stored recovery-code digest —
1021
- > those are keyed by an HMAC derived from the secret, so users lose the codes they printed and
1022
- > filed. With it, both keep working while tokens issued under the old secret drain, and a
1023
- > rotation becomes a rollout. Remove the entry once the longest-lived token signed under it has
1024
- > expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
1025
- > way, through its own list — see below.
849
+ > accepted for verification only. Without it, changing `jwt.secret` signs every user out and
850
+ > invalidates every stored recovery-code digest, since those are keyed by an HMAC derived from the
851
+ > secret. With it both keep working while old tokens drain. Remove an entry once the longest-lived
852
+ > token signed under it has expired: every entry is a key that still opens the door.
853
+ > `mfa.encryptionKey` rotates the same way, through its own list, below.
1026
854
  >
1027
- > **Pin `identifierKey` before you rotate.** Every Redis name that identifies an account — the
1028
- > session index, the token epoch, the MFA keys, the recent-authentication marker, and the OTP and
1029
- > rate-limit identifiers — is an HMAC under a key derived from `jwt.secret` unless you set
1030
- > `identifierKey`, and so are the stored MFA recovery-code digests. Rotate `jwt.secret` alone and
1031
- > all of them are renamed: live sessions lose their index, every token epoch reads zero, so a token
1032
- > that a password reset or a revoke-all had refused is accepted again until it expires, and
1033
- > recovery codes stop verifying unless the old secret is listed in `jwt.previousSecrets`. `identifierKey` is a secret of its own for those names and
1034
- > digests; it is validated like `jwt.secret` and never signs or verifies a token. The value is
1035
- > simply the secret you want them to keep deriving from — there is nothing to compute.
855
+ > **Pin `identifierKey` before you rotate.** Every Redis name that identifies an account (the
856
+ > session index, the token epoch, the MFA keys, the recent-authentication marker, the OTP and
857
+ > rate-limit identifiers) and every stored MFA recovery-code digest is an HMAC under a key derived
858
+ > from `jwt.secret`, unless you set `identifierKey`. Rotate `jwt.secret` alone and all of them are
859
+ > renamed: live sessions lose their index, every token epoch reads zero (so a token that a password
860
+ > reset had refused is accepted again until it expires), and recovery codes stop verifying.
861
+ > `identifierKey` is a secret of its own for those names and digests, validated like `jwt.secret`;
862
+ > it never signs or verifies a token. Its value is simply the secret you want them to keep deriving
863
+ > from.
1036
864
  >
1037
865
  > | | Routine rotation — keep sessions, epochs and recovery codes | Rotation after a compromise — cut the link |
1038
866
  > | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -1043,101 +871,69 @@ All options are configurable via `registerAsync()`. Here are the key configurati
1043
871
  > | 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. |
1044
872
  >
1045
873
  > Pinning to the old secret leaves the derived Redis names computable by anyone who knows that
1046
- > secret. They are names, not signing material, and using one still needs access to your Redis;
1047
- > if cutting that link matters more than keeping sessions, take the second column. Without
1048
- > `identifierKey` a rotation moves the names as the second column does, whether or not you wanted them to.
874
+ > secret. They are names, not signing material, and using one still needs access to your Redis; if
875
+ > cutting that link matters more than keeping sessions, take the second column.
1049
876
 
1050
877
  > [!TIP]
1051
- > **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
1052
- > a rotation of `mfa.encryptionKey`. The stored ciphertext carries no key identifier, so without
1053
- > the list a change of key makes every enrolled user's TOTP secret undecryptable at once, with no
1054
- > way back — their authenticator simply stops matching. With it, a stored secret that opened
1055
- > under a retired key is **re-encrypted under the current one** on the next successful challenge,
1056
- > so the rotation drains on its own instead of requiring the retired key to stay configured
1057
- > forever. Each entry is validated at startup exactly like the current key (base64, exactly 32
1058
- > bytes, and never equal to the current key or to another entry), because a malformed one would
1059
- > otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
1060
- > enrolled users have had time to authenticate at least once.
878
+ > **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by a
879
+ > rotation of `mfa.encryptionKey`. The stored ciphertext carries no key identifier, so without the
880
+ > list a change of key makes every enrolled TOTP secret undecryptable at once. With it, a secret
881
+ > that opened under a retired key is **re-encrypted under the current one** on the next successful
882
+ > challenge, so the rotation drains on its own. Each entry is validated at startup like the current
883
+ > key (base64, exactly 32 bytes, never equal to the current key or another entry). Drop an entry
884
+ > once your enrolled users have authenticated at least once.
1061
885
 
1062
886
  > [!WARNING]
1063
- > **Keep your `updateMfa` fast.** Every MFA state change
1064
- > rewrites the account's MFA record through your repository's `updateMfa`, and the library
1065
- > serializes those writes per account with a lock that expires on its own
1066
- > (`MFA_TRANSITION_LOCK_TTL_SECONDS`, 10 seconds) so a process that dies mid-write cannot strand
1067
- > the account. The lock cannot outlast a write that is still running: if your `updateMfa` stalls
1068
- > past that time, a second change takes the lock, reads the record, and writes it, and the stalled
1069
- > write then lands _after_ it and overwrites it. The repository interface offers no
1070
- > compare-and-set for the library to use, so it cannot detect this. Keep `updateMfa` well under the
1071
- > lock's lifetime (a plain single-row update is, but a call that waits on a contended lock or a slow
1072
- > replica may not be). A guard of your own inside `updateMfa` can narrow the window only for a stall
1073
- > that happens after the guard's own read, such as a wait on a row lock inside the `UPDATE`: the
1074
- > library passes `updateMfa` the new values and not the ones it read, so closing the window
1075
- > completely would need those values passed in. The lock is held
1076
- > across the read the transition makes inside it as well as the write, so a slow `findById` counts
1077
- > against the same lifetime.
887
+ > **Keep your `updateMfa` fast.** The library serializes MFA writes per account with a lock that
888
+ > expires on its own (`MFA_TRANSITION_LOCK_TTL_SECONDS`, 10 seconds), so a process that dies
889
+ > mid-write cannot strand the account. The lock cannot outlast a write that is still running: if
890
+ > your `updateMfa` stalls past that time, a second change takes the lock and writes, and the stalled
891
+ > write then lands _after_ it and overwrites it. The repository interface has no compare-and-set, so
892
+ > the library cannot detect this. Keep `updateMfa` well under the lock's lifetime (a plain
893
+ > single-row update is). The lock also covers the read the transition makes inside it, so a slow
894
+ > `findById` counts against the same lifetime.
1078
895
 
1079
896
  > [!IMPORTANT]
1080
- > **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
1081
- > must be `0..=10`: the window counts 30-second steps on _either_ side of now, so `2n + 1`
1082
- > codes are valid at once — three at the default of 1, but 121 at 60, which makes a six-digit
1083
- > code a hundred times easier to guess while the configuration still reads as "MFA enabled".
1084
- > `mfa.recoveryCodeCount` must be `1..=50`, because zero enrols an account with no way back
1085
- > if the authenticator is lost. `password.blockSize` must be at least 8 and
1086
- > `password.parallelization` at least 1: scrypt's memory cost is `128 * N * r`, so a smaller
1087
- > block size divides the hardness that `password.costFactor`'s floor exists to guarantee —
1088
- > invisibly, since the bounded parameter is still intact. `rust-auth` enforces the identical
1089
- > ranges.
897
+ > **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow` must
898
+ > be `0..=2`: the window counts 30-second steps on _either_ side of now, so `2n + 1` codes are
899
+ > valid at once (three at the default of 1). `mfa.recoveryCodeCount` must be `1..=50`,
900
+ > because zero enrols an account with no way back if the authenticator is lost.
901
+ > `password.blockSize` must be at least 8 and `password.parallelization` at least 1: scrypt's memory
902
+ > cost is `128 * N * r`, so a smaller block size divides the hardness `password.costFactor`'s floor
903
+ > exists to guarantee.
1090
904
 
1091
905
  > [!IMPORTANT]
1092
- > `jwt.accessExpiresIn` must not exceed **30 days**, the window the store keeps a bumped token
1093
- > epoch readable. The epoch is what makes a stateless access token revocable: a password reset
1094
- > advances it and every token stamped below it stops verifying — but only while the bumped value
1095
- > is still there. A longer-lived access token would outlive it, the lookup would fall back to
1096
- > `0`, and a token the reset revoked would verify again. Startup refuses the configuration
1097
- > rather than letting it fail open, and rejects an unreadable time span or a non-positive
1098
- > lifetime on the same pass.
906
+ > `jwt.accessExpiresIn` must not exceed **30 days**, the window the store keeps a bumped token epoch
907
+ > readable. A longer-lived access token would outlive the epoch, the lookup would fall back to `0`,
908
+ > and a token a password reset had revoked would verify again. Startup refuses the configuration
909
+ > rather than failing open, and rejects an unreadable time span or a non-positive lifetime on the
910
+ > same pass.
1099
911
 
1100
912
  > [!WARNING]
1101
913
  > **Do not gate on the access token's `status` claim.** It is **point-in-time, never
1102
- > authoritative**, and which of its three states you get depends on things a client cannot see:
1103
- >
1104
- > | how the token was minted | `status` |
1105
- > | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
1106
- > | login, register, OAuth, MFA challenge | the account's value **at that moment** |
1107
- > | an ordinary refresh rotation | **empty string** — the session record carries no live status, so there is nothing to copy |
1108
- > | a refresh that re-signs because `role`, `tenantId` or `mfaEnabled` changed | the account's value **at that moment**, read during that request |
914
+ > authoritative**:
1109
915
  >
1110
- > `rust-auth` stamps the same empty string on its rotation path, deliberately and with a test
1111
- > pinning it, so the middle row is a shared contract rather than a defect in either library.
916
+ > | how the token was minted | `status` |
917
+ > | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
918
+ > | login, register, OAuth, MFA challenge | the account's value **at that moment** |
919
+ > | an ordinary refresh rotation | **empty string**: the session record carries no live status, so there is nothing to copy |
920
+ > | a refresh that re-signs because `role`, `tenantId` or `mfaEnabled` changed | the account's value **at that moment**, read during that request |
1112
921
  >
1113
- > Every populated value is stale the instant the account changes, because status can change under
1114
- > an unexpired token and nothing re-stamps it. So a route that reads the claim is wrong in **both**
1115
- > directions: `status !== 'active'` refuses everyone whose session has been refreshed ordinarily,
1116
- > and `status === 'suspended'` refuses nobody, ever. Both fail quietly and hours from the code
1117
- > that caused them — the first looks like a broken login, the second like nothing at all.
922
+ > Every populated value is stale the instant the account changes, so a route that reads the claim
923
+ > is wrong in **both** directions: `status !== 'active'` refuses everyone whose session was
924
+ > refreshed ordinarily, and `status === 'suspended'` refuses nobody. Resolve status per request:
925
+ > mount `UserStatusGuard` on the route (on a WebSocket, SSE stream or message consumer, call
926
+ > `AuthTokenVerifierService.verifyAccessToken`, which resolves status through the same cache before
927
+ > it applies the MFA policy), and for anything richer read the account **tenant-scoped**:
928
+ > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is
929
+ > required by the port because ids may collide across tenants.
1118
930
  >
1119
- > The exceptional re-stamp is the worst of the three for a reader, not the best: it makes the
1120
- > claim _usually_ wrong instead of _reliably_ empty, which is the failure mode that survives
1121
- > testing.
1122
- >
1123
- > Status is resolved per request or not at all: mount `UserStatusGuard` on the route (on a
1124
- > WebSocket, SSE stream or message consumer, call `AuthTokenVerifierService.verifyAccessToken`,
1125
- > which resolves status through the same cache before it applies the MFA policy), and for
1126
- > anything richer read the account **tenant-scoped**, the way that guard does —
1127
- > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is required by the
1128
- > port and cannot be dropped: ids may collide across tenants, so a lookup by bare id can resolve
1129
- > another tenant's account. That is what the library's own guards do, which
1130
- > is why the claim can be left as it is. `mfaVerified` behaves the same way and for the same
1131
- > reason — it is always `false` after a rotation, so step-up does not survive a refresh and a
1132
- > user re-acquires it through the MFA challenge.
1133
- >
1134
- > One consequence worth planning for: the guard reads a status cache with a
1135
- > `userStatusCacheTtlSeconds` window (default **60**), so a suspension takes up to that long to
1136
- > bite on a guarded route, and a reactivation the same to restore. Call
1137
- > `AccountStatusService.invalidate({ userId, tenantId })` after persisting a status change to drop
1138
- > that account's cached status immediately; a request already resolving can still write the old
1139
- > value back, so the window narrows to one repository read rather than to zero (see
1140
- > [Invalidating the account cache](#invalidating-the-account-cache--accountstatusserviceinvalidate)).
931
+ > The guard reads a status cache with a `userStatusCacheTtlSeconds` window (default **60**), so a
932
+ > suspension takes up to that long to bite on a guarded route, and a reactivation the same to
933
+ > restore. Call `AccountStatusService.invalidate({ userId, tenantId })` after persisting a status
934
+ > change to drop that account's cached status at once (a request already resolving can still write
935
+ > the old value back; see
936
+ > [Invalidating the account cache](./docs/server-services.md#invalidating-the-account-cache--accountstatusserviceinvalidate)).
1141
937
  > `bumpUserTokenEpoch` is the heavier lever: it ends every session the user has. Lower
1142
938
  > `userStatusCacheTtlSeconds` if a faster answer matters more than the repository reads it costs.
1143
939
 
@@ -1158,6 +954,35 @@ behaviour for origins that already exist. It is required as soon as `cookies.sam
1158
954
  is set, and refused otherwise — that posture is the only one where the browser sends the session
1159
955
  cookie cross-site, and it is the only one where the origin check has anything to authorize.
1160
956
 
957
+ > [!IMPORTANT]
958
+ > **Bound your Redis client.** Every authentication and authorization decision here reads Redis and
959
+ > **fails closed**: when Redis is unreachable the request is answered with a `5xx` or a refusal,
960
+ > never admitted. What the library cannot do is bound how long the client waits before it gives
961
+ > up, because the client is yours (`BYMAX_AUTH_REDIS_CLIENT`). With ioredis defaults the offline
962
+ > queue is on and a command retries up to 20 times, so a Redis outage reads as requests that hang
963
+ > before they fail, and `maxRetriesPerRequest: null` waits forever. Build the client with a
964
+ > deadline on every command and a bounded reconnect:
965
+ >
966
+ > ```typescript
967
+ > new Redis(url, {
968
+ > commandTimeout: 500, // ms; every command rejects after this, which the guards answer as a 5xx
969
+ > maxRetriesPerRequest: 1, // do not queue a command through repeated reconnects
970
+ > enableOfflineQueue: false, // refuse a command while disconnected instead of holding it
971
+ > retryStrategy: (attempt) => Math.min(attempt * 200, 2000) // bounded, never `null` in a server
972
+ > })
973
+ > ```
974
+ >
975
+ > This is the **auth** client: give a BullMQ queue its own connection. BullMQ workers require `maxRetriesPerRequest: null`, which is the opposite of the setting
976
+ > above, so one shared client forces a choice between the two.
977
+ >
978
+ > The module warns at startup when the client carries no `commandTimeout`, and it sends `PING`
979
+ > at bootstrap every quarter second for up to 5 seconds, so a Redis that is still starting does not
980
+ > fail the boot on its first refusal, while a mis-pointed address or a wrong password stops the
981
+ > process from starting, with a message that names only the host and port, instead of surfacing as the first
982
+ > request's `5xx`. Expect `5xx` on login, refresh, rate-limited routes and every guarded route for
983
+ > as long as Redis is down: that is the fail-closed behaviour, and a health check on Redis belongs
984
+ > next to your readiness probe.
985
+
1161
986
  The breach check is opt-in for a different reason: it is the only part of the credential path
1162
987
  that reaches the network, and a library should not start talking to a third party because it was
1163
988
  upgraded. Wire it explicitly:
@@ -1214,7 +1039,7 @@ fails at startup and says which is missing.
1214
1039
  | `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. |
1215
1040
  | `prefix` | `'bak'` | Literal start of every issued key, for secret scanners. Lowercase letters and digits, 2 to 16, no underscore. |
1216
1041
  | `lastUsedFlushSeconds` | `60` | How often coalesced `lastUsedAt` values are written, in one batch. 1 to 3600. |
1217
- | `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). |
1042
+ | `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](./docs/service-api-keys.md#audit). |
1218
1043
 
1219
1044
  ### Protect a route
1220
1045
 
@@ -1305,136 +1130,18 @@ export class KeysAdminController {
1305
1130
  not rotated (`auth.api_key_not_found`): that would re-issue access nobody holds.
1306
1131
  - `revoke(id)` takes effect on the very next request: the row is read on every request, and
1307
1132
  there is no verification cache.
1308
- - **Who did it.** `issue`, `revoke` and `rotate` emit no hook of their own — they run inside
1309
- your admin route, which already knows the operator, so attribute them there (log or audit it
1310
- beside the call). The per-request hook below covers requests _made with_ a key. If you want
1311
- provenance stored with the key, add your own columns: `IApiKeyRepository.create` receives the
1312
- row and your implementation can persist whatever else it knows. That is why `issue()` takes
1313
- no `createdBy`.
1314
-
1315
- ### The repository
1316
-
1317
- You implement `IApiKeyRepository`, as you do for users. The library supplies the `id` and the
1318
- `digest`; the store only persists them.
1319
-
1320
- | Method | Contract |
1321
- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1322
- | `findById(id)` | One primary-key read per request. Return revoked and expired rows too: the library decides validity. |
1323
- | `create(row)` | Insert `{ id, label, digest, scopes, createdAt, expiresAt }`. Do not make `label` unique. |
1324
- | `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`. |
1325
- | `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. |
1326
- | `limitExpiry(id, at)` | **Optional, recommended.** An atomic minimum: lower the expiry to `at`, never raise it (`SET expires_at = LEAST(COALESCE(expires_at, :at), :at)`). `false` when unknown. Rotation uses it when present; without it two rotations of one key can interleave and leave the old key valid past the shortest overlap, so serialize rotation per key. |
1327
- | `touchLastUsed(entries)` | One batch. **Must be monotonic**: `GREATEST(last_used_at, :at)`, never backwards — several instances flush independently. |
1328
- | `listByLabel(label)` | Every key of a label, for your admin screen. |
1329
-
1330
- ### How a key is stored and checked
1331
-
1332
- A key looks like `bak_<keyId>_<secret>`: a literal prefix, the row's UUID (a public handle that
1333
- makes verification an indexed read), and 43 base64url characters carrying 32 random bytes. Only
1334
- `HMAC-SHA-256(pepper, secret)` is stored, as lowercase hex. Labels and scopes are not part of the
1335
- digest, so editing them never invalidates a key. The grammar and the digest are pinned by
1336
- [`conformance/wire-contract.json`](./conformance/wire-contract.json) with a vector, because
1337
- `rust-auth` mints and verifies the same keys.
1338
-
1339
- **Why a fast HMAC rather than a slow password hash.** This is the library's own reasoning, not
1340
- an OWASP rule: the OWASP Password Storage Cheat Sheet's case against fast hashes is about
1341
- passwords, which people choose and which can be guessed. A key's secret is 256 bits from the
1342
- CSPRNG, so the work factor of the hash adds nothing to its resistance, and a per-request scrypt
1343
- would only hand an attacker a cheap way to burn CPU. The pepper is what the cheat sheet calls
1344
- the HMAC key: kept apart from the database, so a leaked table of digests cannot be tested
1345
- offline.
1346
-
1347
- **Every key takes the same steps.** Parse (substituting a dummy when it does not parse), read a
1348
- row (always), compute the digest, compare two 32-byte buffers with `timingSafeEqual` (against a
1349
- dummy digest when there is no row), and only then decide. An unknown, malformed, wrong, revoked
1350
- or expired key all answer `401 auth.api_key_invalid` with the same body; the operator sees the
1351
- real reason in the audit event. A key is valid strictly before its `expiresAt`, and not at all once `revokedAt` is set.
1352
-
1353
- Two things this does _not_ claim. The store round trip costs differently for a present and an
1354
- absent row, and no library can hide that — put a per-address throttle in front (below). And the
1355
- fail-closed branch (a bound route with no scopes) intentionally takes different steps: it
1356
- depends on route configuration, not on the key, so there is nothing for the key to leak.
1357
-
1358
- **Changing the pepper makes every issued key unverifiable.** Digests are not portable across
1359
- peppers, so a new pepper means re-issuing every key. There is no pepper rotation in this
1360
- version.
1361
-
1362
- ### Audit
1363
-
1364
- Implement `onApiKeyRequest` on your `IAuthHooks`. It fires once for every guarded request:
1365
-
1366
- ```typescript
1367
- import type { ApiKeyAccessEvent, HookContext, IAuthHooks } from '@bymax-one/nest-auth'
1368
-
1369
- export class AuditHooks implements IAuthHooks {
1370
- async onApiKeyRequest(event: ApiKeyAccessEvent, context: HookContext): Promise<void> {
1371
- // event.outcome: 'allowed' | 'denied'
1372
- // event.reason: null, or missing | malformed | unknown | wrong_secret | revoked | expired
1373
- // | scope_insufficient | route_undeclared | store_error
1374
- // event.label, event.keyId, event.method, event.route (the PATTERN, e.g. /videos/:id),
1375
- // event.requiredScopes, event.ip
1376
- await this.audit.write({ ...event, userAgent: context.userAgent })
1377
- }
1378
- }
1379
- ```
1380
-
1381
- 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
1382
- denied** (`500 auth.internal`): use that when the audit row is a record you must have.
1383
-
1384
- ### Keep the key out of your logs
1385
-
1386
- The library never logs, throws or emits the presented key, and strips the key header from the
1387
- hook's `sanitizedHeaders`. Your HTTP logger sits outside the library, so redact the header
1388
- there, custom `apiKeys.header` included:
1389
-
1390
- ```typescript
1391
- // nest-logger
1392
- LoggerModule.forRoot({ redactPaths: ['req.headers["x-machine-key"]'] })
1393
- ```
1394
-
1395
- ```typescript
1396
- // plain pino
1397
- const logger = pino({ redact: ['req.headers["x-api-key"]'] })
1398
- ```
1399
-
1400
- ### Rate limiting
1401
-
1402
- Rate limiting is deliberately not built in. Use `@nestjs/throttler` in two layers: a per-address
1403
- limit in front of everything, which is the only protection for the pre-verification lookup; and
1404
- a per-key limit placed **after** `ApiKeyGuard`, keyed on the verified key id:
1405
1133
 
1406
- ```typescript
1407
- import { UseGuards, Get } from '@nestjs/common'
1408
- import { ServiceKey } from '@bymax-one/nest-auth'
1409
- import type { ApiKeyPrincipal } from '@bymax-one/nest-auth'
1410
- import { ThrottlerGuard } from '@nestjs/throttler'
1411
-
1412
- export class KeyThrottlerGuard extends ThrottlerGuard {
1413
- protected override async getTracker(req: Record<string, unknown>): Promise<string> {
1414
- const key = req['apiKey'] as ApiKeyPrincipal | undefined
1415
- return key?.id ?? String(req['ip'])
1416
- }
1417
- }
1418
-
1419
- export class LimitedController {
1420
- // @UseGuards sits ABOVE @ServiceKey: decorators run bottom-up and the guards run in that
1421
- // order, so the key guard verifies first and the tracker sees `request.apiKey`.
1422
- @UseGuards(KeyThrottlerGuard)
1423
- @ServiceKey('read')
1424
- @Get('limited')
1425
- limited() {}
1426
- }
1427
- ```
1428
-
1429
- A request that fails verification never reaches the second guard, so garbage cannot spend a real
1430
- key's budget. This example is exercised end to end in `test/e2e/api-keys.e2e-spec.ts`.
1431
-
1432
- ### Last-used tracking, and what it costs
1134
+ Everything else is in [Service API keys: reference](./docs/service-api-keys.md):
1433
1135
 
1434
- A verified request does a map write, nothing else; every `lastUsedFlushSeconds` the values are
1435
- written to your repository in one batch. With **N instances** a key is written up to N times
1436
- per window instead of once, and a crash loses at most one window of `lastUsedAt`. The field is
1437
- advisory: authorization never reads it.
1136
+ - **The repository** you implement (`IApiKeyRepository`): what each method must guarantee.
1137
+ - **How a key is stored and checked**: `bak_<keyId>_<secret>`, only `HMAC-SHA-256(pepper, secret)`
1138
+ is stored, every key takes the same steps and every refusal answers `401 auth.api_key_invalid`.
1139
+ Changing the pepper makes every issued key unverifiable.
1140
+ - **Audit**: implement `onApiKeyRequest` on your `IAuthHooks`; it fires for every guarded request,
1141
+ refused ones included. With `apiKeys.auditMode: 'required'` a throwing hook denies the request.
1142
+ - **Logs and rate limiting**: the library never logs the key, but your HTTP logger sits outside it,
1143
+ so redact the key header there. Rate limiting is deliberately not built in; use
1144
+ `@nestjs/throttler` per address before the guard and per key after it.
1438
1145
 
1439
1146
  ## 🗂️ Workspaces (one identity, many workspaces)
1440
1147
 
@@ -1477,7 +1184,8 @@ BymaxAuthModule.registerAsync({
1477
1184
 
1478
1185
  `controllers.workspaces` mounts the routes and needs `workspaces.enabled` and both repositories.
1479
1186
  `controllers.workspaceInvitations` also needs an email provider that implements
1480
- `sendWorkspaceInvitation`. The module refuses to boot when a piece is missing. With
1187
+ `sendWorkspaceInvitation`, which the bundled `DefaultAuthEmailProvider` does. The module refuses to
1188
+ boot when a piece is missing. With
1481
1189
  `workspaces.enabled: false`, the default, nothing in this section exists in your application.
1482
1190
 
1483
1191
  You implement two ports: `IWorkspaceRepository` (`createWithOwner`, `findById`, `rename`,
@@ -1505,8 +1213,9 @@ the last owner.
1505
1213
 
1506
1214
  `registration: 'invitation-only'` closes sign-up except through an invitation for that exact address
1507
1215
  (password registration and the OAuth `create` action answer `403 auth.registration_closed`; the
1508
- invitation accept routes stay open; existing accounts keep signing in). Startup refuses the mode when
1509
- workspaces and tenant invitations are both disabled.
1216
+ invitation accept routes stay open; existing accounts keep signing in). Startup refuses the mode unless an
1217
+ invitation controller is mounted (`controllers.workspaceInvitations` with `workspaces.enabled`, or
1218
+ `controllers.invitations` with `invitations.enabled`), and names what is missing.
1510
1219
 
1511
1220
  ### Protect a route
1512
1221
 
@@ -1571,52 +1280,6 @@ start, `GET /oauth/:provider?workspaceInvitation=<token>`: it stores only the to
1571
1280
  state record and answers with `Referrer-Policy: no-referrer`. On your accept page, put the token in
1572
1281
  the URL fragment and set `Referrer-Policy: no-referrer` there.
1573
1282
 
1574
- ### Hooks and events
1575
-
1576
- `beforeWorkspaceCreate(user, { name }, context)` can refuse a creation. `onWorkspaceEvent(event,
1577
- context)` receives, after the change has committed, `workspace.created`, `.renamed`,
1578
- `.deletion_scheduled`, `.restored` and `.deleted`; `member.invited`, `invitation.resent`,
1579
- `.revoked` and `.accepted`; `member.role_changed`, `.removed` and `.left`; `ownership.transferred`;
1580
- `workspace.switched`; and `access.denied` (with the `surface`, the public `code` and a host-only
1581
- `reason`). It is best-effort and informational: the repository's persisted audit row is the record.
1582
-
1583
- ### Deleting an account
1584
-
1585
- The library never deletes a user: `IUserRepository` has no delete. A host that deletes or anonymises
1586
- a user row must remove that user's memberships first, or the rows stay behind, still count as
1587
- members of their workspaces, and a deleted owner keeps a workspace from ever being seen as
1588
- orphaned. Call `MembershipService.removeAllForUser(tenantId, userId, actorUserId, context)` before
1589
- the delete. `actorUserId` is the account itself, an administrator, or `null` for a job.
1590
-
1591
- It removes every membership of the account, in every membership status and every workspace, with one
1592
- `member.removed` event per removal and the cached access of each dropped, so access ends at the next
1593
- request. Only the repository can find them all (`listForUser` lists active memberships of active
1594
- workspaces only), so it is one call on the membership port, `removeAllForUser`, which you implement
1595
- in one transaction together with the audit rows.
1596
-
1597
- - **It refuses while the account is the only owner of an active or suspended workspace:** `409
1598
- auth.last_owner` with `details.workspaces` (`{ id, name, status }`, at most 100; `{ id }` alone for one the repository found during the write), and nothing is
1599
- removed. Transfer ownership or schedule the workspace's deletion first.
1600
- - **A workspace pending deletion does not block.** No one can finalize a pending deletion before
1601
- its grace period ends, so an owner who scheduled one would otherwise be unable to delete their own
1602
- account for the whole period. Their membership there is removed with the rest, the workspace can no
1603
- longer be restored (restoring is owner-only), and your finalize job deletes it when the grace period
1604
- ends.
1605
- - **If a cache bump fails after the commit,** the call throws `MembershipBumpFailedError` with
1606
- `removed` and `failed`. The removal is already committed, so calling it again removes nothing: drop
1607
- the access of each entry of `failed` with `WorkspaceAccessService.invalidateMembership`, or wait out
1608
- `membershipCacheTtlSeconds`.
1609
-
1610
- ### Accepting an invitation through OAuth, and MFA
1611
-
1612
- An OAuth flow started with a workspace invitation vets the invitation against the provider's profile
1613
- before your `onOAuthLogin` hook runs, and completes it for the account that results. **When that
1614
- account has a second factor, the library does not complete the invitation:** the callback answers the
1615
- MFA challenge as it does for any OAuth sign-in, the invitation stays pending and unspent, and it is
1616
- not resumed after the challenge. The signed-in caller accepts it with `POST
1617
- workspaces/invitations/accept` and the same token, so a host whose members use MFA should send the
1618
- token again from its accept page after sign-in.
1619
-
1620
1283
  ### Frontend
1621
1284
 
1622
1285
  ```typescript
@@ -1655,14 +1318,14 @@ writes the cookie and the value carries no authority; the layout's reader decide
1655
1318
  an inbound `x-workspace-id` and never sets one. Path values go through `fillRoute` and `pathSegment`
1656
1319
  (`./shared`), which refuse an empty value, `.` and `..` and percent-encode the rest.
1657
1320
 
1658
- ### Threat model
1321
+ ### Hooks, account deletion and the threat model
1659
1322
 
1660
- A workspace id is never trusted from the body, a header or a stored default; the guard resolves it
1661
- from the route and the membership from the repository. Non-members and nonexistent workspaces are
1662
- indistinguishable. A platform token has no implicit bypass. Memberships are cached for
1663
- `membershipCacheTtlSeconds` and read under version counters, so a stale value is never served after a
1664
- change the library made. The host's rate limiting on guarded routes is what bounds a caller probing
1665
- workspace ids.
1323
+ `beforeWorkspaceCreate` can refuse a creation and `onWorkspaceEvent` receives every committed change.
1324
+ A host that deletes a user must call `MembershipService.removeAllForUser(tenantId, userId,
1325
+ actorUserId, context)` first; it refuses with `409 auth.last_owner` while the account is the only
1326
+ owner of an active or suspended workspace. A workspace id is never trusted from the body, a header
1327
+ or a stored default, and non-members and nonexistent workspaces are indistinguishable. All of it is in
1328
+ [Workspaces: reference](./docs/workspaces.md).
1666
1329
 
1667
1330
  ---
1668
1331
 
@@ -1730,14 +1393,6 @@ The `tenantId` is always extracted from the validated JWT — never from the req
1730
1393
 
1731
1394
  Access tokens are short-lived (default 15 minutes) and immediately revocable via a Redis JTI blacklist. Refresh tokens rotate on every use with a configurable grace window to handle concurrent requests. This is the industry-standard hybrid approach used by Auth0, Okta, and SuperTokens — combining short lifetimes for low-latency revocation with rotating refresh tokens for session continuity.
1732
1395
 
1733
- ### Password Hashing
1734
-
1735
- Passwords are hashed with **scrypt** via `node:crypto`, which is memory-hard and resistant to GPU-based brute-force attacks. All secret comparisons use `crypto.timingSafeEqual` for constant-time evaluation — [a requirement explicitly documented](https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b) in the Node.js crypto documentation.
1736
-
1737
- ### No External Cryptographic Dependencies
1738
-
1739
- All security-critical operations use the OpenSSL-backed `node:crypto` module — no bcrypt, argon2, otpauth, uuid, or nanoid packages. This eliminates the supply chain attack surface for the most sensitive code paths.
1740
-
1741
1396
  ### Security Checklist
1742
1397
 
1743
1398
  When integrating `@bymax-one/nest-auth` in production, verify each of the following:
@@ -1789,9 +1444,6 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1789
1444
  | Rate Limiting | Per-IP fixed-window counters in Redis, keyed by `HMAC(ip)` — enforced by the library, not by the host |
1790
1445
  | Session Lifetime | Optional absolute cap on how long one login can be extended by rotation |
1791
1446
 
1792
- > [!IMPORTANT]
1793
- > This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
1794
-
1795
1447
  ---
1796
1448
 
1797
1449
  ## 🧱 Tech Stack
@@ -1939,16 +1591,13 @@ Three constraints are worth stating because they are not visible from the field
1939
1591
  length here would leak it as a pre-KDF timing signal, because a request failing validation
1940
1592
  returns before the hash runs.
1941
1593
 
1942
- #### On `@bymax-one/nest-core`, the security posture writes itself
1594
+ #### OpenAPI: the security posture writes itself
1943
1595
 
1944
1596
  A deployment that builds its OpenAPI document with `@bymax-one/nest-core` **1.4.0 or later** gets
1945
- this library's operations described automatically — which schemes exist, which operation requires
1946
- which, and which are reachable unauthenticated. Nothing to enable and nothing to import: the
1947
- module registers a contributor, nest-core discovers it while building the document, and the
1948
- fragments are merged.
1949
-
1950
- It has to be derived at your boot rather than shipped as a static file, because the answer
1951
- depends on your configuration:
1597
+ this library's operations described automatically: which schemes exist, which operation requires
1598
+ which, and which are reachable unauthenticated. Nothing to enable and nothing to import; the module
1599
+ registers a contributor and nest-core merges its fragments. The answer depends on your
1600
+ configuration, so it is derived at your boot:
1952
1601
 
1953
1602
  | your options | what the document says |
1954
1603
  | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -1958,17 +1607,15 @@ depends on your configuration:
1958
1607
  | `controllers.platform: true` | `bymaxPlatformAccessBearer` — always bearer, in every mode, because platform credentials are read from the header whatever `tokenDelivery` says. The **registration** switch decides, not `platform.enabled`: the module mounts the platform controllers on `controllers.platform` and validates the `platform` config only then |
1959
1608
  | a controller you did not mount | nothing at all: no operation, and no scheme only it would have referenced |
1960
1609
 
1961
- A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced — a
1962
- document that defines a credential the server will not read tells a generated client to offer it.
1610
+ A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced.
1963
1611
 
1964
1612
  The four names — `bymaxAuthAccessCookie`, `bymaxAuthAccessBearer`, `bymaxAuthRefreshCookie`,
1965
1613
  `bymaxPlatformAccessBearer` — are stable identifiers. Renaming one is a break a generated client
1966
1614
  feels, so they will not change; their **definitions** are config-derived.
1967
1615
 
1968
- Import them rather than spelling them. A platform-only deployment guarding its own routes with
1969
- `JwtAuthGuard` has to declare the dashboard access scheme itself — the fragment will not, because
1970
- `schemesFor` gates dashboard schemes on what you mounted — and a hand-written literal in a section
1971
- about literals drifting from configuration is the wrong instruction:
1616
+ Import them rather than spelling them: a hand-written literal drifts from your configuration. A
1617
+ platform-only deployment guarding its own routes with `JwtAuthGuard` has to declare the dashboard
1618
+ access scheme itself, because the fragment only declares what you mounted.
1972
1619
 
1973
1620
  ```typescript
1974
1621
  import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
@@ -1977,518 +1624,24 @@ import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
1977
1624
  const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
1978
1625
  ```
1979
1626
 
1980
- > **This package does not depend on `@bymax-one/nest-core`** — not as a dependency, a peer, or a
1981
- > devDependency. The contract revision is inlined, the discovery marker is the documented string
1982
- > literal, and a gate fails the build if any file here imports another Bymax library. That keeps
1983
- > your install graph free of a package you may not use, and it moves one check to your side:
1984
- >
1985
- > ```typescript
1986
- > // in your suite, where both packages are installed at the versions you run
1987
- > import {
1988
- > BYMAX_OPENAPI_CONTRACT_VERSION,
1989
- > BYMAX_OPENAPI_CONTRIBUTOR_METADATA
1990
- > } from '@bymax-one/nest-core/openapi'
1991
- >
1992
- > expect(fragment.contractVersion).toBe(BYMAX_OPENAPI_CONTRACT_VERSION)
1993
- > expect(Reflect.getMetadata(BYMAX_OPENAPI_CONTRIBUTOR_METADATA, contributor.constructor)).toBe(
1994
- > true
1995
- > )
1996
- > ```
1997
- >
1998
- > Worth writing once. A revision mismatch fails your document build loudly and names the
1999
- > contributor, but a **marker** mismatch is silent: the provider is simply never discovered and
2000
- > the document renders without the fragments — the same symptom as running nest-core < 1.4.0.
2001
-
2002
- > **On nest-core older than 1.4.0 the fragments are silently ignored.** There is no contributor
2003
- > lane to discover them, so the document renders exactly as before — no error, no warning, no
2004
- > failed boot. If you add a document and the auth schemes do not appear, check in this order:
2005
- > whether this library is new enough to contribute them at all, and only then your nest-core
2006
- > version. The two states look identical from the document.
2007
-
2008
- #### On `@bymax-one/nest-core` 1.6.1 or later, the request bodies are described too
2009
-
2010
- The same contributor offers the request-body schema of every DTO that the controllers your
2011
- deployment mounted take (`LoginDto`, `RegisterDto`, `ResetPasswordDto` and the rest), derived from
2012
- their `class-validator` decorators. Without a contribution `@nestjs/swagger` registers each of them as
2013
- `{"type":"object","properties":{}}`, because this package is built without its CLI plugin, and a
2014
- client generated from the document types every request body as `{}`.
2015
-
2016
- > **Request schemas appear with `@bymax-one/nest-core` ≥ 1.6.1; older versions ignore the
2017
- > contribution without a signal.** Through 1.6.0 an empty placeholder counts as a declaration, so
2018
- > the schema offered here is dropped and the document renders exactly as before: no error, no
2019
- > warning, and no `discarded` field on what `applyBymaxOpenApi` returns. From 1.6.1 the
2020
- > placeholder is filled from the contribution. A schema of the same name that carries properties
2021
- > of its own is a declaration and wins, and `applyBymaxOpenApi` reports the contribution that
2022
- > lost in `discarded`. Components are keyed by the DTO's class name, so a DTO of your own that
2023
- > shares a name with one of this library's (a `LoginDto`, say) and is itself an empty placeholder
2024
- > is filled with this library's schema: name your own classes differently.
2025
-
2026
- Two limits, so a missing field is not mistaken for a bug. The OAuth endpoints take their input as
2027
- query parameters, which the builder describes as operation parameters rather than as a component,
2028
- so no schema is offered for those two DTOs. And what a decorator cannot express (which proof
2029
- `ResetPasswordDto` accepts for the configured `passwordReset.method`, the deployment's
2030
- `password.minLength`) is not in the schema and is not described elsewhere in the served document.
2031
-
2032
- **If you already wrote these by hand, delete them** — not because they are wrong. They are what
2033
- makes your document correct today; the deletion is what hands the job to the library, and it is
2034
- needed precisely because they were doing it. Precedence, read from nest-core's
2035
- `augmentOperation` rather than summarised: the generated operation's own `security` outranks
2036
- everything, then your `openapi.operationSecurity` override, then this library's fragment, then
2037
- nest-core's policy. So a stale scheme name or an override for an auth route keeps winning and the
2038
- contributed one never lands — the document goes on describing whatever you wrote when you wrote
2039
- it, including cookie names you have since changed.
2040
-
2041
- > **Delete the entries for THESE routes. Keep your document-level `security`.** They are usually
2042
- > written in the same options block, and taking the block out is the failure this warning exists
2043
- > for — reported by a consumer who ran the comparison below and found their document **more wrong
2044
- > after adopting than before**. The mechanism is in `augmentOperation`: an operation with no
2045
- > requirement of its own, no override and no fragment falls through to `ownRouteSecurity`, which
2046
- > answers `undefined` for anything that is not a route nest-core answers for itself — the health
2047
- > probes, and from **nest-core 1.5.3** an unprotected metrics endpoint (through 1.5.2 metrics was
2048
- > not among them). So **your** guarded routes carry no requirement and inherit the document
2049
- > default. Remove that default and every one of those routes reads as needing no credential.
2050
- >
2051
- > **Keep the condition attached, because it decides how much of your API is affected.** This
2052
- > reaches the routes that state nothing of their own — no `@ApiSecurity`-style decorator feeding
2053
- > the scanned operation, no entry in nest-core's `operationSecurity`, and not a route nest-core
2054
- > answers for itself. Anything carrying its own requirement outranks the document default and is
2055
- > untouched, which is exactly why the fix works at all. If your backend annotates every guarded
2056
- > route individually, this note does not apply to you; the reason it bit two consumers is that
2057
- > annotating each route is the thing a document-level default exists to avoid.
2058
- >
2059
- > **nest-core's own routes are the exception that still moves.** It emits an explicit `security: []`
2060
- > for the health probes — and, from 1.5.3, for a metrics endpoint left unprotected — but only when
2061
- > the **served document actually carries a non-empty top-level `security`**, whether that came from
2062
- > `openapi.security` or was already on the generated document handed to nest-core.
2063
- > Remove the default and the `[]` goes with it. Write the default as an explicit empty list and
2064
- > nothing is being overridden, so the member stays absent either way.
2065
- >
2066
- > (Through 1.5.2 that condition read `openapi.security.length > 0` alone, which answered `false`
2067
- > for a document that carried its own default without one being configured — so those routes
2068
- > inherited a credential nest-core does not check. If you build the document yourself rather than
2069
- > handing the default to `openapi.security`, that is your shape, and 1.5.3 is the fix.)
2070
- >
2071
- > **On nest-core below 1.5.0, nothing reports this.** No error, no unmatched key, no failing
2072
- > build — the document simply stops asking for credentials on the routes the library never knew
2073
- > about, which are the ones your backend owns. **nest-core 1.5.0 warns**, on exactly this shape:
2074
- > a document with no top-level `security` where some other operation does state a requirement, so
2075
- > the bare ones are bare against a described posture rather than in a document that describes
2076
- > none. It names the operations and never throws. That makes the failure visible, not impossible —
2077
- > a warning in a build log is still something a person has to read.
2078
- >
2079
- > Keep the default, and **derive it rather than writing a literal**. Since 1.4.4 the derivation
2080
- > ships, so the common case is one call rather than a rule you apply by hand:
2081
- >
2082
- > ```ts
2083
- > import { authDocumentSecurity } from '@bymax-one/nest-auth'
2084
- >
2085
- > BymaxCoreModule.forRoot({
2086
- > openapi: {
2087
- > // `tokenDelivery` here is the SAME value you pass to BymaxAuthModule.forRoot — read it from
2088
- > // one place. A default derived from a second copy drifts exactly like a literal does.
2089
- > security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
2090
- > }
2091
- > })
2092
- > ```
2093
- >
2094
- > It answers the delivery axis of both questions below — the scheme name for your guard family,
2095
- > and the two-entry alternation under `'both'` that a hand-written default usually collapses into
2096
- > a single AND entry. **It does not know what you mounted**, which is the third row of the table
2097
- > in question 2 and the one case you still have to answer yourself. Read on for that, and for why
2098
- > the recipe takes two questions rather than one:
2099
- >
2100
- > **1. Which guard protects your own routes?** That decides the credential family, and
2101
- > `tokenDelivery` does not enter into it for one of them.
2102
- >
2103
- > - `JwtAuthGuard` (the dashboard family) → an access scheme, chosen by delivery. Go to question 2.
2104
- > - `JwtPlatformGuard` → **`bymaxPlatformAccessBearer`, in every mode**. `extractPlatformAccessToken`
2105
- > reads the `Authorization` header whatever `tokenDelivery` says, and `schemesFor` declares that
2106
- > scheme with no delivery condition on it. A platform-guarded route wants it under `cookie`
2107
- > delivery exactly as much as under `bearer`.
2108
- > - **Both, on different routes** → the default cannot express this, though not because it is
2109
- > limited to one entry. A document `security` array may hold both requirements — but the entries
2110
- > are **alternatives**, and the whole array applies to every operation that inherits it. Listing
2111
- > both therefore documents each credential as valid for _either_ family, which says your platform
2112
- > routes accept a member token. That is not a missing detail; it is a false statement about who
2113
- > can call what. Give the minority family per-operation `security` (via your own decorator or
2114
- > nest-core's `operationSecurity`) and let the default cover the majority.
2115
- >
2116
- > **2. For the dashboard family — which schemes does this deployment actually declare?** Delivery
2117
- > decides, and so does what you mounted. Take a default written as `[{ bymaxAuthAccessCookie: [] }]`:
2118
- >
2119
- > | deployment | this contributor declares | that literal default |
2120
- > | -------------------------------------- | --------------------------------- | ----------------------------------------------------------- |
2121
- > | dashboard mounted, `cookie` | the cookie scheme only | correct |
2122
- > | dashboard mounted, `both` | the cookie **and** bearer schemes | resolves, but describes only one of the two channels |
2123
- > | dashboard mounted, `bearer` | no cookie scheme at all | names an undeclared scheme — `assertSchemesDeclared` throws |
2124
- > | **no dashboard surface, any delivery** | **neither dashboard scheme** | names an undeclared scheme — throws, `cookie` included |
2125
- >
2126
- > That last row is the one a delivery-only recipe gets wrong, and **"no dashboard surface" is
2127
- > wider than it first sounds.** `schemesFor` gates both dashboard schemes on one of `auth`,
2128
- > `passwordReset`, `mfa`, `sessions`, `invitations` or `emailChange` being registered. `oauth` is
2129
- > **not** in that list — its operations are public and reference no credential — so an OAuth-only
2130
- > deployment contributes operations and zero schemes, exactly like a platform-only one. Any
2131
- > deployment with no dashboard controller is in this row, and `cookie` delivery, which the recipe
2132
- > would call the safe case, throws just as hard as `bearer`.
2133
- >
2134
- > **And that row needs a remedy, not just a warning, because these deployments are legitimate.**
2135
- > `JwtAuthGuard` is registered and exported unconditionally — it is not gated on any controller
2136
- > flag — so mounting no dashboard controller does **not** stop you from guarding your own routes
2137
- > with a dashboard access token. Both shapes are real: the platform surface plus your own routes
2138
- > on the member credential; or the OAuth surface alone, where sign-in happens through a provider
2139
- > and your app issues member tokens itself. In each case the guard is available and the scheme
2140
- > describing it is not. Deriving correctly there lands you on "the scheme I need does not exist",
2141
- > which is an accurate answer and not a usable
2142
- > one.
2143
- >
2144
- > **Declare it yourself, in your own `openapi.securitySchemes`.** This is the one case where
2145
- > "delete your hand-written `securitySchemes`" has an exception, and the exception exists because
2146
- > the contributor deliberately declares only what its own operations reference — defining a
2147
- > dashboard scheme on a deployment with no dashboard operation would put an unreferenced
2148
- > credential in every such document, which is the opposite error and the reason for the gate.
2149
- >
2150
- > **Which scheme you declare is still a function of delivery** — the exception is to the deletion
2151
- > rule, not to the derivation rule, and writing one fixed definition here reintroduces the very
2152
- > literal this section is about:
2153
- >
2154
- > - `cookie` → the `apiKey`-in-cookie definition, carrying the `cookies.accessTokenName` you
2155
- > configured. The cookie name is yours to choose, so this is the one that must match what the
2156
- > server actually reads.
2157
- > - `bearer` → the HTTP bearer definition. There is no cookie name to carry.
2158
- > - `both` → **both of them**, or your document is incomplete in exactly the quiet way described
2159
- > above.
2160
- >
2161
- > One note on doing any of it: **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, so
2162
- > import the names rather than writing `bymaxAuthAccessCookie` and `bymaxAuthAccessBearer` as
2163
- > string literals. The compiler then checks the PROPERTY you reach for, so a typo is a build
2164
- > error rather than a document declaring a scheme nothing defines — and if a scheme's identifier
2165
- > is ever renamed, your document carries the new one instead of a literal that has quietly gone
2166
- > stale. Renaming the value is not itself a build error, since `AUTH_SECURITY_SCHEMES.accessCookie`
2167
- > stays valid and only its string changes; that is precisely why importing beats copying.
2168
- >
2169
- > **The wrong outcomes are not one failure, and the difference is the point.** Where the scheme
2170
- > does not exist, nest-core's `assertSchemesDeclared` **throws** and the document never builds —
2171
- > loud, immediate, impossible to ship. Under `both` the scheme does exist, so nothing throws; the
2172
- > default is merely **incomplete**, telling a reader that your own routes take a cookie when they
2173
- > equally accept a bearer token. That one is quiet, and it is the same class of quiet as the bug
2174
- > this whole note is about. A literal written against a bearer-only deployment inverts the table
2175
- > and fails under `cookie` for the same reasons.
2176
- >
2177
- > So the advice that fixes a silently wrong document can introduce a loud broken one **or a second
2178
- > quiet one**, depending on where you land. Derive from the same inputs the contributor reads —
2179
- > the guard your routes use, your delivery mode, and the controllers you registered — and the
2180
- > answer is right everywhere at once, instead of correct in one configuration and checked forever.
2181
- >
2182
- > The default is what covers your routes, and it cannot disturb this library's: a per-operation
2183
- > requirement outranks a document-level one, and every operation the contributor describes carries
2184
- > its own.
2185
- >
2186
- > **What an empty `{}` alternative says, and where this library uses it as an approximation.**
2187
- > In OpenAPI it means one thing: authentication is **optional** for that operation — a caller
2188
- > presenting none of the named schemes is valid. Tooling reads it as anonymous access and infers
2189
- > nothing about a request body from it.
2190
- >
2191
- > On `logout` that is exactly right, in **every** delivery mode including `cookie`: the operation
2192
- > really does answer a caller who presents nothing, which is why a user whose access token
2193
- > expired can still sign out. How many alternatives you see depends on the mode, since each one
2194
- > is a combination of the credentials that mode actually has:
2195
- >
2196
- > | operation | `cookie` | `bearer` | `both` |
2197
- > | ----------------- | -------- | -------- | ------ |
2198
- > | `logout` | 4 | 2 | 6 |
2199
- > | `password/change` | 2 | 1 | 4 |
2200
- >
2201
- > On `refresh` under `tokenDelivery: 'both'` it is an **approximation, and a permissive one**.
2202
- > That operation refuses a caller with no credential at all; the token may simply arrive in the
2203
- > request body, which `security` has no vocabulary for. The empty entry is what lets the document
2204
- > describe the body-only caller, and the cost is that it also tells tooling anonymous access is
2205
- > acceptable when it is not.
2206
- >
2207
- > The `requestBody` beside it **documents the body channel; it does not carry the requirement**.
2208
- > Under `'both'` it is `required: false` and its schema does not list `refreshToken` as required,
2209
- > because either channel satisfies the server and a body that omits the token is valid when the
2210
- > cookie carries it. So the document as a whole permits a request with neither, and the server
2211
- > refuses that request. **OpenAPI cannot express "one of these two channels" across a security
2212
- > requirement and a request body**, and this is the shape of that limitation rather than an
2213
- > oversight. Under `'bearer'`, where the cookie does not exist, the body becomes required at both
2214
- > levels and the document is exact.
2215
- >
2216
- > Written out because two earlier versions of this note were wrong in opposite directions: one
2217
- > called `{}` "a credential this member cannot model", which is the intent rather than the
2218
- > notation; the other claimed the `requestBody` carried the requirement, which it does not.
2219
- >
2220
- > **Verify with a diff, not by reasoning.** Render the document with the contributor active and
2221
- > again with your entries in place, and compare only the operations you mount. The consumer who
2222
- > did this found their own three differences were improvements — a configured cookie name over
2223
- > the exported default, `logout` gaining the access-only and refresh-only alternatives their map
2224
- > called unsatisfiable — and one regression that no status-code probe could have surfaced,
2225
- > because the routes it broke still answered correctly at runtime.
2226
- >
2227
- > **And there is one shape no warning will catch for you, however new your nest-core.** If you
2228
- > remove _every_ requirement at once — no library describing anything, no decorator, no override,
2229
- > no document default — what remains is indistinguishable from the document of an API that is
2230
- > public on purpose. Both are a set of operations that ask for nothing. **No general-purpose tool** can separate the two from the rendered document alone
2231
- > without also shouting at every genuinely public API, which is how a warning earns the right to
2232
- > be ignored. This is why nest-core's warning requires that _some_ operation still state a
2233
- > requirement: the gap is deliberate, not an omission, and no version closes it.
2234
- >
2235
- > **But it is a limit on document-only checks, not on you** — and the distinction matters, because
2236
- > the better answer is the one a general-purpose tool cannot supply. **You** know your API is not
2237
- > public, which is exactly the intent no renderer can recover, so write it down as an assertion in
2238
- > your own suite: that the built document carries a top-level `security`, or that every route
2239
- > behind your auth guard renders with some requirement. That is a standing check, it runs on every
2240
- > commit, and it does not depend on anyone remembering to compare. Prefer it to the diff.
2241
- >
2242
- > Render the document twice and compare when you are **changing** this — adopting the contributor,
2243
- > moving delivery mode, adding a surface — because a diff shows you what moved without your having
2244
- > to predict it in advance. Then turn what you learned into the assertion, so the next change is
2245
- > caught rather than inspected.
2246
-
2247
- **That chain is about `security` alone, and the other members run the opposite rule** — worth
2248
- stating because generalising either one produces a wrong belief about the other. There is no
2249
- configuration channel for a `description`, a `summary` or a tag: `mergeFragment` merges the
2250
- scanned operation **over** the fragment, so a contributed member lands unless the handler itself
2251
- declared that member, and the handler is this library's. Concretely, the `description` on
2252
- `logout` cannot be shadowed by anything in your options — only by an `@ApiOperation` on a handler
2253
- you do not own. Nothing to delete for that half; the deletion above is entirely about `security`.
2254
-
2255
- > **Your own document test will not catch this.** A consumer seat measured it on their own
2256
- > repository: ten `operationSecurity` entries, all for this library's routes, and a suite
2257
- > asserting the operation-to-posture map with `toEqual`. On adoption, every contributed fragment
2258
- > loses to those entries, the old scheme names survive — and the suite stays **green**, because
2259
- > it is asserting the old answer that is still being served. A test that pins your document
2260
- > confirms the staleness rather than finding it. The deletion is the step; nothing downstream
2261
- > will remind you.
2262
-
2263
- Do it as one change: delete the literals, update whatever pins your document to the four-name
2264
- vocabulary, rebuild it, and regenerate any typed client — the operation ids do not move, but the
2265
- scheme names and the per-operation requirements do.
2266
-
2267
- #### Machine-readable schemas
2268
-
2269
- The same contracts are published as data in
2270
- [`conformance/openapi-request-schemas.json`](./conformance/openapi-request-schemas.json) —
2271
- OpenAPI 3.0 schemas for all 22 DTOs, generated from the decorators themselves and regenerated by
2272
- `pnpm gen:openapi-schemas`. Alongside it,
2273
- [`openapi-request-descriptions.json`](./conformance/openapi-request-descriptions.json) carries the
2274
- facts no keyword expresses: the twelve e-mail fields that are **trimmed and lowercased before
2275
- validation**, each entry shipping the probe that verifies its own sentence.
2276
-
2277
- A third file,
2278
- [`openapi-declared-structures.json`](./conformance/openapi-declared-structures.json), carries the
2279
- contracts the generated header names and no decorator can express — as **structure**, not prose:
2280
-
2281
- | Declared | As |
2282
- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
2283
- | `reset-password` takes exactly one of `token`, `otp`, `verifiedToken` | `oneOf` |
2284
- | An OAuth callback with neither `code` nor `error` is the **handler's** refusal, not the pipe's | probes the pipe accepts and the handler answers `auth.oauth_failed` |
2285
- | The 8-character floor is structural, not your policy | probes showing the pipe accepting what the deployment refuses |
2286
- | `forgot-password`, `resend-otp`, `resend-verification`, `verify-email` answer identically for an unknown address | probes asserting the two responses are **equal** |
2287
-
2288
- Three rules keep it honest. Only `required`, `oneOf` and `anyOf` may appear — `allOf` and `not`
2289
- are valid OpenAPI 3.0 and are **refused at load**, because a keyword nothing evaluates publishes
2290
- a claim nothing checks. Every entry carries probes, and both suites run them: the unit suite
2291
- evaluates each body against its own structure and reads what the pipe answers, the e2e suite
2292
- answers the rest with a real application. An entry whose two layers disagree — the pipe accepting
2293
- what the handler or the service then refuses — is split across the two suites on purpose, because
2294
- neither can see the pair. And presence means _present and not `null`_ — this
2295
- server's rule rather than JSON Schema's, because `@IsOptional()` treats `null` as absent, so a
2296
- body sending `null` and one omitting the key are the same request.
2297
-
2298
- A structure is a **necessary** condition, never a sufficient one, and `reset-password` shows why:
2299
- which of the three proofs is eligible depends on `passwordReset.method`, and an ineligible proof
2300
- is refused with the same code a structural violation gets. That narrowing is declared with its
2301
- own probes and is deliberately not something a client can generate against.
2302
-
2303
- Another file,
2304
- [`openapi-operation-security.json`](./conformance/openapi-operation-security.json), maps every
2305
- operation this library mounts (`METHOD /path`, relative to your route prefix) to the **kind** of
2306
- credential it requires, with the meaning of each kind alongside. It is generated from the table the
2307
- OpenAPI fragment is built from and the controllers' route metadata, regenerated by
2308
- `pnpm gen:openapi-security`, and a spec fails when it differs. How a kind becomes a security
2309
- requirement depends on your `tokenDelivery` and is not in the file.
2310
-
2311
- These are development artifacts — they are not in the published tarball, and nothing reads
2312
- them at runtime yet. They exist so the schemas are a function of the decorators rather than a
2313
- second description maintained by hand.
2314
-
2315
- ### Administrative operations — methods, deliberately not routes
2316
-
2317
- Two support-desk operations ship as **methods with no HTTP route**. Every route above is scoped
2318
- to the caller's own account, and both of these act on somebody else's — so exposing them would
2319
- mean inventing an authorization model ("who is an admin?") that this library does not have and
2320
- your application already does. Call them from your own admin surface, where the caller is
2321
- already authorized.
2322
-
2323
- | Method | Answers |
2324
- | -------------------------------------------------- | --------------------------------------------------- |
2325
- | `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
2326
- | `MfaService.resetMfa(userId, context?, tenantId?)` | "I lost my authenticator **and** my recovery codes" |
2327
-
2328
- **`unlockAccount`** clears the brute-force lockout. It grants no access: the password, the
2329
- status gate, the verification gate and MFA all still apply — it restores the ability to _try_.
2330
- It exists because the counter is keyed by an HMAC under the library's own `hmacKey`, which no
2331
- consumer can derive, so until it existed a lockout could only be waited out. It is also the
2332
- lever an attacker pulls to deny service to one specific account, which makes undoing it part of
2333
- the defence. Idempotent.
2334
-
2335
- **`resetMfa`** removes a second factor without one. Every self-service exit needs the factor
2336
- itself — `disable` wants a valid TOTP code, the recovery codes want the codes — so a user who
2337
- has lost both is locked out permanently by the control meant to protect them (ASVS v5 §6.1.1
2338
- asks for this path for exactly that reason). It invalidates every session and bumps the token
2339
- epoch, so access tokens carrying `mfaVerified: true` die with the factor; it **notifies the
2340
- account holder** through the same channel a self-service disable uses; and it logs at `warn`
2341
- under its own prefix. The notification is not optional: an administrative reset the owner
2342
- cannot see is an account-takeover path, and it is what makes the event detectable and
2343
- disputable. `tenantId` is required when `context` is `'dashboard'` (the default) and ignored for
2344
- `'platform'`. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
2345
- "done".
2346
-
2347
- > `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
2348
- > otherwise add it to `extraProviders` to inject it.
2349
-
2350
- ### Checking revocation outside a guard — `AuthRevocationService`
2351
-
2352
- The three JWT guards do not decide revocation themselves; they delegate to one service, and that
2353
- service is exported so **you can consult the same two channels from a transport the guards never
2354
- see** — a WebSocket, an SSE stream, a message consumer. Without it there is no way to ask the
2355
- question at all outside an HTTP request: a connection whose user logs out keeps its stream until
2356
- the access token expires, while that user's HTTP calls are refused at once.
2357
-
2358
- ```ts
2359
- import { AuthRevocationService } from '@bymax-one/nest-auth'
2360
-
2361
- const revoked = await this.revocation.isAccessTokenRevoked(
2362
- { jti: payload.jti, sub: payload.sub, epoch: payload.epoch, tenantId: payload.tenantId },
2363
- 'dashboard'
2364
- )
2365
- ```
2366
-
2367
- It is registered and exported unconditionally, so it is injectable wherever `BymaxAuthModule` is
2368
- imported — no `extraProviders` entry and no controller flag to turn on.
1627
+ This package does not depend on `@bymax-one/nest-core`. From nest-core 1.6.1 the request-body
1628
+ schemas of every mounted DTO are described too. Which nest-core version contributes what, how to
1629
+ remove hand-written `operationSecurity` entries and derive the document-level default with
1630
+ `authDocumentSecurity`, and the machine-readable schemas under `conformance/` are in
1631
+ [OpenAPI documents and `@bymax-one/nest-core`](./docs/openapi-interop.md).
2369
1632
 
2370
- > [!IMPORTANT]
2371
- > **On the dashboard plane you must forward `tenantId` from the verified token.** It is optional
2372
- > on `RevocableTokenPayload` because the platform plane genuinely has none — its admins are
2373
- > cross-tenant — so **`tsc` will not catch the omission**, and a dashboard payload without it is
2374
- > treated as **revoked** without a store read, with a `warn` naming the missing field.
2375
- >
2376
- > Failing closed is deliberate. The epoch key derives from the tenant-scoped subject, so an absent
2377
- > tenant names a keyspace belonging to no tenant, where nothing has ever been bumped: the read
2378
- > would answer `0`, `stamped < 0` is false for every token, and a bulk-revoked token would be
2379
- > reported **valid**. A revocation check that fails open on malformed input is worse than no check.
2380
- >
2381
- > **Recognise the symptom, because it does not look like an auth bug.** The refusal answers the
2382
- > same `true` a genuinely revoked token answers, throws nothing and emits no event — so a
2383
- > transport that gates a stream on it simply registers nothing. Measured on a consumer's realtime
2384
- > bridge: the SSE handshake answered `200` and the connection registry stayed at `count: 0`.
2385
- > Declaring the tenant **required** on your own port type is the stronger fix, because it turns the
2386
- > next occurrence into a compile error rather than a log line.
2387
-
2388
- **What this method is and is not.** It answers two channels at the moment you call it: the
2389
- per-token blacklist and the user's token epoch. It reads no `exp`, holds no subscription, emits no
2390
- event, and knows nothing about account status, roles, tenant binding or the identity plane. It is
2391
- therefore **one check among the many a guarded HTTP route performs**, and not a substitute for
2392
- them.
2393
-
2394
- Using it to authorise a long-lived transport takes more than this method. Use
2395
- `AuthTokenVerifierService` for that, below.
2396
-
2397
- ### Authorising a long-lived transport — `AuthTokenVerifierService`
2398
-
2399
- A guarded HTTP route establishes seven things before a handler runs. A WebSocket, an SSE stream or
2400
- a message consumer has no guard in front of it, so it must establish the same seven itself — and on
2401
- a cadence, because a connection outlives the request that opened it. Assembling that from the
2402
- exported parts is where it goes wrong: a bridge that calls `isAccessTokenRevoked` alone has checked
2403
- a signature and a blacklist while checking neither the token's **type**, nor its **`exp`**, nor
2404
- whether the **account** behind it still exists.
2405
-
2406
- `AuthTokenVerifierService.verifyAccessToken` is all seven in one call:
2407
-
2408
- ```ts
2409
- import { AuthTokenVerifierService } from '@bymax-one/nest-auth'
2410
-
2411
- const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
2412
- registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
2413
- ```
2414
-
2415
- | It checks | So that |
2416
- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2417
- | 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 |
2418
- | `exp` | A revocation check answers "was this withdrawn", never "is this still current" — `isAccessTokenRevoked` reads no `exp` at all |
2419
- | `jti` a UUID v4; `sub` and (dashboard) `tenantId` bounded non-empty strings | A malformed claim cannot build a Redis key nobody intended |
2420
- | Token `type`, against the plane **you** name | An `mfa_challenge` token — signed with the same secret, half a credential — cannot read as a session |
2421
- | Both revocation channels | A logout's `jti` blacklist AND the epoch a password reset or revoke-all advances |
2422
- | 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 |
2423
- | 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 |
2424
-
2425
- On the dashboard plane that last row reads a cache, and **its freshness is bounded by
2426
- `userStatusCacheTtlSeconds` (default 60 s), not by how often you call**: a stream re-verifying every
2427
- five seconds still serves a banned account until the entry expires. What shortens that is
2428
- [`AccountStatusService.invalidate`](#invalidating-the-account-cache--accountstatusserviceinvalidate)
2429
- — call it wherever you change a status, and read the caveat under that method: a request already
2430
- resolving when you invalidate can write the old value back, so the window narrows to one repository
2431
- read rather than to zero. Failing that, lower the TTL. The platform plane is uncached and genuinely current, at one repository read per call.
2432
-
2433
- The plane is **yours to declare**, never inferred from the token. Inferring it would make the plane
2434
- attacker-chosen: a platform token would open a dashboard stream by saying it is one. Passing a
2435
- value that is neither throws a `TypeError` rather than refusing quietly — the fall-through would
2436
- otherwise be the cross-tenant platform arm.
2437
-
2438
- Every refusal is an `AuthException`, and each mirrors the code the equivalent guard already
2439
- answers. Most answer `auth.token_invalid` so a caller cannot tell "valid but revoked" from "never
2440
- valid"; `auth.mfa_required`, the `ACCOUNT_*` codes, `auth.email_not_verified` (dashboard plane) and — on
2441
- the platform plane only — `auth.platform_auth_required` name themselves, because a legitimate
2442
- client acts on each differently. The account codes are answered whether or not an MFA challenge
2443
- is pending; `auth.mfa_required` is answered only for a usable account.
2444
-
2445
- > [!IMPORTANT]
2446
- > **Three things it still does not do.** Route **authorization** is yours — this answers who the
2447
- > caller is, never what they may do, so your `@Roles()` equivalent belongs on every message a
2448
- > stream carries, not only on the handshake. **Tenant binding** (`enforceTenantBinding`) needs the
2449
- > request its resolver reads, so pass the handshake as `request` to `verifyAccessToken` (the same
2450
- > `headers`/`url`/`hostname` request as on `WsJwtGuard`, fail-closed on a resolver that cannot answer);
2451
- > without it the binding is not applied to that call, and one warning per service instance says so. And it holds **no
2452
- > subscription**: it answers at the moment you call it, so a stream that calls it once at connect
2453
- > is authorized for the lifetime of the token rather than of the session. Call it again on a
2454
- > cadence and treat a rejection as a disconnect.
2455
-
2456
- `AccountStatusService` is exported alongside it for the narrower case: you already hold a verified
2457
- payload and want to re-ask only the one question whose answer changes while a stream is open.
2458
-
2459
- ### Invalidating the account cache — `AccountStatusService.invalidate`
2460
-
2461
- Account status is read through a Redis cache with a `userStatusCacheTtlSeconds` lifetime (60 s by
2462
- default), so a change made **outside** this library is not seen until the entry expires. Suspend a
2463
- user through your own admin surface and they keep reaching protected routes for up to a minute.
2464
-
2465
- ```ts
2466
- import { AccountStatusService } from '@bymax-one/nest-auth'
2467
-
2468
- await this.accountStatus.invalidate({ userId, tenantId })
2469
- ```
2470
-
2471
- Call it whenever you change an account's status yourself. It drops both cached facts — the status
2472
- and the email-verified flag — and is idempotent, so you need not know whether the account was
2473
- cached. The tenant is required: a repository id is unique only within one, so a bare id would name
2474
- another tenant's entry. An empty or blank `userId` or `tenantId` throws a `TypeError` rather than
2475
- deleting nothing and resolving.
1633
+ ### Server services for operations that are not routes
2476
1634
 
2477
- **Persist the status change first, then invalidate.** The read path fills the cache in two steps —
2478
- resolve from the repository, then write — so a request that resolved the old value just before your
2479
- update lands will write it back afterwards, with a full TTL, however promptly you call this. The
2480
- window is one repository read wide rather than one TTL, which is the improvement; it is not zero.
2481
- Writing first means any request whose read starts after your write already sees the new value, and
2482
- only genuinely concurrent ones can lose the race. Closing it entirely would need the fill to be
2483
- conditional on nothing having invalidated in between, which this service does not do today.
1635
+ Services cover what a guard or a route cannot, each documented in
1636
+ [Server services](./docs/server-services.md):
2484
1637
 
2485
- > [!IMPORTANT]
2486
- > **Do not delete the cache keys yourself**, even though the `<namespace>:*` prefix is yours to
2487
- > read. Their format is this library's to change — it already changed once, in v1.3.2, which added
2488
- > the tenant segment — and a delete that stops matching **fails silently**: no error, no event, just
2489
- > a status change that takes a full TTL to land. That is a security control degrading quietly. This
2490
- > method is the supported way to ask, and it is the only thing that stays correct when the format
2491
- > moves.
1638
+ - **Administrative operations** — support-desk operations that ship as methods with no HTTP route.
1639
+ - **`AuthRevocationService`** — check revocation outside a guard.
1640
+ - **`AuthTokenVerifierService`** — authorise a long-lived transport (a WebSocket, an SSE stream, a
1641
+ message consumer): signature, token type, both revocation channels, account status and the MFA
1642
+ policy, with the same refusals the guards give.
1643
+ - **`AccountStatusService.invalidate`** — drop an account's cached status after you persist a
1644
+ status change.
2492
1645
 
2493
1646
  ### Server Guards
2494
1647
 
@@ -2532,7 +1685,7 @@ thrown one.
2532
1685
  > **Do not register it on a `@bymax-one/nest-core` application.** The two filters are mutually
2533
1686
  > exclusive and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER` provider, and
2534
1687
  > `@Catch()` with no argument catches everything, so nest-core's envelope filter never runs.
2535
- > Measured — the same request answers `{ error: { code, message, details } }` with this filter
1688
+ > The same request answers `{ error: { code, message, details } }` with this filter
2536
1689
  > registered and the flat `{ statusCode, code, message, timestamp, path, details }` without it.
2537
1690
  > Registering both therefore **loses** `statusCode`, `timestamp`, `path` and the correlation id,
2538
1691
  > which is the opposite of what adding a filter looks like it should do.
@@ -2547,65 +1700,18 @@ thrown one.
2547
1700
 
2548
1701
  #### On a WebSocket, the envelope needs its own filter
2549
1702
 
2550
- `WsJwtGuard` throws the same `AuthException` every HTTP guard throws — and `AuthException`
2551
- extends `HttpException`, which Nest's **WebSocket** exception layer does not recognise. It
2552
- understands `WsException` and nothing else, so without a filter a refused socket client receives:
2553
-
2554
- ```json
2555
- { "status": "error", "message": "Internal server error" }
2556
- ```
2557
-
2558
- The refusal itself is correct: the handler never runs. What is lost is everything the client
2559
- could act on. A reconnect policy cannot tell a dead credential from a crashed handler, and the
2560
- sensible default for an unknown error is to retry — so an expired token becomes a reconnect loop
2561
- against an endpoint that will refuse it forever.
2562
-
2563
- > **Socket.IO only, measured.** `WsJwtGuard` reads both credential channels from the client's
2564
- > `handshake`, and only a Socket.IO client has one: with `@nestjs/platform-ws` the gateway
2565
- > receives the raw `ws` socket, which carries no `handshake` — and `ws` does not retain the
2566
- > upgrade request either, so there is nothing to read. Such a connection is **refused** with
2567
- > `auth.token_invalid` rather than crashing the socket, and the filter below delivers that
2568
- > refusal, but the guard cannot authenticate anyone on that adapter. Supporting it needs the
2569
- > gateway to stash the upgrade request in `handleConnection`, which is a contract this library
2570
- > does not have today.
2571
-
2572
- Register the filter on any gateway that applies the guard:
2573
-
2574
- ```typescript
2575
- @UseFilters(new WsAuthExceptionFilter())
2576
- @UseGuards(WsJwtGuard)
2577
- @WebSocketGateway()
2578
- export class FeedGateway {}
2579
- ```
2580
-
2581
- ```json
2582
- { "status": "error", "error": { "code": "auth.token_invalid", "message": "...", "details": null } }
2583
- ```
2584
-
2585
- `status: 'error'` is kept — it is the field Nest itself sets and the one socket.io clients
2586
- already branch on — and the envelope is added beside it, so a client handling both shapes needs
2587
- no second listener. The `AuthException` travels whole, so a `details` payload survives.
2588
-
2589
- The filter is scoped to `AuthException` on purpose. An argument-less `@Catch()` would claim
2590
- every exception the gateway raises, so a `WsException` an unrelated handler throws — a domain
2591
- error with its own contract — would be rewritten as an `auth.*` code, and following this README
2592
- would silently break errors a consumer already ships. Everything that is not this library's
2593
- refusal keeps travelling through Nest's own exception layer, untouched.
2594
-
2595
- Both transports are answered. A Socket.IO client is dispatched to with `emit`; a native `ws`
2596
- client is written to with `send`, in the `{event, data}` envelope `@nestjs/platform-ws` uses for
2597
- every other message — emitting on one of those succeeds, dispatches a local event and sends the
2598
- peer nothing, which is the failure this ordering exists to prevent. Both paths are driven over a
2599
- real handshake in `test/e2e/ws-guard.e2e-spec.ts`.
1703
+ `AuthException` extends `HttpException`, which Nest's WebSocket layer does not recognise, so a
1704
+ gateway that applies `WsJwtGuard` also needs `WsAuthExceptionFilter`; without it the refusal reaches
1705
+ the client as `Internal server error`. See
1706
+ [On a WebSocket, the envelope needs its own filter](./docs/websocket-upgrades.md#on-a-websocket-the-envelope-needs-its-own-filter).
2600
1707
 
2601
1708
  #### The HTTP status belongs to the code
2602
1709
 
2603
1710
  Every code answers exactly one status, and the status is derived from the code rather than
2604
1711
  chosen at the throw site — `AuthException` takes no status argument. A client can switch on
2605
- `error.code` and the status line together and get the same answer from either implementation:
2606
- `@bymax-one/nest-auth` and `rust-auth` read the same table, pinned in
1712
+ `error.code` and the status line together. The table is pinned in
2607
1713
  [`conformance/wire-contract.json`](./conformance/wire-contract.json) under
2608
- `errorCatalog.statuses` and asserted by both suites against that file.
1714
+ `errorCatalog.statuses` and asserted against that file.
2609
1715
 
2610
1716
  | Status | Codes |
2611
1717
  | -----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -2625,19 +1731,11 @@ it:
2625
1731
  import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared'
2626
1732
  ```
2627
1733
 
2628
- Shown as an import rather than described, on purpose: this package's README contract test reads
2629
- import statements, so a symbol that stops being exported from the subpath named here fails the
2630
- suite. It scans prose too — for scheme names it invented and for claims that something is not
2631
- public — but it cannot check a sentence that merely _says_ where a symbol ships from. That claim
2632
- went one release stated and unenforced.
2633
-
2634
1734
  > **Assert your fixtures against the catalogue, not against string literals.** `AUTH_ERROR_CODES`
2635
1735
  > is exported from `@bymax-one/nest-auth/shared` so a suite can check that every code it branches
2636
- > on is one the server can actually produce. A frontend seat found three invented codes this way —
2637
- > `auth.unauthorized` among them, which does not exist — and a branch on a code the server never
2638
- > sends is silent forever: it simply never runs, and the handler it replaces is the one that
2639
- > matters. The check is one test over your own source, and it is worth having standing rather than
2640
- > as a one-off audit.
1736
+ > on is one the server can actually produce. A branch on a code the server never sends (for example
1737
+ > `auth.unauthorized`, which does not exist) is silent forever: it simply never runs, and the
1738
+ > handler it replaces is the one that matters. The check is one test over your own source.
2641
1739
  >
2642
1740
  > **Five codes are internal-only and never reach a client**: `auth.token_expired`,
2643
1741
  > `auth.token_revoked`, `auth.token_missing` (all collapsed onto `auth.token_invalid`) and
@@ -2699,6 +1797,18 @@ went one release stated and unenforced.
2699
1797
 
2700
1798
  ---
2701
1799
 
1800
+ ## 🚫 What This Library Does NOT Do
1801
+
1802
+ - **It does not store your users.** You implement `IUserRepository` (and the workspace, membership and API-key repositories if you enable those); the library never imports an ORM or a database driver.
1803
+ - **It does not send email.** You implement `IEmailProvider`; the bundled `DefaultAuthEmailProvider` renders messages and hands them to a transport you supply.
1804
+ - **It does not delete users.** `IUserRepository` has no delete; a host that deletes one removes its workspace memberships first.
1805
+ - **It does not mount an admin API for service keys or platform operations.** `ApiKeyService` and the support-desk operations are methods; the routes and who may call them are yours.
1806
+ - **It does not rate-limit per service key.** Per-address limits on the auth routes are built in; limits on your own routes and on a verified key are yours (`@nestjs/throttler`).
1807
+ - **It does not authenticate a WebSocket on `@nestjs/platform-ws`.** `WsJwtGuard` reads a Socket.IO `handshake`, which the raw `ws` adapter does not provide.
1808
+ - **It does not depend on Passport, a crypto package, or `@bymax-one/nest-core`.** Cryptography is `node:crypto`; guards verify the JWT through `@nestjs/jwt`.
1809
+
1810
+ ---
1811
+
2702
1812
  ## 🤝 Contributing
2703
1813
 
2704
1814
  Contributions are welcome! Please read our contributing guidelines before submitting a pull request.