@bymax-one/nest-auth 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.3] - 2026-05-25
11
+
12
+ ### Fixed
13
+
14
+ - **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.
15
+
16
+ ### Tests — E2E coverage (audit-driven, surface gaps closed)
17
+
18
+ A systematic audit of `test/e2e/` against the lib's HTTP surface identified
19
+ several uncovered scenarios. Each new spec exercises real routes via supertest
20
+ against a fully-bootstrapped NestJS app — no controller methods are called
21
+ directly, no network is touched (Google OAuth + email + Redis are mocked).
22
+ The full e2e count goes from **9 suites / 59 tests** to **14 suites / 89 tests**.
23
+
24
+ - **[`test/e2e/platform-auth-flow.e2e-spec.ts`](test/e2e/platform-auth-flow.e2e-spec.ts)** — closes
25
+ the entire platform admin HTTP surface (previously zero e2e coverage):
26
+ `/platform/login`, `/platform/me`, `/platform/refresh`, `/platform/logout`,
27
+ `DELETE /platform/sessions`, plus cross-context rejection (dashboard token →
28
+ `/platform/me` returns 401, and platform token → `/me` returns 401).
29
+ - **[`test/e2e/mfa-disable-flow.e2e-spec.ts`](test/e2e/mfa-disable-flow.e2e-spec.ts)** — closes
30
+ the MFA lifecycle's final transition. Asserts `/mfa/disable` returns 204
31
+ with a valid TOTP, flips `mfaEnabled` to false on the persisted user,
32
+ restores the no-challenge login path, and rejects with `MFA_INVALID_CODE` /
33
+ `MFA_NOT_ENABLED` on the negative paths.
34
+ - **[`test/e2e/email-verification-flow.e2e-spec.ts`](test/e2e/email-verification-flow.e2e-spec.ts)** —
35
+ closes `/verify-email` + `/resend-verification` (both previously untouched
36
+ by e2e). Verifies the OTP-driven happy path, OTP_INVALID rejection, fresh
37
+ OTP dispatch on resend, and anti-enumeration responses for unknown +
38
+ already-verified emails.
39
+ - **[`test/e2e/negative-paths.e2e-spec.ts`](test/e2e/negative-paths.e2e-spec.ts)** — bundles
40
+ eight negative-path scenarios that were silent gaps: unknown invitation
41
+ token, single-use invitation replay, foreign-user session revoke (auth-
42
+ bypass class), `DELETE /sessions/all` without a refresh token, unknown
43
+ password-reset token, wrong reset OTP, unknown OAuth provider, OAuth init
44
+ without `tenantId`.
45
+ - **[`test/e2e/hooks-lifecycle.e2e-spec.ts`](test/e2e/hooks-lifecycle.e2e-spec.ts)** — replaces
46
+ the implicit "if it works, the hook fired" assumption with explicit spy
47
+ assertions on `beforeRegister`, `afterRegister`, `beforeLogin`, `afterLogin`,
48
+ `afterLogout`, `afterMfaEnabled`, `afterEmailVerified`, and
49
+ `afterPasswordReset`. Each hook is verified to receive a `HookContext`
50
+ carrying `ip`, `userAgent`, and sanitized headers — a regression that drops
51
+ any single dispatch would fail the corresponding scenario.
52
+
53
+ ### Tests — Helpers
54
+
55
+ - **`MockPlatformUserRepository.seed(user)`** ([`test/e2e/setup.ts`](test/e2e/setup.ts)) — exposes
56
+ a deterministic seed entry-point that populates both the user map AND the
57
+ internal `emailIndex` so `findByEmail` resolves the row. Required for the
58
+ platform spec; useful for any future test that needs pre-existing platform
59
+ admins (the lib intentionally ships no `createPlatformUser` endpoint).
60
+
10
61
  ## [1.0.2] - 2026-05-25
11
62
 
12
63
  ### Security
@@ -39,6 +90,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
39
90
  ### Added
40
91
 
41
92
  **Next.js subpath (`@bymax-one/nest-auth/nextjs`)**
