@bymax-one/nest-auth 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.4] - 2026-05-25
11
+
12
+ ### Added
13
+
14
+ - **`oauth.successRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts)). When set, `GET /auth/oauth/:provider/callback` issues a `302` redirect to the configured URL after delivering tokens, instead of returning the JSON body that API/SPA consumers expect. Cookies are still set on the same response — the destination page lands fully authenticated. This closes a UX gap that left browser users on the JSON payload after a successful OAuth round-trip (every consumer was forced to reimplement the OAuth controller just to get a redirect). The option is opt-in and the legacy JSON-body contract is preserved when it is omitted. Aligns the lib with `passport.successRedirect`, `next-auth.callbackUrl`, and `auth0.returnTo`.
15
+
16
+ Validated at startup by [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts) with three rules:
17
+ 1. Must be a non-empty string when set.
18
+ 2. Must use `https://` or be a same-origin path (`/...`) in production — HTTP rejected so the post-callback leg cannot strip cookie `Secure` guarantees.
19
+ 3. Requires `tokenDelivery: 'cookie'` or `'both'` — `bearer` is rejected because the 302 would discard the JSON body that carries the access token.
20
+
21
+ Covered by 3 new unit tests in [`src/server/oauth/oauth.controller.spec.ts`](src/server/oauth/oauth.controller.spec.ts), 7 new validator tests in [`src/server/config/resolved-options.spec.ts`](src/server/config/resolved-options.spec.ts), and 2 new e2e scenarios in [`test/e2e/oauth-flow.e2e-spec.ts`](test/e2e/oauth-flow.e2e-spec.ts) (cookie-attached 302 to the configured URL + Set-Cookie headers on the redirect response).
22
+
23
+ ## [1.0.3] - 2026-05-25
24
+
25
+ ### Fixed
26
+
27
+ - **OAuth callback accepts standard provider query parameters** ([`src/server/dto/oauth-callback-query.dto.ts`](src/server/dto/oauth-callback-query.dto.ts)). Previously the controller-level `ValidationPipe(forbidNonWhitelisted: true)` paired with a `code` + `state`-only DTO rejected real-world Google callbacks with `HTTP 400 — property iss should not exist` because Google appends `iss` (OAuth 2.0 Issuer Identification, RFC 9207), `scope` (RFC 6749 §3.3 echoed grants), `authuser` (Google Account-chooser index), `prompt` (which prompt was shown), and `hd` (Workspace hosted-domain) to the redirect. The DTO now declares all five as `@IsOptional()` strings with sensible `@MaxLength` bounds — the values are validated for shape and ignored by the service. Covered by a new e2e scenario in [`test/e2e/oauth-flow.e2e-spec.ts`](test/e2e/oauth-flow.e2e-spec.ts) that submits the exact param set Google sends. No breaking change — existing `code` + `state`-only callbacks continue to work.
28
+
29
+ ### Tests — E2E coverage (audit-driven, surface gaps closed)
30
+
31
+ A systematic audit of `test/e2e/` against the lib's HTTP surface identified
32
+ several uncovered scenarios. Each new spec exercises real routes via supertest
33
+ against a fully-bootstrapped NestJS app — no controller methods are called
34
+ directly, no network is touched (Google OAuth + email + Redis are mocked).
35
+ The full e2e count goes from **9 suites / 59 tests** to **14 suites / 89 tests**.
36
+
37
+ - **[`test/e2e/platform-auth-flow.e2e-spec.ts`](test/e2e/platform-auth-flow.e2e-spec.ts)** — closes
38
+ the entire platform admin HTTP surface (previously zero e2e coverage):
39
+ `/platform/login`, `/platform/me`, `/platform/refresh`, `/platform/logout`,
40
+ `DELETE /platform/sessions`, plus cross-context rejection (dashboard token →
41
+ `/platform/me` returns 401, and platform token → `/me` returns 401).
42
+ - **[`test/e2e/mfa-disable-flow.e2e-spec.ts`](test/e2e/mfa-disable-flow.e2e-spec.ts)** — closes
43
+ the MFA lifecycle's final transition. Asserts `/mfa/disable` returns 204
44
+ with a valid TOTP, flips `mfaEnabled` to false on the persisted user,
45
+ restores the no-challenge login path, and rejects with `MFA_INVALID_CODE` /
46
+ `MFA_NOT_ENABLED` on the negative paths.
47
+ - **[`test/e2e/email-verification-flow.e2e-spec.ts`](test/e2e/email-verification-flow.e2e-spec.ts)** —
48
+ closes `/verify-email` + `/resend-verification` (both previously untouched
49
+ by e2e). Verifies the OTP-driven happy path, OTP_INVALID rejection, fresh
50
+ OTP dispatch on resend, and anti-enumeration responses for unknown +
51
+ already-verified emails.
52
+ - **[`test/e2e/negative-paths.e2e-spec.ts`](test/e2e/negative-paths.e2e-spec.ts)** — bundles
53
+ eight negative-path scenarios that were silent gaps: unknown invitation
54
+ token, single-use invitation replay, foreign-user session revoke (auth-
55
+ bypass class), `DELETE /sessions/all` without a refresh token, unknown
56
+ password-reset token, wrong reset OTP, unknown OAuth provider, OAuth init
57
+ without `tenantId`.
58
+ - **[`test/e2e/hooks-lifecycle.e2e-spec.ts`](test/e2e/hooks-lifecycle.e2e-spec.ts)** — replaces
59
+ the implicit "if it works, the hook fired" assumption with explicit spy
60
+ assertions on `beforeRegister`, `afterRegister`, `beforeLogin`, `afterLogin`,
61
+ `afterLogout`, `afterMfaEnabled`, `afterEmailVerified`, and
62
+ `afterPasswordReset`. Each hook is verified to receive a `HookContext`
63
+ carrying `ip`, `userAgent`, and sanitized headers — a regression that drops
64
+ any single dispatch would fail the corresponding scenario.
65
+
66
+ ### Tests — Helpers
67
+
68
+ - **`MockPlatformUserRepository.seed(user)`** ([`test/e2e/setup.ts`](test/e2e/setup.ts)) — exposes
69
+ a deterministic seed entry-point that populates both the user map AND the
70
+ internal `emailIndex` so `findByEmail` resolves the row. Required for the
71
+ platform spec; useful for any future test that needs pre-existing platform
72
+ admins (the lib intentionally ships no `createPlatformUser` endpoint).
73
+
10
74
  ## [1.0.2] - 2026-05-25
11
75
 
12
76
  ### Security
@@ -39,6 +103,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
39
103
  ### Added
40
104
 
41
105
  **Next.js subpath (`@bymax-one/nest-auth/nextjs`)**
106
+
42
107
  - `createAuthProxy(config)` — Edge-Runtime factory that produces a Next.js 16 proxy function. Classifies routes (`/api/auth/*`, public, protected, unmatched), reads the access-cookie JWT (HS256 verify via Web Crypto when `jwtSecret` is provided; decode-only fallback otherwise), and dispatches to public / protected handlers. Strips client-spoofed identity headers on every response path and propagates trusted `x-user-id`, `x-user-role`, `x-tenant-id`, `x-tenant-domain` from the verified token via `NextResponse.next({ request: { headers } })`.
43
108
  - **Anti-redirect-loop defence-in-depth** — two guards must BOTH fail before the proxy issues a silent-refresh redirect: a `_r` query-param counter (clamped to `maxRefreshAttempts`, rides on the DESTINATION so it survives the handler round-trip) AND a `reason=expired` signal that the silent-refresh handler sets on its terminal fallback. Either guard alone stops the loop.
