@bymax-one/nest-auth 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -530,6 +530,15 @@ export function Providers({ children }: { children: React.ReactNode }) {
530
530
  }
531
531
  ```
532
532
 
533
+ > **Which 401 spends a refresh.** The client's `authFetch` retries through `/refresh` only when
534
+ > the 401 says the access token is the problem — `auth.token_invalid`, or a body carrying no
535
+ > readable code. A route can sit behind the JWT guard _and_ verify a second credential, so
536
+ > `auth.invalid_credentials` from a password change and an expired token arrive at the same URL
537
+ > with the same status; the code separates them, the path never could. Any other 401 is returned
538
+ > to the caller untouched, and `createAuthClient({ onSessionExpired })` fires only when a refresh
539
+ > was warranted and failed. `AuthProvider`'s own `onSessionExpired` prop is a different hook: it
540
+ > reacts to a 401 from the session read itself.
541
+
533
542
  ```tsx
534
543
  // app/(dashboard)/profile.tsx
535
544
  'use client'
@@ -553,6 +562,30 @@ export function Profile() {
553
562
  }
554
563
  ```
555
564
 
565
+ #### Plain SPAs — set `refreshEndpoint`
566
+
567
+ The example above is a Next.js app, where the default works. **A Vite/CRA SPA talking straight to
568
+ a Nest backend must set `refreshEndpoint`**, because it defaults to `/api/auth/client-refresh` —
569
+ a Next.js proxy route this library ships for that framework, and a path a plain SPA serves
570
+ nothing at.
571
+
572
+ ```ts
573
+ const authClient = createAuthClient({
574
+ baseUrl: 'https://api.example.com',
575
+ // Without this, refresh POSTs to the Next proxy route and 404s.
576
+ refreshEndpoint: 'https://api.example.com/auth/refresh'
577
+ })
578
+ ```
579
+
580
+ **The symptom, because it does not look like a configuration problem:** _if every access-token
581
+ expiry logs the user out, check `refreshEndpoint` before looking at cookies._ The 404 is silent —
582
+ refresh fails, the session ends, and it presents as a session bug rather than as a missing route.
583
+
584
+ Also note `tenantId` is **optional** on every client input. Whether the server wants it is the
585
+ deployment's answer, not the type's: it is required when no `tenantIdResolver` is configured and
586
+ **refused** when one is, answering `auth.validation` with a `tenantId` field detail either way.
587
+ Send it, or do not, according to the deployment you talk to.
588
+
556
589
  ### 7. Frontend Integration (Next.js 16)
557
590
 
558
591
  Mount the Edge-Runtime auth proxy at the project root and expose the
@@ -669,6 +702,15 @@ satisfied MFA, so a ticket never carries more authority than the request that as
669
702
  Non-browser clients that can set headers keep using `Authorization: Bearer` at the handshake;
670
703
  both channels are accepted, and a ticket wins when both are present.
671
704
 
705
+ Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
706
+ `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
707
+ does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
708
+ `auth.token_invalid` instead of crashing on it, but it cannot authenticate anyone on that
709
+ adapter. And because `AuthException` extends `HttpException`, which Nest's WebSocket layer does
710
+ not recognise, a gateway that applies the guard also needs `WsAuthExceptionFilter` for the
711
+ refusal to reach the client as anything but `Internal server error` — see
712
+ [On a WebSocket, the envelope needs its own filter](#on-a-websocket-the-envelope-needs-its-own-filter).
713
+
672
714
  ---
673
715
 
674
716
  ## ⚙️ Configuration
@@ -796,6 +838,46 @@ All options are configurable via `registerAsync()`. Here are the key configurati
796
838
  > rather than letting it fail open, and rejects an unreadable time span or a non-positive
797
839
  > lifetime on the same pass.
798
840
 
841
+ > [!WARNING]
842
+ > **Do not gate on the access token's `status` claim.** It is **point-in-time, never
843
+ > authoritative**, and which of its three states you get depends on things a client cannot see:
844
+ >
845
+ > | how the token was minted | `status` |
846
+ > | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
847
+ > | login, register, OAuth, MFA challenge | the account's value **at that moment** |
848
+ > | an ordinary refresh rotation | **empty string** — the session record carries no live status, so there is nothing to copy |
849
+ > | a refresh that re-signs because `role`, `tenantId` or `mfaEnabled` changed | the account's value **at that moment**, read during that request |
850
+ >
851
+ > `rust-auth` stamps the same empty string on its rotation path, deliberately and with a test
852
+ > pinning it, so the middle row is a shared contract rather than a defect in either library.
853
+ >
854
+ > Every populated value is stale the instant the account changes, because status can change under
855
+ > an unexpired token and nothing re-stamps it. So a route that reads the claim is wrong in **both**
856
+ > directions: `status !== 'active'` refuses everyone whose session has been refreshed ordinarily,
857
+ > and `status === 'suspended'` refuses nobody, ever. Both fail quietly and hours from the code
858
+ > that caused them — the first looks like a broken login, the second like nothing at all.
859
+ >
860
+ > The exceptional re-stamp is the worst of the three for a reader, not the best: it makes the
861
+ > claim _usually_ wrong instead of _reliably_ empty, which is the failure mode that survives
862
+ > testing.
863
+ >
864
+ > Status is resolved per request or not at all: mount `UserStatusGuard` on the route, and for
865
+ > anything richer read the account **tenant-scoped**, the way that guard does —
866
+ > `findById(request.user.sub, request.user.tenantId)`. The tenant argument is not optional in
867
+ > practice: ids may collide across tenants, and `findById` accepts an absent tenant only for
868
+ > flows that are deliberately cross-tenant, so dropping it here can resolve another tenant's
869
+ > account. That is what the library's own guards do, which
870
+ > is why the claim can be left as it is. `mfaVerified` behaves the same way and for the same
871
+ > reason — it is always `false` after a rotation, so step-up does not survive a refresh and a
872
+ > user re-acquires it through the MFA challenge.
873
+ >
874
+ > One consequence worth planning for: the guard reads a status cache with a
875
+ > `userStatusCacheTtlSeconds` window (default **60**), so a suspension takes up to that long to
876
+ > bite on a guarded route, and a reactivation the same to restore. Nothing exported invalidates
877
+ > that key for one user today — the only immediate lever is `bumpUserTokenEpoch`, which ends
878
+ > every session the user has rather than refreshing one cached string. Lower the TTL if a faster
879
+ > answer matters more than the repository reads it costs.
880
+
799
881
  `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
800
882
  **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
801
883
  SHALL and puts it at no more than 30 days for AAL1. Without a cap, a client refreshing every
@@ -913,6 +995,19 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
913
995
  `cookies.sameSite: 'strict'`. CSRF does not rest on this setting — `TrustedOriginGuard` is
914
996
  applied to every controller and runs before authentication.
915
997
 
998
+ **The tokens are never readable from JavaScript, and verifying that end-to-end is yours.** Under
999
+ cookie delivery this library never writes a token to `localStorage`, `sessionStorage`, or a
1000
+ JS-readable cookie: `access_token` and `refresh_token` are `HttpOnly`, and the only readable
1001
+ cookie is `has_session=1`, a hint carrying no credential so a SPA can tell a session probably
1002
+ exists without touching a token.
1003
+
1004
+ This library's suite asserts **its half** — that the `Set-Cookie` headers carry those flags — and
1005
+ it structurally cannot assert the other half. A token leaking into JS-readable storage is
1006
+ invisible from the server: the API answers identically, the wire looks correct, and every test
1007
+ here passes. Only a browser observes it. **If you run a browser suite, assert there that
1008
+ `localStorage` and `sessionStorage` are empty and that `document.cookie` carries neither token**;
1009
+ it is the one guarantee cookie delivery exists for and the one no server-side test can reach.
1010
+
916
1011
  ---
917
1012
 
918
1013
  ## 🛡️ Security Table
@@ -958,9 +1053,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
958
1053
  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
1054
 
960
1055
  - ✅ **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
1056
+ - ✅ **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))
1057
+ - ✅ **3,971 tests** — 3,721 unit and 250 end-to-end, spanning all five subpaths
1058
+ - ✅ **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
1059
 
965
1060
  ```bash
966
1061
  pnpm test # unit suite
@@ -979,40 +1074,55 @@ pnpm mutation # Stryker mutation testing
979
1074
 
980
1075
  Conditionally registered controllers (mfa, sessions, platform, invitations, oauth, password-reset) only mount their endpoints when the corresponding feature is enabled in `BymaxAuthModule.registerAsync()`.
981
1076
 
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 |
1077
+ | Method | Path | Auth / Guard | Description |
1078
+ | ------ | ------------------------------ | ---------------------------------- | ----------------------------------------------------------- |
1079
+ | POST | `/register` | Public | Register a new dashboard user and issue tokens |
1080
+ | POST | `/login` | Public | Authenticate with email/password (may return MFA challenge) |
1081
+ | POST | `/logout` | Public (reads both credentials) | Revoke the session; blacklists the access token it is given |
1082
+ | POST | `/refresh` | Public (refresh cookie or body) | Rotate refresh token, issue new access token |
1083
+ | GET | `/me` | `JwtAuthGuard` | Current dashboard user payload |
1084
+ | POST | `/ws-ticket` | `JwtAuthGuard` | Mint a single-use ticket for a WebSocket upgrade |
1085
+ | POST | `/verify-email` | Public | Verify email with OTP |
1086
+ | POST | `/resend-verification` | Public | Resend email-verification OTP |
1087
+ | POST | `/password/forgot-password` | Public | Request password reset (token or OTP) |
1088
+ | POST | `/password/reset-password` | Public | Submit new password with reset token |
1089
+ | POST | `/password/verify-otp` | Public | Verify password-reset OTP |
1090
+ | POST | `/password/resend-otp` | Public | Resend password-reset OTP |
1091
+ | POST | `/mfa/setup` | `JwtAuthGuard` | Generate TOTP secret and recovery codes |
1092
+ | POST | `/mfa/verify-enable` | `JwtAuthGuard` | Confirm setup and enable MFA |
1093
+ | POST | `/mfa/challenge` | Public + `@SkipMfa()` | Submit TOTP/recovery code after login |
1094
+ | POST | `/mfa/disable` | `JwtAuthGuard` | Disable MFA for the current user |
1095
+ | POST | `/mfa/recovery-codes` | `JwtAuthGuard` | Replace the recovery codes, proving a fresh OTP |
1096
+ | GET | `/sessions` | `JwtAuthGuard`, `UserStatusGuard` | List active sessions for the current user |
1097
+ | POST | `/sessions/revoke-all` | `JwtAuthGuard`, `UserStatusGuard` | Revoke every session except the caller's |
1098
+ | DELETE | `/sessions/:id` | `JwtAuthGuard`, `UserStatusGuard` | Revoke a specific session |
1099
+ | POST | `/invitations` | `JwtAuthGuard`, `UserStatusGuard` | Create a tenant invitation |
1100
+ | POST | `/invitations/accept` | Public | Accept an invitation and create the user |
1101
+ | POST | `/invitations/revoke` | `JwtAuthGuard`, `UserStatusGuard` | Withdraw a pending invitation |
1102
+ | POST | `/email/change` | `JwtAuthGuard`, `UserStatusGuard` | Request an address change (re-proves the current password) |
1103
+ | POST | `/email/change/confirm` | Public | Confirm it with the token mailed to the new address |
1104
+ | POST | `/platform/login` | Public | Platform admin login (separate token context) |
1105
+ | POST | `/platform/mfa/challenge` | Public | Platform admin MFA challenge |
1106
+ | GET | `/platform/me` | `JwtPlatformGuard` | Current platform admin payload |
1107
+ | POST | `/platform/logout` | Public (refresh token in body) | Revoke the session; blacklists the access token it is given |
1108
+ | POST | `/platform/refresh` | Public (refresh token in body) | Rotate the platform refresh token |
1109
+ | DELETE | `/platform/sessions` | `JwtPlatformGuard` | Revoke all platform sessions |
1110
+ | POST | `/platform/mfa/setup` | `JwtPlatformGuard` | Generate the admin's TOTP secret and recovery codes |
1111
+ | POST | `/platform/mfa/verify-enable` | `JwtPlatformGuard` | Confirm setup and enable MFA for the admin |
1112
+ | POST | `/platform/mfa/disable` | `JwtPlatformGuard` | Disable the admin's MFA, proving a fresh OTP |
1113
+ | POST | `/platform/mfa/recovery-codes` | `JwtPlatformGuard` | Replace the admin's recovery codes |
1114
+ | POST | `/password/change` | `JwtAuthGuard` + `UserStatusGuard` | Change the password, proving the current one |
1115
+ | GET | `/oauth/:provider` | Public + `@SkipMfa()` | Initiate OAuth authorization redirect |
1116
+ | GET | `/oauth/:provider/callback` | Public + `@SkipMfa()` | Handle OAuth callback, exchange code, issue tokens |
1117
+
1118
+ > **The platform plane never uses a refresh cookie.** `extractPlatformRefreshToken` reads
1119
+ > `req.body.refreshToken` in every `tokenDelivery` mode, and the access token is always the
1120
+ > `Authorization` header — so a consumer sending platform credentials as cookies is sending
1121
+ > something the server does not read. `platform/logout` and `platform/refresh` are `@Public()`
1122
+ > for the same reason their dashboard twins are: an operator whose fifteen-minute access token
1123
+ > expired must still be able to end the session, or the seven-day refresh session of the
1124
+ > highest-privilege identity in the system outlives the console they walked away from. Both
1125
+ > still READ the access token when one is sent, and `logout` blacklists its `jti`.
1016
1126
 
1017
1127
  > **The OAuth routes require `cookie-parser`.** `GET /oauth/:provider` plants an HttpOnly
1018
1128
  > `oauth_state` cookie carrying the flow's `state`, and the callback refuses any request that
@@ -1027,9 +1137,17 @@ unknown property is a `400 auth.validation` rather than a silently ignored field
1027
1137
  optional on every **unauthenticated** body below (≤128 chars, no control characters) and scopes
1028
1138
  the operation to one organization. `POST /password/change` is the exception: it is behind
1029
1139
  `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.
1140
+ unknown property, and `forbidNonWhitelisted` answers `400 auth.validation`. That same rule is why
1141
+ it **declares** `refreshToken`: an undeclared field would be refused rather than read. Email
1142
+ fields are trimmed and lowercased before they reach the service, so the stored identity matches
1143
+ the case-insensitive lookup and every email-keyed control.
1144
+
1145
+ `refreshToken` is **optional, and both answers are valid requests.** Send it and the device making
1146
+ the change stays signed in; omit it and every session ends — which is the right answer when you are
1147
+ rotating a credential you believe was stolen. Where the server looks for it follows
1148
+ `tokenDelivery`: the refresh cookie under `'cookie'`, this body field under `'bearer'`, and the
1149
+ cookie first then this field under `'both'` — so a `'both'` caller with no refresh cookie must send
1150
+ it here to keep its session.
1033
1151
 
1034
1152
  | Endpoint | Body |
1035
1153
  | -------------------------------- | -------------------------------------------------------------------------------- |
@@ -1041,7 +1159,7 @@ case-insensitive lookup and every email-keyed control.
1041
1159
  | `POST /password/verify-otp` | `{ email, otp }` |
1042
1160
  | `POST /password/resend-otp` | `{ email }` |
1043
1161
  | `POST /password/reset-password` | `{ email, newPassword }` **plus exactly one** of `token`, `otp`, `verifiedToken` |
1044
- | `POST /password/change` | `{ currentPassword, newPassword }` |
1162
+ | `POST /password/change` | `{ currentPassword, newPassword }` — optional `refreshToken`, see below |
1045
1163
 
1046
1164
  Three constraints are worth stating because they are not visible from the field names:
1047
1165
 
@@ -1061,6 +1179,89 @@ Three constraints are worth stating because they are not visible from the field
1061
1179
  length here would leak it as a pre-KDF timing signal, because a request failing validation
1062
1180
  returns before the hash runs.
1063
1181
 
1182
+ #### On `@bymax-one/nest-core`, the security posture writes itself
1183
+
1184
+ A deployment that builds its OpenAPI document with `@bymax-one/nest-core` **1.4.0 or later** gets
1185
+ this library's operations described automatically — which schemes exist, which operation requires
1186
+ which, and which are reachable unauthenticated. Nothing to enable and nothing to import: the
1187
+ module registers a contributor, nest-core discovers it while building the document, and the
1188
+ fragments are merged.
1189
+
1190
+ It has to be derived at your boot rather than shipped as a static file, because the answer
1191
+ depends on your configuration:
1192
+
1193
+ | your options | what the document says |
1194
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1195
+ | `tokenDelivery: 'cookie'` | `bymaxAuthAccessCookie` and `bymaxAuthRefreshCookie`, **carrying your cookie names** |
1196
+ | `tokenDelivery: 'bearer'` | `bymaxAuthAccessBearer` only — no refresh scheme exists, and `logout`/`refresh` instead carry a documented `{ refreshToken }` body |
1197
+ | `tokenDelivery: 'both'` | both access schemes as **alternatives** (`security: [{cookie}, {bearer}]`, which OpenAPI reads as OR) |
1198
+ | `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 |
1199
+ | a controller you did not mount | nothing at all: no operation, and no scheme only it would have referenced |
1200
+
1201
+ A scheme the resolved options cannot satisfy is **absent**, never defined-and-unreferenced — a
1202
+ document that defines a credential the server will not read tells a generated client to offer it.
1203
+
1204
+ The four names — `bymaxAuthAccessCookie`, `bymaxAuthAccessBearer`, `bymaxAuthRefreshCookie`,
1205
+ `bymaxPlatformAccessBearer` — are stable identifiers. Renaming one is a break a generated client
1206
+ feels, so they will not change; their **definitions** are config-derived.
1207
+
1208
+ > **This package does not depend on `@bymax-one/nest-core`** — not as a dependency, a peer, or a
1209
+ > devDependency. The contract revision is inlined, the discovery marker is the documented string
1210
+ > literal, and a gate fails the build if any file here imports another Bymax library. That keeps
1211
+ > your install graph free of a package you may not use, and it moves one check to your side:
1212
+ >
1213
+ > ```typescript
1214
+ > // in your suite, where both packages are installed at the versions you run
1215
+ > import {
1216
+ > BYMAX_OPENAPI_CONTRACT_VERSION,
1217
+ > BYMAX_OPENAPI_CONTRIBUTOR_METADATA
1218
+ > } from '@bymax-one/nest-core/openapi'
1219
+ >
1220
+ > expect(fragment.contractVersion).toBe(BYMAX_OPENAPI_CONTRACT_VERSION)
1221
+ > expect(Reflect.getMetadata(BYMAX_OPENAPI_CONTRIBUTOR_METADATA, contributor.constructor)).toBe(
1222
+ > true
1223
+ > )
1224
+ > ```
1225
+ >
1226
+ > Worth writing once. A revision mismatch fails your document build loudly and names the
1227
+ > contributor, but a **marker** mismatch is silent: the provider is simply never discovered and
1228
+ > the document renders without the fragments — the same symptom as running nest-core < 1.4.0.
1229
+
1230
+ > **On nest-core older than 1.4.0 the fragments are silently ignored.** There is no contributor
1231
+ > lane to discover them, so the document renders exactly as before — no error, no warning, no
1232
+ > failed boot. If you add a document and the auth schemes do not appear, check in this order:
1233
+ > whether this library is new enough to contribute them at all, and only then your nest-core
1234
+ > version. The two states look identical from the document.
1235
+
1236
+ **If you already wrote these by hand, delete them** — not because they are wrong. They are what
1237
+ makes your document correct today; the deletion is what hands the job to the library, and it is
1238
+ needed precisely because they were doing it. Precedence, read from nest-core's
1239
+ `augmentOperation` rather than summarised: the generated operation's own `security` outranks
1240
+ everything, then your `openapi.operationSecurity` override, then this library's fragment, then
1241
+ nest-core's policy. So a stale scheme name or an override for an auth route keeps winning and the
1242
+ contributed one never lands — the document goes on describing whatever you wrote when you wrote
1243
+ it, including cookie names you have since changed.
1244
+
1245
+ **That chain is about `security` alone, and the other members run the opposite rule** — worth
1246
+ stating because generalising either one produces a wrong belief about the other. There is no
1247
+ configuration channel for a `description`, a `summary` or a tag: `mergeFragment` merges the
1248
+ scanned operation **over** the fragment, so a contributed member lands unless the handler itself
1249
+ declared that member, and the handler is this library's. Concretely, the `description` on
1250
+ `logout` cannot be shadowed by anything in your options — only by an `@ApiOperation` on a handler
1251
+ you do not own. Nothing to delete for that half; the deletion above is entirely about `security`.
1252
+
1253
+ > **Your own document test will not catch this.** A consumer seat measured it on their own
1254
+ > repository: ten `operationSecurity` entries, all for this library's routes, and a suite
1255
+ > asserting the operation-to-posture map with `toEqual`. On adoption, every contributed fragment
1256
+ > loses to those entries, the old scheme names survive — and the suite stays **green**, because
1257
+ > it is asserting the old answer that is still being served. A test that pins your document
1258
+ > confirms the staleness rather than finding it. The deletion is the step; nothing downstream
1259
+ > will remind you.
1260
+
1261
+ Do it as one change: delete the literals, update whatever pins your document to the four-name
1262
+ vocabulary, rebuild it, and regenerate any typed client — the operation ids do not move, but the
1263
+ scheme names and the per-operation requirements do.
1264
+
1064
1265
  #### Machine-readable schemas
1065
1266
 
1066
1267
  The same contracts are published as data in
@@ -1071,9 +1272,35 @@ OpenAPI 3.0 schemas for all 22 DTOs, generated from the decorators themselves an
1071
1272
  facts no keyword expresses: the twelve e-mail fields that are **trimmed and lowercased before
1072
1273
  validation**, each entry shipping the probe that verifies its own sentence.
1073
1274
 
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`.
1275
+ A third file,
1276
+ [`openapi-declared-structures.json`](./conformance/openapi-declared-structures.json), carries the
1277
+ contracts the generated header names and no decorator can express — as **structure**, not prose:
1278
+
1279
+ | Declared | As |
1280
+ | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
1281
+ | `reset-password` takes exactly one of `token`, `otp`, `verifiedToken` | `oneOf` |
1282
+ | 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` |
1283
+ | The 8-character floor is structural, not your policy | probes showing the pipe accepting what the deployment refuses |
1284
+ | `forgot-password`, `resend-otp`, `resend-verification`, `verify-email` answer identically for an unknown address | probes asserting the two responses are **equal** |
1285
+
1286
+ Three rules keep it honest. Only `required`, `oneOf` and `anyOf` may appear — `allOf` and `not`
1287
+ are valid OpenAPI 3.0 and are **refused at load**, because a keyword nothing evaluates publishes
1288
+ a claim nothing checks. Every entry carries probes, and both suites run them: the unit suite
1289
+ evaluates each body against its own structure and reads what the pipe answers, the e2e suite
1290
+ answers the rest with a real application. An entry whose two layers disagree — the pipe accepting
1291
+ what the handler or the service then refuses — is split across the two suites on purpose, because
1292
+ neither can see the pair. And presence means _present and not `null`_ — this
1293
+ server's rule rather than JSON Schema's, because `@IsOptional()` treats `null` as absent, so a
1294
+ body sending `null` and one omitting the key are the same request.
1295
+
1296
+ A structure is a **necessary** condition, never a sufficient one, and `reset-password` shows why:
1297
+ which of the three proofs is eligible depends on `passwordReset.method`, and an ineligible proof
1298
+ is refused with the same code a structural violation gets. That narrowing is declared with its
1299
+ own probes and is deliberately not something a client can generate against.
1300
+
1301
+ All three are development artifacts — they are not in the published tarball, and nothing reads
1302
+ them at runtime yet. They exist so the schemas are a function of the decorators rather than a
1303
+ second description maintained by hand, and so the same file can be asserted from `rust-auth`.
1077
1304
 
1078
1305
  ### Administrative operations — methods, deliberately not routes
1079
1306
 
@@ -1147,6 +1374,75 @@ It passes an `AuthException` through untouched, keeps the status any other `Http
1147
1374
  chose, and answers an unhandled throw with `auth.internal` and a generic message — never the
1148
1375
  thrown one.
1149
1376
 
1377
+ > **Do not register it on a `@bymax-one/nest-core` application.** The two filters are mutually
1378
+ > exclusive and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER` provider, and
1379
+ > `@Catch()` with no argument catches everything, so nest-core's envelope filter never runs.
1380
+ > Measured — the same request answers `{ error: { code, message, details } }` with this filter
1381
+ > registered and the flat `{ statusCode, code, message, timestamp, path, details }` without it.
1382
+ > Registering both therefore **loses** `statusCode`, `timestamp`, `path` and the correlation id,
1383
+ > which is the opposite of what adding a filter looks like it should do.
1384
+ >
1385
+ > On nest-core, take theirs: it already recognises this library's envelope and passes the code,
1386
+ > message and per-field details through unchanged. The symptom of getting it wrong is a body
1387
+ > nested under `error` where the rest of your application answers flat.
1388
+ >
1389
+ > **This library does not test the composition** — it would have to depend on nest-core to do so,
1390
+ > and it depends on nothing. Assert it in your own suite: the code, the per-field details, and the
1391
+ > flat fields (`statusCode`, `timestamp`, `path`) surviving a real request.
1392
+
1393
+ #### On a WebSocket, the envelope needs its own filter
1394
+
1395
+ `WsJwtGuard` throws the same `AuthException` every HTTP guard throws — and `AuthException`
1396
+ extends `HttpException`, which Nest's **WebSocket** exception layer does not recognise. It
1397
+ understands `WsException` and nothing else, so without a filter a refused socket client receives:
1398
+
1399
+ ```json
1400
+ { "status": "error", "message": "Internal server error" }
1401
+ ```
1402
+
1403
+ The refusal itself is correct: the handler never runs. What is lost is everything the client
1404
+ could act on. A reconnect policy cannot tell a dead credential from a crashed handler, and the
1405
+ sensible default for an unknown error is to retry — so an expired token becomes a reconnect loop
1406
+ against an endpoint that will refuse it forever.
1407
+
1408
+ > **Socket.IO only, measured.** `WsJwtGuard` reads both credential channels from the client's
1409
+ > `handshake`, and only a Socket.IO client has one: with `@nestjs/platform-ws` the gateway
1410
+ > receives the raw `ws` socket, which carries no `handshake` — and `ws` does not retain the
1411
+ > upgrade request either, so there is nothing to read. Such a connection is **refused** with
1412
+ > `auth.token_invalid` rather than crashing the socket, and the filter below delivers that
1413
+ > refusal, but the guard cannot authenticate anyone on that adapter. Supporting it needs the
1414
+ > gateway to stash the upgrade request in `handleConnection`, which is a contract this library
1415
+ > does not have today.
1416
+
1417
+ Register the filter on any gateway that applies the guard:
1418
+
1419
+ ```typescript
1420
+ @UseFilters(new WsAuthExceptionFilter())
1421
+ @UseGuards(WsJwtGuard)
1422
+ @WebSocketGateway()
1423
+ export class FeedGateway {}
1424
+ ```
1425
+
1426
+ ```json
1427
+ { "status": "error", "error": { "code": "auth.token_invalid", "message": "...", "details": null } }
1428
+ ```
1429
+
1430
+ `status: 'error'` is kept — it is the field Nest itself sets and the one socket.io clients
1431
+ already branch on — and the envelope is added beside it, so a client handling both shapes needs
1432
+ no second listener. The `AuthException` travels whole, so a `details` payload survives.
1433
+
1434
+ The filter is scoped to `AuthException` on purpose. An argument-less `@Catch()` would claim
1435
+ every exception the gateway raises, so a `WsException` an unrelated handler throws — a domain
1436
+ error with its own contract — would be rewritten as an `auth.*` code, and following this README
1437
+ would silently break errors a consumer already ships. Everything that is not this library's
1438
+ refusal keeps travelling through Nest's own exception layer, untouched.
1439
+
1440
+ Both transports are answered. A Socket.IO client is dispatched to with `emit`; a native `ws`
1441
+ client is written to with `send`, in the `{event, data}` envelope `@nestjs/platform-ws` uses for
1442
+ every other message — emitting on one of those succeeds, dispatches a local event and sends the
1443
+ peer nothing, which is the failure this ordering exists to prevent. Both paths are driven over a
1444
+ real handshake in `test/e2e/ws-guard.e2e-spec.ts`.
1445
+
1150
1446
  #### The HTTP status belongs to the code
1151
1447
 
1152
1448
  Every code answers exactly one status, and the status is derived from the code rather than
@@ -1169,6 +1465,21 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1169
1465
  `AUTH_ERROR_STATUS` is exported if you need the mapping at runtime — for a typed client, an
1170
1466
  API document, or a test that asserts against it.
1171
1467
 
1468
+ > **Assert your fixtures against the catalogue, not against string literals.** `AUTH_ERROR_CODES`
1469
+ > is exported from `@bymax-one/nest-auth/shared` so a suite can check that every code it branches
1470
+ > on is one the server can actually produce. A frontend seat found three invented codes this way —
1471
+ > `auth.unauthorized` among them, which does not exist — and a branch on a code the server never
1472
+ > sends is silent forever: it simply never runs, and the handler it replaces is the one that
1473
+ > matters. The check is one test over your own source, and it is worth having standing rather than
1474
+ > as a one-off audit.
1475
+ >
1476
+ > **Five codes are internal-only and never reach a client**: `auth.token_expired`,
1477
+ > `auth.token_revoked`, `auth.token_missing` (all collapsed onto `auth.token_invalid`) and
1478
+ > `auth.otp_expired`, `auth.otp_max_attempts` (onto `auth.otp_invalid`). Each says so in its own
1479
+ > JSDoc. They are in the catalogue because both implementations share it and both use them
1480
+ > internally for logs and control flow — branching on them client-side is the same dead branch as
1481
+ > an invented code, for a subtler reason.
1482
+
1172
1483
  > **Anti-enumeration reads through the status too.** `POST /forgot-password` answers `200` and
1173
1484
  > `POST /verify-email` / the resend endpoints answer `204` **whether or not the address exists**.
1174
1485
  > A `200` there does not mean an email was sent, and treating it as confirmation re-introduces
@@ -22,6 +22,23 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
22
22
  return false;
23
23
  }