93
+
42
94
  - `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
95
  - **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
96
  - **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 +104,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
52
104
  - **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
105
 
54
106
  **React subpath (`@bymax-one/nest-auth/react`)**
107
+
55
108
  - `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
109
  - `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
110
  - `useSession()` — reactive snapshot: `{ user, status, isLoading, refresh, lastValidation }` read from context (the `refresh` method triggers an ad-hoc revalidation).
@@ -59,11 +112,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
59
112
  - `AuthContext`, `AuthContextValue`, `AuthStatus`, `AuthProviderProps` types exported from the subpath barrel.
60
113
 
61
114
  **Client subpath (`@bymax-one/nest-auth/client`)**
115
+
62
116
  - `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
117
  - `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
118
  - `AuthFetch`, `AuthFetchConfig`, `AuthClient`, `AuthClientConfig`, `LoginInput`, `RegisterInput`, `ResetPasswordInput` types exported from the subpath barrel
65
119
 
66
120
  **Shared subpath (`@bymax-one/nest-auth/shared`)**
121
+
67
122
  - `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
123
  - `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
124
 
@@ -103,6 +158,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
103
158
  #### Phase 1 — Foundation and Infrastructure (NEST-001 to NEST-042)
104
159
 
105
160
  **Scaffold and tooling**
161
+
106
162
  - `package.json` with scope `@bymax-one`, peer dependencies (NestJS 11, ioredis, class-validator), zero direct runtime dependencies
107
163
  - `tsconfig.json` and `tsconfig.build.json` with `strict: true`, ES2022 target, decorator support
108
164
  - `tsconfig.jest.json` for ts-jest compilation
@@ -114,6 +170,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
114
170
  - MIT License, `.gitignore`, `AGENTS.md`, `CLAUDE.md`
115
171
 
116
172
  **Interfaces**
173
+
117
174
  - `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
175
  - `AuthUser` and `SafeAuthUser` — user entity interfaces (15 fields) with credential-free safe variant
119
176
  - `IUserRepository` — data access interface with 11 methods (findById, findByEmail, create, updatePassword, updateMfa, updateLastLogin, updateStatus, updateEmailVerified, findByOAuthId, linkOAuth, createWithOAuth)
@@ -129,37 +186,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
129
186
  - `OAuthProfile` and `OAuthLoginResult` — OAuth profile and hook result types
130
187
 
131
188
  **Constants and configuration**
189
+
132
190
  - 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
191
  - `DEFAULT_OPTIONS` — all default values (jwt.accessExpiresIn `'15m'`, refreshExpiresInDays `7`, tokenDelivery `'cookie'`, bruteForce 5 attempts / 900s window, etc.)
134
192
  - `resolveOptions()` — startup function that merges consumer options with defaults, validates all security invariants, and produces `ResolvedOptions` with no optional fields
135
193
  - Throttle configurations (`THROTTLE_CONFIGS`) per endpoint category
136
194
 
137
195
  **Crypto utilities** (`src/server/crypto/`)
196
+
138
197
  - `sha256(input)` — deterministic SHA-256 hex digest via `node:crypto`
139
198
  - `hmacSha256(input, secret)` — keyed HMAC-SHA256 hex digest for low-entropy inputs (composite keys with email addresses)
140
199
  - `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
200
  - `generateSecureToken()` — cryptographically random opaque token via `node:crypto.randomBytes`
142
201
 
143
202
  **Error handling** (`src/server/errors/`)
203
+
144
204
  - `AUTH_ERROR_CODES` — typed string union of all 30+ error codes with Portuguese end-user messages
145
205
  - `AuthException` — NestJS `HttpException` subclass carrying structured `{ code, message, details? }` response body
146
206
 
147
207
  **Redis layer** (`src/server/redis/`)
208
+
148
209
  - `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
210
  - `AuthRedisModule` — internal NestJS module registering `AuthRedisService`
150
211
 
151
212
  **Services** (`src/server/services/`)
213
+
152
214
  - `PasswordService` — scrypt-based password hashing and constant-time comparison; configurable cost factor, block size, and parallelization