44
109
  - **RBAC + status blocking** — `protectedRoutes` patterns support exact, `:segment`, and trailing-wildcard matches. Role mismatch redirects to `getDefaultDashboard(role)?error=forbidden`; blocked `status` claim (case-insensitive against `blockedUserStatuses` via `toLocaleLowerCase('en-US')`) redirects to `loginPath?reason=<allowlist-entry>`. The `reason` value is pulled from the configured allowlist, never from the raw JWT claim.
@@ -52,6 +117,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
52
117
  - **Factory-time validation** — every factory validates its config at construction time: `apiBase` must be absolute HTTP(S); `loginPath` / `redirectPath` must be same-origin pathnames with no CR/LF/NUL/backslash; cookie names must match RFC 6265 token grammar; cookie paths must start with `/` and contain no attribute-smuggling characters; `logoutPath` / `refreshPath` must not contain `..`, `?`, `#`, or control bytes; protected-route patterns reject mid-pattern wildcards and segment-0 catch-alls.
53
118
 
54
119
  **React subpath (`@bymax-one/nest-auth/react`)**
120
+
55
121
  - `AuthProvider({ client, onSessionExpired?, revalidateInterval? })` — React 19 provider that owns the `loading → authenticated / unauthenticated` state machine, bridges a `createAuthClient` instance into the auth context, and schedules a best-effort revalidation loop (default 5 minutes) so long-lived UIs surface role/status changes without a manual refresh. `onSessionExpired` fires only on a live `authenticated → unauthenticated` transition (not on initial mount or explicit logout).
56
122
  - `useAuth()` — imperative API: `login`, `register`, `logout`, `forgotPassword`, and `resetPassword`, bound to the provider's client with stable identity. The MFA challenge is exposed through `AuthClient.mfaChallenge()`; session revalidation is exposed through `useSession().refresh()`.
57
123
  - `useSession()` — reactive snapshot: `{ user, status, isLoading, refresh, lastValidation }` read from context (the `refresh` method triggers an ad-hoc revalidation).
@@ -59,11 +125,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
59
125
  - `AuthContext`, `AuthContextValue`, `AuthStatus`, `AuthProviderProps` types exported from the subpath barrel.
60
126
 
61
127
  **Client subpath (`@bymax-one/nest-auth/client`)**
128
+
62
129
  - `createAuthFetch(config)` — fetch wrapper with cookie-mode defaults, single-flight 401 refresh interception, per-instance dedup, configurable timeout (`AbortController`-based), prototype-pollution-safe header merging, and `routePrefix` option for deployments mounted under non-default prefixes
63
130
  - `createAuthClient(config)` — typed `AuthClient` facade with `login`, `register`, `logout`, `refresh`, `getMe`, `mfaChallenge`, `forgotPassword`, and `resetPassword` methods; composes on top of `createAuthFetch` and supports a pre-built `authFetch` override for sharing dedup state across clients
64
131
  - `AuthFetch`, `AuthFetchConfig`, `AuthClient`, `AuthClientConfig`, `LoginInput`, `RegisterInput`, `ResetPasswordInput` types exported from the subpath barrel
65
132
 
66
133
  **Shared subpath (`@bymax-one/nest-auth/shared`)**
134
+
67
135
  - `buildAuthRefreshSkipSuffixes(routePrefix?)` — factory producing the pathname-suffix skip list used by the client's 401 refresh interception, parameterized by the NestJS `routePrefix`; backwards-compat `AUTH_REFRESH_SKIP_PATH_SUFFIXES` retained for the default `'auth'` prefix
68
136
  - `AuthResponseCode` type — `AuthErrorCode | (string & {})` union so consumers get autocomplete on known codes while preserving flexibility for non-auth Nest exceptions (e.g. `ValidationPipe` 400s)
69
137
 
@@ -103,6 +171,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
103
171
  #### Phase 1 — Foundation and Infrastructure (NEST-001 to NEST-042)
104
172
 
105
173
  **Scaffold and tooling**
174
+
106
175
  - `package.json` with scope `@bymax-one`, peer dependencies (NestJS 11, ioredis, class-validator), zero direct runtime dependencies
107
176
  - `tsconfig.json` and `tsconfig.build.json` with `strict: true`, ES2022 target, decorator support
108
177
  - `tsconfig.jest.json` for ts-jest compilation
@@ -114,6 +183,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
114
183
  - MIT License, `.gitignore`, `AGENTS.md`, `CLAUDE.md`
115
184
 
116
185
  **Interfaces**
186
+
117
187
  - `BymaxAuthModuleOptions` — full module configuration interface with 15 optional groups (jwt, password, tokenDelivery, cookies, mfa, sessions, bruteForce, passwordReset, emailVerification, platform, invitations, roles, blockedStatuses, oauth, controllers)
118
188
  - `AuthUser` and `SafeAuthUser` — user entity interfaces (15 fields) with credential-free safe variant
119
189
  - `IUserRepository` — data access interface with 11 methods (findById, findByEmail, create, updatePassword, updateMfa, updateLastLogin, updateStatus, updateEmailVerified, findByOAuthId, linkOAuth, createWithOAuth)
@@ -129,37 +199,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
129
199
  - `OAuthProfile` and `OAuthLoginResult` — OAuth profile and hook result types
130
200
 
131
201
  **Constants and configuration**
202
+
132
203
  - 6 Symbol-based DI injection tokens: `BYMAX_AUTH_OPTIONS`, `BYMAX_AUTH_USER_REPOSITORY`, `BYMAX_AUTH_PLATFORM_USER_REPOSITORY`, `BYMAX_AUTH_EMAIL_PROVIDER`, `BYMAX_AUTH_HOOKS`, `BYMAX_AUTH_REDIS_CLIENT`
133
204
  - `DEFAULT_OPTIONS` — all default values (jwt.accessExpiresIn `'15m'`, refreshExpiresInDays `7`, tokenDelivery `'cookie'`, bruteForce 5 attempts / 900s window, etc.)
134
205
  - `resolveOptions()` — startup function that merges consumer options with defaults, validates all security invariants, and produces `ResolvedOptions` with no optional fields
135
206
  - Throttle configurations (`THROTTLE_CONFIGS`) per endpoint category
136
207
 
137
208
  **Crypto utilities** (`src/server/crypto/`)
209
+
138
210
  - `sha256(input)` — deterministic SHA-256 hex digest via `node:crypto`
139
211
  - `hmacSha256(input, secret)` — keyed HMAC-SHA256 hex digest for low-entropy inputs (composite keys with email addresses)
140
212
  - `encrypt(plaintext, keyBase64)` / `decrypt(ciphertext, keyBase64)` — AES-256-GCM authenticated encryption using random 12-byte IV per call; wire format `base64(iv):base64(authTag):base64(ciphertext)`
141
213
  - `generateSecureToken()` — cryptographically random opaque token via `node:crypto.randomBytes`
142
214
 
143
215
  **Error handling** (`src/server/errors/`)
216
+
144
217
  - `AUTH_ERROR_CODES` — typed string union of all 30+ error codes with Portuguese end-user messages
145
218
  - `AuthException` — NestJS `HttpException` subclass carrying structured `{ code, message, details? }` response body
146
219
 
147
220
  **Redis layer** (`src/server/redis/`)
221
+
148
222
  - `AuthRedisService` — typed wrapper around ioredis with automatic namespace prefixing; exposes `get`, `set`, `del`, `setnx`, `incr`, `expire`, `ttl`, `sadd`, `srem`, `smembers`, `sismember`, `eval`, `getdel`, `incrWithFixedTtl`
149
223
  - `AuthRedisModule` — internal NestJS module registering `AuthRedisService`
150
224
 
151
225
  **Services** (`src/server/services/`)
226
+
152
227
  - `PasswordService` — scrypt-based password hashing and constant-time comparison; configurable cost factor, block size, and parallelization
