@bymax-one/nest-auth 1.5.2 → 1.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +187 -1
- package/README.md +232 -1116
- package/dist/client/index.cjs +18 -1
- package/dist/client/index.d.cts +2 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.mjs +18 -1
- package/dist/nextjs/index.cjs +30 -9
- package/dist/nextjs/index.d.cts +58 -6
- package/dist/nextjs/index.d.ts +58 -6
- package/dist/nextjs/index.mjs +30 -9
- package/dist/react/index.cjs +16 -12
- package/dist/react/index.d.cts +3 -0
- package/dist/react/index.d.ts +3 -0
- package/dist/react/index.mjs +16 -12
- package/dist/server/index.cjs +593 -228
- package/dist/server/index.d.cts +1305 -1146
- package/dist/server/index.d.ts +1305 -1146
- package/dist/server/index.mjs +582 -229
- package/dist/shared/index.cjs +8 -2
- package/dist/shared/index.d.cts +5 -0
- package/dist/shared/index.d.ts +5 -0
- package/dist/shared/index.mjs +8 -2
- package/package.json +2 -2
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="#-
|
|
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,11 @@ 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
|
|
310
|
-
>
|
|
311
|
-
>
|
|
312
|
-
>
|
|
313
|
-
>
|
|
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).
|
|
373
315
|
|
|
374
316
|
> [!NOTE]
|
|
375
317
|
> The bundled `DefaultAuthEmailProvider` implements every method of `IEmailProvider`, the optional
|
|
@@ -768,6 +710,21 @@ export const config = {
|
|
|
768
710
|
}
|
|
769
711
|
```
|
|
770
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
|
+
|
|
771
728
|
How the route lists match a path: an entry matches the path that equals it and anything under
|
|
772
729
|
it (`'/auth'` covers `/auth/login`), and takes no wildcards (`'/auth/*'` matches nothing). An
|
|
773
730
|
entry ending in `/` is a plain prefix, so `'/'` matches every path. In `publicRoutes` that is
|
|
@@ -813,124 +770,8 @@ export const POST = createLogoutHandler({
|
|
|
813
770
|
})
|
|
814
771
|
```
|
|
815
772
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
### WebSocket upgrades
|
|
819
|
-
|
|
820
|
-
The browser `WebSocket` API cannot set handshake headers, so a browser client cannot send
|
|
821
|
-
`Authorization: Bearer <token>` at the upgrade. The usual workaround puts the access token in the
|
|
822
|
-
query string, where it lands in access logs, browser history and proxy caches — a long-lived
|
|
823
|
-
credential in plaintext. `WsJwtGuard` refuses it.
|
|
824
|
-
|
|
825
|
-
The supported path is a single-use ticket:
|
|
826
|
-
|
|
827
|
-
```typescript
|
|
828
|
-
// 1. Mint from an authenticated session (POST, cookies or bearer as usual).
|
|
829
|
-
const { ticket, expiresIn } = await fetch('/auth/ws-ticket', {
|
|
830
|
-
method: 'POST',
|
|
831
|
-
credentials: 'include'
|
|
832
|
-
}).then((r) => r.json())
|
|
833
|
-
|
|
834
|
-
// 2. Open the socket with it. The ticket is consumed by the first redemption.
|
|
835
|
-
const socket = new WebSocket(`wss://api.example.com/socket?ticket=${ticket}`)
|
|
836
|
-
```
|
|
837
|
-
|
|
838
|
-
The ticket is opaque, 32 bytes of CSPRNG output, and lives at most 30 seconds, ending a second before the access
|
|
839
|
-
token that minted it does at the latest: `expiresIn` in the response is that capped lifetime in seconds, so a client
|
|
840
|
-
schedules its upgrade by it, and a token with no life left mints nothing. Only `sha256(ticket)` is
|
|
841
|
-
ever a Redis key, and the stored value is a verified-identity **snapshot** — no signature, no
|
|
842
|
-
expiry of its own — so a redeemed ticket authorizes a socket and cannot be turned back into a
|
|
843
|
-
session. It carries the `jti` and `epoch` of the access token that minted it, the two keys the
|
|
844
|
-
revocation channels are read by, and redemption is refused when that token has been blacklisted by
|
|
845
|
-
a logout or stamped below the user's current epoch (sign-out-everywhere, password change, MFA
|
|
846
|
-
reset): a ticket does not outlive the session that asked for it. A logout blacklists only
|
|
847
|
-
the access token it was given and does not move the epoch, so a ticket minted from an access token
|
|
848
|
-
that a refresh had already replaced is not refused after that logout, as a bearer token of that
|
|
849
|
-
kind is not; it is refused only after a later epoch bump (a password reset or change, an MFA
|
|
850
|
-
enable, disable or reset, or revoking another session or all of them). Minting requires an authenticated session in good standing that has already
|
|
851
|
-
satisfied MFA, so a ticket never carries more authority than the request that asked for it.
|
|
852
|
-
|
|
853
|
-
Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
|
|
854
|
-
both channels are accepted, and a ticket wins when both are present. `WsJwtGuard` checks
|
|
855
|
-
signature, token type and revocation on the Bearer path but not account status or MFA; where the
|
|
856
|
-
socket must also refuse a blocked account or an unfinished second factor, authorize with
|
|
857
|
-
`AuthTokenVerifierService.verifyAccessToken` (see
|
|
858
|
-
[Authorising a long-lived transport](#authorising-a-long-lived-transport--authtokenverifierservice)).
|
|
859
|
-
|
|
860
|
-
**Tenant binding on the socket.** With `enforceTenantBinding` on, `WsJwtGuard` re-resolves the
|
|
861
|
-
tenant of the upgrade and refuses (`auth.token_invalid`, the same code HTTP answers) a ticket or
|
|
862
|
-
token minted for another tenant, as `JwtAuthGuard` does on a mismatch. An upgrade has no Express request,
|
|
863
|
-
so your `tenantIdResolver` is handed a request-like object with **only** these fields:
|
|
864
|
-
|
|
865
|
-
| Field | Value |
|
|
866
|
-
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
867
|
-
| `headers` | The handshake headers, names lowercased |
|
|
868
|
-
| `url` | The upgrade URL, `''` when the transport exposes none |
|
|
869
|
-
| `hostname` | The `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets), `''` if absent; see below for `X-Forwarded-Host` |
|
|
870
|
-
|
|
871
|
-
There is **no** `cookies` (the `Cookie` header is present in `headers`, but nothing parses it the way
|
|
872
|
-
`cookie-parser` does on HTTP) and no `ip` or `ips`. `hostname` is the `Host` as received unless you
|
|
873
|
-
set `isTrustedProxy` (below). The resolver's parameter is typed
|
|
874
|
-
`TenantResolverRequest` (exported), so a resolver that reads one of the absent fields does not
|
|
875
|
-
compile. If a resolver still throws at runtime, or returns anything other than the credential's
|
|
876
|
-
tenant, the connection is **refused**, never bound to the wrong tenant. Resolve from `headers` or
|
|
877
|
-
`hostname` so one resolver
|
|
878
|
-
serves both HTTP and sockets.
|
|
879
|
-
|
|
880
|
-
**Behind a proxy that rewrites `Host`.** nginx's default `proxy_set_header Host $proxy_host` presents
|
|
881
|
-
the upstream name in `Host` and the public one in `X-Forwarded-Host`. Over HTTP, Express resolves
|
|
882
|
-
`req.hostname` from the forwarded header when its `trust proxy` setting trusts the peer; a socket has
|
|
883
|
-
no Express request, so without more the resolver sees the upstream host and the binding refuses every
|
|
884
|
-
stream. Declare the same trust decision once with `isTrustedProxy`, a function that takes the TCP peer
|
|
885
|
-
address and answers a boolean:
|
|
886
|
-
|
|
887
|
-
```typescript
|
|
888
|
-
// The module factory runs before the app exists, so it reads the policy per connection.
|
|
889
|
-
// Until main.ts fills it in, no peer is trusted.
|
|
890
|
-
export const proxyPolicy = { trusts: (_peer: string): boolean => false }
|
|
891
|
-
|
|
892
|
-
BymaxAuthModule.registerAsync({
|
|
893
|
-
useFactory: () => ({
|
|
894
|
-
// ...
|
|
895
|
-
enforceTenantBinding: true,
|
|
896
|
-
tenantIdResolver: (req) => req.hostname.split('.')[0] ?? '',
|
|
897
|
-
isTrustedProxy: (peer) => proxyPolicy.trusts(peer)
|
|
898
|
-
})
|
|
899
|
-
})
|
|
900
|
-
|
|
901
|
-
// main.ts
|
|
902
|
-
import { proxyPolicy } from './app.module' // wherever the module is configured
|
|
903
|
-
|
|
904
|
-
const app = await NestFactory.create<NestExpressApplication>(AppModule)
|
|
905
|
-
const expressApp = app.getHttpAdapter().getInstance()
|
|
906
|
-
expressApp.set('trust proxy', 'loopback, 10.0.0.0/8')
|
|
907
|
-
proxyPolicy.trusts = (peer) => expressApp.get('trust proxy fn')(peer, 0)
|
|
908
|
-
```
|
|
909
|
-
|
|
910
|
-
Read the compiled policy from the **Express instance**, `app.getHttpAdapter().getInstance()`. On a
|
|
911
|
-
Nest application, `app.get()` resolves a provider from the container and does not read an Express
|
|
912
|
-
setting, so `app.get('trust proxy fn')` looks for a provider of that name and fails.
|
|
913
|
-
|
|
914
|
-
The predicate receives the peer **exactly as the transport reported it**, so an IPv4-mapped form such
|
|
915
|
-
as `::ffff:10.0.0.1` reaches it unchanged; Express's compiled setting understands that form, which
|
|
916
|
-
is why the recipe delegates to it. When it answers `true`, the first element of a single
|
|
917
|
-
`X-Forwarded-Host` is used, with the port cut like `Host`. Unset, which is the default,
|
|
918
|
-
`X-Forwarded-Host` is never read. Every other case falls back to `Host`: no peer address, a header handed
|
|
919
|
-
over as separate values, an empty first element, a predicate that throws or answers anything but
|
|
920
|
-
`true`. (Node joins a header repeated on the wire into one comma-separated string, and its first
|
|
921
|
-
element is used, as in Express.) Those cases can therefore only make the binding stricter, never
|
|
922
|
-
admit a tenant the client chose. The
|
|
923
|
-
peer address comes from `WsJwtGuard` itself (Socket.IO's `handshake.address`); a caller of
|
|
924
|
-
`AuthTokenVerifierService.verifyAccessToken` passes it as `request.remoteAddress`.
|
|
925
|
-
|
|
926
|
-
Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
|
|
927
|
-
`@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
|
|
928
|
-
does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
|
|
929
|
-
`auth.token_invalid` instead of crashing on it, but it cannot authenticate anyone on that
|
|
930
|
-
adapter. And because `AuthException` extends `HttpException`, which Nest's WebSocket layer does
|
|
931
|
-
not recognise, a gateway that applies the guard also needs `WsAuthExceptionFilter` for the
|
|
932
|
-
refusal to reach the client as anything but `Internal server error` — see
|
|
933
|
-
[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).
|
|
934
775
|
|
|
935
776
|
---
|
|
936
777
|
|
|
@@ -966,84 +807,60 @@ All options are configurable via `registerAsync()`. Here are the key configurati
|
|
|
966
807
|
> [!IMPORTANT]
|
|
967
808
|
> **`environment` is how the module decides whether this is production, and it defaults to
|
|
968
809
|
> saying yes.** It drives cookie `Secure`, the HTTPS requirement on the OAuth `callbackUrl`, and
|
|
969
|
-
>
|
|
970
|
-
>
|
|
971
|
-
>
|
|
972
|
-
>
|
|
973
|
-
> passed in. The consequence to plan for: a local or test setup must now say
|
|
974
|
-
> `environment: 'development'` (or `'test'`) explicitly, or it will be held to production rules —
|
|
975
|
-
> an `http://` callback URL is refused, and cookies are marked `Secure` and never sent over
|
|
976
|
-
> plaintext. That failure is loud, which is the point; the old one was silent. Matches
|
|
977
|
-
> `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.
|
|
978
814
|
|
|
979
815
|
> [!NOTE]
|
|
980
|
-
> **`password.minLength` defaults to 15, not 8.** The DTOs keep a structural floor of 8
|
|
981
|
-
>
|
|
982
|
-
>
|
|
983
|
-
>
|
|
984
|
-
>
|
|
985
|
-
> `8..=128`, validated at startup: below 8 changes no outcome (the DTOs refuse the request
|
|
986
|
-
> first), and above 128 is longer than any password the validation layer accepts. It is checked
|
|
987
|
-
> in the service rather than a decorator because a decorator is evaluated when the class is
|
|
988
|
-
> defined, before any configuration exists — and it answers the same `auth.validation` code and
|
|
989
|
-
> the same `{ field, message }[]` details a length failure already produced, so a client
|
|
990
|
-
> 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.
|
|
991
821
|
|
|
992
822
|
> [!IMPORTANT]
|
|
993
|
-
> **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled
|
|
994
|
-
>
|
|
995
|
-
>
|
|
996
|
-
>
|
|
997
|
-
>
|
|
998
|
-
>
|
|
999
|
-
>
|
|
1000
|
-
>
|
|
1001
|
-
> no limiter at all in the other — `'peer'` behind a proxy puts every client in **one** bucket,
|
|
1002
|
-
> so a single caller can rate-limit your whole user base with no credential, and
|
|
1003
|
-
> `'trusted-proxy'` without a proxy lets the caller choose their own key. Both look like a
|
|
1004
|
-
> working limiter at runtime. Pass `rateLimit.enabled: false` if the limits are enforced at the
|
|
1005
|
-
> 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.
|
|
1006
831
|
>
|
|
1007
|
-
> `'trusted-proxy'` is only as honest as the hops in front of the app
|
|
1008
|
-
>
|
|
1009
|
-
>
|
|
1010
|
-
>
|
|
1011
|
-
>
|
|
1012
|
-
> 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.
|
|
1013
837
|
|
|
1014
838
|
> [!TIP]
|
|
1015
839
|
> **Binding tokens to an issuer and an audience.** `jwt.issuer` and `jwt.audience` are off by
|
|
1016
840
|
> default. Set either and its value is stamped on every token this backend mints and **required**
|
|
1017
|
-
> on every token it verifies
|
|
1018
|
-
>
|
|
1019
|
-
>
|
|
1020
|
-
>
|
|
1021
|
-
>
|
|
1022
|
-
>
|
|
1023
|
-
> same pair, or they stop accepting each other's tokens. And enabling it invalidates the access
|
|
1024
|
-
> tokens already in flight, since those were minted without the claims — a window of one
|
|
1025
|
-
> access-token lifetime, which clients close by refreshing. An empty string reads as unconfigured
|
|
1026
|
-
> rather than as "require the empty issuer", so an unset environment variable cannot turn the
|
|
1027
|
-
> 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.
|
|
1028
847
|
|
|
1029
848
|
> **Rotating the signing secret.** `jwt.previousSecrets` lists secrets retired by a rotation,
|
|
1030
|
-
> accepted for verification only. Without it, changing `jwt.secret` signs every user out
|
|
1031
|
-
>
|
|
1032
|
-
>
|
|
1033
|
-
>
|
|
1034
|
-
>
|
|
1035
|
-
> expired: every entry is a key that still opens the door. `mfa.encryptionKey` rotates the same
|
|
1036
|
-
> 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.
|
|
1037
854
|
>
|
|
1038
|
-
> **Pin `identifierKey` before you rotate.** Every Redis name that identifies an account
|
|
1039
|
-
> session index, the token epoch, the MFA keys, the recent-authentication marker,
|
|
1040
|
-
> rate-limit identifiers
|
|
1041
|
-
> `
|
|
1042
|
-
>
|
|
1043
|
-
>
|
|
1044
|
-
>
|
|
1045
|
-
>
|
|
1046
|
-
>
|
|
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.
|
|
1047
864
|
>
|
|
1048
865
|
> | | Routine rotation — keep sessions, epochs and recovery codes | Rotation after a compromise — cut the link |
|
|
1049
866
|
> | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -1054,101 +871,69 @@ All options are configurable via `registerAsync()`. Here are the key configurati
|
|
|
1054
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. |
|
|
1055
872
|
>
|
|
1056
873
|
> Pinning to the old secret leaves the derived Redis names computable by anyone who knows that
|
|
1057
|
-
> secret. They are names, not signing material, and using one still needs access to your Redis;
|
|
1058
|
-
>
|
|
1059
|
-
> `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.
|
|
1060
876
|
|
|
1061
877
|
> [!TIP]
|
|
1062
|
-
> **Rotating the MFA encryption key.** `mfa.previousEncryptionKeys` lists AES-256 keys retired by
|
|
1063
|
-
>
|
|
1064
|
-
>
|
|
1065
|
-
>
|
|
1066
|
-
>
|
|
1067
|
-
>
|
|
1068
|
-
>
|
|
1069
|
-
> bytes, and never equal to the current key or to another entry), because a malformed one would
|
|
1070
|
-
> otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
|
|
1071
|
-
> 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.
|
|
1072
885
|
|
|
1073
886
|
> [!WARNING]
|
|
1074
|
-
> **Keep your `updateMfa` fast.**
|
|
1075
|
-
>
|
|
1076
|
-
>
|
|
1077
|
-
>
|
|
1078
|
-
>
|
|
1079
|
-
>
|
|
1080
|
-
>
|
|
1081
|
-
>
|
|
1082
|
-
> lock's lifetime (a plain single-row update is, but a call that waits on a contended lock or a slow
|
|
1083
|
-
> replica may not be). A guard of your own inside `updateMfa` can narrow the window only for a stall
|
|
1084
|
-
> that happens after the guard's own read, such as a wait on a row lock inside the `UPDATE`: the
|
|
1085
|
-
> library passes `updateMfa` the new values and not the ones it read, so closing the window
|
|
1086
|
-
> completely would need those values passed in. The lock is held
|
|
1087
|
-
> across the read the transition makes inside it as well as the write, so a slow `findById` counts
|
|
1088
|
-
> 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.
|
|
1089
895
|
|
|
1090
896
|
> [!IMPORTANT]
|
|
1091
|
-
> **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
|
|
1092
|
-
>
|
|
1093
|
-
>
|
|
1094
|
-
>
|
|
1095
|
-
> `
|
|
1096
|
-
>
|
|
1097
|
-
>
|
|
1098
|
-
> block size divides the hardness that `password.costFactor`'s floor exists to guarantee —
|
|
1099
|
-
> invisibly, since the bounded parameter is still intact. `rust-auth` enforces the identical
|
|
1100
|
-
> 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.
|
|
1101
904
|
|
|
1102
905
|
> [!IMPORTANT]
|
|
1103
|
-
> `jwt.accessExpiresIn` must not exceed **30 days**, the window the store keeps a bumped token
|
|
1104
|
-
>
|
|
1105
|
-
>
|
|
1106
|
-
>
|
|
1107
|
-
>
|
|
1108
|
-
> rather than letting it fail open, and rejects an unreadable time span or a non-positive
|
|
1109
|
-
> 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.
|
|
1110
911
|
|
|
1111
912
|
> [!WARNING]
|
|
1112
913
|
> **Do not gate on the access token's `status` claim.** It is **point-in-time, never
|
|
1113
|
-
> authoritative
|
|
1114
|
-
>
|
|
1115
|
-
> | how the token was minted | `status` |
|
|
1116
|
-
> | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
1117
|
-
> | login, register, OAuth, MFA challenge | the account's value **at that moment** |
|
|
1118
|
-
> | an ordinary refresh rotation | **empty string** — the session record carries no live status, so there is nothing to copy |
|
|
1119
|
-
> | a refresh that re-signs because `role`, `tenantId` or `mfaEnabled` changed | the account's value **at that moment**, read during that request |
|
|
1120
|
-
>
|
|
1121
|
-
> `rust-auth` stamps the same empty string on its rotation path, deliberately and with a test
|
|
1122
|
-
> pinning it, so the middle row is a shared contract rather than a defect in either library.
|
|
1123
|
-
>
|
|
1124
|
-
> Every populated value is stale the instant the account changes, because status can change under
|
|
1125
|
-
> an unexpired token and nothing re-stamps it. So a route that reads the claim is wrong in **both**
|
|
1126
|
-
> directions: `status !== 'active'` refuses everyone whose session has been refreshed ordinarily,
|
|
1127
|
-
> and `status === 'suspended'` refuses nobody, ever. Both fail quietly and hours from the code
|
|
1128
|
-
> that caused them — the first looks like a broken login, the second like nothing at all.
|
|
914
|
+
> authoritative**:
|
|
1129
915
|
>
|
|
1130
|
-
>
|
|
1131
|
-
>
|
|
1132
|
-
>
|
|
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 |
|
|
1133
921
|
>
|
|
1134
|
-
>
|
|
1135
|
-
>
|
|
1136
|
-
>
|
|
1137
|
-
>
|
|
1138
|
-
> `
|
|
1139
|
-
>
|
|
1140
|
-
>
|
|
1141
|
-
>
|
|
1142
|
-
> reason — it is always `false` after a rotation, so step-up does not survive a refresh and a
|
|
1143
|
-
> user re-acquires it through the MFA challenge.
|
|
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.
|
|
1144
930
|
>
|
|
1145
|
-
>
|
|
1146
|
-
>
|
|
1147
|
-
>
|
|
1148
|
-
>
|
|
1149
|
-
>
|
|
1150
|
-
>
|
|
1151
|
-
> [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)).
|
|
1152
937
|
> `bumpUserTokenEpoch` is the heavier lever: it ends every session the user has. Lower
|
|
1153
938
|
> `userStatusCacheTtlSeconds` if a faster answer matters more than the repository reads it costs.
|
|
1154
939
|
|
|
@@ -1169,6 +954,51 @@ behaviour for origins that already exist. It is required as soon as `cookies.sam
|
|
|
1169
954
|
is set, and refused otherwise — that posture is the only one where the browser sends the session
|
|
1170
955
|
cookie cross-site, and it is the only one where the origin check has anything to authorize.
|
|
1171
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 refused with `503
|
|
960
|
+
auth.service_unavailable`, 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 library answers as a 503
|
|
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 error. While Redis is down, login, refresh, logout, rate-limited routes and every
|
|
983
|
+
> guarded route answer `503` with `error.code` `auth.service_unavailable` and the envelope
|
|
984
|
+
> `{ error: { code, message, details: null } }`; nothing of the store reaches the body, and no
|
|
985
|
+
> `Retry-After` is sent, because nothing here knows when Redis returns. It is the fail-closed
|
|
986
|
+
> behaviour, and a client may retry. A Redis outage is a timeout, a closed or refused connection,
|
|
987
|
+
> or a server that answers it cannot serve (`READONLY` after a failover, `LOADING`, `MASTERDOWN`,
|
|
988
|
+
> `CLUSTERDOWN`); one function classifies them, and any other Redis reply error (a script that is
|
|
989
|
+
> not loaded, a key of the wrong type) is a defect and stays `500 auth.internal`.
|
|
990
|
+
>
|
|
991
|
+
> The 503 is an `AuthException` whose `cause` is the ioredis error, so a host filter that logs 5xx
|
|
992
|
+
> answers (nest-core's, for one) records the real reason. The library's own `AuthExceptionFilter`
|
|
993
|
+
> writes no log line for it: your readiness probe, not the request log, is the signal that Redis is
|
|
994
|
+
> down, so put a Redis health check next to it. Two answers keep their meaning: a password-reset
|
|
995
|
+
> request refused because the cooldown store cannot answer is the same `503` for every address, and the
|
|
996
|
+
> OAuth callback redirects to your `errorRedirectUrl` with `error=auth.service_unavailable` when you
|
|
997
|
+
> configured one. A failure to cache an answer the library can recompute (the workspace membership
|
|
998
|
+
> cache, the denied-access counter, the session limit) is still absorbed, not refused.
|
|
999
|
+
> The paths, the outcome of each and the test that pins it are in
|
|
1000
|
+
> [`docs/redis-outage.md`](./docs/redis-outage.md).
|
|
1001
|
+
|
|
1172
1002
|
The breach check is opt-in for a different reason: it is the only part of the credential path
|
|
1173
1003
|
that reaches the network, and a library should not start talking to a third party because it was
|
|
1174
1004
|
upgraded. Wire it explicitly:
|
|
@@ -1225,7 +1055,7 @@ fails at startup and says which is missing.
|
|
|
1225
1055
|
| `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. |
|
|
1226
1056
|
| `prefix` | `'bak'` | Literal start of every issued key, for secret scanners. Lowercase letters and digits, 2 to 16, no underscore. |
|
|
1227
1057
|
| `lastUsedFlushSeconds` | `60` | How often coalesced `lastUsedAt` values are written, in one batch. 1 to 3600. |
|
|
1228
|
-
| `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).
|
|
1058
|
+
| `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). |
|
|
1229
1059
|
|
|
1230
1060
|
### Protect a route
|
|
1231
1061
|
|
|
@@ -1316,136 +1146,18 @@ export class KeysAdminController {
|
|
|
1316
1146
|
not rotated (`auth.api_key_not_found`): that would re-issue access nobody holds.
|
|
1317
1147
|
- `revoke(id)` takes effect on the very next request: the row is read on every request, and
|
|
1318
1148
|
there is no verification cache.
|
|
1319
|
-
- **Who did it.** `issue`, `revoke` and `rotate` emit no hook of their own — they run inside
|
|
1320
|
-
your admin route, which already knows the operator, so attribute them there (log or audit it
|
|
1321
|
-
beside the call). The per-request hook below covers requests _made with_ a key. If you want
|
|
1322
|
-
provenance stored with the key, add your own columns: `IApiKeyRepository.create` receives the
|
|
1323
|
-
row and your implementation can persist whatever else it knows. That is why `issue()` takes
|
|
1324
|
-
no `createdBy`.
|
|
1325
|
-
|
|
1326
|
-
### The repository
|
|
1327
|
-
|
|
1328
|
-
You implement `IApiKeyRepository`, as you do for users. The library supplies the `id` and the
|
|
1329
|
-
`digest`; the store only persists them.
|
|
1330
|
-
|
|
1331
|
-
| Method | Contract |
|
|
1332
|
-
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1333
|
-
| `findById(id)` | One primary-key read per request. Return revoked and expired rows too: the library decides validity. |
|
|
1334
|
-
| `create(row)` | Insert `{ id, label, digest, scopes, createdAt, expiresAt }`. Do not make `label` unique. |
|
|
1335
|
-
| `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`. |
|
|
1336
|
-
| `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. |
|
|
1337
|
-
| `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. |
|
|
1338
|
-
| `touchLastUsed(entries)` | One batch. **Must be monotonic**: `GREATEST(last_used_at, :at)`, never backwards — several instances flush independently. |
|
|
1339
|
-
| `listByLabel(label)` | Every key of a label, for your admin screen. |
|
|
1340
|
-
|
|
1341
|
-
### How a key is stored and checked
|
|
1342
|
-
|
|
1343
|
-
A key looks like `bak_<keyId>_<secret>`: a literal prefix, the row's UUID (a public handle that
|
|
1344
|
-
makes verification an indexed read), and 43 base64url characters carrying 32 random bytes. Only
|
|
1345
|
-
`HMAC-SHA-256(pepper, secret)` is stored, as lowercase hex. Labels and scopes are not part of the
|
|
1346
|
-
digest, so editing them never invalidates a key. The grammar and the digest are pinned by
|
|
1347
|
-
[`conformance/wire-contract.json`](./conformance/wire-contract.json) with a vector, because
|
|
1348
|
-
`rust-auth` mints and verifies the same keys.
|
|
1349
|
-
|
|
1350
|
-
**Why a fast HMAC rather than a slow password hash.** This is the library's own reasoning, not
|
|
1351
|
-
an OWASP rule: the OWASP Password Storage Cheat Sheet's case against fast hashes is about
|
|
1352
|
-
passwords, which people choose and which can be guessed. A key's secret is 256 bits from the
|
|
1353
|
-
CSPRNG, so the work factor of the hash adds nothing to its resistance, and a per-request scrypt
|
|
1354
|
-
would only hand an attacker a cheap way to burn CPU. The pepper is what the cheat sheet calls
|
|
1355
|
-
the HMAC key: kept apart from the database, so a leaked table of digests cannot be tested
|
|
1356
|
-
offline.
|
|
1357
|
-
|
|
1358
|
-
**Every key takes the same steps.** Parse (substituting a dummy when it does not parse), read a
|
|
1359
|
-
row (always), compute the digest, compare two 32-byte buffers with `timingSafeEqual` (against a
|
|
1360
|
-
dummy digest when there is no row), and only then decide. An unknown, malformed, wrong, revoked
|
|
1361
|
-
or expired key all answer `401 auth.api_key_invalid` with the same body; the operator sees the
|
|
1362
|
-
real reason in the audit event. A key is valid strictly before its `expiresAt`, and not at all once `revokedAt` is set.
|
|
1363
|
-
|
|
1364
|
-
Two things this does _not_ claim. The store round trip costs differently for a present and an
|
|
1365
|
-
absent row, and no library can hide that — put a per-address throttle in front (below). And the
|
|
1366
|
-
fail-closed branch (a bound route with no scopes) intentionally takes different steps: it
|
|
1367
|
-
depends on route configuration, not on the key, so there is nothing for the key to leak.
|
|
1368
|
-
|
|
1369
|
-
**Changing the pepper makes every issued key unverifiable.** Digests are not portable across
|
|
1370
|
-
peppers, so a new pepper means re-issuing every key. There is no pepper rotation in this
|
|
1371
|
-
version.
|
|
1372
|
-
|
|
1373
|
-
### Audit
|
|
1374
|
-
|
|
1375
|
-
Implement `onApiKeyRequest` on your `IAuthHooks`. It fires once for every guarded request:
|
|
1376
|
-
|
|
1377
|
-
```typescript
|
|
1378
|
-
import type { ApiKeyAccessEvent, HookContext, IAuthHooks } from '@bymax-one/nest-auth'
|
|
1379
|
-
|
|
1380
|
-
export class AuditHooks implements IAuthHooks {
|
|
1381
|
-
async onApiKeyRequest(event: ApiKeyAccessEvent, context: HookContext): Promise<void> {
|
|
1382
|
-
// event.outcome: 'allowed' | 'denied'
|
|
1383
|
-
// event.reason: null, or missing | malformed | unknown | wrong_secret | revoked | expired
|
|
1384
|
-
// | scope_insufficient | route_undeclared | store_error
|
|
1385
|
-
// event.label, event.keyId, event.method, event.route (the PATTERN, e.g. /videos/:id),
|
|
1386
|
-
// event.requiredScopes, event.ip
|
|
1387
|
-
await this.audit.write({ ...event, userAgent: context.userAgent })
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
```
|
|
1391
|
-
|
|
1392
|
-
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
|
|
1393
|
-
denied** (`500 auth.internal`): use that when the audit row is a record you must have.
|
|
1394
|
-
|
|
1395
|
-
### Keep the key out of your logs
|
|
1396
|
-
|
|
1397
|
-
The library never logs, throws or emits the presented key, and strips the key header from the
|
|
1398
|
-
hook's `sanitizedHeaders`. Your HTTP logger sits outside the library, so redact the header
|
|
1399
|
-
there, custom `apiKeys.header` included:
|
|
1400
|
-
|
|
1401
|
-
```typescript
|
|
1402
|
-
// nest-logger
|
|
1403
|
-
LoggerModule.forRoot({ redactPaths: ['req.headers["x-machine-key"]'] })
|
|
1404
|
-
```
|
|
1405
|
-
|
|
1406
|
-
```typescript
|
|
1407
|
-
// plain pino
|
|
1408
|
-
const logger = pino({ redact: ['req.headers["x-api-key"]'] })
|
|
1409
|
-
```
|
|
1410
|
-
|
|
1411
|
-
### Rate limiting
|
|
1412
|
-
|
|
1413
|
-
Rate limiting is deliberately not built in. Use `@nestjs/throttler` in two layers: a per-address
|
|
1414
|
-
limit in front of everything, which is the only protection for the pre-verification lookup; and
|
|
1415
|
-
a per-key limit placed **after** `ApiKeyGuard`, keyed on the verified key id:
|
|
1416
|
-
|
|
1417
|
-
```typescript
|
|
1418
|
-
import { UseGuards, Get } from '@nestjs/common'
|
|
1419
|
-
import { ServiceKey } from '@bymax-one/nest-auth'
|
|
1420
|
-
import type { ApiKeyPrincipal } from '@bymax-one/nest-auth'
|
|
1421
|
-
import { ThrottlerGuard } from '@nestjs/throttler'
|
|
1422
1149
|
|
|
1423
|
-
|
|
1424
|
-
protected override async getTracker(req: Record<string, unknown>): Promise<string> {
|
|
1425
|
-
const key = req['apiKey'] as ApiKeyPrincipal | undefined
|
|
1426
|
-
return key?.id ?? String(req['ip'])
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1150
|
+
Everything else is in [Service API keys: reference](./docs/service-api-keys.md):
|
|
1429
1151
|
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
A request that fails verification never reaches the second guard, so garbage cannot spend a real
|
|
1441
|
-
key's budget. This example is exercised end to end in `test/e2e/api-keys.e2e-spec.ts`.
|
|
1442
|
-
|
|
1443
|
-
### Last-used tracking, and what it costs
|
|
1444
|
-
|
|
1445
|
-
A verified request does a map write, nothing else; every `lastUsedFlushSeconds` the values are
|
|
1446
|
-
written to your repository in one batch. With **N instances** a key is written up to N times
|
|
1447
|
-
per window instead of once, and a crash loses at most one window of `lastUsedAt`. The field is
|
|
1448
|
-
advisory: authorization never reads it.
|
|
1152
|
+
- **The repository** you implement (`IApiKeyRepository`): what each method must guarantee.
|
|
1153
|
+
- **How a key is stored and checked**: `bak_<keyId>_<secret>`, only `HMAC-SHA-256(pepper, secret)`
|
|
1154
|
+
is stored, every key takes the same steps and every refusal answers `401 auth.api_key_invalid`.
|
|
1155
|
+
Changing the pepper makes every issued key unverifiable.
|
|
1156
|
+
- **Audit**: implement `onApiKeyRequest` on your `IAuthHooks`; it fires for every guarded request,
|
|
1157
|
+
refused ones included. With `apiKeys.auditMode: 'required'` a throwing hook denies the request.
|
|
1158
|
+
- **Logs and rate limiting**: the library never logs the key, but your HTTP logger sits outside it,
|
|
1159
|
+
so redact the key header there. Rate limiting is deliberately not built in; use
|
|
1160
|
+
`@nestjs/throttler` per address before the guard and per key after it.
|
|
1449
1161
|
|
|
1450
1162
|
## 🗂️ Workspaces (one identity, many workspaces)
|
|
1451
1163
|
|
|
@@ -1584,52 +1296,6 @@ start, `GET /oauth/:provider?workspaceInvitation=<token>`: it stores only the to
|
|
|
1584
1296
|
state record and answers with `Referrer-Policy: no-referrer`. On your accept page, put the token in
|
|
1585
1297
|
the URL fragment and set `Referrer-Policy: no-referrer` there.
|
|
1586
1298
|
|
|
1587
|
-
### Hooks and events
|
|
1588
|
-
|
|
1589
|
-
`beforeWorkspaceCreate(user, { name }, context)` can refuse a creation. `onWorkspaceEvent(event,
|
|
1590
|
-
context)` receives, after the change has committed, `workspace.created`, `.renamed`,
|
|
1591
|
-
`.deletion_scheduled`, `.restored` and `.deleted`; `member.invited`, `invitation.resent`,
|
|
1592
|
-
`.revoked` and `.accepted`; `member.role_changed`, `.removed` and `.left`; `ownership.transferred`;
|
|
1593
|
-
`workspace.switched`; and `access.denied` (with the `surface`, the public `code` and a host-only
|
|
1594
|
-
`reason`). It is best-effort and informational: the repository's persisted audit row is the record.
|
|
1595
|
-
|
|
1596
|
-
### Deleting an account
|
|
1597
|
-
|
|
1598
|
-
The library never deletes a user: `IUserRepository` has no delete. A host that deletes or anonymises
|
|
1599
|
-
a user row must remove that user's memberships first, or the rows stay behind, still count as
|
|
1600
|
-
members of their workspaces, and a deleted owner keeps a workspace from ever being seen as
|
|
1601
|
-
orphaned. Call `MembershipService.removeAllForUser(tenantId, userId, actorUserId, context)` before
|
|
1602
|
-
the delete. `actorUserId` is the account itself, an administrator, or `null` for a job.
|
|
1603
|
-
|
|
1604
|
-
It removes every membership of the account, in every membership status and every workspace, with one
|
|
1605
|
-
`member.removed` event per removal and the cached access of each dropped, so access ends at the next
|
|
1606
|
-
request. Only the repository can find them all (`listForUser` lists active memberships of active
|
|
1607
|
-
workspaces only), so it is one call on the membership port, `removeAllForUser`, which you implement
|
|
1608
|
-
in one transaction together with the audit rows.
|
|
1609
|
-
|
|
1610
|
-
- **It refuses while the account is the only owner of an active or suspended workspace:** `409
|
|
1611
|
-
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
|
|
1612
|
-
removed. Transfer ownership or schedule the workspace's deletion first.
|
|
1613
|
-
- **A workspace pending deletion does not block.** No one can finalize a pending deletion before
|
|
1614
|
-
its grace period ends, so an owner who scheduled one would otherwise be unable to delete their own
|
|
1615
|
-
account for the whole period. Their membership there is removed with the rest, the workspace can no
|
|
1616
|
-
longer be restored (restoring is owner-only), and your finalize job deletes it when the grace period
|
|
1617
|
-
ends.
|
|
1618
|
-
- **If a cache bump fails after the commit,** the call throws `MembershipBumpFailedError` with
|
|
1619
|
-
`removed` and `failed`. The removal is already committed, so calling it again removes nothing: drop
|
|
1620
|
-
the access of each entry of `failed` with `WorkspaceAccessService.invalidateMembership`, or wait out
|
|
1621
|
-
`membershipCacheTtlSeconds`.
|
|
1622
|
-
|
|
1623
|
-
### Accepting an invitation through OAuth, and MFA
|
|
1624
|
-
|
|
1625
|
-
An OAuth flow started with a workspace invitation vets the invitation against the provider's profile
|
|
1626
|
-
before your `onOAuthLogin` hook runs, and completes it for the account that results. **When that
|
|
1627
|
-
account has a second factor, the library does not complete the invitation:** the callback answers the
|
|
1628
|
-
MFA challenge as it does for any OAuth sign-in, the invitation stays pending and unspent, and it is
|
|
1629
|
-
not resumed after the challenge. The signed-in caller accepts it with `POST
|
|
1630
|
-
workspaces/invitations/accept` and the same token, so a host whose members use MFA should send the
|
|
1631
|
-
token again from its accept page after sign-in.
|
|
1632
|
-
|
|
1633
1299
|
### Frontend
|
|
1634
1300
|
|
|
1635
1301
|
```typescript
|
|
@@ -1668,14 +1334,14 @@ writes the cookie and the value carries no authority; the layout's reader decide
|
|
|
1668
1334
|
an inbound `x-workspace-id` and never sets one. Path values go through `fillRoute` and `pathSegment`
|
|
1669
1335
|
(`./shared`), which refuse an empty value, `.` and `..` and percent-encode the rest.
|
|
1670
1336
|
|
|
1671
|
-
###
|
|
1337
|
+
### Hooks, account deletion and the threat model
|
|
1672
1338
|
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1339
|
+
`beforeWorkspaceCreate` can refuse a creation and `onWorkspaceEvent` receives every committed change.
|
|
1340
|
+
A host that deletes a user must call `MembershipService.removeAllForUser(tenantId, userId,
|
|
1341
|
+
actorUserId, context)` first; it refuses with `409 auth.last_owner` while the account is the only
|
|
1342
|
+
owner of an active or suspended workspace. A workspace id is never trusted from the body, a header
|
|
1343
|
+
or a stored default, and non-members and nonexistent workspaces are indistinguishable. All of it is in
|
|
1344
|
+
[Workspaces: reference](./docs/workspaces.md).
|
|
1679
1345
|
|
|
1680
1346
|
---
|
|
1681
1347
|
|
|
@@ -1743,14 +1409,6 @@ The `tenantId` is always extracted from the validated JWT — never from the req
|
|
|
1743
1409
|
|
|
1744
1410
|
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.
|
|
1745
1411
|
|
|
1746
|
-
### Password Hashing
|
|
1747
|
-
|
|
1748
|
-
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.
|
|
1749
|
-
|
|
1750
|
-
### No External Cryptographic Dependencies
|
|
1751
|
-
|
|
1752
|
-
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.
|
|
1753
|
-
|
|
1754
1412
|
### Security Checklist
|
|
1755
1413
|
|
|
1756
1414
|
When integrating `@bymax-one/nest-auth` in production, verify each of the following:
|
|
@@ -1802,9 +1460,6 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
|
|
|
1802
1460
|
| Rate Limiting | Per-IP fixed-window counters in Redis, keyed by `HMAC(ip)` — enforced by the library, not by the host |
|
|
1803
1461
|
| Session Lifetime | Optional absolute cap on how long one login can be extended by rotation |
|
|
1804
1462
|
|
|
1805
|
-
> [!IMPORTANT]
|
|
1806
|
-
> This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
|
|
1807
|
-
|
|
1808
1463
|
---
|
|
1809
1464
|
|
|
1810
1465
|
## 🧱 Tech Stack
|
|
@@ -1952,16 +1607,13 @@ Three constraints are worth stating because they are not visible from the field
|
|
|
1952
1607
|
length here would leak it as a pre-KDF timing signal, because a request failing validation
|
|
1953
1608
|
returns before the hash runs.
|
|
1954
1609
|
|
|
1955
|
-
####
|
|
1610
|
+
#### OpenAPI: the security posture writes itself
|
|
1956
1611
|
|
|
1957
1612
|
A deployment that builds its OpenAPI document with `@bymax-one/nest-core` **1.4.0 or later** gets
|
|
1958
|
-
this library's operations described automatically
|
|
1959
|
-
which, and which are reachable unauthenticated. Nothing to enable and nothing to import
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
It has to be derived at your boot rather than shipped as a static file, because the answer
|
|
1964
|
-
depends on your configuration:
|
|
1613
|
+
this library's operations described automatically: which schemes exist, which operation requires
|
|
1614
|
+
which, and which are reachable unauthenticated. Nothing to enable and nothing to import; the module
|
|
1615
|
+
registers a contributor and nest-core merges its fragments. The answer depends on your
|
|
1616
|
+
configuration, so it is derived at your boot:
|
|
1965
1617
|
|
|
1966
1618
|
| your options | what the document says |
|
|
1967
1619
|
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -1971,17 +1623,15 @@ depends on your configuration:
|
|
|
1971
1623
|
| `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 |
|
|
1972
1624
|
| a controller you did not mount | nothing at all: no operation, and no scheme only it would have referenced |
|
|
1973
1625
|
|
|
1974
|
-
A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced
|
|
1975
|
-
document that defines a credential the server will not read tells a generated client to offer it.
|
|
1626
|
+
A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced.
|
|
1976
1627
|
|
|
1977
1628
|
The four names — `bymaxAuthAccessCookie`, `bymaxAuthAccessBearer`, `bymaxAuthRefreshCookie`,
|
|
1978
1629
|
`bymaxPlatformAccessBearer` — are stable identifiers. Renaming one is a break a generated client
|
|
1979
1630
|
feels, so they will not change; their **definitions** are config-derived.
|
|
1980
1631
|
|
|
1981
|
-
Import them rather than spelling them
|
|
1982
|
-
`JwtAuthGuard` has to declare the dashboard
|
|
1983
|
-
|
|
1984
|
-
about literals drifting from configuration is the wrong instruction:
|
|
1632
|
+
Import them rather than spelling them: a hand-written literal drifts from your configuration. A
|
|
1633
|
+
platform-only deployment guarding its own routes with `JwtAuthGuard` has to declare the dashboard
|
|
1634
|
+
access scheme itself, because the fragment only declares what you mounted.
|
|
1985
1635
|
|
|
1986
1636
|
```typescript
|
|
1987
1637
|
import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
|
|
@@ -1990,518 +1640,24 @@ import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
|
|
|
1990
1640
|
const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
|
|
1991
1641
|
```
|
|
1992
1642
|
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
> ```typescript
|
|
1999
|
-
> // in your suite, where both packages are installed at the versions you run
|
|
2000
|
-
> import {
|
|
2001
|
-
> BYMAX_OPENAPI_CONTRACT_VERSION,
|
|
2002
|
-
> BYMAX_OPENAPI_CONTRIBUTOR_METADATA
|
|
2003
|
-
> } from '@bymax-one/nest-core/openapi'
|
|
2004
|
-
>
|
|
2005
|
-
> expect(fragment.contractVersion).toBe(BYMAX_OPENAPI_CONTRACT_VERSION)
|
|
2006
|
-
> expect(Reflect.getMetadata(BYMAX_OPENAPI_CONTRIBUTOR_METADATA, contributor.constructor)).toBe(
|
|
2007
|
-
> true
|
|
2008
|
-
> )
|
|
2009
|
-
> ```
|
|
2010
|
-
>
|
|
2011
|
-
> Worth writing once. A revision mismatch fails your document build loudly and names the
|
|
2012
|
-
> contributor, but a **marker** mismatch is silent: the provider is simply never discovered and
|
|
2013
|
-
> the document renders without the fragments — the same symptom as running nest-core < 1.4.0.
|
|
2014
|
-
|
|
2015
|
-
> **On nest-core older than 1.4.0 the fragments are silently ignored.** There is no contributor
|
|
2016
|
-
> lane to discover them, so the document renders exactly as before — no error, no warning, no
|
|
2017
|
-
> failed boot. If you add a document and the auth schemes do not appear, check in this order:
|
|
2018
|
-
> whether this library is new enough to contribute them at all, and only then your nest-core
|
|
2019
|
-
> version. The two states look identical from the document.
|
|
2020
|
-
|
|
2021
|
-
#### On `@bymax-one/nest-core` 1.6.1 or later, the request bodies are described too
|
|
2022
|
-
|
|
2023
|
-
The same contributor offers the request-body schema of every DTO that the controllers your
|
|
2024
|
-
deployment mounted take (`LoginDto`, `RegisterDto`, `ResetPasswordDto` and the rest), derived from
|
|
2025
|
-
their `class-validator` decorators. Without a contribution `@nestjs/swagger` registers each of them as
|
|
2026
|
-
`{"type":"object","properties":{}}`, because this package is built without its CLI plugin, and a
|
|
2027
|
-
client generated from the document types every request body as `{}`.
|
|
2028
|
-
|
|
2029
|
-
> **Request schemas appear with `@bymax-one/nest-core` ≥ 1.6.1; older versions ignore the
|
|
2030
|
-
> contribution without a signal.** Through 1.6.0 an empty placeholder counts as a declaration, so
|
|
2031
|
-
> the schema offered here is dropped and the document renders exactly as before: no error, no
|
|
2032
|
-
> warning, and no `discarded` field on what `applyBymaxOpenApi` returns. From 1.6.1 the
|
|
2033
|
-
> placeholder is filled from the contribution. A schema of the same name that carries properties
|
|
2034
|
-
> of its own is a declaration and wins, and `applyBymaxOpenApi` reports the contribution that
|
|
2035
|
-
> lost in `discarded`. Components are keyed by the DTO's class name, so a DTO of your own that
|
|
2036
|
-
> shares a name with one of this library's (a `LoginDto`, say) and is itself an empty placeholder
|
|
2037
|
-
> is filled with this library's schema: name your own classes differently.
|
|
2038
|
-
|
|
2039
|
-
Two limits, so a missing field is not mistaken for a bug. The OAuth endpoints take their input as
|
|
2040
|
-
query parameters, which the builder describes as operation parameters rather than as a component,
|
|
2041
|
-
so no schema is offered for those two DTOs. And what a decorator cannot express (which proof
|
|
2042
|
-
`ResetPasswordDto` accepts for the configured `passwordReset.method`, the deployment's
|
|
2043
|
-
`password.minLength`) is not in the schema and is not described elsewhere in the served document.
|
|
2044
|
-
|
|
2045
|
-
**If you already wrote these by hand, delete them** — not because they are wrong. They are what
|
|
2046
|
-
makes your document correct today; the deletion is what hands the job to the library, and it is
|
|
2047
|
-
needed precisely because they were doing it. Precedence, read from nest-core's
|
|
2048
|
-
`augmentOperation` rather than summarised: the generated operation's own `security` outranks
|
|
2049
|
-
everything, then your `openapi.operationSecurity` override, then this library's fragment, then
|
|
2050
|
-
nest-core's policy. So a stale scheme name or an override for an auth route keeps winning and the
|
|
2051
|
-
contributed one never lands — the document goes on describing whatever you wrote when you wrote
|
|
2052
|
-
it, including cookie names you have since changed.
|
|
2053
|
-
|
|
2054
|
-
> **Delete the entries for THESE routes. Keep your document-level `security`.** They are usually
|
|
2055
|
-
> written in the same options block, and taking the block out is the failure this warning exists
|
|
2056
|
-
> for — reported by a consumer who ran the comparison below and found their document **more wrong
|
|
2057
|
-
> after adopting than before**. The mechanism is in `augmentOperation`: an operation with no
|
|
2058
|
-
> requirement of its own, no override and no fragment falls through to `ownRouteSecurity`, which
|
|
2059
|
-
> answers `undefined` for anything that is not a route nest-core answers for itself — the health
|
|
2060
|
-
> probes, and from **nest-core 1.5.3** an unprotected metrics endpoint (through 1.5.2 metrics was
|
|
2061
|
-
> not among them). So **your** guarded routes carry no requirement and inherit the document
|
|
2062
|
-
> default. Remove that default and every one of those routes reads as needing no credential.
|
|
2063
|
-
>
|
|
2064
|
-
> **Keep the condition attached, because it decides how much of your API is affected.** This
|
|
2065
|
-
> reaches the routes that state nothing of their own — no `@ApiSecurity`-style decorator feeding
|
|
2066
|
-
> the scanned operation, no entry in nest-core's `operationSecurity`, and not a route nest-core
|
|
2067
|
-
> answers for itself. Anything carrying its own requirement outranks the document default and is
|
|
2068
|
-
> untouched, which is exactly why the fix works at all. If your backend annotates every guarded
|
|
2069
|
-
> route individually, this note does not apply to you; the reason it bit two consumers is that
|
|
2070
|
-
> annotating each route is the thing a document-level default exists to avoid.
|
|
2071
|
-
>
|
|
2072
|
-
> **nest-core's own routes are the exception that still moves.** It emits an explicit `security: []`
|
|
2073
|
-
> for the health probes — and, from 1.5.3, for a metrics endpoint left unprotected — but only when
|
|
2074
|
-
> the **served document actually carries a non-empty top-level `security`**, whether that came from
|
|
2075
|
-
> `openapi.security` or was already on the generated document handed to nest-core.
|
|
2076
|
-
> Remove the default and the `[]` goes with it. Write the default as an explicit empty list and
|
|
2077
|
-
> nothing is being overridden, so the member stays absent either way.
|
|
2078
|
-
>
|
|
2079
|
-
> (Through 1.5.2 that condition read `openapi.security.length > 0` alone, which answered `false`
|
|
2080
|
-
> for a document that carried its own default without one being configured — so those routes
|
|
2081
|
-
> inherited a credential nest-core does not check. If you build the document yourself rather than
|
|
2082
|
-
> handing the default to `openapi.security`, that is your shape, and 1.5.3 is the fix.)
|
|
2083
|
-
>
|
|
2084
|
-
> **On nest-core below 1.5.0, nothing reports this.** No error, no unmatched key, no failing
|
|
2085
|
-
> build — the document simply stops asking for credentials on the routes the library never knew
|
|
2086
|
-
> about, which are the ones your backend owns. **nest-core 1.5.0 warns**, on exactly this shape:
|
|
2087
|
-
> a document with no top-level `security` where some other operation does state a requirement, so
|
|
2088
|
-
> the bare ones are bare against a described posture rather than in a document that describes
|
|
2089
|
-
> none. It names the operations and never throws. That makes the failure visible, not impossible —
|
|
2090
|
-
> a warning in a build log is still something a person has to read.
|
|
2091
|
-
>
|
|
2092
|
-
> Keep the default, and **derive it rather than writing a literal**. Since 1.4.4 the derivation
|
|
2093
|
-
> ships, so the common case is one call rather than a rule you apply by hand:
|
|
2094
|
-
>
|
|
2095
|
-
> ```ts
|
|
2096
|
-
> import { authDocumentSecurity } from '@bymax-one/nest-auth'
|
|
2097
|
-
>
|
|
2098
|
-
> BymaxCoreModule.forRoot({
|
|
2099
|
-
> openapi: {
|
|
2100
|
-
> // `tokenDelivery` here is the SAME value you pass to BymaxAuthModule.forRoot — read it from
|
|
2101
|
-
> // one place. A default derived from a second copy drifts exactly like a literal does.
|
|
2102
|
-
> security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
|
|
2103
|
-
> }
|
|
2104
|
-
> })
|
|
2105
|
-
> ```
|
|
2106
|
-
>
|
|
2107
|
-
> It answers the delivery axis of both questions below — the scheme name for your guard family,
|
|
2108
|
-
> and the two-entry alternation under `'both'` that a hand-written default usually collapses into
|
|
2109
|
-
> a single AND entry. **It does not know what you mounted**, which is the third row of the table
|
|
2110
|
-
> in question 2 and the one case you still have to answer yourself. Read on for that, and for why
|
|
2111
|
-
> the recipe takes two questions rather than one:
|
|
2112
|
-
>
|
|
2113
|
-
> **1. Which guard protects your own routes?** That decides the credential family, and
|
|
2114
|
-
> `tokenDelivery` does not enter into it for one of them.
|
|
2115
|
-
>
|
|
2116
|
-
> - `JwtAuthGuard` (the dashboard family) → an access scheme, chosen by delivery. Go to question 2.
|
|
2117
|
-
> - `JwtPlatformGuard` → **`bymaxPlatformAccessBearer`, in every mode**. `extractPlatformAccessToken`
|
|
2118
|
-
> reads the `Authorization` header whatever `tokenDelivery` says, and `schemesFor` declares that
|
|
2119
|
-
> scheme with no delivery condition on it. A platform-guarded route wants it under `cookie`
|
|
2120
|
-
> delivery exactly as much as under `bearer`.
|
|
2121
|
-
> - **Both, on different routes** → the default cannot express this, though not because it is
|
|
2122
|
-
> limited to one entry. A document `security` array may hold both requirements — but the entries
|
|
2123
|
-
> are **alternatives**, and the whole array applies to every operation that inherits it. Listing
|
|
2124
|
-
> both therefore documents each credential as valid for _either_ family, which says your platform
|
|
2125
|
-
> routes accept a member token. That is not a missing detail; it is a false statement about who
|
|
2126
|
-
> can call what. Give the minority family per-operation `security` (via your own decorator or
|
|
2127
|
-
> nest-core's `operationSecurity`) and let the default cover the majority.
|
|
2128
|
-
>
|
|
2129
|
-
> **2. For the dashboard family — which schemes does this deployment actually declare?** Delivery
|
|
2130
|
-
> decides, and so does what you mounted. Take a default written as `[{ bymaxAuthAccessCookie: [] }]`:
|
|
2131
|
-
>
|
|
2132
|
-
> | deployment | this contributor declares | that literal default |
|
|
2133
|
-
> | -------------------------------------- | --------------------------------- | ----------------------------------------------------------- |
|
|
2134
|
-
> | dashboard mounted, `cookie` | the cookie scheme only | correct |
|
|
2135
|
-
> | dashboard mounted, `both` | the cookie **and** bearer schemes | resolves, but describes only one of the two channels |
|
|
2136
|
-
> | dashboard mounted, `bearer` | no cookie scheme at all | names an undeclared scheme — `assertSchemesDeclared` throws |
|
|
2137
|
-
> | **no dashboard surface, any delivery** | **neither dashboard scheme** | names an undeclared scheme — throws, `cookie` included |
|
|
2138
|
-
>
|
|
2139
|
-
> That last row is the one a delivery-only recipe gets wrong, and **"no dashboard surface" is
|
|
2140
|
-
> wider than it first sounds.** `schemesFor` gates both dashboard schemes on one of `auth`,
|
|
2141
|
-
> `passwordReset`, `mfa`, `sessions`, `invitations` or `emailChange` being registered. `oauth` is
|
|
2142
|
-
> **not** in that list — its operations are public and reference no credential — so an OAuth-only
|
|
2143
|
-
> deployment contributes operations and zero schemes, exactly like a platform-only one. Any
|
|
2144
|
-
> deployment with no dashboard controller is in this row, and `cookie` delivery, which the recipe
|
|
2145
|
-
> would call the safe case, throws just as hard as `bearer`.
|
|
2146
|
-
>
|
|
2147
|
-
> **And that row needs a remedy, not just a warning, because these deployments are legitimate.**
|
|
2148
|
-
> `JwtAuthGuard` is registered and exported unconditionally — it is not gated on any controller
|
|
2149
|
-
> flag — so mounting no dashboard controller does **not** stop you from guarding your own routes
|
|
2150
|
-
> with a dashboard access token. Both shapes are real: the platform surface plus your own routes
|
|
2151
|
-
> on the member credential; or the OAuth surface alone, where sign-in happens through a provider
|
|
2152
|
-
> and your app issues member tokens itself. In each case the guard is available and the scheme
|
|
2153
|
-
> describing it is not. Deriving correctly there lands you on "the scheme I need does not exist",
|
|
2154
|
-
> which is an accurate answer and not a usable
|
|
2155
|
-
> one.
|
|
2156
|
-
>
|
|
2157
|
-
> **Declare it yourself, in your own `openapi.securitySchemes`.** This is the one case where
|
|
2158
|
-
> "delete your hand-written `securitySchemes`" has an exception, and the exception exists because
|
|
2159
|
-
> the contributor deliberately declares only what its own operations reference — defining a
|
|
2160
|
-
> dashboard scheme on a deployment with no dashboard operation would put an unreferenced
|
|
2161
|
-
> credential in every such document, which is the opposite error and the reason for the gate.
|
|
2162
|
-
>
|
|
2163
|
-
> **Which scheme you declare is still a function of delivery** — the exception is to the deletion
|
|
2164
|
-
> rule, not to the derivation rule, and writing one fixed definition here reintroduces the very
|
|
2165
|
-
> literal this section is about:
|
|
2166
|
-
>
|
|
2167
|
-
> - `cookie` → the `apiKey`-in-cookie definition, carrying the `cookies.accessTokenName` you
|
|
2168
|
-
> configured. The cookie name is yours to choose, so this is the one that must match what the
|
|
2169
|
-
> server actually reads.
|
|
2170
|
-
> - `bearer` → the HTTP bearer definition. There is no cookie name to carry.
|
|
2171
|
-
> - `both` → **both of them**, or your document is incomplete in exactly the quiet way described
|
|
2172
|
-
> above.
|
|
2173
|
-
>
|
|
2174
|
-
> One note on doing any of it: **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, so
|
|
2175
|
-
> import the names rather than writing `bymaxAuthAccessCookie` and `bymaxAuthAccessBearer` as
|
|
2176
|
-
> string literals. The compiler then checks the PROPERTY you reach for, so a typo is a build
|
|
2177
|
-
> error rather than a document declaring a scheme nothing defines — and if a scheme's identifier
|
|
2178
|
-
> is ever renamed, your document carries the new one instead of a literal that has quietly gone
|
|
2179
|
-
> stale. Renaming the value is not itself a build error, since `AUTH_SECURITY_SCHEMES.accessCookie`
|
|
2180
|
-
> stays valid and only its string changes; that is precisely why importing beats copying.
|
|
2181
|
-
>
|
|
2182
|
-
> **The wrong outcomes are not one failure, and the difference is the point.** Where the scheme
|
|
2183
|
-
> does not exist, nest-core's `assertSchemesDeclared` **throws** and the document never builds —
|
|
2184
|
-
> loud, immediate, impossible to ship. Under `both` the scheme does exist, so nothing throws; the
|
|
2185
|
-
> default is merely **incomplete**, telling a reader that your own routes take a cookie when they
|
|
2186
|
-
> equally accept a bearer token. That one is quiet, and it is the same class of quiet as the bug
|
|
2187
|
-
> this whole note is about. A literal written against a bearer-only deployment inverts the table
|
|
2188
|
-
> and fails under `cookie` for the same reasons.
|
|
2189
|
-
>
|
|
2190
|
-
> So the advice that fixes a silently wrong document can introduce a loud broken one **or a second
|
|
2191
|
-
> quiet one**, depending on where you land. Derive from the same inputs the contributor reads —
|
|
2192
|
-
> the guard your routes use, your delivery mode, and the controllers you registered — and the
|
|
2193
|
-
> answer is right everywhere at once, instead of correct in one configuration and checked forever.
|
|
2194
|
-
>
|
|
2195
|
-
> The default is what covers your routes, and it cannot disturb this library's: a per-operation
|
|
2196
|
-
> requirement outranks a document-level one, and every operation the contributor describes carries
|
|
2197
|
-
> its own.
|
|
2198
|
-
>
|
|
2199
|
-
> **What an empty `{}` alternative says, and where this library uses it as an approximation.**
|
|
2200
|
-
> In OpenAPI it means one thing: authentication is **optional** for that operation — a caller
|
|
2201
|
-
> presenting none of the named schemes is valid. Tooling reads it as anonymous access and infers
|
|
2202
|
-
> nothing about a request body from it.
|
|
2203
|
-
>
|
|
2204
|
-
> On `logout` that is exactly right, in **every** delivery mode including `cookie`: the operation
|
|
2205
|
-
> really does answer a caller who presents nothing, which is why a user whose access token
|
|
2206
|
-
> expired can still sign out. How many alternatives you see depends on the mode, since each one
|
|
2207
|
-
> is a combination of the credentials that mode actually has:
|
|
2208
|
-
>
|
|
2209
|
-
> | operation | `cookie` | `bearer` | `both` |
|
|
2210
|
-
> | ----------------- | -------- | -------- | ------ |
|
|
2211
|
-
> | `logout` | 4 | 2 | 6 |
|
|
2212
|
-
> | `password/change` | 2 | 1 | 4 |
|
|
2213
|
-
>
|
|
2214
|
-
> On `refresh` under `tokenDelivery: 'both'` it is an **approximation, and a permissive one**.
|
|
2215
|
-
> That operation refuses a caller with no credential at all; the token may simply arrive in the
|
|
2216
|
-
> request body, which `security` has no vocabulary for. The empty entry is what lets the document
|
|
2217
|
-
> describe the body-only caller, and the cost is that it also tells tooling anonymous access is
|
|
2218
|
-
> acceptable when it is not.
|
|
2219
|
-
>
|
|
2220
|
-
> The `requestBody` beside it **documents the body channel; it does not carry the requirement**.
|
|
2221
|
-
> Under `'both'` it is `required: false` and its schema does not list `refreshToken` as required,
|
|
2222
|
-
> because either channel satisfies the server and a body that omits the token is valid when the
|
|
2223
|
-
> cookie carries it. So the document as a whole permits a request with neither, and the server
|
|
2224
|
-
> refuses that request. **OpenAPI cannot express "one of these two channels" across a security
|
|
2225
|
-
> requirement and a request body**, and this is the shape of that limitation rather than an
|
|
2226
|
-
> oversight. Under `'bearer'`, where the cookie does not exist, the body becomes required at both
|
|
2227
|
-
> levels and the document is exact.
|
|
2228
|
-
>
|
|
2229
|
-
> Written out because two earlier versions of this note were wrong in opposite directions: one
|
|
2230
|
-
> called `{}` "a credential this member cannot model", which is the intent rather than the
|
|
2231
|
-
> notation; the other claimed the `requestBody` carried the requirement, which it does not.
|
|
2232
|
-
>
|
|
2233
|
-
> **Verify with a diff, not by reasoning.** Render the document with the contributor active and
|
|
2234
|
-
> again with your entries in place, and compare only the operations you mount. The consumer who
|
|
2235
|
-
> did this found their own three differences were improvements — a configured cookie name over
|
|
2236
|
-
> the exported default, `logout` gaining the access-only and refresh-only alternatives their map
|
|
2237
|
-
> called unsatisfiable — and one regression that no status-code probe could have surfaced,
|
|
2238
|
-
> because the routes it broke still answered correctly at runtime.
|
|
2239
|
-
>
|
|
2240
|
-
> **And there is one shape no warning will catch for you, however new your nest-core.** If you
|
|
2241
|
-
> remove _every_ requirement at once — no library describing anything, no decorator, no override,
|
|
2242
|
-
> no document default — what remains is indistinguishable from the document of an API that is
|
|
2243
|
-
> 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
|
|
2244
|
-
> without also shouting at every genuinely public API, which is how a warning earns the right to
|
|
2245
|
-
> be ignored. This is why nest-core's warning requires that _some_ operation still state a
|
|
2246
|
-
> requirement: the gap is deliberate, not an omission, and no version closes it.
|
|
2247
|
-
>
|
|
2248
|
-
> **But it is a limit on document-only checks, not on you** — and the distinction matters, because
|
|
2249
|
-
> the better answer is the one a general-purpose tool cannot supply. **You** know your API is not
|
|
2250
|
-
> public, which is exactly the intent no renderer can recover, so write it down as an assertion in
|
|
2251
|
-
> your own suite: that the built document carries a top-level `security`, or that every route
|
|
2252
|
-
> behind your auth guard renders with some requirement. That is a standing check, it runs on every
|
|
2253
|
-
> commit, and it does not depend on anyone remembering to compare. Prefer it to the diff.
|
|
2254
|
-
>
|
|
2255
|
-
> Render the document twice and compare when you are **changing** this — adopting the contributor,
|
|
2256
|
-
> moving delivery mode, adding a surface — because a diff shows you what moved without your having
|
|
2257
|
-
> to predict it in advance. Then turn what you learned into the assertion, so the next change is
|
|
2258
|
-
> caught rather than inspected.
|
|
2259
|
-
|
|
2260
|
-
**That chain is about `security` alone, and the other members run the opposite rule** — worth
|
|
2261
|
-
stating because generalising either one produces a wrong belief about the other. There is no
|
|
2262
|
-
configuration channel for a `description`, a `summary` or a tag: `mergeFragment` merges the
|
|
2263
|
-
scanned operation **over** the fragment, so a contributed member lands unless the handler itself
|
|
2264
|
-
declared that member, and the handler is this library's. Concretely, the `description` on
|
|
2265
|
-
`logout` cannot be shadowed by anything in your options — only by an `@ApiOperation` on a handler
|
|
2266
|
-
you do not own. Nothing to delete for that half; the deletion above is entirely about `security`.
|
|
2267
|
-
|
|
2268
|
-
> **Your own document test will not catch this.** A consumer seat measured it on their own
|
|
2269
|
-
> repository: ten `operationSecurity` entries, all for this library's routes, and a suite
|
|
2270
|
-
> asserting the operation-to-posture map with `toEqual`. On adoption, every contributed fragment
|
|
2271
|
-
> loses to those entries, the old scheme names survive — and the suite stays **green**, because
|
|
2272
|
-
> it is asserting the old answer that is still being served. A test that pins your document
|
|
2273
|
-
> confirms the staleness rather than finding it. The deletion is the step; nothing downstream
|
|
2274
|
-
> will remind you.
|
|
2275
|
-
|
|
2276
|
-
Do it as one change: delete the literals, update whatever pins your document to the four-name
|
|
2277
|
-
vocabulary, rebuild it, and regenerate any typed client — the operation ids do not move, but the
|
|
2278
|
-
scheme names and the per-operation requirements do.
|
|
2279
|
-
|
|
2280
|
-
#### Machine-readable schemas
|
|
2281
|
-
|
|
2282
|
-
The same contracts are published as data in
|
|
2283
|
-
[`conformance/openapi-request-schemas.json`](./conformance/openapi-request-schemas.json) —
|
|
2284
|
-
OpenAPI 3.0 schemas for all 22 DTOs, generated from the decorators themselves and regenerated by
|
|
2285
|
-
`pnpm gen:openapi-schemas`. Alongside it,
|
|
2286
|
-
[`openapi-request-descriptions.json`](./conformance/openapi-request-descriptions.json) carries the
|
|
2287
|
-
facts no keyword expresses: the twelve e-mail fields that are **trimmed and lowercased before
|
|
2288
|
-
validation**, each entry shipping the probe that verifies its own sentence.
|
|
2289
|
-
|
|
2290
|
-
A third file,
|
|
2291
|
-
[`openapi-declared-structures.json`](./conformance/openapi-declared-structures.json), carries the
|
|
2292
|
-
contracts the generated header names and no decorator can express — as **structure**, not prose:
|
|
2293
|
-
|
|
2294
|
-
| Declared | As |
|
|
2295
|
-
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
|
2296
|
-
| `reset-password` takes exactly one of `token`, `otp`, `verifiedToken` | `oneOf` |
|
|
2297
|
-
| 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` |
|
|
2298
|
-
| The 8-character floor is structural, not your policy | probes showing the pipe accepting what the deployment refuses |
|
|
2299
|
-
| `forgot-password`, `resend-otp`, `resend-verification`, `verify-email` answer identically for an unknown address | probes asserting the two responses are **equal** |
|
|
2300
|
-
|
|
2301
|
-
Three rules keep it honest. Only `required`, `oneOf` and `anyOf` may appear — `allOf` and `not`
|
|
2302
|
-
are valid OpenAPI 3.0 and are **refused at load**, because a keyword nothing evaluates publishes
|
|
2303
|
-
a claim nothing checks. Every entry carries probes, and both suites run them: the unit suite
|
|
2304
|
-
evaluates each body against its own structure and reads what the pipe answers, the e2e suite
|
|
2305
|
-
answers the rest with a real application. An entry whose two layers disagree — the pipe accepting
|
|
2306
|
-
what the handler or the service then refuses — is split across the two suites on purpose, because
|
|
2307
|
-
neither can see the pair. And presence means _present and not `null`_ — this
|
|
2308
|
-
server's rule rather than JSON Schema's, because `@IsOptional()` treats `null` as absent, so a
|
|
2309
|
-
body sending `null` and one omitting the key are the same request.
|
|
2310
|
-
|
|
2311
|
-
A structure is a **necessary** condition, never a sufficient one, and `reset-password` shows why:
|
|
2312
|
-
which of the three proofs is eligible depends on `passwordReset.method`, and an ineligible proof
|
|
2313
|
-
is refused with the same code a structural violation gets. That narrowing is declared with its
|
|
2314
|
-
own probes and is deliberately not something a client can generate against.
|
|
2315
|
-
|
|
2316
|
-
Another file,
|
|
2317
|
-
[`openapi-operation-security.json`](./conformance/openapi-operation-security.json), maps every
|
|
2318
|
-
operation this library mounts (`METHOD /path`, relative to your route prefix) to the **kind** of
|
|
2319
|
-
credential it requires, with the meaning of each kind alongside. It is generated from the table the
|
|
2320
|
-
OpenAPI fragment is built from and the controllers' route metadata, regenerated by
|
|
2321
|
-
`pnpm gen:openapi-security`, and a spec fails when it differs. How a kind becomes a security
|
|
2322
|
-
requirement depends on your `tokenDelivery` and is not in the file.
|
|
2323
|
-
|
|
2324
|
-
These are development artifacts — they are not in the published tarball, and nothing reads
|
|
2325
|
-
them at runtime yet. They exist so the schemas are a function of the decorators rather than a
|
|
2326
|
-
second description maintained by hand.
|
|
2327
|
-
|
|
2328
|
-
### Administrative operations — methods, deliberately not routes
|
|
2329
|
-
|
|
2330
|
-
Two support-desk operations ship as **methods with no HTTP route**. Every route above is scoped
|
|
2331
|
-
to the caller's own account, and both of these act on somebody else's — so exposing them would
|
|
2332
|
-
mean inventing an authorization model ("who is an admin?") that this library does not have and
|
|
2333
|
-
your application already does. Call them from your own admin surface, where the caller is
|
|
2334
|
-
already authorized.
|
|
2335
|
-
|
|
2336
|
-
| Method | Answers |
|
|
2337
|
-
| -------------------------------------------------- | --------------------------------------------------- |
|
|
2338
|
-
| `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
|
|
2339
|
-
| `MfaService.resetMfa(userId, context?, tenantId?)` | "I lost my authenticator **and** my recovery codes" |
|
|
2340
|
-
|
|
2341
|
-
**`unlockAccount`** clears the brute-force lockout. It grants no access: the password, the
|
|
2342
|
-
status gate, the verification gate and MFA all still apply — it restores the ability to _try_.
|
|
2343
|
-
It exists because the counter is keyed by an HMAC under the library's own `hmacKey`, which no
|
|
2344
|
-
consumer can derive, so until it existed a lockout could only be waited out. It is also the
|
|
2345
|
-
lever an attacker pulls to deny service to one specific account, which makes undoing it part of
|
|
2346
|
-
the defence. Idempotent.
|
|
2347
|
-
|
|
2348
|
-
**`resetMfa`** removes a second factor without one. Every self-service exit needs the factor
|
|
2349
|
-
itself — `disable` wants a valid TOTP code, the recovery codes want the codes — so a user who
|
|
2350
|
-
has lost both is locked out permanently by the control meant to protect them (ASVS v5 §6.1.1
|
|
2351
|
-
asks for this path for exactly that reason). It invalidates every session and bumps the token
|
|
2352
|
-
epoch, so access tokens carrying `mfaVerified: true` die with the factor; it **notifies the
|
|
2353
|
-
account holder** through the same channel a self-service disable uses; and it logs at `warn`
|
|
2354
|
-
under its own prefix. The notification is not optional: an administrative reset the owner
|
|
2355
|
-
cannot see is an account-takeover path, and it is what makes the event detectable and
|
|
2356
|
-
disputable. `tenantId` is required when `context` is `'dashboard'` (the default) and ignored for
|
|
2357
|
-
`'platform'`. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
|
|
2358
|
-
"done".
|
|
2359
|
-
|
|
2360
|
-
> `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
|
|
2361
|
-
> otherwise add it to `extraProviders` to inject it.
|
|
2362
|
-
|
|
2363
|
-
### Checking revocation outside a guard — `AuthRevocationService`
|
|
2364
|
-
|
|
2365
|
-
The three JWT guards do not decide revocation themselves; they delegate to one service, and that
|
|
2366
|
-
service is exported so **you can consult the same two channels from a transport the guards never
|
|
2367
|
-
see** — a WebSocket, an SSE stream, a message consumer. Without it there is no way to ask the
|
|
2368
|
-
question at all outside an HTTP request: a connection whose user logs out keeps its stream until
|
|
2369
|
-
the access token expires, while that user's HTTP calls are refused at once.
|
|
2370
|
-
|
|
2371
|
-
```ts
|
|
2372
|
-
import { AuthRevocationService } from '@bymax-one/nest-auth'
|
|
2373
|
-
|
|
2374
|
-
const revoked = await this.revocation.isAccessTokenRevoked(
|
|
2375
|
-
{ jti: payload.jti, sub: payload.sub, epoch: payload.epoch, tenantId: payload.tenantId },
|
|
2376
|
-
'dashboard'
|
|
2377
|
-
)
|
|
2378
|
-
```
|
|
2379
|
-
|
|
2380
|
-
It is registered and exported unconditionally, so it is injectable wherever `BymaxAuthModule` is
|
|
2381
|
-
imported — no `extraProviders` entry and no controller flag to turn on.
|
|
2382
|
-
|
|
2383
|
-
> [!IMPORTANT]
|
|
2384
|
-
> **On the dashboard plane you must forward `tenantId` from the verified token.** It is optional
|
|
2385
|
-
> on `RevocableTokenPayload` because the platform plane genuinely has none — its admins are
|
|
2386
|
-
> cross-tenant — so **`tsc` will not catch the omission**, and a dashboard payload without it is
|
|
2387
|
-
> treated as **revoked** without a store read, with a `warn` naming the missing field.
|
|
2388
|
-
>
|
|
2389
|
-
> Failing closed is deliberate. The epoch key derives from the tenant-scoped subject, so an absent
|
|
2390
|
-
> tenant names a keyspace belonging to no tenant, where nothing has ever been bumped: the read
|
|
2391
|
-
> would answer `0`, `stamped < 0` is false for every token, and a bulk-revoked token would be
|
|
2392
|
-
> reported **valid**. A revocation check that fails open on malformed input is worse than no check.
|
|
2393
|
-
>
|
|
2394
|
-
> **Recognise the symptom, because it does not look like an auth bug.** The refusal answers the
|
|
2395
|
-
> same `true` a genuinely revoked token answers, throws nothing and emits no event — so a
|
|
2396
|
-
> transport that gates a stream on it simply registers nothing. Measured on a consumer's realtime
|
|
2397
|
-
> bridge: the SSE handshake answered `200` and the connection registry stayed at `count: 0`.
|
|
2398
|
-
> Declaring the tenant **required** on your own port type is the stronger fix, because it turns the
|
|
2399
|
-
> next occurrence into a compile error rather than a log line.
|
|
2400
|
-
|
|
2401
|
-
**What this method is and is not.** It answers two channels at the moment you call it: the
|
|
2402
|
-
per-token blacklist and the user's token epoch. It reads no `exp`, holds no subscription, emits no
|
|
2403
|
-
event, and knows nothing about account status, roles, tenant binding or the identity plane. It is
|
|
2404
|
-
therefore **one check among the many a guarded HTTP route performs**, and not a substitute for
|
|
2405
|
-
them.
|
|
2406
|
-
|
|
2407
|
-
Using it to authorise a long-lived transport takes more than this method. Use
|
|
2408
|
-
`AuthTokenVerifierService` for that, below.
|
|
2409
|
-
|
|
2410
|
-
### Authorising a long-lived transport — `AuthTokenVerifierService`
|
|
2411
|
-
|
|
2412
|
-
A guarded HTTP route establishes seven things before a handler runs. A WebSocket, an SSE stream or
|
|
2413
|
-
a message consumer has no guard in front of it, so it must establish the same seven itself — and on
|
|
2414
|
-
a cadence, because a connection outlives the request that opened it. Assembling that from the
|
|
2415
|
-
exported parts is where it goes wrong: a bridge that calls `isAccessTokenRevoked` alone has checked
|
|
2416
|
-
a signature and a blacklist while checking neither the token's **type**, nor its **`exp`**, nor
|
|
2417
|
-
whether the **account** behind it still exists.
|
|
2418
|
-
|
|
2419
|
-
`AuthTokenVerifierService.verifyAccessToken` is all seven in one call:
|
|
2420
|
-
|
|
2421
|
-
```ts
|
|
2422
|
-
import { AuthTokenVerifierService } from '@bymax-one/nest-auth'
|
|
2423
|
-
|
|
2424
|
-
const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
|
|
2425
|
-
registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
|
|
2426
|
-
```
|
|
2427
|
-
|
|
2428
|
-
| It checks | So that |
|
|
2429
|
-
| -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2430
|
-
| 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 |
|
|
2431
|
-
| `exp` | A revocation check answers "was this withdrawn", never "is this still current" — `isAccessTokenRevoked` reads no `exp` at all |
|
|
2432
|
-
| `jti` a UUID v4; `sub` and (dashboard) `tenantId` bounded non-empty strings | A malformed claim cannot build a Redis key nobody intended |
|
|
2433
|
-
| Token `type`, against the plane **you** name | An `mfa_challenge` token — signed with the same secret, half a credential — cannot read as a session |
|
|
2434
|
-
| Both revocation channels | A logout's `jti` blacklist AND the epoch a password reset or revoke-all advances |
|
|
2435
|
-
| 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 |
|
|
2436
|
-
| 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 |
|
|
2437
|
-
|
|
2438
|
-
On the dashboard plane that last row reads a cache, and **its freshness is bounded by
|
|
2439
|
-
`userStatusCacheTtlSeconds` (default 60 s), not by how often you call**: a stream re-verifying every
|
|
2440
|
-
five seconds still serves a banned account until the entry expires. What shortens that is
|
|
2441
|
-
[`AccountStatusService.invalidate`](#invalidating-the-account-cache--accountstatusserviceinvalidate)
|
|
2442
|
-
— call it wherever you change a status, and read the caveat under that method: a request already
|
|
2443
|
-
resolving when you invalidate can write the old value back, so the window narrows to one repository
|
|
2444
|
-
read rather than to zero. Failing that, lower the TTL. The platform plane is uncached and genuinely current, at one repository read per call.
|
|
2445
|
-
|
|
2446
|
-
The plane is **yours to declare**, never inferred from the token. Inferring it would make the plane
|
|
2447
|
-
attacker-chosen: a platform token would open a dashboard stream by saying it is one. Passing a
|
|
2448
|
-
value that is neither throws a `TypeError` rather than refusing quietly — the fall-through would
|
|
2449
|
-
otherwise be the cross-tenant platform arm.
|
|
2450
|
-
|
|
2451
|
-
Every refusal is an `AuthException`, and each mirrors the code the equivalent guard already
|
|
2452
|
-
answers. Most answer `auth.token_invalid` so a caller cannot tell "valid but revoked" from "never
|
|
2453
|
-
valid"; `auth.mfa_required`, the `ACCOUNT_*` codes, `auth.email_not_verified` (dashboard plane) and — on
|
|
2454
|
-
the platform plane only — `auth.platform_auth_required` name themselves, because a legitimate
|
|
2455
|
-
client acts on each differently. The account codes are answered whether or not an MFA challenge
|
|
2456
|
-
is pending; `auth.mfa_required` is answered only for a usable account.
|
|
2457
|
-
|
|
2458
|
-
> [!IMPORTANT]
|
|
2459
|
-
> **Three things it still does not do.** Route **authorization** is yours — this answers who the
|
|
2460
|
-
> caller is, never what they may do, so your `@Roles()` equivalent belongs on every message a
|
|
2461
|
-
> stream carries, not only on the handshake. **Tenant binding** (`enforceTenantBinding`) needs the
|
|
2462
|
-
> request its resolver reads, so pass the handshake as `request` to `verifyAccessToken` (the same
|
|
2463
|
-
> `headers`/`url`/`hostname` request as on `WsJwtGuard`, fail-closed on a resolver that cannot answer);
|
|
2464
|
-
> without it the binding is not applied to that call, and one warning per service instance says so. And it holds **no
|
|
2465
|
-
> subscription**: it answers at the moment you call it, so a stream that calls it once at connect
|
|
2466
|
-
> is authorized for the lifetime of the token rather than of the session. Call it again on a
|
|
2467
|
-
> cadence and treat a rejection as a disconnect.
|
|
2468
|
-
|
|
2469
|
-
`AccountStatusService` is exported alongside it for the narrower case: you already hold a verified
|
|
2470
|
-
payload and want to re-ask only the one question whose answer changes while a stream is open.
|
|
2471
|
-
|
|
2472
|
-
### Invalidating the account cache — `AccountStatusService.invalidate`
|
|
2473
|
-
|
|
2474
|
-
Account status is read through a Redis cache with a `userStatusCacheTtlSeconds` lifetime (60 s by
|
|
2475
|
-
default), so a change made **outside** this library is not seen until the entry expires. Suspend a
|
|
2476
|
-
user through your own admin surface and they keep reaching protected routes for up to a minute.
|
|
2477
|
-
|
|
2478
|
-
```ts
|
|
2479
|
-
import { AccountStatusService } from '@bymax-one/nest-auth'
|
|
2480
|
-
|
|
2481
|
-
await this.accountStatus.invalidate({ userId, tenantId })
|
|
2482
|
-
```
|
|
1643
|
+
This package does not depend on `@bymax-one/nest-core`. From nest-core 1.6.1 the request-body
|
|
1644
|
+
schemas of every mounted DTO are described too. Which nest-core version contributes what, how to
|
|
1645
|
+
remove hand-written `operationSecurity` entries and derive the document-level default with
|
|
1646
|
+
`authDocumentSecurity`, and the machine-readable schemas under `conformance/` are in
|
|
1647
|
+
[OpenAPI documents and `@bymax-one/nest-core`](./docs/openapi-interop.md).
|
|
2483
1648
|
|
|
2484
|
-
|
|
2485
|
-
and the email-verified flag — and is idempotent, so you need not know whether the account was
|
|
2486
|
-
cached. The tenant is required: a repository id is unique only within one, so a bare id would name
|
|
2487
|
-
another tenant's entry. An empty or blank `userId` or `tenantId` throws a `TypeError` rather than
|
|
2488
|
-
deleting nothing and resolving.
|
|
1649
|
+
### Server services for operations that are not routes
|
|
2489
1650
|
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
update lands will write it back afterwards, with a full TTL, however promptly you call this. The
|
|
2493
|
-
window is one repository read wide rather than one TTL, which is the improvement; it is not zero.
|
|
2494
|
-
Writing first means any request whose read starts after your write already sees the new value, and
|
|
2495
|
-
only genuinely concurrent ones can lose the race. Closing it entirely would need the fill to be
|
|
2496
|
-
conditional on nothing having invalidated in between, which this service does not do today.
|
|
1651
|
+
Services cover what a guard or a route cannot, each documented in
|
|
1652
|
+
[Server services](./docs/server-services.md):
|
|
2497
1653
|
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
1654
|
+
- **Administrative operations** — support-desk operations that ship as methods with no HTTP route.
|
|
1655
|
+
- **`AuthRevocationService`** — check revocation outside a guard.
|
|
1656
|
+
- **`AuthTokenVerifierService`** — authorise a long-lived transport (a WebSocket, an SSE stream, a
|
|
1657
|
+
message consumer): signature, token type, both revocation channels, account status and the MFA
|
|
1658
|
+
policy, with the same refusals the guards give.
|
|
1659
|
+
- **`AccountStatusService.invalidate`** — drop an account's cached status after you persist a
|
|
1660
|
+
status change.
|
|
2505
1661
|
|
|
2506
1662
|
### Server Guards
|
|
2507
1663
|
|
|
@@ -2545,7 +1701,7 @@ thrown one.
|
|
|
2545
1701
|
> **Do not register it on a `@bymax-one/nest-core` application.** The two filters are mutually
|
|
2546
1702
|
> exclusive and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER` provider, and
|
|
2547
1703
|
> `@Catch()` with no argument catches everything, so nest-core's envelope filter never runs.
|
|
2548
|
-
>
|
|
1704
|
+
> The same request answers `{ error: { code, message, details } }` with this filter
|
|
2549
1705
|
> registered and the flat `{ statusCode, code, message, timestamp, path, details }` without it.
|
|
2550
1706
|
> Registering both therefore **loses** `statusCode`, `timestamp`, `path` and the correlation id,
|
|
2551
1707
|
> which is the opposite of what adding a filter looks like it should do.
|
|
@@ -2560,65 +1716,18 @@ thrown one.
|
|
|
2560
1716
|
|
|
2561
1717
|
#### On a WebSocket, the envelope needs its own filter
|
|
2562
1718
|
|
|
2563
|
-
`
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
```json
|
|
2568
|
-
{ "status": "error", "message": "Internal server error" }
|
|
2569
|
-
```
|
|
2570
|
-
|
|
2571
|
-
The refusal itself is correct: the handler never runs. What is lost is everything the client
|
|
2572
|
-
could act on. A reconnect policy cannot tell a dead credential from a crashed handler, and the
|
|
2573
|
-
sensible default for an unknown error is to retry — so an expired token becomes a reconnect loop
|
|
2574
|
-
against an endpoint that will refuse it forever.
|
|
2575
|
-
|
|
2576
|
-
> **Socket.IO only, measured.** `WsJwtGuard` reads both credential channels from the client's
|
|
2577
|
-
> `handshake`, and only a Socket.IO client has one: with `@nestjs/platform-ws` the gateway
|
|
2578
|
-
> receives the raw `ws` socket, which carries no `handshake` — and `ws` does not retain the
|
|
2579
|
-
> upgrade request either, so there is nothing to read. Such a connection is **refused** with
|
|
2580
|
-
> `auth.token_invalid` rather than crashing the socket, and the filter below delivers that
|
|
2581
|
-
> refusal, but the guard cannot authenticate anyone on that adapter. Supporting it needs the
|
|
2582
|
-
> gateway to stash the upgrade request in `handleConnection`, which is a contract this library
|
|
2583
|
-
> does not have today.
|
|
2584
|
-
|
|
2585
|
-
Register the filter on any gateway that applies the guard:
|
|
2586
|
-
|
|
2587
|
-
```typescript
|
|
2588
|
-
@UseFilters(new WsAuthExceptionFilter())
|
|
2589
|
-
@UseGuards(WsJwtGuard)
|
|
2590
|
-
@WebSocketGateway()
|
|
2591
|
-
export class FeedGateway {}
|
|
2592
|
-
```
|
|
2593
|
-
|
|
2594
|
-
```json
|
|
2595
|
-
{ "status": "error", "error": { "code": "auth.token_invalid", "message": "...", "details": null } }
|
|
2596
|
-
```
|
|
2597
|
-
|
|
2598
|
-
`status: 'error'` is kept — it is the field Nest itself sets and the one socket.io clients
|
|
2599
|
-
already branch on — and the envelope is added beside it, so a client handling both shapes needs
|
|
2600
|
-
no second listener. The `AuthException` travels whole, so a `details` payload survives.
|
|
2601
|
-
|
|
2602
|
-
The filter is scoped to `AuthException` on purpose. An argument-less `@Catch()` would claim
|
|
2603
|
-
every exception the gateway raises, so a `WsException` an unrelated handler throws — a domain
|
|
2604
|
-
error with its own contract — would be rewritten as an `auth.*` code, and following this README
|
|
2605
|
-
would silently break errors a consumer already ships. Everything that is not this library's
|
|
2606
|
-
refusal keeps travelling through Nest's own exception layer, untouched.
|
|
2607
|
-
|
|
2608
|
-
Both transports are answered. A Socket.IO client is dispatched to with `emit`; a native `ws`
|
|
2609
|
-
client is written to with `send`, in the `{event, data}` envelope `@nestjs/platform-ws` uses for
|
|
2610
|
-
every other message — emitting on one of those succeeds, dispatches a local event and sends the
|
|
2611
|
-
peer nothing, which is the failure this ordering exists to prevent. Both paths are driven over a
|
|
2612
|
-
real handshake in `test/e2e/ws-guard.e2e-spec.ts`.
|
|
1719
|
+
`AuthException` extends `HttpException`, which Nest's WebSocket layer does not recognise, so a
|
|
1720
|
+
gateway that applies `WsJwtGuard` also needs `WsAuthExceptionFilter`; without it the refusal reaches
|
|
1721
|
+
the client as `Internal server error`. See
|
|
1722
|
+
[On a WebSocket, the envelope needs its own filter](./docs/websocket-upgrades.md#on-a-websocket-the-envelope-needs-its-own-filter).
|
|
2613
1723
|
|
|
2614
1724
|
#### The HTTP status belongs to the code
|
|
2615
1725
|
|
|
2616
1726
|
Every code answers exactly one status, and the status is derived from the code rather than
|
|
2617
1727
|
chosen at the throw site — `AuthException` takes no status argument. A client can switch on
|
|
2618
|
-
`error.code` and the status line together
|
|
2619
|
-
`@bymax-one/nest-auth` and `rust-auth` read the same table, pinned in
|
|
1728
|
+
`error.code` and the status line together. The table is pinned in
|
|
2620
1729
|
[`conformance/wire-contract.json`](./conformance/wire-contract.json) under
|
|
2621
|
-
`errorCatalog.statuses` and asserted
|
|
1730
|
+
`errorCatalog.statuses` and asserted against that file.
|
|
2622
1731
|
|
|
2623
1732
|
| Status | Codes |
|
|
2624
1733
|
| -----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -2629,6 +1738,7 @@ chosen at the throw site — `AuthException` takes no status argument. A client
|
|
|
2629
1738
|
| `409` | `auth.email_already_exists` · `auth.mfa_already_enabled` · `auth.mfa_state_conflict` · `auth.oauth_email_mismatch` |
|
|
2630
1739
|
| `429` | `auth.account_locked` · `auth.too_many_requests` |
|
|
2631
1740
|
| `500` | `auth.internal` |
|
|
1741
|
+
| `503` | `auth.service_unavailable` |
|
|
2632
1742
|
|
|
2633
1743
|
`AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
|
|
2634
1744
|
need the mapping at runtime — for a typed client, an API document, or a test that asserts against
|
|
@@ -2638,19 +1748,11 @@ it:
|
|
|
2638
1748
|
import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared'
|
|
2639
1749
|
```
|
|
2640
1750
|
|
|
2641
|
-
Shown as an import rather than described, on purpose: this package's README contract test reads
|
|
2642
|
-
import statements, so a symbol that stops being exported from the subpath named here fails the
|
|
2643
|
-
suite. It scans prose too — for scheme names it invented and for claims that something is not
|
|
2644
|
-
public — but it cannot check a sentence that merely _says_ where a symbol ships from. That claim
|
|
2645
|
-
went one release stated and unenforced.
|
|
2646
|
-
|
|
2647
1751
|
> **Assert your fixtures against the catalogue, not against string literals.** `AUTH_ERROR_CODES`
|
|
2648
1752
|
> is exported from `@bymax-one/nest-auth/shared` so a suite can check that every code it branches
|
|
2649
|
-
> on is one the server can actually produce. A
|
|
2650
|
-
> `auth.unauthorized
|
|
2651
|
-
>
|
|
2652
|
-
> matters. The check is one test over your own source, and it is worth having standing rather than
|
|
2653
|
-
> as a one-off audit.
|
|
1753
|
+
> on is one the server can actually produce. A branch on a code the server never sends (for example
|
|
1754
|
+
> `auth.unauthorized`, which does not exist) is silent forever: it simply never runs, and the
|
|
1755
|
+
> handler it replaces is the one that matters. The check is one test over your own source.
|
|
2654
1756
|
>
|
|
2655
1757
|
> **Five codes are internal-only and never reach a client**: `auth.token_expired`,
|
|
2656
1758
|
> `auth.token_revoked`, `auth.token_missing` (all collapsed onto `auth.token_invalid`) and
|
|
@@ -2669,10 +1771,12 @@ went one release stated and unenforced.
|
|
|
2669
1771
|
> (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
|
|
2670
1772
|
> registered, since only a record that exists can reach one.
|
|
2671
1773
|
|
|
2672
|
-
> **When a password-reset request fails.** A failure that is the same for every address
|
|
2673
|
-
>
|
|
2674
|
-
> (`auth.internal`)
|
|
2675
|
-
>
|
|
1774
|
+
> **When a password-reset request fails.** A failure that is the same for every address answers
|
|
1775
|
+
> after the same timing floor as every other exit: `503` (`auth.service_unavailable`) when the
|
|
1776
|
+
> resend-cooldown store cannot answer, `500` (`auth.internal`) for any other failure of it and for
|
|
1777
|
+
> your repository's `findByEmail` throwing. The answer is the same for every address because the
|
|
1778
|
+
> cooldown is the first thing every request consults, and a later failure releases the cooldown so
|
|
1779
|
+
> the retry is not refused. A failure after the account is known (storing the
|
|
2676
1780
|
> code, or the mail provider failing after the response has left) is logged and the `200` stands,
|
|
2677
1781
|
> because it happens only for a registered address. Two limits are left as they are. A `findByEmail`
|
|
2678
1782
|
> that takes longer than the cooldown (60 seconds) and then fails releases the cooldown by key, and
|
|
@@ -2712,6 +1816,18 @@ went one release stated and unenforced.
|
|
|
2712
1816
|
|
|
2713
1817
|
---
|
|
2714
1818
|
|
|
1819
|
+
## 🚫 What This Library Does NOT Do
|
|
1820
|
+
|
|
1821
|
+
- **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.
|
|
1822
|
+
- **It does not send email.** You implement `IEmailProvider`; the bundled `DefaultAuthEmailProvider` renders messages and hands them to a transport you supply.
|
|
1823
|
+
- **It does not delete users.** `IUserRepository` has no delete; a host that deletes one removes its workspace memberships first.
|
|
1824
|
+
- **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.
|
|
1825
|
+
- **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`).
|
|
1826
|
+
- **It does not authenticate a WebSocket on `@nestjs/platform-ws`.** `WsJwtGuard` reads a Socket.IO `handshake`, which the raw `ws` adapter does not provide.
|
|
1827
|
+
- **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`.
|
|
1828
|
+
|
|
1829
|
+
---
|
|
1830
|
+
|
|
2715
1831
|
## 🤝 Contributing
|
|
2716
1832
|
|
|
2717
1833
|
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
|