153
215
  - `BruteForceService` — fixed-window rate limiting via atomic `incrWithFixedTtl` Lua script; lockout with `getRemainingLockoutSeconds`
154
216
  - `TokenManagerService` — JWT issuance (`issueTokens`, `issueMfaTempToken`), token rotation (`reissueTokens`), revocation blacklist via Redis `rv:{jti}` keys, raw refresh token storage via `rt:{sha256(token)}`
155
217
  - `TokenDeliveryService` — cookie/bearer/both delivery modes; multi-domain support via `resolveDomains` callback; `extractAccessToken`, `extractRefreshToken`, `clearAuthSession`
156
218
 
157
219
  **Utilities** (`src/server/utils/`)
220
+
158
221
  - `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
222
  - `sleep(ms)` — Promise-based delay for timing normalization in anti-enumeration flows
160
223
  - `hasRole(userRole, requiredRole, hierarchy)` — recursive role hierarchy checker supporting denormalized role trees
161
224
 
162
225
  **NoOp fallback providers**
226
+
163
227
  - `NoOpEmailProvider` — silent no-op implementation of `IEmailProvider` (registered when consumer does not supply one)
164
228
  - `NoOpAuthHooks` — silent no-op implementation of `IAuthHooks` (registered when consumer does not supply one)
165
229
 
@@ -170,28 +234,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
170
234
  #### Phase 2 — Core Authentication (NEST-043 to NEST-064)
171
235
 
172
236
  **Guards** (`src/server/guards/`)
237
+
173
238
  - `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
239
  - `RolesGuard` — hierarchical role guard using denormalized `roles.hierarchy`; reads `@Roles()` metadata via `Reflector`; throws `INSUFFICIENT_ROLE` (403) on failure
175
240
  - `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
241
  - `assertTokenType` utility — reusable guard helper that throws `TOKEN_INVALID` when the JWT `type` claim does not match the expected value
177
242
 
178
243
  **Decorators** (`src/server/decorators/`)
244
+
179
245
  - `@CurrentUser(property?)` — param decorator extracting `request.user` or a specific property from it
180
246
  - `@Roles(...roles)` — metadata decorator setting `ROLES_KEY` for `RolesGuard`
181
247
  - `@Public()` — metadata decorator setting `IS_PUBLIC_KEY` to skip `JwtAuthGuard`
182
248
 
183
249
  **DTOs** (`src/server/dto/`)
250
+
184
251
  - `RegisterDto` — `email`, `password` (8–128 chars), `name` (2+ chars), `tenantId`; all with class-validator decorators
185
252
  - `LoginDto` — `email`, `password` (no `@MinLength` — deliberate anti-enumeration), `tenantId`
186
253
 
187
254
  **Services** (`src/server/services/`)
255
+
188
256
  - `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
257
  - `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
258
 
191
259
  **Controllers** (`src/server/controllers/`)
260
+
192
261
  - `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
262
 
194
263
  **Module**
264
+
195
265
  - `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
266
 
197
267
  **Phase 2 barrel export** — adds `BymaxAuthModule`, `AuthService`, `JwtAuthGuard`, `RolesGuard`, `UserStatusGuard`, `CurrentUser`, `Roles`, `ROLES_KEY`, `Public`, `IS_PUBLIC_KEY`, `RegisterDto`, `LoginDto`
@@ -201,6 +271,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
201
271
  #### Phase 3 — Multi-Factor Authentication (TOTP)
202
272
 
203
273
  **Crypto utilities** (`src/server/crypto/totp.ts`)
274
+
204
275
  - `generateTotpSecret()` — generates a cryptographically random 20-byte TOTP secret via `node:crypto.randomBytes`; returns both raw `Buffer` and `base32`-encoded string
205
276
  - `buildTotpUri(secret, account, issuer)` — constructs a standard `otpauth://totp/` URI for QR code generation
206
277
  - `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 +279,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
208
279
  - `fromBase32(input)` / `toBase32(buf)` — pure Base32 encode/decode without external dependencies; `fromBase32` strips whitespace, hyphens, and padding before decoding
209
280
 
210
281
  **Services** (`src/server/services/mfa.service.ts`)
282
+
211
283
  - `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