153
228
  - `BruteForceService` — fixed-window rate limiting via atomic `incrWithFixedTtl` Lua script; lockout with `getRemainingLockoutSeconds`
154
229
  - `TokenManagerService` — JWT issuance (`issueTokens`, `issueMfaTempToken`), token rotation (`reissueTokens`), revocation blacklist via Redis `rv:{jti}` keys, raw refresh token storage via `rt:{sha256(token)}`
155
230
  - `TokenDeliveryService` — cookie/bearer/both delivery modes; multi-domain support via `resolveDomains` callback; `extractAccessToken`, `extractRefreshToken`, `clearAuthSession`
156
231
 
157
232
  **Utilities** (`src/server/utils/`)
233
+
158
234
  - `sanitizeHeaders()` — removes sensitive headers (authorization, cookie, x-api-key, x-auth-token, x-csrf-token, x-session-id, pattern `/^x-.*-token$/i`) before passing to hook context
159
235
  - `sleep(ms)` — Promise-based delay for timing normalization in anti-enumeration flows
160
236
  - `hasRole(userRole, requiredRole, hierarchy)` — recursive role hierarchy checker supporting denormalized role trees
161
237
 
162
238
  **NoOp fallback providers**
239
+
163
240
  - `NoOpEmailProvider` — silent no-op implementation of `IEmailProvider` (registered when consumer does not supply one)
164
241
  - `NoOpAuthHooks` — silent no-op implementation of `IAuthHooks` (registered when consumer does not supply one)
165
242
 
@@ -170,28 +247,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
170
247
  #### Phase 2 — Core Authentication (NEST-043 to NEST-064)
171
248
 
172
249
  **Guards** (`src/server/guards/`)
250
+
173
251
  - `JwtAuthGuard` — native NestJS guard (no Passport); verifies JWT via `@nestjs/jwt` `JwtService.verify()` with algorithm pinning from `ResolvedOptions.jwt.algorithm`; checks `rv:{jti}` revocation blacklist; skips public routes decorated with `@Public()`; asserts token type is `'dashboard'` via `assertTokenType` utility
174
252
  - `RolesGuard` — hierarchical role guard using denormalized `roles.hierarchy`; reads `@Roles()` metadata via `Reflector`; throws `INSUFFICIENT_ROLE` (403) on failure
175
253
  - `UserStatusGuard` — status-based access guard with Redis caching (`us:{userId}`, TTL from `userStatusCacheTtlSeconds`); maps blocked statuses to specific error codes (ACCOUNT_BANNED, ACCOUNT_INACTIVE, ACCOUNT_SUSPENDED, PENDING_APPROVAL) with ACCOUNT_INACTIVE as fallback
176
254
  - `assertTokenType` utility — reusable guard helper that throws `TOKEN_INVALID` when the JWT `type` claim does not match the expected value
177
255
 
178
256
  **Decorators** (`src/server/decorators/`)
257
+
179
258
  - `@CurrentUser(property?)` — param decorator extracting `request.user` or a specific property from it
180
259
  - `@Roles(...roles)` — metadata decorator setting `ROLES_KEY` for `RolesGuard`
181
260
  - `@Public()` — metadata decorator setting `IS_PUBLIC_KEY` to skip `JwtAuthGuard`
182
261
 
183
262
  **DTOs** (`src/server/dto/`)
263
+
184
264
  - `RegisterDto` — `email`, `password` (8–128 chars), `name` (2+ chars), `tenantId`; all with class-validator decorators
185
265
  - `LoginDto` — `email`, `password` (no `@MinLength` — deliberate anti-enumeration), `tenantId`
186
266
 
187
267
  **Services** (`src/server/services/`)
268
+
188
269
  - `OtpService` — `generate(length)` via `crypto.randomInt` with leading-zero padding; `store(purpose, identifier, code, ttl)` to Redis; `verify(purpose, identifier, code)` with constant-time comparison via `crypto.timingSafeEqual` (safe for different-length inputs), max-attempt enforcement (5), key deletion on exhaustion, and timing normalization (100ms floor); atomic attempt increment via Lua eval (single round-trip preserving TTL)
189
270
  - `AuthService` — full authentication lifecycle: `register`, `login`, `logout`, `refresh`, `getMe`, `verifyEmail`, `resendVerificationEmail`; `@Optional()` hooks with fire-and-forget error isolation; tenant resolution via `tenantIdResolver`; brute-force integration; MFA challenge path
190
271
 
191
272
  **Controllers** (`src/server/controllers/`)
273
+
192
274
  - `AuthController` — 7 endpoints: `POST /register`, `POST /login`, `POST /logout`, `POST /refresh`, `GET /me`, `POST /verify-email`, `POST /resend-verification`; `@UsePipes(new ValidationPipe({ whitelist: true }))` at class level; conditional registration via `controllers.auth` option
193
275
 
194
276
  **Module**
277
+
195
278
  - `BymaxAuthModule.registerAsync(options)` — dynamic NestJS module; wraps consumer factory with `resolveOptions()`; conditionally registers `AuthController`; registers NoOp fallback providers when consumer omits email/hooks tokens; class-shorthand provider detection in `hasProviderToken`; `JwtModule.registerAsync` reads `jwt.secret` directly (no double `resolveOptions` call)
196
279
 
197
280
  **Phase 2 barrel export** — adds `BymaxAuthModule`, `AuthService`, `JwtAuthGuard`, `RolesGuard`, `UserStatusGuard`, `CurrentUser`, `Roles`, `ROLES_KEY`, `Public`, `IS_PUBLIC_KEY`, `RegisterDto`, `LoginDto`
@@ -201,6 +284,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
201
284
  #### Phase 3 — Multi-Factor Authentication (TOTP)
202
285
 
203
286
  **Crypto utilities** (`src/server/crypto/totp.ts`)
287
+
204
288
  - `generateTotpSecret()` — generates a cryptographically random 20-byte TOTP secret via `node:crypto.randomBytes`; returns both raw `Buffer` and `base32`-encoded string
205
289
  - `buildTotpUri(secret, account, issuer)` — constructs a standard `otpauth://totp/` URI for QR code generation
206
290
  - `verifyTotp(secret, code, window)` — validates a 6-digit TOTP code within a configurable step window (±1 by default) using HMAC-SHA1 per RFC 6238
@@ -208,33 +292,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
208
292
  - `fromBase32(input)` / `toBase32(buf)` — pure Base32 encode/decode without external dependencies; `fromBase32` strips whitespace, hyphens, and padding before decoding
209
293
 
210
294
  **Services** (`src/server/services/mfa.service.ts`)
295
+
211
296
  - `MfaService.setup(userId)` — generates TOTP secret and recovery codes; uses atomic `setIfAbsent` to guarantee idempotency under concurrent requests; encrypts secret with AES-256-GCM; returns plain recovery codes once (then discarded)
212
297
  - `MfaService.verifyAndEnable(userId, code, ip, userAgent)` — validates the first TOTP code against the pending setup key; atomically consumes the setup key to prevent double-enable races; persists encrypted secret and hashed recovery codes to the user repository; invalidates all existing refresh sessions
213
298
  - `MfaService.challenge(tempToken, code, ip, userAgent)` — exchanges a short-lived MFA temp token for full auth tokens; accepts both TOTP codes and recovery codes; enforces anti-replay via 90-second `setnx` key; brute-force lockout with `challenge:`-namespaced counter; supports both `dashboard` and `platform` contexts
214
299
  - `MfaService.disable(userId, code, ip, userAgent, context)` — disables MFA after TOTP verification; only accepts TOTP (recovery codes cannot disable by design); invalidates all sessions; supports both dashboard and platform repositories via `context` parameter
