@bymax-one/nest-auth 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,144 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.0] - 2026-08-08
11
+
12
+ Carries the third security audit and the findings that surfaced while driving the mutation
13
+ score, across two pull requests that landed without versions of their own.
14
+
15
+ > **Action required for two deployments.** The Next.js proxy now **requires** `jwtSecret`;
16
+ > the decode-only fallback is gone, so a consumer that never set it fails at boot instead of
17
+ > trusting an unverified token. And the password floor moved from 8 to **15** by default —
18
+ > existing stored passwords keep working, but a set or change below 15 is now refused unless
19
+ > `password.minLength` says otherwise.
20
+
21
+ ### Security
22
+
23
+ - **A live session could hide from revoke-all.** Pruning removed members whose `rt:` key was
24
+ still present, so a session survived the call meant to end every session for an account.
25
+ Prune now removes only a member whose `rt:` key is actually gone.
26
+ - **The Next.js proxy fell back to decoding a token without verifying it.** `jwtSecret` is
27
+ required and the decode-only path is removed. An unverified decode answers with whatever
28
+ the token claims.
29
+ - **A crafted password record could OOM-kill the process.** `compare()` derived scrypt's
30
+ `maxmem` from the stored PHC parameters and widened it to fit, so `ln=31` with the shipped
31
+ `r=8` asked for 2 TiB — which does not fail the request, it takes the process and every
32
+ in-flight connection with it. The ceiling is a constant that input cannot widen. A block
33
+ size above the parameter ceiling that the memory ceiling let through is closed with it.
34
+ - **An OTP check could pass on two absent values.** A non-string stored code fell back to
35
+ `''`, and `timingSafeEqual` answers true for two empty buffers, so an empty submitted code
36
+ compared equal to the placeholder and verification succeeded. The non-string record is
37
+ refused instead.
38
+ - **Two guards were exported but unusable.** `UserStatusGuard` was missing
39
+ `BYMAX_AUTH_USER_REPOSITORY` and `WsJwtGuard` was missing `WsTicketService` from the
40
+ module's exports, so `@UseGuards(JwtAuthGuard, UserStatusGuard)` failed a consumer's boot
41
+ and every route on a derived backend was protected by token validity alone — a suspended
42
+ or deleted account kept access for a full access-token lifetime. The ticket handshake was
43
+ likewise unreachable, so realtime authenticators replayed the access-token cookie and never
44
+ consulted the revocation blacklist. All nine guards' constructor deps were audited; these
45
+ were the only gaps.
46
+ - **OAuth `state` was not bound to its provider** (RFC 9700 mix-up). The provider is carried
47
+ in the state record.
48
+ - **A cookie prefix whose attributes cannot satisfy it** is dropped silently by the browser.
49
+ The contract is validated at boot.
50
+ - **The absolute session lifetime inherited no cap.** Capped at 30 days (NIST SP 800-63B-4
51
+ §3).
52
+ - **The rate limit charged a single IPv6 address**, which costs an attacker nothing to move
53
+ within. Charged to the /64.
54
+ - **"Is this production" was sniffed from `NODE_ENV`** in six places. An explicit
55
+ `environment` option decides it, defaulting to production.
56
+
57
+ ### Added
58
+
59
+ - **`password.minLength`** — configurable, defaulting to **15**. NIST SP 800-63B-4 §3.1.1.1
60
+ allows 8 only for a password used as part of multi-factor authentication and requires 15
61
+ for a single factor; MFA here is opt-in per user, so the default deployment is
62
+ single-factor. The check moved to `PasswordService.assertAcceptable`, one entry point for
63
+ the four sites that set a password, screening length before the breach corpus — a password
64
+ refused for being short should not cost a round trip nor be sent anywhere first.
65
+ - **`MfaService.resetMfa`** — administrative removal of a second factor, for a user who lost
66
+ both the authenticator and the recovery codes. Every self-service exit needs the factor
67
+ itself, so without it that user is locked out permanently by the control meant to protect
68
+ them (ASVS v5 §6.1.1). It ships as a method and **not** a route, the decision
69
+ `unlockAccount` already made: every route this library exposes is scoped to the caller's
70
+ own account, and who may reset whom is a question only the host can answer. It invalidates
71
+ sessions, bumps the token epoch so `mfaVerified: true` tokens die with the factor, and
72
+ notifies the account holder — an administrative reset the owner cannot see is an
73
+ account-takeover path.
74
+ - Log lines where the response is deliberately uninformative, so the log is the only record
75
+ the event happened: ws-ticket refusals, invitation and revoke-rank refusals, email-change
76
+ and change-password lockouts, MFA re-authentication refusals, and corrupted MFA setup
77
+ payloads.
78
+
79
+ ### Changed
80
+
81
+ - **`sendNewSessionAlert` is optional.** It was a required provider method the library never
82
+ called, with a docstring claiming it fired on login. Without device recognition it would
83
+ fire on every login, and an alert on every login is one the user learns to dismiss — the
84
+ control stops existing while appearing to be in place. `onNewSession` already fires on
85
+ every session created; the docs now say what is true.
86
+
87
+ ## [1.1.1] - 2026-08-05
88
+
89
+ This release carries the second cross-implementation security audit as well as the dependency-injection fix below. Both landed as separate pull requests; the audit one carried no version of its own, so its account is here.
90
+
91
+ ### Security
92
+
93
+ - **The AES key over every stored second factor was enumerable.** `1.1.0` hid `jwt.secret`, its
94
+ rotation predecessors and the derived HMAC keys, but not `mfa.encryptionKey` or
95
+ `mfa.previousEncryptionKeys` — the AES-256-GCM key protecting every enrolled user's TOTP secret
96
+ and their recovery-code set. `JSON.stringify`, object spread and `util.inspect` on the resolved
97
+ options all emitted it, which is what a structured logger does when handed a provider.
98
+ - **Refresh-token reuse was logged anonymously.** The strongest compromise signal this library
99
+ produces reached only a consumer who had wired the hook, and the shipped hooks are no-ops.
100
+ - **A `getMe()` in flight could resurrect a session after logout.** `status` returned to
101
+ `authenticated` and the profile returned to context, so `useAuthStatus().isAuthenticated` — which
102
+ this library's own JSDoc calls safe to gate protected routes on — answered `true` after sign-out.
103
+
104
+ ### Fixed
105
+
106
+ - **The two libraries could not read each other's password hashes.** This library wrote
107
+ `scrypt:N:r:p:{saltHex}:{derivedHex}` while `rust-auth` writes PHC. Neither parser accepted the
108
+ other's output, and because verification is total the failure surfaced as `invalid_credentials`
109
+ rather than a parse error — so five correct attempts by the owner tripped the brute-force
110
+ counter the two backends key identically and locked the account out of both.
111
+ - **Every non-Latin password was refused as compromised.** Two ASCII filters in the breach screen:
112
+ `isDecoration` used `\W`, so Cyrillic, Greek, Han, Kana, Arabic, Hebrew and Thai characters all
113
+ counted as decoration and were stripped, and what survived was filtered to `[a-z0-9]`.
114
+ - **`baseUrl: '/api'` sent every request to `/api/api/auth/*`.** The client composed the full URL
115
+ and also handed `baseUrl` to the fetch wrapper it builds — the value the README and
116
+ `AuthProvider`'s own example document for the same-origin/Next-proxy setup.
117
+ - **A new session was written with five loose Redis commands**, where `rust-auth` does the same
118
+ work in one `MULTI/EXEC`. A revoke-all landing between the record write and the index `SADD`
119
+ swept an index the session was not in yet, and a dropped connection between the `SADD` and the
120
+ `EXPIRE` left the index with no expiry at all, permanently.
121
+ - **The session index grew one permanent member per refresh.** A rotation adds `rp:{old}`
122
+ alongside `rt:{new}`, only a full revoke-all ever removed it, and the rotation re-armed the
123
+ set's TTL each time. Every reader is linear in its size, including the script a password reset
124
+ runs, which blocks the whole single-threaded store.
125
+
126
+ ### Fixed
127
+
128
+ - **Dependency injection no longer depends on a transitive dev dependency.** Seventy-one
129
+ constructor parameters across thirty classes were resolved from `design:paramtypes`,
130
+ the metadata TypeScript emits — and this package emitted it only because `@swc/core`
131
+ happened to be in the tree via `ts-node`. tsup enables its SWC transform when that
132
+ package is present and prints a warning when it is not:
133
+
134
+ ```
135
+ You have emitDecoratorMetadata enabled but @swc/core was not installed, skipping swc plugin
136
+ ```
137
+
138
+ Nine sibling packages get that second path and none of their bundles carry the metadata. Had the transitive dependency moved,
139
+ every one of those parameters would have stopped resolving at once — silently wherever
140
+ `@Optional()` is present. They now carry explicit `@Inject`, which writes
141
+ `self:paramtypes` and is independent of any build transform.
142
+
143
+ - `@swc/core` is a declared devDependency. The metadata is still needed — `ValidationPipe`
144
+ finds a DTO class through the reflected parameter type, and thirty-one controller
145
+ parameters here are typed by DTO — so the emission stays. It is now deliberate rather
146
+ than inherited.
147
+
10
148
  ## [1.1.0] - 2026-08-03