284
  - `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
285
  - `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
286
  - `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
287
 
216
288
  **Guards** (`src/server/guards/mfa-required.guard.ts`)
289
+
217
290
  - `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
291
 
219
292
  **Decorators** (`src/server/decorators/skip-mfa.decorator.ts`)
293
+
220
294
  - `@SkipMfa()` — metadata decorator that marks an endpoint as exempt from `MfaRequiredGuard`; used on `POST /mfa/challenge` and any other pre-MFA routes
221
295
 
222
296
  **DTOs** (`src/server/dto/`)
297
+
223
298
  - `MfaChallengeDto` — `mfaTempToken` (string) + `code` (string); `@MaxLength(14)` as defence-in-depth before regex
224
299
  - `MfaVerifyDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`
225
300
  - `MfaDisableDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`; JSDoc explains why recovery codes are not accepted
226
301
 
227
302
  **Controllers** (`src/server/controllers/mfa.controller.ts`)
303
+
228
304
  - `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
305
  - `POST /mfa/verify-enable` — submits the first TOTP code to permanently activate MFA; returns 204 No Content
230
306
  - `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
307
  - `POST /mfa/disable` — disables MFA for dashboard or platform users; derived `context` from `user.type` JWT claim; returns 204 No Content
232
308
 
233
309
  **Redis additions** (`src/server/redis/auth-redis.service.ts`)
310
+
234
311
  - `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
312
  - `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
313
 
237
314
  **Module integration** (`src/server/bymax-auth.module.ts`)
315
+
238
316
  - `controllers.mfa: true` option conditionally registers `MfaController`; startup validation throws if `controllers.mfa: true` is set without the `mfa` configuration group
239
317
 
240
318
  ---
@@ -242,24 +320,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
242
320
  #### Phase 4 — Sessions & Password Reset
243
321
 
244
322
  **Services** (`src/server/services/`)
323
+
245
324
  - `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
325
  - `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
326
 
248
327
  **Controllers** (`src/server/controllers/`)
328
+
249
329
  - `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
330
  - `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
331
 
252
332
  **DTOs** (`src/server/dto/`)
333
+
253
334
  - `ForgotPasswordDto` — `email` (normalized lowercase) + `tenantId`
254
335
  - `ResetPasswordDto` — `email`, `newPassword` (8–128 chars), exactly one of `token` / `otp` / `verifiedToken`, `tenantId`
255
336
  - `VerifyOtpDto` — `email`, `otp` (4–8 chars), `tenantId`
256
337
  - `ResendOtpDto` — `email` + `tenantId`
257
338
 
258
339
  **Configuration** (`BymaxAuthModuleOptions`)
340
+
259
341
  - `sessions.enabled`, `sessions.defaultMaxSessions` (default 5), `sessions.maxSessionsResolver`, `sessions.evictionStrategy` (`'fifo'`)
260
342
  - `passwordReset.method` (`'token'` | `'otp'`, default `'token'`), `passwordReset.tokenTtlSeconds` (default 3600), `passwordReset.otpTtlSeconds` (default 600), `passwordReset.otpLength` (default 6)
261
343
 
262
344
  **Module integration** (`src/server/bymax-auth.module.ts`)
345
+
263
346
  - `controllers.sessions: true` opt-in gate with startup cross-validation: throws if `sessions.enabled` is not `true` in the factory return value
264
347
  - `controllers.passwordReset` opt-out gate (enabled by default); `PasswordResetService` only registered when controller is active
265
348
  - `SessionService` always registered unconditionally — `AuthService.login()` and `AuthService.refresh()` call session methods regardless of whether the sessions controller is exposed
@@ -271,23 +354,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
271
354
  #### Phase 5 — Platform Authentication, OAuth & Invitations
272
355
 
273
356
  **Services**
357
+
274
358
  - `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
359
  - `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
360
  - `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
361
 
278
362
  **Guards** (`src/server/guards/`)
363
+
279
364
  - `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