215
300
 
216
301
  **Guards** (`src/server/guards/mfa-required.guard.ts`)
302
+
217
303
  - `MfaRequiredGuard` — enforces MFA verification on routes where the authenticated JWT has `mfaEnabled: true`; gates on `mfaVerified: true` claim; respects `@SkipMfa()` decorator to exclude specific endpoints (e.g. the challenge endpoint itself)
218
304
 
219
305
  **Decorators** (`src/server/decorators/skip-mfa.decorator.ts`)
306
+
220
307
  - `@SkipMfa()` — metadata decorator that marks an endpoint as exempt from `MfaRequiredGuard`; used on `POST /mfa/challenge` and any other pre-MFA routes
221
308
 
222
309
  **DTOs** (`src/server/dto/`)
310
+
223
311
  - `MfaChallengeDto` — `mfaTempToken` (string) + `code` (string); `@MaxLength(14)` as defence-in-depth before regex
224
312
  - `MfaVerifyDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`
225
313
  - `MfaDisableDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`; JSDoc explains why recovery codes are not accepted
226
314
 
227
315
  **Controllers** (`src/server/controllers/mfa.controller.ts`)
316
+
228
317
  - `POST /mfa/setup` — initiates TOTP setup; returns secret, QR URI, and plain recovery codes (shown once); idempotent within 10-minute window; dashboard users only
229
318
  - `POST /mfa/verify-enable` — submits the first TOTP code to permanently activate MFA; returns 204 No Content
230
319
  - `POST /mfa/challenge` — public endpoint (protected only by temp token); exchanges temp token + TOTP or recovery code for full auth tokens; returns cookie or bearer response for dashboard, plain JSON for platform
231
320
  - `POST /mfa/disable` — disables MFA for dashboard or platform users; derived `context` from `user.type` JWT claim; returns 204 No Content
232
321
 
233
322
  **Redis additions** (`src/server/redis/auth-redis.service.ts`)
323
+
234
324
  - `setIfAbsent(key, value, ttl)` — atomic `SET NX EX`; returns `true` if the key was newly created, `false` if it already existed; used for idempotent setup key reservation
235
325
  - `invalidateUserSessions(userId)` — Lua script that reads all members of `sess:{userId}`, deletes each session key (including grace pointers tracked in the SET), and removes the SET itself in a single round-trip
236
326
 
237
327
  **Module integration** (`src/server/bymax-auth.module.ts`)
328
+
238
329
  - `controllers.mfa: true` option conditionally registers `MfaController`; startup validation throws if `controllers.mfa: true` is set without the `mfa` configuration group
239
330
 
240
331
  ---
@@ -242,24 +333,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
242
333
  #### Phase 4 — Sessions & Password Reset
243
334
 
244
335
  **Services** (`src/server/services/`)
336
+
245
337
  - `SessionService` — full session lifecycle management: `createSession` records device/IP metadata and enforces concurrent session limit via FIFO eviction; `listSessions` returns sorted `SessionInfo[]` with `isCurrent` marked via timing-safe comparison; `revokeSession` atomically verifies ownership (SISMEMBER) before deletion; `revokeAllExceptCurrent` preserves the caller's session while revoking all others; `rotateSession` atomically renames session detail key on token rotation, preserving `createdAt`; device parsing is regex-only (no external libraries); two Lua scripts (`REVOKE_SESSION_LUA`, `ROTATE_SESSION_DETAIL_LUA`) prevent TOCTOU races
246
338
  - `PasswordResetService` — dual-flow password reset supporting `token` and `otp` modes (configured via `passwordReset.method`); `initiateReset` always returns success (anti-enumeration); `resetPassword` validates mutual exclusivity of proof fields and delegates to `resetWithToken`, `resetWithOtp`, or `resetWithVerifiedToken`; `verifyOtp` exchanges a validated OTP for a 5-minute `verifiedToken`; `resendOtp` subject to atomic 60-second cooldown via Redis NX key; all tokens consumed atomically via `getdel()` (single-use); `applyPasswordReset` hashes the new password and invalidates all sessions via Lua script; `initiateReset` and `resendOtp` apply a 300ms timing floor to prevent email-existence probing
247
339
 
248
340
  **Controllers** (`src/server/controllers/`)
341
+
249
342
  - `SessionController` — 3 endpoints: `GET /sessions` (list active sessions), `DELETE /sessions/all` (revoke all except current), `DELETE /sessions/:id` (revoke single session by 64-char hash); all require `JwtAuthGuard` + `UserStatusGuard`; current session identified by extracting refresh token via `TokenDeliveryService`
250
343
  - `PasswordResetController` — 4 endpoints: `POST /password/forgot-password`, `POST /password/reset-password`, `POST /password/verify-otp`, `POST /password/resend-otp`; all `@Public()`; all return 200/204 regardless of email existence; per-endpoint throttle configs
251
344
 
252
345
  **DTOs** (`src/server/dto/`)
346
+
253
347
  - `ForgotPasswordDto` — `email` (normalized lowercase) + `tenantId`
254
348
  - `ResetPasswordDto` — `email`, `newPassword` (8–128 chars), exactly one of `token` / `otp` / `verifiedToken`, `tenantId`
255
349
  - `VerifyOtpDto` — `email`, `otp` (4–8 chars), `tenantId`
256
350
  - `ResendOtpDto` — `email` + `tenantId`
257
351
 
258
352
  **Configuration** (`BymaxAuthModuleOptions`)
353
+
259
354
  - `sessions.enabled`, `sessions.defaultMaxSessions` (default 5), `sessions.maxSessionsResolver`, `sessions.evictionStrategy` (`'fifo'`)
260
355
  - `passwordReset.method` (`'token'` | `'otp'`, default `'token'`), `passwordReset.tokenTtlSeconds` (default 3600), `passwordReset.otpTtlSeconds` (default 600), `passwordReset.otpLength` (default 6)
261
356
 
262
357
  **Module integration** (`src/server/bymax-auth.module.ts`)
358
+
263
359
  - `controllers.sessions: true` opt-in gate with startup cross-validation: throws if `sessions.enabled` is not `true` in the factory return value
264
360
  - `controllers.passwordReset` opt-out gate (enabled by default); `PasswordResetService` only registered when controller is active
265
361
  - `SessionService` always registered unconditionally — `AuthService.login()` and `AuthService.refresh()` call session methods regardless of whether the sessions controller is exposed
@@ -271,23 +367,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
271
367
  #### Phase 5 — Platform Authentication, OAuth & Invitations
272
368
 
273
369
  **Services**
370
+
274
371
  - `PlatformAuthService` (`src/server/services/`) — operator/super-admin authentication layer backed by `IPlatformUserRepository`; `login` validates credentials, applies brute-force protection (HMAC-SHA-256 identifier, no PII in Redis), and returns `PlatformAuthResult` or `MfaChallengeResult`; `logout` blacklists JTI and deletes primary + grace session keys; `refresh` delegates to `TokenManagerService.reissuePlatformTokens()`; `getMe` returns `SafeAuthPlatformUser` (no credential fields); `revokeAllPlatformSessions` atomically deletes all session keys via `invalidateUserSessions()` Lua script; platform sessions are always bearer-mode (never cookies)
275
372
  - `OAuthService` (`src/server/oauth/`) — provider-agnostic Authorization Code flow; `initiateOAuth` validates provider name format, generates 64-char hex CSRF state nonce stored under `os:{sha256(state)}` (10-min TTL), and redirects to provider authorize URL; `handleCallback` atomically consumes state via `getdel()`, exchanges authorization code for access token, fetches normalized profile, calls required `hooks.onOAuthLogin` for account resolution (`'create'` / `'link'` / `'reject'`), and issues dashboard tokens; creates session if `sessions.enabled: true`; currently supports Google OAuth 2.0