11
149
 
12
150
  The API changes marked **Breaking** below are breaking against `1.0.11`. They are
@@ -1014,7 +1152,9 @@ ever installable.
1014
1152
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
1015
1153
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
1016
1154
 
1017
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.1.0...HEAD
1155
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.2.0...HEAD
1156
+ [1.2.0]: https://github.com/bymaxone/nest-auth/compare/v1.1.1...v1.2.0
1157
+ [1.1.1]: https://github.com/bymaxone/nest-auth/compare/v1.1.0...v1.1.1
1018
1158
  [1.1.0]: https://github.com/bymaxone/nest-auth/compare/v1.0.11...v1.1.0
1019
1159
  [1.0.11]: https://github.com/bymaxone/nest-auth/compare/v1.0.10...v1.0.11
1020
1160
  [1.0.10]: https://github.com/bymaxone/nest-auth/compare/v1.0.9...v1.0.10
package/README.md CHANGED
@@ -66,7 +66,7 @@ pnpm add @bymax-one/nest-auth
66
66
 
67
67
  - ✅ **Zero External Crypto** — All cryptography via native `node:crypto` (scrypt, AES-256-GCM, HMAC-SHA1, TOTP)
68
68
  - ✅ **Brute-Force Protection** — Configurable rate limiting per email + tenant