365
  - `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
366
 
282
367
  **Decorators** (`src/server/decorators/`)
368
+
283
369
  - `@PlatformRoles(...roles)` — metadata decorator under `PLATFORM_ROLES_KEY` symbol; declares required platform role(s) for a route handler
284
370
 
285
371
  **Controllers**
372
+
286
373
  - `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
374
  - `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
375
  - `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
376
 
290
377
  **DTOs** (`src/server/dto/`)
378
+
291
379
  - `PlatformLoginDto` — `email` (normalized lowercase) + `password` (12–128 chars)
292
380
  - `CreateInvitationDto` — `email`, `role`, optional `tenantName` (max 128 chars)
293
381
  - `AcceptInvitationDto` — `token` (exactly 64 hex chars), `name` (2–100 chars), `password` (8–128 chars)
@@ -295,16 +383,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
295
383
  - `OAuthCallbackQueryDto` — `code` (32–2048 chars), `state` (max 128 chars)
296
384
 
297
385
  **OAuth module** (`src/server/oauth/`)
386
+
298
387
  - `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
388
  - `OAUTH_PLUGINS` — Symbol injection token for the `OAuthProviderPlugin[]` array; internal to the library (not exported in public API)
300
389
 
301
390
  **Configuration** (`BymaxAuthModuleOptions`)
391
+
302
392
  - `platform.enabled` (default `false`); requires `roles.platformHierarchy`
303
393
  - `oauth.google` — `clientId`, `clientSecret`, `callbackUrl` (required), `scope` (optional, default `['openid', 'email', 'profile']`)
304
394
  - `invitations.enabled` (default `false`), `invitations.tokenTtlSeconds` (default 172800 — 48 hours)
305
395
  - `roles.platformHierarchy` — required when `platform.enabled: true`
306
396
 
307
397
  **Module integration** (`src/server/bymax-auth.module.ts`)
398
+
308
399
  - `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
400
  - `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
401
  - `controllers.invitations: true` opt-in gate with startup cross-validation: requires `invitations.enabled: true`
@@ -317,11 +408,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
317
408
  #### Phase 6 — Integration, Polish, and Publication (NEST-122 to NEST-151)
318
409
 
319
410
  **Additional guards** (3)
411
+
320
412
  - `WsJwtGuard` — WebSocket dashboard JWT guard (header-only, soft peer-dep on `@nestjs/websockets`, runtime check via dynamic import)
321
413
  - `SelfOrAdminGuard` — self-access or admin override with strict SHA-256 session-hash validation; documents multi-tenant ownership limitation
322
414
  - `OptionalAuthGuard` — extends `JwtAuthGuard`, allows unauthenticated access while validating tokens when present
323
415
 
324
416
  **E2E test suite** (`test/e2e/`)
417
+
325
418
  - Full auth flow (bearer + cookie modes)
326
419
  - MFA flow (setup, verify, challenge with TOTP and recovery codes)
327
420
  - Sessions flow (3-device login, list, revoke single, revoke all-except-current)
@@ -333,15 +426,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
333
426
  - Security scenarios (brute-force lockout, blacklist, missing jti, MFA cross-context token rejection, OTP cooldown)
334
427
 
335
428
  **Security audits**
429
+
336
430
  - Password & crypto audit — scrypt parameters, AES-256-GCM, recovery code hashing, opaque refresh tokens, `crypto.timingSafeEqual` (PASS)
337
431
  - Token & session audit — refresh rotation grace window, blacklist, HttpOnly+SameSite cookies, algorithm pinning HS256, SHA-256 Redis keys (PASS)
338
432
  - 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
433
 
340
434
  **Documentation**
435
+
341
436
  - README.md — install, configuration, IUserRepository + IEmailProvider reference implementations with XSS warning, endpoints table, guards/decorators table, security checklist, throttler version note
342
437
  - JSDoc completion across all public services, guards, and decorators
343
438
 
344
439
  **Test infrastructure**
440
+
345
441
  - Jest E2E config (`jest.e2e.config.ts`)
346
442
  - ioredis-mock + supertest test harness
347
443
  - Shared bootstrap helper (`test/e2e/setup.ts`) with mock repositories, email capture, and in-memory Redis
@@ -351,6 +447,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
351
447
  ### Fixed
352
448
 
353
449
  #### Phase 6 — Bug fixes
450
+
354
451
  - `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