276
373
  - `InvitationService` (`src/server/services/`) — `invite` validates the target role against the inviter's own role via `hasRole()` (cannot invite higher), stores `StoredInvitation` JSON under `inv:{sha256(token)}`, and emails the raw token; `acceptInvitation` atomically consumes the token via `getdel()`, re-validates role against the hierarchy (prevents Redis tampering), verifies email uniqueness, hashes password, creates the user with `emailVerified: true`, issues dashboard tokens, creates session if enabled, and fires `hooks.afterInvitationAccepted`
277
374
 
278
375
  **Guards** (`src/server/guards/`)
376
+
279
377
  - `JwtPlatformGuard` — validates HS256-signed JWTs for platform routes; reads token exclusively from Authorization Bearer header; enforces `type: 'platform'` claim; throws `PLATFORM_AUTH_REQUIRED` (not `TOKEN_INVALID`) when a dashboard token is submitted, enabling precise cross-context error detection; algorithm pinned from `options.jwt.algorithm`; checks `rv:{jti}` revocation blacklist; respects `@Public()`
280
378
  - `PlatformRolesGuard` — enforces role-based access on platform routes via `@PlatformRoles()` metadata; requires fully denormalized `roles.platformHierarchy`; denies access by default when hierarchy is missing
281
379
 
282
380
  **Decorators** (`src/server/decorators/`)
381
+
283
382
  - `@PlatformRoles(...roles)` — metadata decorator under `PLATFORM_ROLES_KEY` symbol; declares required platform role(s) for a route handler
284
383
 
285
384
  **Controllers**
385
+
286
386
  - `PlatformAuthController` (`src/server/controllers/`) — 6 endpoints: `POST /platform/login`, `POST /platform/mfa/challenge`, `GET /platform/me`, `POST /platform/logout`, `POST /platform/refresh`, `DELETE /platform/sessions`; all authenticated routes use `JwtPlatformGuard`; `mfa/challenge` cross-validates token context and throws `PLATFORM_AUTH_REQUIRED` on dashboard-context token submission
287
387
  - `OAuthController` (`src/server/oauth/`) — 2 endpoints: `GET /oauth/:provider` (initiate, 302 redirect) and `GET /oauth/:provider/callback` (handle, issues auth tokens); both `@Public()` + `@SkipMfa()`; per-endpoint throttle configs
288
388
  - `InvitationController` (`src/server/controllers/`) — 2 endpoints: `POST /invitations` (authenticated, `tenantId` extracted from JWT never from body) and `POST /invitations/accept` (public, returns 201 with auth response)
289
389
 
290
390
  **DTOs** (`src/server/dto/`)
391
+
291
392
  - `PlatformLoginDto` — `email` (normalized lowercase) + `password` (12–128 chars)
292
393
  - `CreateInvitationDto` — `email`, `role`, optional `tenantName` (max 128 chars)
293
394
  - `AcceptInvitationDto` — `token` (exactly 64 hex chars), `name` (2–100 chars), `password` (8–128 chars)
@@ -295,16 +396,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
295
396
  - `OAuthCallbackQueryDto` — `code` (32–2048 chars), `state` (max 128 chars)
296
397
 
297
398
  **OAuth module** (`src/server/oauth/`)
399
+
298
400
  - `OAuthModule` — exposes `getOAuthProviders()` and `getOAuthControllers()` static methods for inline inclusion in `BymaxAuthModule` providers/controllers arrays, avoiding sub-module circular dependency; `buildOAuthPlugins()` factory constructs registered provider plugins from `ResolvedOptions`
299
401
  - `OAUTH_PLUGINS` — Symbol injection token for the `OAuthProviderPlugin[]` array; internal to the library (not exported in public API)
300
402
 
301
403
  **Configuration** (`BymaxAuthModuleOptions`)
404
+
302
405
  - `platform.enabled` (default `false`); requires `roles.platformHierarchy`
303
406
  - `oauth.google` — `clientId`, `clientSecret`, `callbackUrl` (required), `scope` (optional, default `['openid', 'email', 'profile']`)
304
407
  - `invitations.enabled` (default `false`), `invitations.tokenTtlSeconds` (default 172800 — 48 hours)
305
408
  - `roles.platformHierarchy` — required when `platform.enabled: true`
306
409
 
307
410
  **Module integration** (`src/server/bymax-auth.module.ts`)
411
+
308
412
  - `controllers.platform: true` opt-in gate with three startup cross-validations: requires `platform.enabled: true`, the `mfa` config group, and `BYMAX_AUTH_PLATFORM_USER_REPOSITORY` in `extraProviders`
309
413
  - `controllers.oauth: true` opt-in gate with startup cross-validation: requires `oauth` config group; `OAUTH_PLUGINS` built lazily via factory provider after `BYMAX_AUTH_OPTIONS` resolves
310
414
  - `controllers.invitations: true` opt-in gate with startup cross-validation: requires `invitations.enabled: true`
@@ -317,11 +421,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
317
421
  #### Phase 6 — Integration, Polish, and Publication (NEST-122 to NEST-151)
318
422
 
319
423
  **Additional guards** (3)
424
+
320
425
  - `WsJwtGuard` — WebSocket dashboard JWT guard (header-only, soft peer-dep on `@nestjs/websockets`, runtime check via dynamic import)
321
426
  - `SelfOrAdminGuard` — self-access or admin override with strict SHA-256 session-hash validation; documents multi-tenant ownership limitation
322
427
  - `OptionalAuthGuard` — extends `JwtAuthGuard`, allows unauthenticated access while validating tokens when present
323
428
 
324
429
  **E2E test suite** (`test/e2e/`)
430
+
325
431
  - Full auth flow (bearer + cookie modes)
326
432
  - MFA flow (setup, verify, challenge with TOTP and recovery codes)
327
433
  - Sessions flow (3-device login, list, revoke single, revoke all-except-current)
@@ -333,15 +439,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
333
439
  - Security scenarios (brute-force lockout, blacklist, missing jti, MFA cross-context token rejection, OTP cooldown)
334
440
 
335
441
  **Security audits**
442
+
336
443
  - Password & crypto audit — scrypt parameters, AES-256-GCM, recovery code hashing, opaque refresh tokens, `crypto.timingSafeEqual` (PASS)
337
444
  - Token & session audit — refresh rotation grace window, blacklist, HttpOnly+SameSite cookies, algorithm pinning HS256, SHA-256 Redis keys (PASS)
338
445
  - Anti-enumeration & brute-force audit — per-tenant identifier (fixed prefix-collision in identifier separator), rate limiting on 15 sensitive endpoints, generic error responses, PII masking, TOTP anti-replay, OTP attempt limit, hook header sanitization
339
446
 
340
447
  **Documentation**
448
+
341
449
  - README.md — install, configuration, IUserRepository + IEmailProvider reference implementations with XSS warning, endpoints table, guards/decorators table, security checklist, throttler version note
342
450
  - JSDoc completion across all public services, guards, and decorators
343
451
 
344
452
  **Test infrastructure**
453
+
345
454
  - Jest E2E config (`jest.e2e.config.ts`)
346
455
  - ioredis-mock + supertest test harness
347
456
  - Shared bootstrap helper (`test/e2e/setup.ts`) with mock repositories, email capture, and in-memory Redis
@@ -351,6 +460,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
351
460
  ### Fixed
352
461
 
353
462
  #### Phase 6 — Bug fixes
463
+
354
464
  - `auth.service.ts` brute-force identifier separator: added explicit `:` between tenantId and email to prevent prefix-collision (e.g., tenant `'abc'` + email `'x@y.com'` no longer collides with tenant `'abcx'` + email `'@y.com'`)