69
- - ✅ **Session Management** — Track active sessions with FIFO eviction and new-session alerts
69
+ - ✅ **Session Management** — Track active sessions with FIFO eviction, and an `onNewSession` hook fired on every session created (alerting on it is yours to decide — see `sendNewSessionAlert`)
70
70
  - ✅ **HttpOnly Cookies** — Secure, SameSite, path-scoped refresh tokens by default
71
71
  - ✅ **Timing-Safe Comparisons** — All secret comparisons use `crypto.timingSafeEqual`
72
72
  - ✅ **JWT Revocation** — Instant access token revocation via Redis JTI blacklist
@@ -534,7 +534,10 @@ backend.
534
534
  // proxy.ts — Next.js 16 Edge middleware
535
535
  import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
536
536
 
537
- export const { proxy } = createAuthProxy({
537
+ // Next 16 scans this file for a function exported as `proxy` (or as the default), and it
538
+ // does not recognise a destructuring pattern: `export const { proxy } = ...` fails the build
539
+ // with "The file ./proxy.ts must export a function". Bind first, then export.
540
+ const authProxy = createAuthProxy({
538
541
  publicRoutes: ['/', '/auth/login', '/auth/register'],
539
542
  publicRoutesRedirectIfAuthenticated: ['/auth/login', '/auth/register'],
540
543
  protectedRoutes: [
@@ -559,6 +562,8 @@ export const { proxy } = createAuthProxy({
559
562
  blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
560
563
  })
561
564
 
565
+ export const proxy = authProxy.proxy
566
+
562
567
  export const config = {
563
568
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
564
569
  }
@@ -642,7 +647,8 @@ All options are configurable via `registerAsync()`. Here are the key configurati
642
647
  | Group | Key Options | Default |
643
648
  | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
644
649
  | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, off, `HS256`, both off |
645
- | **password** | `costFactor`, `blockSize`, `parallelization` | scrypt N=2¹⁷, r=8, p=1 |
650
+ | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
651
+ | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
646
652
  | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
647
653
  | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
648
654
  | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
@@ -661,6 +667,32 @@ All options are configurable via `registerAsync()`. Here are the key configurati
661
667
  > [!NOTE]
662
668
  > When a feature is not configured (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead.
663
669
 
670
+ > [!IMPORTANT]
671
+ > **`environment` is how the module decides whether this is production, and it defaults to
672
+ > saying yes.** It drives cookie `Secure`, the HTTPS requirement on the OAuth `callbackUrl`, and
673
+ > three redirect validations. It used to be read from `NODE_ENV`, which failed **open** on every
674
+ > near miss — unset, `'staging'`, `'prod'`, or `'production '` with a trailing space each
675
+ > silently took the insecure branch, in all six places at once. Whether a deployment is
676
+ > production is something the deployer knows and the process environment only hints at, so it is
677
+ > passed in. The consequence to plan for: a local or test setup must now say
678
+ > `environment: 'development'` (or `'test'`) explicitly, or it will be held to production rules —
679
+ > an `http://` callback URL is refused, and cookies are marked `Secure` and never sent over
680
+ > plaintext. That failure is loud, which is the point; the old one was silent. Matches
681
+ > `Environment` in rust-auth.
682
+
683
+ > [!NOTE]
684
+ > **`password.minLength` defaults to 15, not 8.** The DTOs keep a structural floor of 8 — the
685
+ > lowest NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance — and this is the
686
+ > deployment's policy on top of it. §3.1.1.1 allows 8 only for a password used as part of
687
+ > multi-factor authentication and requires 15 for one used as a single factor; MFA here is
688
+ > opt-in per user, so the default deployment **is** single-factor. Configurable to anything in
689
+ > `8..=128`, validated at startup: below 8 changes no outcome (the DTOs refuse the request
690
+ > first), and above 128 is longer than any password the validation layer accepts. It is checked
691
+ > in the service rather than a decorator because a decorator is evaluated when the class is
692
+ > defined, before any configuration exists — and it answers the same `auth.validation` code and
693
+ > the same `{ field, message }[]` details a length failure already produced, so a client
694
+ > handling short passwords sees no new shape.
695
+
664
696
  > [!IMPORTANT]
665
697
  > **`rateLimit.clientIpSource` is required** whenever rate limiting is enabled — there is no
666
698
  > default. The option group is a discriminated union, so TypeScript refuses the omission at
@@ -836,7 +868,11 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
836
868
  - `@MaxLength(128)` on password DTOs prevents algorithmic-DoS via oversized scrypt inputs
837
869
  - JWT algorithm pinning to HS256 prevents algorithm-confusion attacks
838
870
  - Constant-time comparisons via `crypto.timingSafeEqual` for all secret comparisons
839
- - HttpOnly cookies; `Secure` enforced in production; `SameSite=Strict` for refresh tokens
871
+ - HttpOnly cookies; `Secure` enforced in production; `SameSite=Lax` by default on every auth
872
+ cookie, so the OAuth provider's cross-site redirect back to your app still carries them.
873
+ Deployments that do not need that redirect can take the stricter posture with
874
+ `cookies.sameSite: 'strict'`. CSRF does not rest on this setting — `TrustedOriginGuard` is
875
+ applied to every controller and runs before authentication.
840
876
 
841
877
  ---
842
878
 
@@ -850,7 +886,7 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
850
886
  | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
851
887
  | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
852
888
  | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
853
- | Cookies | HttpOnly, Secure, SameSite=Strict, path-scoped |
889
+ | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), path-scoped |
854
890
  | Brute-Force | Redis atomic counters per HMAC(email, jwt.secret) |
855
891
  | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
856
892
  | Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
@@ -945,6 +981,40 @@ Conditionally registered controllers (mfa, sessions, platform, invitations, oaut
945
981
  > hand a victim a callback URL and have the victim's browser complete the attacker's login.
946
982
  > Mount `app.use(cookieParser())` before the module's routes or every callback answers 401.
947
983
 
984
+ ### Administrative operations — methods, deliberately not routes
985
+
986
+ Two support-desk operations ship as **methods with no HTTP route**. Every route above is scoped
987
+ to the caller's own account, and both of these act on somebody else's — so exposing them would
988
+ mean inventing an authorization model ("who is an admin?") that this library does not have and
989
+ your application already does. Call them from your own admin surface, where the caller is
990
+ already authorized.
991
+
992
+ | Method | Answers |
993
+ | ------------------------------------------ | --------------------------------------------------- |
994
+ | `AuthService.unlockAccount(email, tenant)` | "I am locked out and I need in now" |
995
+ | `MfaService.resetMfa(userId, context?)` | "I lost my authenticator **and** my recovery codes" |
996
+
997
+ **`unlockAccount`** clears the brute-force lockout. It grants no access: the password, the
998
+ status gate, the verification gate and MFA all still apply — it restores the ability to _try_.
999
+ It exists because the counter is keyed by an HMAC under the library's own `hmacKey`, which no
1000
+ consumer can derive, so until it existed a lockout could only be waited out. It is also the
1001
+ lever an attacker pulls to deny service to one specific account, which makes undoing it part of
1002
+ the defence. Idempotent.
1003
+
1004
+ **`resetMfa`** removes a second factor without one. Every self-service exit needs the factor
1005
+ itself — `disable` wants a valid TOTP code, the recovery codes want the codes — so a user who
1006
+ has lost both is locked out permanently by the control meant to protect them (ASVS v5 §6.1.1
1007
+ asks for this path for exactly that reason). It invalidates every session and bumps the token
1008
+ epoch, so access tokens carrying `mfaVerified: true` die with the factor; it **notifies the
1009
+ account holder** through the same channel a self-service disable uses; and it logs at `warn`
1010
+ under its own prefix. The notification is not optional: an administrative reset the owner
1011
+ cannot see is an account-takeover path, and it is what makes the event detectable and
1012
+ disputable. Idempotent; throws for an id that resolves to nobody, so a typo cannot read as
1013
+ "done".
1014
+
1015
+ > `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
1016
+ > otherwise add it to `extraProviders` to inject it.
1017
+
948
1018
  ### Server Guards
949
1019
 
950
1020
  | Guard | Decorator | Purpose |
@@ -282,7 +282,14 @@ function createAuthClient(config) {
282
282
  const baseUrl = normalizeBaseUrl(config.baseUrl);
283
283
  const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
284
284
  const authFetch = config.authFetch ?? createAuthFetch({
285
- baseUrl,
285
+ // Deliberately NO `baseUrl`. This client composes the full URL itself in `url()` below,
286
+ // and `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute —
287
+ // so passing it here applied the base TWICE. With the documented same-origin setting
288
+ // (`baseUrl: '/api'`, used by the README and by AuthProvider's own example) every call
289
+ // went to `/api/api/auth/*` and 404'd: login, register, logout, refresh and getMe, all
290
+ // of them. An absolute base hid it, because the second prepend is skipped for anything
291
+ // matching `^https?://` — which is why every test in this file, all of which use an
292
+ // absolute base AND inject a stub `authFetch`, stayed green.
286
293
  routePrefix,
287
294
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
288
295
  ...config.refreshEndpoint !== void 0 ? {
@@ -281,7 +281,14 @@ function createAuthClient(config) {
281
281
  const baseUrl = normalizeBaseUrl(config.baseUrl);
282
282
  const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
283
283
  const authFetch = config.authFetch ?? createAuthFetch({
284
- baseUrl,
284
+ // Deliberately NO `baseUrl`. This client composes the full URL itself in `url()` below,
285
+ // and `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute —
286
+ // so passing it here applied the base TWICE. With the documented same-origin setting
287
+ // (`baseUrl: '/api'`, used by the README and by AuthProvider's own example) every call
288
+ // went to `/api/api/auth/*` and 404'd: login, register, logout, refresh and getMe, all
289
+ // of them. An absolute base hid it, because the second prepend is skipped for anything
290
+ // matching `^https?://` — which is why every test in this file, all of which use an
291
+ // absolute base AND inject a stub `authFetch`, stayed green.
285
292
  routePrefix,
286
293
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
287
294
  ...config.refreshEndpoint !== void 0 ? {
@@ -264,9 +264,8 @@ function decodeJwtToken(token) {
264
264
  }
265
265
  __name(decodeJwtToken, "decodeJwtToken");
266
266
  async function verifyJwtToken(token, secret) {
267
- if (secret === void 0 || secret === null || secret.length === 0) {
268
- return emptyDecoded();
269
- }
267
+ if (secret === void 0 || secret === null) return emptyDecoded();
268
+ if (secret.length === 0) return emptyDecoded();
270
269
  const parts = token.split(".");
271
270
  if (parts.length !== 3) return emptyDecoded();
272
271
  const headerSegment = parts[0] ?? "";
@@ -539,19 +538,11 @@ function resolveConfig(config) {
539
538
  };
540
539
  }
541
540
  __name(resolveConfig, "resolveConfig");
542
- function warnOnInsecureConfiguration(config) {
541
+ function assertJwtSecretConfigured(config) {
543
542
  if (config.jwtSecret !== void 0 && config.jwtSecret.length > 0) return;
544
- if (isProductionEnv()) {
545
- throw new Error("createAuthProxy: jwtSecret is required in production. Without it the proxy runs in decode-only mode where RBAC and status-blocking trust unverified tokens \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret` or move signature verification to an upstream gateway and explicitly opt out by running outside of a production environment.");
546
- }
547
- if (typeof console === "undefined" || typeof console.warn !== "function") return;
548
- console.warn("[@bymax-one/nest-auth] createAuthProxy: jwtSecret is not configured. The proxy is running in decode-only mode \u2014 JWT signatures are NOT verified. Every RBAC and status-blocking decision trusts the raw token contents, and forged tokens with a future `exp` can impersonate any role. Ensure an upstream gateway verifies signatures before requests reach downstream server components that read the injected identity headers. In production this condition throws instead of warning.");
549
- }
550
- __name(warnOnInsecureConfiguration, "warnOnInsecureConfiguration");
551
- function isProductionEnv() {
552
- return process.env["NODE_ENV"] === "production";
543
+ throw new Error("createAuthProxy: jwtSecret is required. Without it no JWT signature can be verified, so route gating, role checks, status blocking and the identity headers injected into server components would all trust unverified token contents \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret`; supply it even when an upstream gateway also verifies signatures.");
553
544
  }
554
- __name(isProductionEnv, "isProductionEnv");
545
+ __name(assertJwtSecretConfigured, "assertJwtSecretConfigured");
555
546
  var FORBIDDEN_IN_PATH = /[\u0000-\u001f\u007f]/;
556
547
  function toSameOriginPath(path) {
557
548
  if (!path.startsWith("/")) return "/";
@@ -847,8 +838,7 @@ async function readTokenState(request, config) {
847
838
  signatureVerified: false
848
839
  };
849
840
  }
850
- const hasSecret = config.jwtSecret !== void 0 && config.jwtSecret.length > 0;
851
- const decoded = hasSecret ? await verifyJwtToken(raw, config.jwtSecret) : decodeJwtToken(raw);
841
+ const decoded = await verifyJwtToken(raw, config.jwtSecret);
852
842
  const isSession = decoded.isValid && isAccessToken(decoded);
853
843
  return {
854
844
  token: decoded,
@@ -872,7 +862,7 @@ __name(isAccessToken, "isAccessToken");
872
862
  function createAuthProxy(config) {
873
863
  validateConfig(config);
874
864
  const resolved = resolveConfig(config);
875
- warnOnInsecureConfiguration(resolved);
865
+ assertJwtSecretConfigured(resolved);
876
866
  return {
877
867
  proxy: /* @__PURE__ */ __name((request) => runProxy(request, resolved), "proxy"),
878
868
  config: resolved
@@ -462,11 +462,18 @@ declare function decodeJwtToken(token: string): DecodedToken;
462
462
  * {@link decodeJwtToken} remains the explicit, correctly-named entry
463
463
  * point for the non-authoritative read.
464
464
  *
465
- * The empty string is refused for a second reason of its own: an
466
- * empty HMAC key is technically valid to the Web Crypto API and
467
- * would verify a token signed with the same empty key — a common
468
- * misconfiguration (`JWT_SECRET=""` in an environment file) that
469
- * must not silently downgrade to a no-op.
465
+ * The empty string — `JWT_SECRET=""` in an environment file, the
466
+ * ordinary way a missing secret arrives as a present one — is refused
467
+ * by its own check rather than left to the crypto layer. WebCrypto
468
+ * already rejects zero-length HMAC key material (`importKey` throws
469
+ * `DataError`, which the catch below converts into the same
470
+ * `emptyDecoded()`), so the check changes no outcome here. It is kept
471
+ * because "this function refuses to verify without a secret" should be
472
+ * readable in the function, and should not rest on an exception thrown
473
+ * several layers down and swallowed by a broad `catch` — a `catch` that
474
+ * a later refactor can narrow without knowing it was load-bearing.
475
+ * No test can distinguish the two, so the mutants on it carry a
476
+ * suppression.
470
477
  *
471
478
  * @param token - JWS compact serialisation.
472
479
  * @param secret - HS256 shared secret. A missing or empty value
@@ -539,7 +546,7 @@ declare function getTenantId(token: DecodedToken): string | undefined;
539
546
  * // proxy.ts
540
547
  * import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
541
548
  *
542
- * export const { proxy } = createAuthProxy({
549
+ * const authProxy = createAuthProxy({
543
550
  * publicRoutes: ['/', '/auth/login'],
544
551
  * publicRoutesRedirectIfAuthenticated: ['/auth/login'],
545
552
  * protectedRoutes: [
@@ -554,6 +561,10 @@ declare function getTenantId(token: DecodedToken): string | undefined;
554
561
  * blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
555
562
  * })
556
563
  *
564
+ * // Bound first, then exported: Next 16 scans this file for a function exported as `proxy`
565
+ * // and does not recognise `export const { proxy } = ...`, which fails the build.
566
+ * export const proxy = authProxy.proxy
567
+ *
557
568
  * export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }
558
569
  * ```
559
570
  *
@@ -682,11 +693,19 @@ interface AuthProxyConfig {
682
693
  */
683
694
  interface AuthProxyInstance {
684
695
  /**
685
- * The Next.js 16 proxy function. Destructure and re-export:
696
+ * The Next.js 16 proxy function. Bind the instance, then re-export this property:
686
697
  *
687
698
  * ```ts
688
- * export const { proxy } = createAuthProxy({ ... })
699
+ * const authProxy = createAuthProxy({ ... })
700
+ * export const proxy = authProxy.proxy
689
701
  * ```
702
+ *
703
+ * NOT `export const { proxy } = createAuthProxy({ ... })`. Next 16 statically scans
704
+ * `proxy.ts` for a function exported under that name and does not recognise a destructuring
705
+ * pattern, so the destructured form fails the production build outright: "The file
706
+ * ./proxy.ts must export a function, either as a default export or as a named 'proxy'
707
+ * export." It was the documented form here and in the README until a real Next build was
708
+ * run against the published artifact.
690
709
  */
691
710
  readonly proxy: (request: NextRequest) => Promise<NextResponse>;
692
711
  /**
@@ -462,11 +462,18 @@ declare function decodeJwtToken(token: string): DecodedToken;
462
462
  * {@link decodeJwtToken} remains the explicit, correctly-named entry
463
463
  * point for the non-authoritative read.
464
464
  *
465
- * The empty string is refused for a second reason of its own: an
466
- * empty HMAC key is technically valid to the Web Crypto API and
467
- * would verify a token signed with the same empty key — a common
468
- * misconfiguration (`JWT_SECRET=""` in an environment file) that
469
- * must not silently downgrade to a no-op.
465
+ * The empty string — `JWT_SECRET=""` in an environment file, the
466
+ * ordinary way a missing secret arrives as a present one — is refused
467
+ * by its own check rather than left to the crypto layer. WebCrypto
468
+ * already rejects zero-length HMAC key material (`importKey` throws
469
+ * `DataError`, which the catch below converts into the same
470
+ * `emptyDecoded()`), so the check changes no outcome here. It is kept
471
+ * because "this function refuses to verify without a secret" should be
472
+ * readable in the function, and should not rest on an exception thrown
473
+ * several layers down and swallowed by a broad `catch` — a `catch` that
474
+ * a later refactor can narrow without knowing it was load-bearing.
475
+ * No test can distinguish the two, so the mutants on it carry a
476
+ * suppression.
470
477
  *
471
478
  * @param token - JWS compact serialisation.
472
479
  * @param secret - HS256 shared secret. A missing or empty value
@@ -539,7 +546,7 @@ declare function getTenantId(token: DecodedToken): string | undefined;
539
546
  * // proxy.ts
540
547
  * import { createAuthProxy } from '@bymax-one/nest-auth/nextjs'
541
548
  *
542
- * export const { proxy } = createAuthProxy({
549
+ * const authProxy = createAuthProxy({
543
550
  * publicRoutes: ['/', '/auth/login'],
544
551
  * publicRoutesRedirectIfAuthenticated: ['/auth/login'],
545
552
  * protectedRoutes: [
@@ -554,6 +561,10 @@ declare function getTenantId(token: DecodedToken): string | undefined;
554
561
  * blockedUserStatuses: ['BANNED', 'INACTIVE', 'EXPIRED']
555
562
  * })
556
563
  *
564
+ * // Bound first, then exported: Next 16 scans this file for a function exported as `proxy`
565
+ * // and does not recognise `export const { proxy } = ...`, which fails the build.
566
+ * export const proxy = authProxy.proxy
567
+ *
557
568
  * export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }
558
569
  * ```
559
570
  *
@@ -682,11 +693,19 @@ interface AuthProxyConfig {
682
693
  */
683
694
  interface AuthProxyInstance {
684
695
  /**
685
- * The Next.js 16 proxy function. Destructure and re-export:
696
+ * The Next.js 16 proxy function. Bind the instance, then re-export this property:
686
697
  *
687
698
  * ```ts
688
- * export const { proxy } = createAuthProxy({ ... })
699
+ * const authProxy = createAuthProxy({ ... })
700
+ * export const proxy = authProxy.proxy
689
701
  * ```
702
+ *
703
+ * NOT `export const { proxy } = createAuthProxy({ ... })`. Next 16 statically scans
704
+ * `proxy.ts` for a function exported under that name and does not recognise a destructuring
705
+ * pattern, so the destructured form fails the production build outright: "The file
706
+ * ./proxy.ts must export a function, either as a default export or as a named 'proxy'
707
+ * export." It was the documented form here and in the README until a real Next build was
708
+ * run against the published artifact.
690
709
  */
691
710
  readonly proxy: (request: NextRequest) => Promise<NextResponse>;
692
711
  /**
@@ -262,9 +262,8 @@ function decodeJwtToken(token) {
262
262
  }
263
263
  __name(decodeJwtToken, "decodeJwtToken");
264
264
  async function verifyJwtToken(token, secret) {
265
- if (secret === void 0 || secret === null || secret.length === 0) {
266
- return emptyDecoded();
267
- }
265
+ if (secret === void 0 || secret === null) return emptyDecoded();
266
+ if (secret.length === 0) return emptyDecoded();
268
267
  const parts = token.split(".");
269
268
  if (parts.length !== 3) return emptyDecoded();
270
269
  const headerSegment = parts[0] ?? "";
@@ -537,19 +536,11 @@ function resolveConfig(config) {
537
536
  };
538
537
  }
539
538
  __name(resolveConfig, "resolveConfig");
540
- function warnOnInsecureConfiguration(config) {
539
+ function assertJwtSecretConfigured(config) {
541
540
  if (config.jwtSecret !== void 0 && config.jwtSecret.length > 0) return;
542
- if (isProductionEnv()) {
543
- throw new Error("createAuthProxy: jwtSecret is required in production. Without it the proxy runs in decode-only mode where RBAC and status-blocking trust unverified tokens \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret` or move signature verification to an upstream gateway and explicitly opt out by running outside of a production environment.");
544
- }
545
- if (typeof console === "undefined" || typeof console.warn !== "function") return;
546
- console.warn("[@bymax-one/nest-auth] createAuthProxy: jwtSecret is not configured. The proxy is running in decode-only mode \u2014 JWT signatures are NOT verified. Every RBAC and status-blocking decision trusts the raw token contents, and forged tokens with a future `exp` can impersonate any role. Ensure an upstream gateway verifies signatures before requests reach downstream server components that read the injected identity headers. In production this condition throws instead of warning.");
547
- }
548
- __name(warnOnInsecureConfiguration, "warnOnInsecureConfiguration");
549
- function isProductionEnv() {
550
- return process.env["NODE_ENV"] === "production";
541
+ throw new Error("createAuthProxy: jwtSecret is required. Without it no JWT signature can be verified, so route gating, role checks, status blocking and the identity headers injected into server components would all trust unverified token contents \u2014 a crafted token with a future `exp` can impersonate any role. Provide `jwtSecret`; supply it even when an upstream gateway also verifies signatures.");
551
542
  }
552
- __name(isProductionEnv, "isProductionEnv");
543
+ __name(assertJwtSecretConfigured, "assertJwtSecretConfigured");
553
544
  var FORBIDDEN_IN_PATH = /[\u0000-\u001f\u007f]/;
554
545
  function toSameOriginPath(path) {
555
546
  if (!path.startsWith("/")) return "/";
@@ -845,8 +836,7 @@ async function readTokenState(request, config) {
845
836
  signatureVerified: false
846
837
  };
847
838
  }
848
- const hasSecret = config.jwtSecret !== void 0 && config.jwtSecret.length > 0;
849
- const decoded = hasSecret ? await verifyJwtToken(raw, config.jwtSecret) : decodeJwtToken(raw);
839
+ const decoded = await verifyJwtToken(raw, config.jwtSecret);
850
840
  const isSession = decoded.isValid && isAccessToken(decoded);
851
841
  return {
852
842
  token: decoded,
@@ -870,7 +860,7 @@ __name(isAccessToken, "isAccessToken");
870
860
  function createAuthProxy(config) {
871
861
  validateConfig(config);
872
862
  const resolved = resolveConfig(config);
873
- warnOnInsecureConfiguration(resolved);
863
+ assertJwtSecretConfigured(resolved);
874
864
  return {
875
865
  proxy: /* @__PURE__ */ __name((request) => runProxy(request, resolved), "proxy"),
876
866
  config: resolved
@@ -56,6 +56,7 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
56
56
  const onSessionExpiredRef = React.useRef(onSessionExpired);
57
57
  const clientRef = React.useRef(client);
58
58
  const statusRef = React.useRef(INITIAL_STATE.status);
59
+ const sessionGenerationRef = React.useRef({});
59
60
  React.useEffect(() => {
60
61
  onSessionExpiredRef.current = onSessionExpired;
61
62
  }, [
@@ -83,8 +84,10 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
83
84
  }
84
85
  }, []);
85
86
  const revalidate = React.useCallback(async (isInitial) => {
87
+ const generation = sessionGenerationRef.current;
86
88
  try {
87
89
  const user = await clientRef.current.getMe();
90
+ if (sessionGenerationRef.current !== generation) return;
88
91
  syncedDispatch({
89
92
  type: "SET_USER",
90
93
  payload: {
@@ -93,6 +96,7 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
93
96
  }
94
97
  });
95
98
  } catch (error) {
99
+ if (sessionGenerationRef.current !== generation) return;
96
100
  const wasAuthenticated = statusRef.current === "authenticated";
97
101
  if (isSessionExpiredError(error)) {
98
102
  if (!isInitial && wasAuthenticated) {
@@ -145,11 +149,13 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
145
149
  tenantId
146
150
  });
147
151
  if ("mfaRequired" in result) {
152
+ sessionGenerationRef.current = {};
148
153
  syncedDispatch({
149
154
  type: "CLEAR_SESSION"
150
155
  });
151
156
  return result;
152
157
  }
158
+ sessionGenerationRef.current = {};
153
159
  syncedDispatch({
154
160
  type: "SET_USER",
155
161
  payload: {
@@ -173,6 +179,7 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
173
179
  });
174
180
  try {
175
181
  const result = await clientRef.current.register(data);
182
+ sessionGenerationRef.current = {};
176
183
  syncedDispatch({
177
184
  type: "SET_USER",
178
185
  payload: {
@@ -194,6 +201,7 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
194
201
  try {
195
202
  await clientRef.current.logout();
196
203
  } finally {
204
+ sessionGenerationRef.current = {};
197
205
  syncedDispatch({
198
206
  type: "CLEAR_SESSION"
199
207
  });