452
  - `self-or-admin.guard.ts` (during initial implementation): replaced `ForbiddenException` wrapping `AuthException` with direct `AuthException` throw for correct error response shape
356
453
  - `ws-jwt.guard.ts` (during initial implementation): replaced `require.resolve` with dynamic `await import()` for ESM compatibility
@@ -363,7 +460,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
363
460
  - **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
461
  - **`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
462
  - **`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
463
+ - **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
464
  - **Atomic resend cooldown** — GET+SET TOCTOU race in `resendVerificationEmail` replaced with atomic `SET NX EX` (`setnx`) preventing duplicate OTP sends under concurrent requests
368
465
  - **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
466
  - **`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
@@ -7152,6 +7152,38 @@ var OAuthCallbackQueryDto = class {
7152
7152
  * 128 is a generous upper bound for future provider variations.
7153
7153
  */
7154
7154
  state;
7155
+ /**
7156
+ * OIDC issuer identifier (RFC 9207). Echoed back by providers that advertise
7157
+ * their issuer in the discovery document — Google currently sends
7158
+ * `https://accounts.google.com`. Accepted but unused; the service derives
7159
+ * the provider from the URL path, not from this field.
7160
+ */
7161
+ iss;
7162
+ /**
7163
+ * Space-delimited list of scopes actually granted by the user, per RFC 6749
7164
+ * §3.3. The lib does not enforce minimum scopes here — the profile fetch
7165
+ * surfaces missing data via the `IUserRepository` mapping instead.
7166
+ */
7167
+ scope;
7168
+ /**
7169
+ * Google Account-chooser index (`0`, `1`, …). Identifies which of the
7170
+ * signed-in Google accounts in the user's browser authorised the request.
7171
+ * Accepted as a generic string to stay agnostic of Google-specific shape.
7172
+ */
7173
+ authuser;
7174
+ /**
7175
+ * Prompt that was shown to the user (`none`, `consent`, `select_account`,
7176
+ * or any combination thereof). Sent back by Google so SPAs can react to a
7177
+ * forced re-consent. Validation here is shape-only — semantics are the
7178
+ * provider's concern.
7179
+ */
7180
+ prompt;
7181
+ /**
7182
+ * Hosted-domain hint sent by Google Workspace — the email's domain when the
7183
+ * authorising account belongs to a managed organisation (e.g. `example.com`).
7184
+ * Useful for consumer apps that gate features by tenant; unused by the lib.
7185
+ */
7186
+ hd;
7155
7187
  };