355
465
  - `self-or-admin.guard.ts` (during initial implementation): replaced `ForbiddenException` wrapping `AuthException` with direct `AuthException` throw for correct error response shape
356
466
  - `ws-jwt.guard.ts` (during initial implementation): replaced `require.resolve` with dynamic `await import()` for ESM compatibility
@@ -363,7 +473,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
363
473
  - **Brute-force counter namespacing** — MFA challenge and disable endpoints use HMAC identifiers prefixed with `challenge:` and `disable:` respectively, preventing a pre-auth attacker from exhausting the disable counter via the public challenge endpoint
364
474
  - **`verifyAndEnable` re-entry guard** — added `MFA_ALREADY_ENABLED` check at entry so that a stale Redis setup key from a previous attempt cannot overwrite an active MFA secret and recovery codes
365
475
  - **`disable()` context-awareness** — the disable flow now accepts a `context` parameter (`'dashboard'` | `'platform'`) and dispatches to the correct repository, preventing platform admins from receiving `TOKEN_INVALID` when attempting to disable MFA
366
- - **HMAC keying for composite Redis keys** — all `sha256(tenantId + email)` call sites replaced with `hmacSha256(..., jwt.secret)` to prevent rainbow-table reversal of email addresses stored as Redis key segments
476
+ - **HMAC keying for composite Redis keys** — all `sha256(tenantId + email)` call sites replaced with `hmacSha256(..., jwt.secret)` to prevent rainbow-table reversal of email addresses stored as Redis key segments
367
477
  - **Atomic resend cooldown** — GET+SET TOCTOU race in `resendVerificationEmail` replaced with atomic `SET NX EX` (`setnx`) preventing duplicate OTP sends under concurrent requests
368
478
  - **Immutable DTO merging** — `Object.assign(dto, hookResult.modifiedData)` replaced with `dto = { ...dto, ...modifiedData }` preventing mutation of the class-validator–validated DTO and bypassing decorator constraints
369
479
  - **`secureCookies` resolved at startup** — `process.env.NODE_ENV === 'production'` check moved from per-request code inside `TokenDeliveryService` to `resolveOptions()`, eliminating an environment-variable read inside library service methods
