@bymax-one/nest-auth 1.4.2 → 1.4.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/README.md CHANGED
@@ -170,8 +170,16 @@ import type {
170
170
  AuthUser,
171
171
  CreateUserData,
172
172
  CreateWithOAuthData,
173
+ FindUserByEmailParams,
174
+ FindUserByOAuthIdParams,
173
175
  IUserRepository,
174
- UpdateMfaData
176
+ LinkOAuthParams,
177
+ TenantScopedUserRef,
178
+ UpdateEmailParams,
179
+ UpdateEmailVerifiedParams,
180
+ UpdateMfaParams,
181
+ UpdatePasswordParams,
182
+ UpdateStatusParams
175
183
  } from '@bymax-one/nest-auth'
176
184
  import { PrismaService } from './prisma.service'
177
185
 
@@ -179,12 +187,13 @@ import { PrismaService } from './prisma.service'
179
187
  export class PrismaUserRepository implements IUserRepository {
180
188
  constructor(private readonly prisma: PrismaService) {}
181
189
 
182
- async findById(id: string, tenantId?: string): Promise<AuthUser | null> {
183
- const where = tenantId ? { id, tenantId } : { id }
184
- return this.prisma.user.findFirst({ where })
190
+ async findById({ id, tenantId }: TenantScopedUserRef): Promise<AuthUser | null> {
191
+ // Both halves of the key, always. An id is unique only within a tenant, so `findUnique`
192
+ // by id alone can answer with another tenant's row.
193
+ return this.prisma.user.findFirst({ where: { id, tenantId } })
185
194
  }
186
195
 
187
- async findByEmail(email: string, tenantId: string): Promise<AuthUser | null> {
196
+ async findByEmail({ email, tenantId }: FindUserByEmailParams): Promise<AuthUser | null> {
188
197
  return this.prisma.user.findUnique({
189
198
  where: { email_tenantId: { email: email.toLowerCase(), tenantId } }
190
199
  })
@@ -205,13 +214,15 @@ export class PrismaUserRepository implements IUserRepository {
205
214
  })
206
215
  }
207
216
 
208
- async updatePassword(id: string, passwordHash: string): Promise<void> {
209
- await this.prisma.user.update({ where: { id }, data: { passwordHash } })
217
+ // Every mutator below uses `updateMany` rather than `update`, for one reason: `update` takes a
218
+ // UNIQUE where-clause, so it cannot accept `{ id, tenantId }` unless your schema declares that
219
+ // pair unique — and `update({ where: { id } })` is the tenant-blind write this port exists to
220
+ // prevent. `updateMany` accepts the compound filter and touches nothing outside the tenant.
221
+ async updatePassword({ id, tenantId, passwordHash }: UpdatePasswordParams): Promise<void> {
222
+ await this.prisma.user.updateMany({ where: { id, tenantId }, data: { passwordHash } })
210
223
  }
211
224
 
212
- async updateMfa(id: string, tenantId: string | undefined, data: UpdateMfaData): Promise<void> {
213
- // Scoped by tenant, like findById: `updateMany` with both id and tenantId so an id shared
214
- // across tenants cannot cross the write onto the wrong account.
225
+ async updateMfa({ id, tenantId, data }: UpdateMfaParams): Promise<void> {
215
226
  await this.prisma.user.updateMany({
216
227
  where: { id, tenantId },
217
228
  data: {
@@ -222,35 +233,44 @@ export class PrismaUserRepository implements IUserRepository {
222
233
  })
223
234
  }
224
235
 
225
- async updateLastLogin(id: string): Promise<void> {
226
- await this.prisma.user.update({ where: { id }, data: { lastLoginAt: new Date() } })
236
+ async updateLastLogin({ id, tenantId }: TenantScopedUserRef): Promise<void> {
237
+ await this.prisma.user.updateMany({
238
+ where: { id, tenantId },
239
+ data: { lastLoginAt: new Date() }
240
+ })
227
241
  }
228
242
 
229
- async updateStatus(id: string, status: string): Promise<void> {
230
- await this.prisma.user.update({ where: { id }, data: { status } })
243
+ async updateStatus({ id, tenantId, status }: UpdateStatusParams): Promise<void> {
244
+ await this.prisma.user.updateMany({ where: { id, tenantId }, data: { status } })
231
245
  }
232
246
 
233
- async updateEmailVerified(id: string, verified: boolean): Promise<void> {
234
- await this.prisma.user.update({ where: { id }, data: { emailVerified: verified } })
247
+ async updateEmailVerified({ id, tenantId, verified }: UpdateEmailVerifiedParams): Promise<void> {
248
+ await this.prisma.user.updateMany({
249
+ where: { id, tenantId },
250
+ data: { emailVerified: verified }
251
+ })
235
252
  }
236
253
 
237
- async updateEmail(id: string, email: string): Promise<void> {
238
- await this.prisma.user.update({ where: { id }, data: { email: email.toLowerCase() } })
254
+ async updateEmail({ id, tenantId, email }: UpdateEmailParams): Promise<void> {
255
+ await this.prisma.user.updateMany({
256
+ where: { id, tenantId },
257
+ data: { email: email.toLowerCase() }
258
+ })
239
259
  }
240
260
 
241
- async findByOAuthId(
242
- provider: string,
243
- providerId: string,
244
- tenantId: string
245
- ): Promise<AuthUser | null> {
261
+ async findByOAuthId({
262
+ provider,
263
+ providerId,
264
+ tenantId
265
+ }: FindUserByOAuthIdParams): Promise<AuthUser | null> {
246
266
  return this.prisma.user.findFirst({
247
267
  where: { oauthProvider: provider, oauthProviderId: providerId, tenantId }
248
268
  })
249
269
  }
250
270
 
251
- async linkOAuth(userId: string, provider: string, providerId: string): Promise<void> {
252
- await this.prisma.user.update({
253
- where: { id: userId },
271
+ async linkOAuth({ id, tenantId, provider, providerId }: LinkOAuthParams): Promise<void> {
272
+ await this.prisma.user.updateMany({
273
+ where: { id, tenantId },
254
274
  data: { oauthProvider: provider, oauthProviderId: providerId }
255
275
  })
256
276
  }
@@ -281,10 +301,76 @@ Email delivery is fully delegated to the consumer — the library never imports
281
301
  > [!WARNING]
282
302
  > 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.
283
303
 
304
+ > [!CAUTION]
305
+ > **Never log the error your transport rejects with — it can contain the code you just sent.**
306
+ > A policy, DLP or anti-spam relay answering `550` commonly **quotes the offending message body**,
307
+ > so the error your `send()` throws carries the OTP or token this library rendered into it. Logging
308
+ > that error, or attaching it as a `cause` to one you log, puts a working credential into your log
309
+ > pipeline in clear text until it expires. Measured on a real relay, not hypothesised.
310
+ >
311
+ > This is your half: the library cannot reach inside your provider implementation.
312
+ > **`describeChannelStatus` is exported for it** — the same helper the bundled provider uses on
313
+ > every one of its own log lines, so you get the whole treatment rather than just redaction:
314
+ >
315
+ > ```typescript
316
+ > import { describeChannelStatus } from '@bymax-one/nest-auth'
317
+ >
318
+ > async sendPasswordResetOtp(tenantId: string, email: string, otp: string): Promise<void> {
319
+ > try {
320
+ > await this.resend.emails.send({ /* ... */ })
321
+ > } catch (error: unknown) {
322
+ > // Never `logger.error(msg, error)` here, and never `new Error(msg, { cause: error })`
323
+ > // into something that logs — both carry the quoted body.
324
+ > this.logger.error(`reset OTP delivery failed: ${describeChannelStatus(error)}`)
325
+ > throw error
326
+ > }
327
+ > }
328
+ > ```
329
+ >
330
+ > Two functions, not one with a mode: which one you call IS the decision, and there is no
331
+ > permissive default to inherit by forgetting.
332
+ >
333
+ > **`describeChannelStatus(error)` wherever the body rendered something you would withhold.** It
334
+ > takes no secrets, and that is the guarantee rather than an omission — nothing the channel wrote
335
+ > is published, so there is nothing to name. Redaction alone does not close this, and neither does
336
+ > a length cap. A relay may quote the body it rejected in transfer encoding rather
337
+ > than verbatim; base64 is the ordinary case and defeats both at once — substring matching finds
338
+ > nothing because the credential's characters are not in the line, and the cap does not help
339
+ > because the encoding runs from the body's first byte, so the code is in the first sentence.
340
+ > Measured: a reset-code body is 96 base64 characters end to end, and the first 200 characters of
341
+ > the line decode straight back to the OTP. Under `describeChannelStatus` NOTHING the channel wrote
342
+ > reaches the line — not the message, not the `name`, not a status parsed off the front. Each of
343
+ > those was tried and each fell: shape validation admits `MTIzNDU2`, the base64 of OTP `123456`;
344
+ > and a status grammar admits `424-242`, an OTP grouped, publishing `424`. What you keep is which
345
+ > message failed. What you lose is the transient-versus-permanent split, which your mail provider's
346
+ > dashboard has and this library does not.
347
+ >
348
+ > **`describeError(error, [values])` for errors whose text you have a reason to trust**, where the
349
+ > values you name appear the way you wrote them and redaction reaches them. The bundled provider
350
+ > uses it nowhere — every one of its paths uses the opaque form, including the notices that
351
+ > render nothing secret, because a relay may re-encode whatever it quotes and the recipient address
352
+ > is in the message either way. If you can say the same about your channel, prefer
353
+ > `describeChannelStatus` and keep this one for strings you built yourself.
354
+ >
355
+ > Neither reads `stack`, and neither reads the transport's own fields — nodemailer hangs the
356
+ > server's full reply on `response`. Beyond that they differ, and the difference is the point:
357
+ > `describeError` reads `name` and `message`, strips the values you named, caps the length and
358
+ > removes control characters so a relay cannot forge extra records in a line-oriented pipeline.
359
+ > `describeChannelStatus` reads **neither** — the only thing it touches is `cause`, walked to count
360
+ > the links. Both walk that chain and never throw, whatever the transport's error does.
361
+ >
362
+ > `redactSecrets(text, [otp])` is exported too, for a string you built yourself and know contains
363
+ > the literal value. It is **not** a substitute for either description on a transport's error: a
364
+ > substring match cannot see through an encoding, which is the whole reason the bundled provider
365
+ > stopped relying on it.
366
+ >
367
+ > If you use the bundled `DefaultAuthEmailProvider` with `onDeliveryError: 'rethrow'`, the error it
368
+ > re-throws is the channel's original and is still yours to contain the same way.
369
+
284
370
  ```typescript
285
371
  // email.provider.ts
286
372
  import { Injectable } from '@nestjs/common'
287
- import type { IEmailProvider, InviteData, SessionInfo } from '@bymax-one/nest-auth'
373
+ import type { IEmailProvider, InviteData, SessionAlertInfo } from '@bymax-one/nest-auth'
288
374
  import { Resend } from 'resend'
289
375
 
290
376
  const escapeHtml = (s: string): string =>
@@ -344,6 +430,13 @@ export class ResendEmailProvider implements IEmailProvider {
344
430
  })
345
431
  }
346
432
 
433
+ // The library does NOT await the three MFA notices — by the time one is sent the factor is
434
+ // already enabled or removed, so a bounced notice must not answer the caller with an error for
435
+ // an operation that succeeded. The consequence is here: an inline send like this one can be
436
+ // lost to a process shutdown or a serverless freeze arriving between the response and the send
437
+ // completing. Where these alerts matter — the administrative reset most of all, since it is what
438
+ // makes a support-desk takeover detectable — enqueue durably and resolve instead of sending
439
+ // inline. Awaiting would not fix it either: a freeze mid-await loses the notice AND the response.
347
440
  async sendMfaEnabledNotification(
348
441
  _tenantId: string,
349
442
  email: string,
@@ -373,7 +466,7 @@ export class ResendEmailProvider implements IEmailProvider {
373
466
  async sendNewSessionAlert(
374
467
  _tenantId: string,
375
468
  email: string,
376
- sessionInfo: SessionInfo,
469
+ sessionInfo: SessionAlertInfo,
377
470
  _locale?: string
378
471
  ): Promise<void> {
379
472
  await this.client.emails.send({
@@ -530,6 +623,15 @@ export function Providers({ children }: { children: React.ReactNode }) {
530
623
  }
531
624
  ```
532
625
 
626
+ > **Which 401 spends a refresh.** The client's `authFetch` retries through `/refresh` only when
627
+ > the 401 says the access token is the problem — `auth.token_invalid`, or a body carrying no
628
+ > readable code. A route can sit behind the JWT guard _and_ verify a second credential, so
629
+ > `auth.invalid_credentials` from a password change and an expired token arrive at the same URL
630
+ > with the same status; the code separates them, the path never could. Any other 401 is returned
631
+ > to the caller untouched, and `createAuthClient({ onSessionExpired })` fires only when a refresh
632
+ > was warranted and failed. `AuthProvider`'s own `onSessionExpired` prop is a different hook: it
633
+ > reacts to a 401 from the session read itself.
634
+
533
635
  ```tsx
534
636
  // app/(dashboard)/profile.tsx
535
637
  'use client'
@@ -553,6 +655,30 @@ export function Profile() {
553
655
  }
554
656
  ```
555
657
 
658
+ #### Plain SPAs — set `refreshEndpoint`
659
+
660
+ The example above is a Next.js app, where the default works. **A Vite/CRA SPA talking straight to
661
+ a Nest backend must set `refreshEndpoint`**, because it defaults to `/api/auth/client-refresh` —
662
+ a Next.js proxy route this library ships for that framework, and a path a plain SPA serves
663
+ nothing at.
664
+
665
+ ```ts
666
+ const authClient = createAuthClient({
667
+ baseUrl: 'https://api.example.com',
668
+ // Without this, refresh POSTs to the Next proxy route and 404s.
669
+ refreshEndpoint: 'https://api.example.com/auth/refresh'
670
+ })
671
+ ```
672
+
673
+ **The symptom, because it does not look like a configuration problem:** _if every access-token
674
+ expiry logs the user out, check `refreshEndpoint` before looking at cookies._ The 404 is silent —
675
+ refresh fails, the session ends, and it presents as a session bug rather than as a missing route.
676
+
677
+ Also note `tenantId` is **optional** on every client input. Whether the server wants it is the
678
+ deployment's answer, not the type's: it is required when no `tenantIdResolver` is configured and
679
+ **refused** when one is, answering `auth.validation` with a `tenantId` field detail either way.
680
+ Send it, or do not, according to the deployment you talk to.
681
+
556
682
  ### 7. Frontend Integration (Next.js 16)
557
683
 
558
684
  Mount the Edge-Runtime auth proxy at the project root and expose the
@@ -669,6 +795,15 @@ satisfied MFA, so a ticket never carries more authority than the request that as
669
795
  Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
670
796
  both channels are accepted, and a ticket wins when both are present.
671
797
 
798
+ Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
799
+ `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
800
+ does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
801
+ `auth.token_invalid` instead of crashing on it, but it cannot authenticate anyone on that
802
+ adapter. And because `AuthException` extends `HttpException`, which Nest's WebSocket layer does
803
+ not recognise, a gateway that applies the guard also needs `WsAuthExceptionFilter` for the
804
+ refusal to reach the client as anything but `Internal server error` — see
805
+ [On a WebSocket, the envelope needs its own filter](#on-a-websocket-the-envelope-needs-its-own-filter).
806
+
672
807
  ---
673
808
 
674
809
  ## ⚙️ Configuration
@@ -796,6 +931,45 @@ All options are configurable via `registerAsync()`. Here are the key configurati
796
931
  > rather than letting it fail open, and rejects an unreadable time span or a non-positive
797
932
  > lifetime on the same pass.
798
933
 
934
+ > [!WARNING]
935
+ > **Do not gate on the access token's `status` claim.** It is **point-in-time, never
936
+ > authoritative**, and which of its three states you get depends on things a client cannot see:
937
+ >
938
+ > | how the token was minted | `status` |
939
+ > | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
940
+ > | login, register, OAuth, MFA challenge | the account's value **at that moment** |
941
+ > | an ordinary refresh rotation | **empty string** — the session record carries no live status, so there is nothing to copy |
942
+ > | a refresh that re-signs because `role`, `tenantId` or `mfaEnabled` changed | the account's value **at that moment**, read during that request |
943
+ >
944
+ > `rust-auth` stamps the same empty string on its rotation path, deliberately and with a test
945
+ > pinning it, so the middle row is a shared contract rather than a defect in either library.
946
+ >
947
+ > Every populated value is stale the instant the account changes, because status can change under
948
+ > an unexpired token and nothing re-stamps it. So a route that reads the claim is wrong in **both**
949
+ > directions: `status !== 'active'` refuses everyone whose session has been refreshed ordinarily,
950
+ > and `status === 'suspended'` refuses nobody, ever. Both fail quietly and hours from the code
951
+ > that caused them — the first looks like a broken login, the second like nothing at all.
952
+ >
953
+ > The exceptional re-stamp is the worst of the three for a reader, not the best: it makes the
954
+ > claim _usually_ wrong instead of _reliably_ empty, which is the failure mode that survives
955
+ > testing.
956
+ >
957
+ > Status is resolved per request or not at all: mount `UserStatusGuard` on the route, and for
958
+ > anything richer read the account **tenant-scoped**, the way that guard does —
959
+ > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is required by the
960
+ > port and cannot be dropped: ids may collide across tenants, so a lookup by bare id can resolve
961
+ > another tenant's account. That is what the library's own guards do, which
962
+ > is why the claim can be left as it is. `mfaVerified` behaves the same way and for the same
963
+ > reason — it is always `false` after a rotation, so step-up does not survive a refresh and a
964
+ > user re-acquires it through the MFA challenge.
965
+ >
966
+ > One consequence worth planning for: the guard reads a status cache with a
967
+ > `userStatusCacheTtlSeconds` window (default **60**), so a suspension takes up to that long to
968
+ > bite on a guarded route, and a reactivation the same to restore. Nothing exported invalidates
969
+ > that key for one user today — the only immediate lever is `bumpUserTokenEpoch`, which ends
970
+ > every session the user has rather than refreshing one cached string. Lower the TTL if a faster
971
+ > answer matters more than the repository reads it costs.
972
+
799
973
  `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
800
974
  **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
801
975
  SHALL and puts it at no more than 30 days for AAL1. Without a cap, a client refreshing every
@@ -913,6 +1087,19 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
913
1087
  `cookies.sameSite: 'strict'`. CSRF does not rest on this setting — `TrustedOriginGuard` is
914
1088
  applied to every controller and runs before authentication.
915
1089
 
1090
+ **The tokens are never readable from JavaScript, and verifying that end-to-end is yours.** Under
1091
+ cookie delivery this library never writes a token to `localStorage`, `sessionStorage`, or a
1092
+ JS-readable cookie: `access_token` and `refresh_token` are `HttpOnly`, and the only readable
1093
+ cookie is `has_session=1`, a hint carrying no credential so a SPA can tell a session probably
1094
+ exists without touching a token.
1095
+
1096
+ This library's suite asserts **its half** — that the `Set-Cookie` headers carry those flags — and
1097
+ it structurally cannot assert the other half. A token leaking into JS-readable storage is
1098
+ invisible from the server: the API answers identically, the wire looks correct, and every test
1099
+ here passes. Only a browser observes it. **If you run a browser suite, assert there that
1100
+ `localStorage` and `sessionStorage` are empty and that `document.cookie` carries neither token**;
1101
+ it is the one guarantee cookie delivery exists for and the one no server-side test can reach.
1102
+
916
1103
  ---
917
1104
 
918
1105
  ## 🛡️ Security Table
@@ -958,9 +1145,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
958
1145
  Authentication is critical infrastructure, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
959
1146
 
960
1147
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
961
- - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 4,989 seeded faults detected (4,968 killed, 21 timed out), **no survivors and nothing left uncovered**, against a `break` threshold of 100 ([measured cold on 2026-08-12](./docs/mutation_testing_results.md#re-measured-cold--2026-08-12))
962
- - ✅ **3,547 tests** — 3,420 unit and 127 end-to-end, spanning all five subpaths
963
- - ✅ **Every equivalent mutant documented** — the 350 mutants that no test can kill (a redundant guard, a dependency array of stable references) each carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
1148
+ - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 5,333 seeded faults detected (5,311 killed, 22 timed out), **no survivors and nothing left uncovered**, against a `break` threshold of 100 ([measured cold on 2026-08-15](./docs/mutation_testing_results.md#re-measured-cold--2026-08-15))
1149
+ - ✅ **3,971 tests** — 3,721 unit and 250 end-to-end, spanning all five subpaths
1150
+ - ✅ **Every equivalent mutant documented** — the 367 mutants that no test can kill (a redundant guard, a dependency array of stable references) each carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
964
1151
 
965
1152
  ```bash
966
1153
  pnpm test # unit suite
@@ -979,40 +1166,55 @@ pnpm mutation # Stryker mutation testing
979
1166
 
980
1167
  Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
981
1168
 
982
- | Method | Path | Auth / Guard | Description |
983
- | ------ | --------------------------- | ---------------------------------- | ----------------------------------------------------------- |
984
- | POST | `/register` | Public | Register a new dashboard user and issue tokens |
985
- | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
986
- | POST | `/logout` | `JwtAuthGuard` | Revoke tokens and clear session |
987
- | POST | `/refresh` | Public (refresh cookie) | Rotate refresh token, issue new access token |
988
- | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
989
- | POST | `/verify-email` | Public | Verify email with OTP |
990
- | POST | `/resend-verification` | Public | Resend email-verification OTP |
991
- | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
992
- | POST | `/password/reset-password` | Public | Submit new password with reset token |
993
- | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
994
- | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
995
- | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
996
- | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
997
- | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
998
- | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
999
- | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
1000
- | DELETE | `/sessions/all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke all sessions |
1001
- | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
1002
- | POST | `/invitations` | `JwtAuthGuard`, `UserStatusGuard` | Create a tenant invitation |
1003
- | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
1004
- | POST | `/invitations/revoke` | `JwtAuthGuard`, `UserStatusGuard` | Withdraw a pending invitation |
1005
- | POST | `/email/change` | `JwtAuthGuard`, `UserStatusGuard` | Request an address change (re-proves the current password) |
1006
- | POST | `/email/change/confirm` | Public | Confirm it with the token mailed to the new address |
1007
- | POST | `/platform/login` | Public | Platform admin login (separate token context) |
1008
- | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
1009
- | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
1010
- | POST | `/platform/logout` | `JwtPlatformGuard` | Revoke platform tokens |
1011
- | POST | `/platform/refresh` | Public (platform refresh cookie) | Rotate platform refresh token |
1012
- | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
1013
- | POST | `/password/change` | `JwtAuthGuard` + `UserStatusGuard` | Change the password, proving the current one |
1014
- | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
1015
- | GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
1169
+ | Method | Path | Auth / Guard | Description |
1170
+ | ------ | ------------------------------ | ---------------------------------- | ----------------------------------------------------------- |
1171
+ | POST | `/register` | Public | Register a new dashboard user and issue tokens |
1172
+ | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
1173
+ | POST | `/logout` | Public (reads both credentials) | Revoke the session; blacklists the access token it is given |
1174
+ | POST | `/refresh` | Public (refresh cookie or body) | Rotate refresh token, issue new access token |
1175
+ | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
1176
+ | POST | `/ws-ticket` | `JwtAuthGuard` | Mint a single-use ticket for a WebSocket upgrade |
1177
+ | POST | `/verify-email` | Public | Verify email with OTP |
1178
+ | POST | `/resend-verification` | Public | Resend email-verification OTP |
1179
+ | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
1180
+ | POST | `/password/reset-password` | Public | Submit new password with reset token |
1181
+ | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
1182
+ | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
1183
+ | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
1184
+ | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
1185
+ | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
1186
+ | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
1187
+ | POST | `/mfa/recovery-codes` | `JwtAuthGuard` | Replace the recovery codes, proving a fresh OTP |
1188
+ | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
1189
+ | POST | `/sessions/revoke-all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke every session except the caller's |
1190
+ | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
1191
+ | POST | `/invitations` | `JwtAuthGuard`, `UserStatusGuard` | Create a tenant invitation |
1192
+ | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
1193
+ | POST | `/invitations/revoke` | `JwtAuthGuard`, `UserStatusGuard` | Withdraw a pending invitation |
1194
+ | POST | `/email/change` | `JwtAuthGuard`, `UserStatusGuard` | Request an address change (re-proves the current password) |
1195
+ | POST | `/email/change/confirm` | Public | Confirm it with the token mailed to the new address |
1196
+ | POST | `/platform/login` | Public | Platform admin login (separate token context) |
1197
+ | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
1198
+ | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
1199
+ | POST | `/platform/logout` | Public (refresh token in body) | Revoke the session; blacklists the access token it is given |
1200
+ | POST | `/platform/refresh` | Public (refresh token in body) | Rotate the platform refresh token |
1201
+ | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
1202
+ | POST | `/platform/mfa/setup` | `JwtPlatformGuard` | Generate the admin's TOTP secret and recovery codes |
1203
+ | POST | `/platform/mfa/verify-enable` | `JwtPlatformGuard` | Confirm setup and enable MFA for the admin |
1204
+ | POST | `/platform/mfa/disable` | `JwtPlatformGuard` | Disable the admin's MFA, proving a fresh OTP |
1205
+ | POST | `/platform/mfa/recovery-codes` | `JwtPlatformGuard` | Replace the admin's recovery codes |
1206
+ | POST | `/password/change` | `JwtAuthGuard` + `UserStatusGuard` | Change the password, proving the current one |
1207
+ | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
1208
+ | GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
1209
+
1210
+ > **The platform plane never uses a refresh cookie.** `extractPlatformRefreshToken` reads
1211
+ > `req.body.refreshToken` in every `tokenDelivery` mode, and the access token is always the
1212
+ > `Authorization` header — so a consumer sending platform credentials as cookies is sending
1213
+ > something the server does not read. `platform/logout` and `platform/refresh` are `@Public()`
1214
+ > for the same reason their dashboard twins are: an operator whose fifteen-minute access token
1215
+ > expired must still be able to end the session, or the seven-day refresh session of the
1216
+ > highest-privilege identity in the system outlives the console they walked away from. Both
1217
+ > still READ the access token when one is sent, and `logout` blacklists its `jti`.
1016
1218
 
1017
1219
  > **The OAuth routes require `cookie-parser`.** `GET /oauth/:provider` plants an HttpOnly
1018
1220
  > `oauth_state` cookie carrying the flow's `state`, and the callback refuses any request that
@@ -1027,9 +1229,17 @@ unknown property is a `400 auth.validation` rather than a silently ignored field
1027
1229
  optional on every **unauthenticated** body below (≤128 chars, no control characters) and scopes
1028
1230
  the operation to one organization. `POST /password/change` is the exception: it is behind
1029
1231
  `JwtAuthGuard`, takes its tenant from the JWT, and declares no `tenantId` — so sending one is an
1030
- unknown property, and `forbidNonWhitelisted` answers `400 auth.validation`. Email fields are
1031
- trimmed and lowercased before they reach the service, so the stored identity matches the
1032
- case-insensitive lookup and every email-keyed control.
1232
+ unknown property, and `forbidNonWhitelisted` answers `400 auth.validation`. That same rule is why
1233
+ it **declares** `refreshToken`: an undeclared field would be refused rather than read. Email
1234
+ fields are trimmed and lowercased before they reach the service, so the stored identity matches
1235
+ the case-insensitive lookup and every email-keyed control.
1236
+
1237
+ `refreshToken` is **optional, and both answers are valid requests.** Send it and the device making
1238
+ the change stays signed in; omit it and every session ends — which is the right answer when you are
1239
+ rotating a credential you believe was stolen. Where the server looks for it follows
1240
+ `tokenDelivery`: the refresh cookie under `'cookie'`, this body field under `'bearer'`, and the
1241
+ cookie first then this field under `'both'` — so a `'both'` caller with no refresh cookie must send
1242
+ it here to keep its session.
1033
1243
 
1034
1244
  | Endpoint | Body |
1035
1245
  | -------------------------------- | -------------------------------------------------------------------------------- |
@@ -1041,7 +1251,7 @@ case-insensitive lookup and every email-keyed control.
1041
1251
  | `POST /password/verify-otp` | `{ email, otp }` |
1042
1252
  | `POST /password/resend-otp` | `{ email }` |
1043
1253
  | `POST /password/reset-password` | `{ email, newPassword }` **plus exactly one** of `token`, `otp`, `verifiedToken` |
1044
- | `POST /password/change` | `{ currentPassword, newPassword }` |
1254
+ | `POST /password/change` | `{ currentPassword, newPassword }` — optional `refreshToken`, see below |
1045
1255
 
1046
1256
  Three constraints are worth stating because they are not visible from the field names:
1047
1257
 
@@ -1061,6 +1271,307 @@ Three constraints are worth stating because they are not visible from the field
1061
1271
  length here would leak it as a pre-KDF timing signal, because a request failing validation
1062
1272
  returns before the hash runs.
1063
1273
 
1274
+ #### On `@bymax-one/nest-core`, the security posture writes itself
1275
+
1276
+ A deployment that builds its OpenAPI document with `@bymax-one/nest-core` **1.4.0 or later** gets
1277
+ this library's operations described automatically — which schemes exist, which operation requires
1278
+ which, and which are reachable unauthenticated. Nothing to enable and nothing to import: the
1279
+ module registers a contributor, nest-core discovers it while building the document, and the
1280
+ fragments are merged.
1281
+
1282
+ It has to be derived at your boot rather than shipped as a static file, because the answer
1283
+ depends on your configuration:
1284
+
1285
+ | your options | what the document says |
1286
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1287
+ | `tokenDelivery: 'cookie'` | `bymaxAuthAccessCookie` and `bymaxAuthRefreshCookie`, **carrying your cookie names** |
1288
+ | `tokenDelivery: 'bearer'` | `bymaxAuthAccessBearer` only — no refresh scheme exists, and `logout`/`refresh` instead carry a documented `{ refreshToken }` body |
1289
+ | `tokenDelivery: 'both'` | both access schemes as **alternatives** (`security: [{cookie}, {bearer}]`, which OpenAPI reads as OR) |
1290
+ | `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 |
1291
+ | a controller you did not mount | nothing at all: no operation, and no scheme only it would have referenced |
1292
+
1293
+ A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced — a
1294
+ document that defines a credential the server will not read tells a generated client to offer it.
1295
+
1296
+ The four names — `bymaxAuthAccessCookie`, `bymaxAuthAccessBearer`, `bymaxAuthRefreshCookie`,
1297
+ `bymaxPlatformAccessBearer` — are stable identifiers. Renaming one is a break a generated client
1298
+ feels, so they will not change; their **definitions** are config-derived.
1299
+
1300
+ Import them rather than spelling them. A platform-only deployment guarding its own routes with
1301
+ `JwtAuthGuard` has to declare the dashboard access scheme itself — the fragment will not, because
1302
+ `schemesFor` gates dashboard schemes on what you mounted — and a hand-written literal in a section
1303
+ about literals drifting from configuration is the wrong instruction:
1304
+
1305
+ ```typescript
1306
+ import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
1307
+
1308
+ // [{ bymaxAuthAccessCookie: [] }], spelled by the package that owns the name
1309
+ const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
1310
+ ```
1311
+
1312
+ > **This package does not depend on `@bymax-one/nest-core`** — not as a dependency, a peer, or a
1313
+ > devDependency. The contract revision is inlined, the discovery marker is the documented string
1314
+ > literal, and a gate fails the build if any file here imports another Bymax library. That keeps
1315
+ > your install graph free of a package you may not use, and it moves one check to your side:
1316
+ >
1317
+ > ```typescript
1318
+ > // in your suite, where both packages are installed at the versions you run
1319
+ > import {
1320
+ > BYMAX_OPENAPI_CONTRACT_VERSION,
1321
+ > BYMAX_OPENAPI_CONTRIBUTOR_METADATA
1322
+ > } from '@bymax-one/nest-core/openapi'
1323
+ >
1324
+ > expect(fragment.contractVersion).toBe(BYMAX_OPENAPI_CONTRACT_VERSION)
1325
+ > expect(Reflect.getMetadata(BYMAX_OPENAPI_CONTRIBUTOR_METADATA, contributor.constructor)).toBe(
1326
+ > true
1327
+ > )
1328
+ > ```
1329
+ >
1330
+ > Worth writing once. A revision mismatch fails your document build loudly and names the
1331
+ > contributor, but a **marker** mismatch is silent: the provider is simply never discovered and
1332
+ > the document renders without the fragments — the same symptom as running nest-core < 1.4.0.
1333
+
1334
+ > **On nest-core older than 1.4.0 the fragments are silently ignored.** There is no contributor
1335
+ > lane to discover them, so the document renders exactly as before — no error, no warning, no
1336
+ > failed boot. If you add a document and the auth schemes do not appear, check in this order:
1337
+ > whether this library is new enough to contribute them at all, and only then your nest-core
1338
+ > version. The two states look identical from the document.
1339
+
1340
+ **If you already wrote these by hand, delete them** — not because they are wrong. They are what
1341
+ makes your document correct today; the deletion is what hands the job to the library, and it is
1342
+ needed precisely because they were doing it. Precedence, read from nest-core's
1343
+ `augmentOperation` rather than summarised: the generated operation's own `security` outranks
1344
+ everything, then your `openapi.operationSecurity` override, then this library's fragment, then
1345
+ nest-core's policy. So a stale scheme name or an override for an auth route keeps winning and the
1346
+ contributed one never lands — the document goes on describing whatever you wrote when you wrote
1347
+ it, including cookie names you have since changed.
1348
+
1349
+ > **Delete the entries for THESE routes. Keep your document-level `security`.** They are usually
1350
+ > written in the same options block, and taking the block out is the failure this warning exists
1351
+ > for — reported by a consumer who ran the comparison below and found their document **more wrong
1352
+ > after adopting than before**. The mechanism is in `augmentOperation`: an operation with no
1353
+ > requirement of its own, no override and no fragment falls through to `ownRouteSecurity`, which
1354
+ > answers `undefined` for anything that is not a route nest-core answers for itself — the health
1355
+ > probes, and from **nest-core 1.5.3** an unprotected metrics endpoint (through 1.5.2 metrics was
1356
+ > not among them). So **your** guarded routes carry no requirement and inherit the document
1357
+ > default. Remove that default and every one of those routes reads as needing no credential.
1358
+ >
1359
+ > **Keep the condition attached, because it decides how much of your API is affected.** This
1360
+ > reaches the routes that state nothing of their own — no `@ApiSecurity`-style decorator feeding
1361
+ > the scanned operation, no entry in nest-core's `operationSecurity`, and not a route nest-core
1362
+ > answers for itself. Anything carrying its own requirement outranks the document default and is
1363
+ > untouched, which is exactly why the fix works at all. If your backend annotates every guarded
1364
+ > route individually, this note does not apply to you; the reason it bit two consumers is that
1365
+ > annotating each route is the thing a document-level default exists to avoid.
1366
+ >
1367
+ > **nest-core's own routes are the exception that still moves.** It emits an explicit `security: []`
1368
+ > for the health probes — and, from 1.5.3, for a metrics endpoint left unprotected — but only when
1369
+ > the **served document actually carries a non-empty top-level `security`**, whether that came from
1370
+ > `openapi.security` or was already on the generated document handed to nest-core.
1371
+ > Remove the default and the `[]` goes with it. Write the default as an explicit empty list and
1372
+ > nothing is being overridden, so the member stays absent either way.
1373
+ >
1374
+ > (Through 1.5.2 that condition read `openapi.security.length > 0` alone, which answered `false`
1375
+ > for a document that carried its own default without one being configured — so those routes
1376
+ > inherited a credential nest-core does not check. If you build the document yourself rather than
1377
+ > handing the default to `openapi.security`, that is your shape, and 1.5.3 is the fix.)
1378
+ >
1379
+ > **On nest-core below 1.5.0, nothing reports this.** No error, no unmatched key, no failing
1380
+ > build — the document simply stops asking for credentials on the routes the library never knew
1381
+ > about, which are the ones your backend owns. **nest-core 1.5.0 warns**, on exactly this shape:
1382
+ > a document with no top-level `security` where some other operation does state a requirement, so
1383
+ > the bare ones are bare against a described posture rather than in a document that describes
1384
+ > none. It names the operations and never throws. That makes the failure visible, not impossible —
1385
+ > a warning in a build log is still something a person has to read.
1386
+ >
1387
+ > Keep the default, and **derive it rather than writing a literal**. Since 1.4.4 the derivation
1388
+ > ships, so the common case is one call rather than a rule you apply by hand:
1389
+ >
1390
+ > ```ts
1391
+ > import { authDocumentSecurity } from '@bymax-one/nest-auth'
1392
+ >
1393
+ > BymaxCoreModule.forRoot({
1394
+ > openapi: {
1395
+ > // `tokenDelivery` here is the SAME value you pass to BymaxAuthModule.forRoot — read it from
1396
+ > // one place. A default derived from a second copy drifts exactly like a literal does.
1397
+ > security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
1398
+ > }
1399
+ > })
1400
+ > ```
1401
+ >
1402
+ > It answers the delivery axis of both questions below — the scheme name for your guard family,
1403
+ > and the two-entry alternation under `'both'` that a hand-written default usually collapses into
1404
+ > a single AND entry. **It does not know what you mounted**, which is the third row of the table
1405
+ > in question 2 and the one case you still have to answer yourself. Read on for that, and for why
1406
+ > the recipe takes two questions rather than one:
1407
+ >
1408
+ > **1. Which guard protects your own routes?** That decides the credential family, and
1409
+ > `tokenDelivery` does not enter into it for one of them.
1410
+ >
1411
+ > - `JwtAuthGuard` (the dashboard family) → an access scheme, chosen by delivery. Go to question 2.
1412
+ > - `JwtPlatformGuard` → **`bymaxPlatformAccessBearer`, in every mode**. `extractPlatformAccessToken`
1413
+ > reads the `Authorization` header whatever `tokenDelivery` says, and `schemesFor` declares that
1414
+ > scheme with no delivery condition on it. A platform-guarded route wants it under `cookie`
1415
+ > delivery exactly as much as under `bearer`.
1416
+ > - **Both, on different routes** → the default cannot express this, though not because it is
1417
+ > limited to one entry. A document `security` array may hold both requirements — but the entries
1418
+ > are **alternatives**, and the whole array applies to every operation that inherits it. Listing
1419
+ > both therefore documents each credential as valid for _either_ family, which says your platform
1420
+ > routes accept a member token. That is not a missing detail; it is a false statement about who
1421
+ > can call what. Give the minority family per-operation `security` (via your own decorator or
1422
+ > nest-core's `operationSecurity`) and let the default cover the majority.
1423
+ >
1424
+ > **2. For the dashboard family — which schemes does this deployment actually declare?** Delivery
1425
+ > decides, and so does what you mounted. Take a default written as `[{ bymaxAuthAccessCookie: [] }]`:
1426
+ >
1427
+ > | deployment | this contributor declares | that literal default |
1428
+ > | -------------------------------------- | --------------------------------- | ----------------------------------------------------------- |
1429
+ > | dashboard mounted, `cookie` | the cookie scheme only | correct |
1430
+ > | dashboard mounted, `both` | the cookie **and** bearer schemes | resolves, but describes only one of the two channels |
1431
+ > | dashboard mounted, `bearer` | no cookie scheme at all | names an undeclared scheme — `assertSchemesDeclared` throws |
1432
+ > | **no dashboard surface, any delivery** | **neither dashboard scheme** | names an undeclared scheme — throws, `cookie` included |
1433
+ >
1434
+ > That last row is the one a delivery-only recipe gets wrong, and **"no dashboard surface" is
1435
+ > wider than it first sounds.** `schemesFor` gates both dashboard schemes on one of `auth`,
1436
+ > `passwordReset`, `mfa`, `sessions`, `invitations` or `emailChange` being registered. `oauth` is
1437
+ > **not** in that list — its operations are public and reference no credential — so an OAuth-only
1438
+ > deployment contributes operations and zero schemes, exactly like a platform-only one. Any
1439
+ > deployment with no dashboard controller is in this row, and `cookie` delivery, which the recipe
1440
+ > would call the safe case, throws just as hard as `bearer`.
1441
+ >
1442
+ > **And that row needs a remedy, not just a warning, because these deployments are legitimate.**
1443
+ > `JwtAuthGuard` is registered and exported unconditionally — it is not gated on any controller
1444
+ > flag — so mounting no dashboard controller does **not** stop you from guarding your own routes
1445
+ > with a dashboard access token. Both shapes are real: the platform surface plus your own routes
1446
+ > on the member credential; or the OAuth surface alone, where sign-in happens through a provider
1447
+ > and your app issues member tokens itself. In each case the guard is available and the scheme
1448
+ > describing it is not. Deriving correctly there lands you on "the scheme I need does not exist",
1449
+ > which is an accurate answer and not a usable
1450
+ > one.
1451
+ >
1452
+ > **Declare it yourself, in your own `openapi.securitySchemes`.** This is the one case where
1453
+ > "delete your hand-written `securitySchemes`" has an exception, and the exception exists because
1454
+ > the contributor deliberately declares only what its own operations reference — defining a
1455
+ > dashboard scheme on a deployment with no dashboard operation would put an unreferenced
1456
+ > credential in every such document, which is the opposite error and the reason for the gate.
1457
+ >
1458
+ > **Which scheme you declare is still a function of delivery** — the exception is to the deletion
1459
+ > rule, not to the derivation rule, and writing one fixed definition here reintroduces the very
1460
+ > literal this section is about:
1461
+ >
1462
+ > - `cookie` → the `apiKey`-in-cookie definition, carrying the `cookies.accessTokenName` you
1463
+ > configured. The cookie name is yours to choose, so this is the one that must match what the
1464
+ > server actually reads.
1465
+ > - `bearer` → the HTTP bearer definition. There is no cookie name to carry.
1466
+ > - `both` → **both of them**, or your document is incomplete in exactly the quiet way described
1467
+ > above.
1468
+ >
1469
+ > One note on doing any of it: **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, so
1470
+ > import the names rather than writing `bymaxAuthAccessCookie` and `bymaxAuthAccessBearer` as
1471
+ > string literals. The compiler then checks the PROPERTY you reach for, so a typo is a build
1472
+ > error rather than a document declaring a scheme nothing defines — and if a scheme's identifier
1473
+ > is ever renamed, your document carries the new one instead of a literal that has quietly gone
1474
+ > stale. Renaming the value is not itself a build error, since `AUTH_SECURITY_SCHEMES.accessCookie`
1475
+ > stays valid and only its string changes; that is precisely why importing beats copying.
1476
+ >
1477
+ > **The wrong outcomes are not one failure, and the difference is the point.** Where the scheme
1478
+ > does not exist, nest-core's `assertSchemesDeclared` **throws** and the document never builds —
1479
+ > loud, immediate, impossible to ship. Under `both` the scheme does exist, so nothing throws; the
1480
+ > default is merely **incomplete**, telling a reader that your own routes take a cookie when they
1481
+ > equally accept a bearer token. That one is quiet, and it is the same class of quiet as the bug
1482
+ > this whole note is about. A literal written against a bearer-only deployment inverts the table
1483
+ > and fails under `cookie` for the same reasons.
1484
+ >
1485
+ > So the advice that fixes a silently wrong document can introduce a loud broken one **or a second
1486
+ > quiet one**, depending on where you land. Derive from the same inputs the contributor reads —
1487
+ > the guard your routes use, your delivery mode, and the controllers you registered — and the
1488
+ > answer is right everywhere at once, instead of correct in one configuration and checked forever.
1489
+ >
1490
+ > The default is what covers your routes, and it cannot disturb this library's: a per-operation
1491
+ > requirement outranks a document-level one, and every operation the contributor describes carries
1492
+ > its own.
1493
+ >
1494
+ > **What an empty `{}` alternative says, and where this library uses it as an approximation.**
1495
+ > In OpenAPI it means one thing: authentication is **optional** for that operation — a caller
1496
+ > presenting none of the named schemes is valid. Tooling reads it as anonymous access and infers
1497
+ > nothing about a request body from it.
1498
+ >
1499
+ > On `logout` that is exactly right, in **every** delivery mode including `cookie`: the operation
1500
+ > really does answer a caller who presents nothing, which is why a user whose access token
1501
+ > expired can still sign out. How many alternatives you see depends on the mode, since each one
1502
+ > is a combination of the credentials that mode actually has:
1503
+ >
1504
+ > | operation | `cookie` | `bearer` | `both` |
1505
+ > | ----------------- | -------- | -------- | ------ |
1506
+ > | `logout` | 4 | 2 | 6 |
1507
+ > | `password/change` | 2 | 1 | 4 |
1508
+ >
1509
+ > On `refresh` under `tokenDelivery: 'both'` it is an **approximation, and a permissive one**.
1510
+ > That operation refuses a caller with no credential at all; the token may simply arrive in the
1511
+ > request body, which `security` has no vocabulary for. The empty entry is what lets the document
1512
+ > describe the body-only caller, and the cost is that it also tells tooling anonymous access is
1513
+ > acceptable when it is not.
1514
+ >
1515
+ > The `requestBody` beside it **documents the body channel; it does not carry the requirement**.
1516
+ > Under `'both'` it is `required: false` and its schema does not list `refreshToken` as required,
1517
+ > because either channel satisfies the server and a body that omits the token is valid when the
1518
+ > cookie carries it. So the document as a whole permits a request with neither, and the server
1519
+ > refuses that request. **OpenAPI cannot express "one of these two channels" across a security
1520
+ > requirement and a request body**, and this is the shape of that limitation rather than an
1521
+ > oversight. Under `'bearer'`, where the cookie does not exist, the body becomes required at both
1522
+ > levels and the document is exact.
1523
+ >
1524
+ > Written out because two earlier versions of this note were wrong in opposite directions: one
1525
+ > called `{}` "a credential this member cannot model", which is the intent rather than the
1526
+ > notation; the other claimed the `requestBody` carried the requirement, which it does not.
1527
+ >
1528
+ > **Verify with a diff, not by reasoning.** Render the document with the contributor active and
1529
+ > again with your entries in place, and compare only the operations you mount. The consumer who
1530
+ > did this found their own three differences were improvements — a configured cookie name over
1531
+ > the exported default, `logout` gaining the access-only and refresh-only alternatives their map
1532
+ > called unsatisfiable — and one regression that no status-code probe could have surfaced,
1533
+ > because the routes it broke still answered correctly at runtime.
1534
+ >
1535
+ > **And there is one shape no warning will catch for you, however new your nest-core.** If you
1536
+ > remove _every_ requirement at once — no library describing anything, no decorator, no override,
1537
+ > no document default — what remains is indistinguishable from the document of an API that is
1538
+ > 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
1539
+ > without also shouting at every genuinely public API, which is how a warning earns the right to
1540
+ > be ignored. This is why nest-core's warning requires that _some_ operation still state a
1541
+ > requirement: the gap is deliberate, not an omission, and no version closes it.
1542
+ >
1543
+ > **But it is a limit on document-only checks, not on you** — and the distinction matters, because
1544
+ > the better answer is the one a general-purpose tool cannot supply. **You** know your API is not
1545
+ > public, which is exactly the intent no renderer can recover, so write it down as an assertion in
1546
+ > your own suite: that the built document carries a top-level `security`, or that every route
1547
+ > behind your auth guard renders with some requirement. That is a standing check, it runs on every
1548
+ > commit, and it does not depend on anyone remembering to compare. Prefer it to the diff.
1549
+ >
1550
+ > Render the document twice and compare when you are **changing** this — adopting the contributor,
1551
+ > moving delivery mode, adding a surface — because a diff shows you what moved without your having
1552
+ > to predict it in advance. Then turn what you learned into the assertion, so the next change is
1553
+ > caught rather than inspected.
1554
+
1555
+ **That chain is about `security` alone, and the other members run the opposite rule** — worth
1556
+ stating because generalising either one produces a wrong belief about the other. There is no
1557
+ configuration channel for a `description`, a `summary` or a tag: `mergeFragment` merges the
1558
+ scanned operation **over** the fragment, so a contributed member lands unless the handler itself
1559
+ declared that member, and the handler is this library's. Concretely, the `description` on
1560
+ `logout` cannot be shadowed by anything in your options — only by an `@ApiOperation` on a handler
1561
+ you do not own. Nothing to delete for that half; the deletion above is entirely about `security`.
1562
+
1563
+ > **Your own document test will not catch this.** A consumer seat measured it on their own
1564
+ > repository: ten `operationSecurity` entries, all for this library's routes, and a suite
1565
+ > asserting the operation-to-posture map with `toEqual`. On adoption, every contributed fragment
1566
+ > loses to those entries, the old scheme names survive — and the suite stays **green**, because
1567
+ > it is asserting the old answer that is still being served. A test that pins your document
1568
+ > confirms the staleness rather than finding it. The deletion is the step; nothing downstream
1569
+ > will remind you.
1570
+
1571
+ Do it as one change: delete the literals, update whatever pins your document to the four-name
1572
+ vocabulary, rebuild it, and regenerate any typed client — the operation ids do not move, but the
1573
+ scheme names and the per-operation requirements do.
1574
+
1064
1575
  #### Machine-readable schemas
1065
1576
 
1066
1577
  The same contracts are published as data in
@@ -1071,9 +1582,35 @@ OpenAPI 3.0 schemas for all 22 DTOs, generated from the decorators themselves an
1071
1582
  facts no keyword expresses: the twelve e-mail fields that are **trimmed and lowercased before
1072
1583
  validation**, each entry shipping the probe that verifies its own sentence.
1073
1584
 
1074
- Both are development artifacts — they are not in the published tarball, and nothing reads them at
1075
- runtime yet. They exist so the schemas are a function of the decorators rather than a second
1076
- description maintained by hand, and so the same file can be asserted from `rust-auth`.
1585
+ A third file,
1586
+ [`openapi-declared-structures.json`](./conformance/openapi-declared-structures.json), carries the
1587
+ contracts the generated header names and no decorator can express — as **structure**, not prose:
1588
+
1589
+ | Declared | As |
1590
+ | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
1591
+ | `reset-password` takes exactly one of `token`, `otp`, `verifiedToken` | `oneOf` |
1592
+ | 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` |
1593
+ | The 8-character floor is structural, not your policy | probes showing the pipe accepting what the deployment refuses |
1594
+ | `forgot-password`, `resend-otp`, `resend-verification`, `verify-email` answer identically for an unknown address | probes asserting the two responses are **equal** |
1595
+
1596
+ Three rules keep it honest. Only `required`, `oneOf` and `anyOf` may appear — `allOf` and `not`
1597
+ are valid OpenAPI 3.0 and are **refused at load**, because a keyword nothing evaluates publishes
1598
+ a claim nothing checks. Every entry carries probes, and both suites run them: the unit suite
1599
+ evaluates each body against its own structure and reads what the pipe answers, the e2e suite
1600
+ answers the rest with a real application. An entry whose two layers disagree — the pipe accepting
1601
+ what the handler or the service then refuses — is split across the two suites on purpose, because
1602
+ neither can see the pair. And presence means _present and not `null`_ — this
1603
+ server's rule rather than JSON Schema's, because `@IsOptional()` treats `null` as absent, so a
1604
+ body sending `null` and one omitting the key are the same request.
1605
+
1606
+ A structure is a **necessary** condition, never a sufficient one, and `reset-password` shows why:
1607
+ which of the three proofs is eligible depends on `passwordReset.method`, and an ineligible proof
1608
+ is refused with the same code a structural violation gets. That narrowing is declared with its
1609
+ own probes and is deliberately not something a client can generate against.
1610
+
1611
+ All three are development artifacts — they are not in the published tarball, and nothing reads
1612
+ them at runtime yet. They exist so the schemas are a function of the decorators rather than a
1613
+ second description maintained by hand, and so the same file can be asserted from `rust-auth`.
1077
1614
 
1078
1615
  ### Administrative operations — methods, deliberately not routes
1079
1616
 
@@ -1147,6 +1684,75 @@ It passes an `AuthException` through untouched, keeps the status any other `Http
1147
1684
  chose, and answers an unhandled throw with `auth.internal` and a generic message — never the
1148
1685
  thrown one.
1149
1686
 
1687
+ > **Do not register it on a `@bymax-one/nest-core` application.** The two filters are mutually
1688
+ > exclusive and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER` provider, and
1689
+ > `@Catch()` with no argument catches everything, so nest-core's envelope filter never runs.
1690
+ > Measured — the same request answers `{ error: { code, message, details } }` with this filter
1691
+ > registered and the flat `{ statusCode, code, message, timestamp, path, details }` without it.
1692
+ > Registering both therefore **loses** `statusCode`, `timestamp`, `path` and the correlation id,
1693
+ > which is the opposite of what adding a filter looks like it should do.
1694
+ >
1695
+ > On nest-core, take theirs: it already recognises this library's envelope and passes the code,
1696
+ > message and per-field details through unchanged. The symptom of getting it wrong is a body
1697
+ > nested under `error` where the rest of your application answers flat.
1698
+ >
1699
+ > **This library does not test the composition** — it would have to depend on nest-core to do so,
1700
+ > and it depends on nothing. Assert it in your own suite: the code, the per-field details, and the
1701
+ > flat fields (`statusCode`, `timestamp`, `path`) surviving a real request.
1702
+
1703
+ #### On a WebSocket, the envelope needs its own filter
1704
+
1705
+ `WsJwtGuard` throws the same `AuthException` every HTTP guard throws — and `AuthException`
1706
+ extends `HttpException`, which Nest's **WebSocket** exception layer does not recognise. It
1707
+ understands `WsException` and nothing else, so without a filter a refused socket client receives:
1708
+
1709
+ ```json
1710
+ { "status": "error", "message": "Internal server error" }
1711
+ ```
1712
+
1713
+ The refusal itself is correct: the handler never runs. What is lost is everything the client
1714
+ could act on. A reconnect policy cannot tell a dead credential from a crashed handler, and the
1715
+ sensible default for an unknown error is to retry — so an expired token becomes a reconnect loop
1716
+ against an endpoint that will refuse it forever.
1717
+
1718
+ > **Socket.IO only, measured.** `WsJwtGuard` reads both credential channels from the client's
1719
+ > `handshake`, and only a Socket.IO client has one: with `@nestjs/platform-ws` the gateway
1720
+ > receives the raw `ws` socket, which carries no `handshake` — and `ws` does not retain the
1721
+ > upgrade request either, so there is nothing to read. Such a connection is **refused** with
1722
+ > `auth.token_invalid` rather than crashing the socket, and the filter below delivers that
1723
+ > refusal, but the guard cannot authenticate anyone on that adapter. Supporting it needs the
1724
+ > gateway to stash the upgrade request in `handleConnection`, which is a contract this library
1725
+ > does not have today.
1726
+
1727
+ Register the filter on any gateway that applies the guard:
1728
+
1729
+ ```typescript
1730
+ @UseFilters(new WsAuthExceptionFilter())
1731
+ @UseGuards(WsJwtGuard)
1732
+ @WebSocketGateway()
1733
+ export class FeedGateway {}
1734
+ ```
1735
+
1736
+ ```json
1737
+ { "status": "error", "error": { "code": "auth.token_invalid", "message": "...", "details": null } }
1738
+ ```
1739
+
1740
+ `status: 'error'` is kept — it is the field Nest itself sets and the one socket.io clients
1741
+ already branch on — and the envelope is added beside it, so a client handling both shapes needs
1742
+ no second listener. The `AuthException` travels whole, so a `details` payload survives.
1743
+
1744
+ The filter is scoped to `AuthException` on purpose. An argument-less `@Catch()` would claim
1745
+ every exception the gateway raises, so a `WsException` an unrelated handler throws — a domain
1746
+ error with its own contract — would be rewritten as an `auth.*` code, and following this README
1747
+ would silently break errors a consumer already ships. Everything that is not this library's
1748
+ refusal keeps travelling through Nest's own exception layer, untouched.
1749
+
1750
+ Both transports are answered. A Socket.IO client is dispatched to with `emit`; a native `ws`
1751
+ client is written to with `send`, in the `{event, data}` envelope `@nestjs/platform-ws` uses for
1752
+ every other message — emitting on one of those succeeds, dispatches a local event and sends the
1753
+ peer nothing, which is the failure this ordering exists to prevent. Both paths are driven over a
1754
+ real handshake in `test/e2e/ws-guard.e2e-spec.ts`.
1755
+
1150
1756
  #### The HTTP status belongs to the code
1151
1757
 
1152
1758
  Every code answers exactly one status, and the status is derived from the code rather than
@@ -1166,8 +1772,34 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1166
1772
  | `429` | `auth.account_locked` · `auth.too_many_requests` |
1167
1773
  | `500` | `auth.internal` |
1168
1774
 
1169
- `AUTH_ERROR_STATUS` is exported if you need the mapping at runtime — for a typed client, an
1170
- API document, or a test that asserts against it.
1775
+ `AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
1776
+ need the mapping at runtime — for a typed client, an API document, or a test that asserts against
1777
+ it:
1778
+
1779
+ ```ts
1780
+ import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared'
1781
+ ```
1782
+
1783
+ Shown as an import rather than described, on purpose: this package's README contract test reads
1784
+ import statements, so a symbol that stops being exported from the subpath named here fails the
1785
+ suite. It scans prose too — for scheme names it invented and for claims that something is not
1786
+ public — but it cannot check a sentence that merely _says_ where a symbol ships from. That claim
1787
+ went one release stated and unenforced.
1788
+
1789
+ > **Assert your fixtures against the catalogue, not against string literals.** `AUTH_ERROR_CODES`
1790
+ > is exported from `@bymax-one/nest-auth/shared` so a suite can check that every code it branches
1791
+ > on is one the server can actually produce. A frontend seat found three invented codes this way —
1792
+ > `auth.unauthorized` among them, which does not exist — and a branch on a code the server never
1793
+ > sends is silent forever: it simply never runs, and the handler it replaces is the one that
1794
+ > matters. The check is one test over your own source, and it is worth having standing rather than
1795
+ > as a one-off audit.
1796
+ >
1797
+ > **Five codes are internal-only and never reach a client**: `auth.token_expired`,
1798
+ > `auth.token_revoked`, `auth.token_missing` (all collapsed onto `auth.token_invalid`) and
1799
+ > `auth.otp_expired`, `auth.otp_max_attempts` (onto `auth.otp_invalid`). Each says so in its own
1800
+ > JSDoc. They are in the catalogue because both implementations share it and both use them
1801
+ > internally for logs and control flow — branching on them client-side is the same dead branch as
1802
+ > an invented code, for a subtler reason.
1171
1803
 
1172
1804
  > **Anti-enumeration reads through the status too.** `POST /forgot-password` answers `200` and
1173
1805
  > `POST /verify-email` / the resend endpoints answer `204` **whether or not the address exists**.