7156
7188
  _ts_decorate41([
7157
7189
  classValidator.IsString(),
@@ -7165,6 +7197,36 @@ _ts_decorate41([
7165
7197
  classValidator.MaxLength(128),
7166
7198
  _ts_metadata40("design:type", String)
7167
7199
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
7200
+ _ts_decorate41([
7201
+ classValidator.IsOptional(),
7202
+ classValidator.IsString(),
7203
+ classValidator.MaxLength(512),
7204
+ _ts_metadata40("design:type", String)
7205
+ ], OAuthCallbackQueryDto.prototype, "iss", void 0);
7206
+ _ts_decorate41([
7207
+ classValidator.IsOptional(),
7208
+ classValidator.IsString(),
7209
+ classValidator.MaxLength(2048),
7210
+ _ts_metadata40("design:type", String)
7211
+ ], OAuthCallbackQueryDto.prototype, "scope", void 0);
7212
+ _ts_decorate41([
7213
+ classValidator.IsOptional(),
7214
+ classValidator.IsString(),
7215
+ classValidator.MaxLength(16),
7216
+ _ts_metadata40("design:type", String)
7217
+ ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
7218
+ _ts_decorate41([
7219
+ classValidator.IsOptional(),
7220
+ classValidator.IsString(),
7221
+ classValidator.MaxLength(64),
7222
+ _ts_metadata40("design:type", String)
7223
+ ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
7224
+ _ts_decorate41([
7225
+ classValidator.IsOptional(),
7226
+ classValidator.IsString(),
7227
+ classValidator.MaxLength(253),
7228
+ _ts_metadata40("design:type", String)
7229
+ ], OAuthCallbackQueryDto.prototype, "hd", void 0);
7168
7230
  function _ts_decorate42(decorators, target, key, desc) {
7169
7231
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7170
7232
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -7150,6 +7150,38 @@ var OAuthCallbackQueryDto = class {
7150
7150
  * 128 is a generous upper bound for future provider variations.
7151
7151
  */
7152
7152
  state;
7153
+ /**
7154
+ * OIDC issuer identifier (RFC 9207). Echoed back by providers that advertise
7155
+ * their issuer in the discovery document — Google currently sends
7156
+ * `https://accounts.google.com`. Accepted but unused; the service derives
7157
+ * the provider from the URL path, not from this field.
7158
+ */
7159
+ iss;
7160
+ /**
7161
+ * Space-delimited list of scopes actually granted by the user, per RFC 6749
7162
+ * §3.3. The lib does not enforce minimum scopes here — the profile fetch
7163
+ * surfaces missing data via the `IUserRepository` mapping instead.
7164
+ */
7165
+ scope;
7166
+ /**
7167
+ * Google Account-chooser index (`0`, `1`, …). Identifies which of the
7168
+ * signed-in Google accounts in the user's browser authorised the request.
7169
+ * Accepted as a generic string to stay agnostic of Google-specific shape.
7170
+ */
7171
+ authuser;
7172
+ /**
7173
+ * Prompt that was shown to the user (`none`, `consent`, `select_account`,
7174
+ * or any combination thereof). Sent back by Google so SPAs can react to a
7175
+ * forced re-consent. Validation here is shape-only — semantics are the
7176
+ * provider's concern.
7177
+ */
7178
+ prompt;
7179
+ /**
7180
+ * Hosted-domain hint sent by Google Workspace — the email's domain when the
7181
+ * authorising account belongs to a managed organisation (e.g. `example.com`).
7182
+ * Useful for consumer apps that gate features by tenant; unused by the lib.
7183
+ */
7184
+ hd;
7153
7185
  };
7154
7186
  _ts_decorate41([
7155
7187
  IsString(),
@@ -7163,6 +7195,36 @@ _ts_decorate41([
7163
7195
  MaxLength(128),
7164
7196
  _ts_metadata40("design:type", String)
7165
7197
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
7198
+ _ts_decorate41([
7199
+ IsOptional(),
7200
+ IsString(),
7201
+ MaxLength(512),
7202
+ _ts_metadata40("design:type", String)
7203
+ ], OAuthCallbackQueryDto.prototype, "iss", void 0);
7204
+ _ts_decorate41([
7205
+ IsOptional(),
7206
+ IsString(),
7207
+ MaxLength(2048),
7208
+ _ts_metadata40("design:type", String)
7209
+ ], OAuthCallbackQueryDto.prototype, "scope", void 0);
7210
+ _ts_decorate41([
7211
+ IsOptional(),
7212
+ IsString(),
7213
+ MaxLength(16),
7214
+ _ts_metadata40("design:type", String)
7215
+ ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
7216
+ _ts_decorate41([
7217
+ IsOptional(),
7218
+ IsString(),
7219
+ MaxLength(64),
7220
+ _ts_metadata40("design:type", String)
7221
+ ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
7222
+ _ts_decorate41([
7223
+ IsOptional(),
7224
+ IsString(),
7225
+ MaxLength(253),
7226
+ _ts_metadata40("design:type", String)
7227
+ ], OAuthCallbackQueryDto.prototype, "hd", void 0);
7166
7228
  function _ts_decorate42(decorators, target, key, desc) {
7167
7229
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7168
7230
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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.3",
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",