24
24
  __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
25
+ var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
26
+ async function isExpiredSessionResponse(response) {
27
+ const clone = response.clone();
28
+ let timer;
29
+ const body = await Promise.race([
30
+ clone.json().catch(() => void 0),
31
+ new Promise((resolve) => {
32
+ timer = setTimeout(() => resolve(void 0), ERROR_BODY_READ_TIMEOUT_MS);
33
+ })
34
+ ]);
35
+ clearTimeout(timer);
36
+ if (typeof body !== "object" || body === null) return true;
37
+ const envelope = body;
38
+ const code = envelope.error?.code ?? envelope.code;
39
+ return typeof code !== "string" || code === shared.AUTH_ERROR_CODES.TOKEN_INVALID;
40
+ }
41
+ __name(isExpiredSessionResponse, "isExpiredSessionResponse");
25
42
  function resolveRequestUrl(input, baseUrl) {
26
43
  if (typeof input === "string") {
27
44
  return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
@@ -102,7 +119,7 @@ async function performRefresh(endpoint, credentials) {
102
119
  }
103
120
  });
104
121
  const ok = response.ok;
105
- await response.body?.cancel().catch(
122
+ void response.body?.cancel().catch(
106
123
  /* istanbul ignore next */
107
124
  () => void 0
108
125
  );
@@ -156,6 +173,9 @@ function createAuthFetch(config = {}) {
156
173
  if (response.status !== 401 || shouldSkipRefreshOnUrl(url, skipRefreshSuffixes)) {
157
174
  return response;
158
175
  }
176
+ if (!await isExpiredSessionResponse(response)) {
177
+ return response;
178
+ }
159
179
  const refreshed = await getOrStartRefresh();
160
180
  if (!refreshed) {
161
181
  try {
@@ -234,7 +254,7 @@ async function expectNoContent(response) {
234
254
  const text = await response.text();
235
255
  throwAuthError(response, text);
236
256
  }
237
- await response.body?.cancel().catch(
257
+ void response.body?.cancel().catch(
238
258
  /* istanbul ignore next */
239
259
  () => void 0
240
260
  );
@@ -365,15 +385,17 @@ function createAuthClient(config) {
365
385
  async forgotPassword(email, tenantId) {
366
386
  return postNoContent(shared.AUTH_ROUTES.password.forgotPassword, {
367
387
  email,
368
- tenantId
388
+ ...tenantId !== void 0 ? {
389
+ tenantId
390
+ } : {}
369
391
  });
370
392
  },
371
393
  async resetPassword(input) {
372
394
  const payload = {
373
395
  email: input.email,
374
- tenantId: input.tenantId,
375
396
  newPassword: input.newPassword
376
397
  };
398
+ if (input.tenantId !== void 0) payload["tenantId"] = input.tenantId;
377
399
  if (input.token !== void 0) payload["token"] = input.token;
378
400
  if (input.otp !== void 0) payload["otp"] = input.otp;
379
401
  if (input.verifiedToken !== void 0) payload["verifiedToken"] = input.verifiedToken;