@@ -142,6 +142,7 @@ function resolveOptions(userOptions) {
142
142
  validatePasswordResetOtpLength(userOptions.passwordReset);
143
143
  validatePasswordCostFactor(userOptions.password);
144
144
  validateOAuthProviders(userOptions.oauth);
145
+ validateOAuthSuccessRedirectUrl(userOptions);
145
146
  validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
146
147
  validateRefreshGraceWindow(userOptions.jwt);
147
148
  const { mfa: _mfa, ...userOptionsWithoutMfa } = userOptions;
@@ -304,7 +305,9 @@ var REQUIRED_OAUTH_FIELDS = [
304
305
  ];
305
306
  function validateOAuthProviders(oauth) {
306
307
  if (!oauth) return;
307
- for (const [provider, rawConfig] of Object.entries(oauth)) {
308
+ for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
309
+ if (providerOrField === "successRedirectUrl") continue;
310
+ const provider = providerOrField;
308
311
  const config = rawConfig;
309
312
  for (const field of REQUIRED_OAUTH_FIELDS) {
310
313
  if (!config[field]) {
@@ -318,6 +321,22 @@ function validateOAuthProviders(oauth) {
318
321
  }
319
322
  }
320
323
  __name(validateOAuthProviders, "validateOAuthProviders");
324
+ function validateOAuthSuccessRedirectUrl(userOptions) {
325
+ const url = userOptions.oauth?.successRedirectUrl;
326
+ if (url === void 0) return;
327
+ if (typeof url !== "string" || url.length === 0) {
328
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must be a non-empty string when set.`);
329
+ }
330
+ const isProduction = process.env["NODE_ENV"] === "production";
331
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
332
+ if (isProduction && !isSafe) {
333
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
334
+ }
335
+ if (userOptions.tokenDelivery === "bearer") {
336
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl is set but tokenDelivery is 'bearer'. A redirect discards the JSON response body, so the access token would never reach the client. Use tokenDelivery: 'cookie' or 'both' when configuring a successRedirectUrl.`);
337
+ }
338
+ }
339
+ __name(validateOAuthSuccessRedirectUrl, "validateOAuthSuccessRedirectUrl");
321
340
  function validateRefreshCookiePath(routePrefix, cookies) {
322
341
  const prefix = routePrefix ?? DEFAULT_OPTIONS.routePrefix;
323
342
  if (prefix !== "auth" && !cookies?.refreshCookiePath) {
@@ -7152,6 +7171,38 @@ var OAuthCallbackQueryDto = class {
7152
7171
  * 128 is a generous upper bound for future provider variations.
7153
7172
  */
7154
7173
  state;
7174
+ /**
7175
+ * OIDC issuer identifier (RFC 9207). Echoed back by providers that advertise
7176
+ * their issuer in the discovery document — Google currently sends
7177
+ * `https://accounts.google.com`. Accepted but unused; the service derives
7178
+ * the provider from the URL path, not from this field.
7179
+ */
7180
+ iss;
7181
+ /**
7182
+ * Space-delimited list of scopes actually granted by the user, per RFC 6749
7183
+ * §3.3. The lib does not enforce minimum scopes here — the profile fetch
7184
+ * surfaces missing data via the `IUserRepository` mapping instead.
7185
+ */
7186
+ scope;
7187
+ /**
7188
+ * Google Account-chooser index (`0`, `1`, …). Identifies which of the
7189
+ * signed-in Google accounts in the user's browser authorised the request.
7190
+ * Accepted as a generic string to stay agnostic of Google-specific shape.
7191
+ */
7192
+ authuser;
7193
+ /**
7194
+ * Prompt that was shown to the user (`none`, `consent`, `select_account`,
7195
+ * or any combination thereof). Sent back by Google so SPAs can react to a
7196
+ * forced re-consent. Validation here is shape-only — semantics are the
7197
+ * provider's concern.
7198
+ */
7199
+ prompt;
7200
+ /**
7201
+ * Hosted-domain hint sent by Google Workspace — the email's domain when the
7202
+ * authorising account belongs to a managed organisation (e.g. `example.com`).
7203
+ * Useful for consumer apps that gate features by tenant; unused by the lib.
7204
+ */
7205
+ hd;
7155
7206
  };
7156
7207
  _ts_decorate41([
7157
7208
  classValidator.IsString(),
@@ -7165,6 +7216,36 @@ _ts_decorate41([
7165
7216
  classValidator.MaxLength(128),
7166
7217
  _ts_metadata40("design:type", String)
7167
7218
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
7219
+ _ts_decorate41([
7220
+ classValidator.IsOptional(),
7221
+ classValidator.IsString(),
7222
+ classValidator.MaxLength(512),
7223
+ _ts_metadata40("design:type", String)
7224
+ ], OAuthCallbackQueryDto.prototype, "iss", void 0);
7225
+ _ts_decorate41([
7226
+ classValidator.IsOptional(),
7227
+ classValidator.IsString(),
7228
+ classValidator.MaxLength(2048),
7229
+ _ts_metadata40("design:type", String)
7230
+ ], OAuthCallbackQueryDto.prototype, "scope", void 0);
7231
+ _ts_decorate41([
7232
+ classValidator.IsOptional(),
7233
+ classValidator.IsString(),
7234
+ classValidator.MaxLength(16),
7235
+ _ts_metadata40("design:type", String)
7236
+ ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
7237
+ _ts_decorate41([
7238
+ classValidator.IsOptional(),
7239
+ classValidator.IsString(),
7240
+ classValidator.MaxLength(64),
7241
+ _ts_metadata40("design:type", String)
7242
+ ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
7243
+ _ts_decorate41([
7244
+ classValidator.IsOptional(),
7245
+ classValidator.IsString(),
7246
+ classValidator.MaxLength(253),
7247
+ _ts_metadata40("design:type", String)
7248
+ ], OAuthCallbackQueryDto.prototype, "hd", void 0);
7168
7249
  function _ts_decorate42(decorators, target, key, desc) {
7169
7250
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7170
7251
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -7223,9 +7304,11 @@ var OAuthController = class {
7223
7304
  }
7224
7305
  oauthService;
7225
7306
  tokenDelivery;
7226
- constructor(oauthService, tokenDelivery) {
7307
+ options;
7308
+ constructor(oauthService, tokenDelivery, options) {
7227
7309
  this.oauthService = oauthService;
7228
7310
  this.tokenDelivery = tokenDelivery;
7311
+ this.options = options;
7229
7312
  }
7230
7313
  // ---------------------------------------------------------------------------
7231
7314
  // GET /oauth/:provider
@@ -7259,17 +7342,30 @@ var OAuthController = class {
7259
7342
  * or oversized values are rejected before reaching the service layer or the
7260
7343
  * token-exchange HTTP call.
7261
7344
  *
7345
+ * If `oauth.successRedirectUrl` is configured, the response is a `302` redirect
7346
+ * to that URL with cookies already set in the same response. This is the
7347
+ * standard browser OAuth flow — without it the browser lands on the JSON
7348
+ * payload returned to API consumers. The redirect is issued by calling
7349
+ * `res.redirect()` and returning `undefined`, which Nest passes through
7350
+ * unchanged (passthrough mode is active).
7351
+ *
7262
7352
  * @param provider - Provider name from the URL path (e.g. `'google'`).
7263
7353
  * @param query - Validated query parameters (contains `code` and `state`).
7264
7354
  * @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
7265
- * @param res - Express response in passthrough mode (used for cookie delivery).
7266
- * @returns Auth response shaped by the configured `tokenDelivery` mode.
7355
+ * @param res - Express response in passthrough mode (used for cookie delivery and the optional redirect).
7356
+ * @returns The auth response shaped by `tokenDelivery`, or `undefined` when a `successRedirectUrl` redirect was issued.
7267
7357
  */
7268
7358
  async callback(provider, query, req, res) {
7269
7359
  const ip = (req.ip ?? "").slice(0, 64);
7270
7360
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
7271
7361
  const result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7272
- return this.tokenDelivery.deliverAuthResponse(res, result, req);
7362
+ const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
7363
+ const redirectUrl = this.options.oauth?.successRedirectUrl;
7364
+ if (redirectUrl !== void 0) {
7365
+ res.redirect(redirectUrl);
7366
+ return void 0;
7367
+ }
7368
+ return body;
7273
7369
  }
7274
7370
  };
7275
7371
  _ts_decorate43([
@@ -7316,10 +7412,12 @@ OAuthController = _ts_decorate43([
7316
7412
  forbidNonWhitelisted: true,
7317
7413
  forbidUnknownValues: true
7318
7414
  })),
7415
+ _ts_param24(2, common.Inject(BYMAX_AUTH_OPTIONS)),
7319
7416
  _ts_metadata42("design:type", Function),
7320
7417
  _ts_metadata42("design:paramtypes", [
7321
7418
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
7322
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
7419
+ typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
7420
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
7323
7421
  ])
7324
7422
  ], OAuthController);
7325
7423
 
@@ -626,6 +626,32 @@ interface BymaxAuthModuleOptions {
626
626
  * Each provider block is optional — only configured providers are registered.
627
627
  */
628
628
  oauth?: {
629
+ /**
630
+ * URL the browser is redirected to after a successful OAuth callback.
631
+ *
632
+ * When set, the OAuth callback endpoint issues a `302` to this URL after
633
+ * delivering tokens (cookies are still set via the same response). When
634
+ * omitted, the callback returns a JSON body — appropriate for API/SPA
635
+ * consumers that XHR/fetch the callback URL, but it leaves browser users
636
+ * staring at a JSON page. Set this for any consumer where the OAuth flow
637
+ * is initiated by a full-page browser navigation.
638
+ *
639
+ * Requires `tokenDelivery: 'cookie'` or `'both'` — bearer-only delivery is
640
+ * incompatible with a redirect because the access token would be discarded
641
+ * in the redirect response body. The module throws at startup if the
642
+ * combination is misconfigured.
643
+ *
644
+ * In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
645
+ * be a relative path (starts with `/`) — same posture as `callbackUrl`.
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * successRedirectUrl: 'https://app.example.com/dashboard'
650
+ * // or, for same-origin deployments:
651
+ * successRedirectUrl: '/dashboard'
652
+ * ```
653
+ */
654
+ successRedirectUrl?: string;
629
655
  /**
630
656
  * Google OAuth 2.0 configuration.
631
657
  * All three fields are required to enable Google login.
@@ -626,6 +626,32 @@ interface BymaxAuthModuleOptions {
626
626
  * Each provider block is optional — only configured providers are registered.
627
627
  */
628
628
  oauth?: {
629
+ /**
630
+ * URL the browser is redirected to after a successful OAuth callback.
631
+ *
632
+ * When set, the OAuth callback endpoint issues a `302` to this URL after
633
+ * delivering tokens (cookies are still set via the same response). When
634
+ * omitted, the callback returns a JSON body — appropriate for API/SPA
635
+ * consumers that XHR/fetch the callback URL, but it leaves browser users
636
+ * staring at a JSON page. Set this for any consumer where the OAuth flow
637
+ * is initiated by a full-page browser navigation.
638
+ *
639
+ * Requires `tokenDelivery: 'cookie'` or `'both'` — bearer-only delivery is
640
+ * incompatible with a redirect because the access token would be discarded
641
+ * in the redirect response body. The module throws at startup if the
642
+ * combination is misconfigured.
643
+ *
644
+ * In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
645
+ * be a relative path (starts with `/`) — same posture as `callbackUrl`.
646
+ *
647
+ * @example
648
+ * ```typescript
649
+ * successRedirectUrl: 'https://app.example.com/dashboard'
650
+ * // or, for same-origin deployments:
651
+ * successRedirectUrl: '/dashboard'
652
+ * ```
653
+ */
654
+ successRedirectUrl?: string;
629
655
  /**
630
656
  * Google OAuth 2.0 configuration.
631
657
  * All three fields are required to enable Google login.
@@ -140,6 +140,7 @@ function resolveOptions(userOptions) {
140
140
  validatePasswordResetOtpLength(userOptions.passwordReset);
141
141
  validatePasswordCostFactor(userOptions.password);
142
142
  validateOAuthProviders(userOptions.oauth);
143
+ validateOAuthSuccessRedirectUrl(userOptions);
143
144
  validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
144
145
  validateRefreshGraceWindow(userOptions.jwt);
145
146
  const { mfa: _mfa, ...userOptionsWithoutMfa } = userOptions;
@@ -302,7 +303,9 @@ var REQUIRED_OAUTH_FIELDS = [
302
303
  ];
303
304
  function validateOAuthProviders(oauth) {
304
305
  if (!oauth) return;
305
- for (const [provider, rawConfig] of Object.entries(oauth)) {
306
+ for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
307
+ if (providerOrField === "successRedirectUrl") continue;
308
+ const provider = providerOrField;
306
309
  const config = rawConfig;
307
310
  for (const field of REQUIRED_OAUTH_FIELDS) {
308
311
  if (!config[field]) {
@@ -316,6 +319,22 @@ function validateOAuthProviders(oauth) {
316
319
  }
317
320
  }
318
321
  __name(validateOAuthProviders, "validateOAuthProviders");
322
+ function validateOAuthSuccessRedirectUrl(userOptions) {
323
+ const url = userOptions.oauth?.successRedirectUrl;
324
+ if (url === void 0) return;
325
+ if (typeof url !== "string" || url.length === 0) {
326
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must be a non-empty string when set.`);
327
+ }
328
+ const isProduction = process.env["NODE_ENV"] === "production";
329
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
330
+ if (isProduction && !isSafe) {
331
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
332
+ }
333
+ if (userOptions.tokenDelivery === "bearer") {
334
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl is set but tokenDelivery is 'bearer'. A redirect discards the JSON response body, so the access token would never reach the client. Use tokenDelivery: 'cookie' or 'both' when configuring a successRedirectUrl.`);
335
+ }
336
+ }
337
+ __name(validateOAuthSuccessRedirectUrl, "validateOAuthSuccessRedirectUrl");
319
338
  function validateRefreshCookiePath(routePrefix, cookies) {
320
339
  const prefix = routePrefix ?? DEFAULT_OPTIONS.routePrefix;
321
340
  if (prefix !== "auth" && !cookies?.refreshCookiePath) {
@@ -7150,6 +7169,38 @@ var OAuthCallbackQueryDto = class {
7150
7169
  * 128 is a generous upper bound for future provider variations.
7151
7170
  */
7152
7171
  state;
7172
+ /**
7173
+ * OIDC issuer identifier (RFC 9207). Echoed back by providers that advertise
7174
+ * their issuer in the discovery document — Google currently sends
7175
+ * `https://accounts.google.com`. Accepted but unused; the service derives
7176
+ * the provider from the URL path, not from this field.
7177
+ */
7178
+ iss;
7179
+ /**
7180
+ * Space-delimited list of scopes actually granted by the user, per RFC 6749
7181
+ * §3.3. The lib does not enforce minimum scopes here — the profile fetch
7182
+ * surfaces missing data via the `IUserRepository` mapping instead.
7183
+ */
7184
+ scope;
7185
+ /**
7186
+ * Google Account-chooser index (`0`, `1`, …). Identifies which of the
7187
+ * signed-in Google accounts in the user's browser authorised the request.
7188
+ * Accepted as a generic string to stay agnostic of Google-specific shape.
7189
+ */
7190
+ authuser;
7191
+ /**
7192
+ * Prompt that was shown to the user (`none`, `consent`, `select_account`,
7193
+ * or any combination thereof). Sent back by Google so SPAs can react to a
7194
+ * forced re-consent. Validation here is shape-only — semantics are the
7195
+ * provider's concern.
7196
+ */
7197
+ prompt;
7198
+ /**
7199
+ * Hosted-domain hint sent by Google Workspace — the email's domain when the
7200
+ * authorising account belongs to a managed organisation (e.g. `example.com`).
7201
+ * Useful for consumer apps that gate features by tenant; unused by the lib.
7202
+ */
7203
+ hd;
7153
7204
  };
7154
7205
  _ts_decorate41([
7155
7206
  IsString(),
@@ -7163,6 +7214,36 @@ _ts_decorate41([
7163
7214
  MaxLength(128),
7164
7215
  _ts_metadata40("design:type", String)
7165
7216
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
7217
+ _ts_decorate41([
7218
+ IsOptional(),
7219
+ IsString(),
7220
+ MaxLength(512),
7221
+ _ts_metadata40("design:type", String)
7222
+ ], OAuthCallbackQueryDto.prototype, "iss", void 0);
7223
+ _ts_decorate41([
7224
+ IsOptional(),
7225
+ IsString(),
7226
+ MaxLength(2048),
7227
+ _ts_metadata40("design:type", String)
7228
+ ], OAuthCallbackQueryDto.prototype, "scope", void 0);
7229
+ _ts_decorate41([
7230
+ IsOptional(),
7231
+ IsString(),
7232
+ MaxLength(16),
7233
+ _ts_metadata40("design:type", String)
7234
+ ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
7235
+ _ts_decorate41([
7236
+ IsOptional(),
7237
+ IsString(),
7238
+ MaxLength(64),
7239
+ _ts_metadata40("design:type", String)
7240
+ ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
7241
+ _ts_decorate41([
7242
+ IsOptional(),
7243
+ IsString(),
7244
+ MaxLength(253),
7245
+ _ts_metadata40("design:type", String)
7246
+ ], OAuthCallbackQueryDto.prototype, "hd", void 0);
7166
7247
  function _ts_decorate42(decorators, target, key, desc) {
7167
7248
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7168
7249
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -7221,9 +7302,11 @@ var OAuthController = class {
7221
7302
  }
7222
7303
  oauthService;
7223
7304
  tokenDelivery;
7224
- constructor(oauthService, tokenDelivery) {
7305
+ options;
7306
+ constructor(oauthService, tokenDelivery, options) {
7225
7307
  this.oauthService = oauthService;
7226
7308
  this.tokenDelivery = tokenDelivery;
7309
+ this.options = options;
7227
7310
  }
7228
7311
  // ---------------------------------------------------------------------------
7229
7312
  // GET /oauth/:provider
@@ -7257,17 +7340,30 @@ var OAuthController = class {
7257
7340
  * or oversized values are rejected before reaching the service layer or the
7258
7341
  * token-exchange HTTP call.
7259
7342
  *
7343
+ * If `oauth.successRedirectUrl` is configured, the response is a `302` redirect
7344
+ * to that URL with cookies already set in the same response. This is the
7345
+ * standard browser OAuth flow — without it the browser lands on the JSON
7346
+ * payload returned to API consumers. The redirect is issued by calling
7347
+ * `res.redirect()` and returning `undefined`, which Nest passes through
7348
+ * unchanged (passthrough mode is active).
7349
+ *
7260
7350
  * @param provider - Provider name from the URL path (e.g. `'google'`).
7261
7351
  * @param query - Validated query parameters (contains `code` and `state`).
7262
7352
  * @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
7263
- * @param res - Express response in passthrough mode (used for cookie delivery).
7264
- * @returns Auth response shaped by the configured `tokenDelivery` mode.
7353
+ * @param res - Express response in passthrough mode (used for cookie delivery and the optional redirect).
7354
+ * @returns The auth response shaped by `tokenDelivery`, or `undefined` when a `successRedirectUrl` redirect was issued.
7265
7355
  */
7266
7356
  async callback(provider, query, req, res) {
7267
7357
  const ip = (req.ip ?? "").slice(0, 64);
7268
7358
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
7269
7359
  const result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7270
- return this.tokenDelivery.deliverAuthResponse(res, result, req);
7360
+ const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
7361
+ const redirectUrl = this.options.oauth?.successRedirectUrl;
7362
+ if (redirectUrl !== void 0) {
7363
+ res.redirect(redirectUrl);
7364
+ return void 0;
7365
+ }
7366
+ return body;
7271
7367
  }
7272
7368
  };
7273
7369
  _ts_decorate43([
@@ -7314,10 +7410,12 @@ OAuthController = _ts_decorate43([
7314
7410
  forbidNonWhitelisted: true,
7315
7411
  forbidUnknownValues: true
7316
7412
  })),
7413
+ _ts_param24(2, Inject(BYMAX_AUTH_OPTIONS)),
7317
7414
  _ts_metadata42("design:type", Function),
7318
7415
  _ts_metadata42("design:paramtypes", [
7319
7416
  typeof OAuthService === "undefined" ? Object : OAuthService,
7320
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
7417
+ typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
7418
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
7321
7419
  ])
7322
7420
  ], OAuthController);
7323
7421
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Full-stack authentication and authorization package for NestJS, React and Next.js — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",