@bymax-one/nest-auth 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +369 -0
- package/LICENSE +21 -0
- package/README.md +886 -0
- package/dist/client/index.cjs +347 -0
- package/dist/client/index.d.cts +301 -0
- package/dist/client/index.d.ts +301 -0
- package/dist/client/index.mjs +341 -0
- package/dist/nextjs/index.cjs +1103 -0
- package/dist/nextjs/index.d.cts +1025 -0
- package/dist/nextjs/index.d.ts +1025 -0
- package/dist/nextjs/index.mjs +1083 -0
- package/dist/react/index.cjs +304 -0
- package/dist/react/index.d.cts +342 -0
- package/dist/react/index.d.ts +342 -0
- package/dist/react/index.mjs +295 -0
- package/dist/server/index.cjs +8039 -0
- package/dist/server/index.d.cts +5092 -0
- package/dist/server/index.d.ts +5092 -0
- package/dist/server/index.mjs +7996 -0
- package/dist/shared/index.cjs +240 -0
- package/dist/shared/index.d.cts +736 -0
- package/dist/shared/index.d.ts +736 -0
- package/dist/shared/index.mjs +223 -0
- package/package.json +195 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@bymax-one/nest-auth` will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [1.0.0] - 2026-05-25
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
**Next.js subpath (`@bymax-one/nest-auth/nextjs`)**
|
|
15
|
+
- `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 } })`.
|
|
16
|
+
- **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.
|
|
17
|
+
- **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.
|
|
18
|
+
- **Background-request handling** — RSC, `Next-Router-Prefetch`, and `Next-Router-State-Tree` fetches return `401 + Cache-Control: no-store, no-cache` instead of redirecting, preventing visible redirect loops on client-side navigation.
|
|
19
|
+
- **Decode-only warning at factory time** — `warnOnInsecureConfiguration` logs a `console.warn` when `jwtSecret` is omitted so the trust-boundary decision is visible in startup logs.
|
|
20
|
+
- `createSilentRefreshHandler(config)` — GET handler for `/api/auth/silent-refresh`. Forwards cookies to the upstream refresh endpoint, propagates deduplicated `Set-Cookie` headers on success, and redirects to `loginPath?reason=expired` with the three auth cookies cleared (`Max-Age=0`) on failure. **Open-redirect defence**: rejects `redirect` query-param values that (a) are empty/null, (b) do not start with `/`, (c) start with `//`, (d) contain CR/LF/NUL/backslash, or (e) resolve to a different origin. Opaque-redirect responses from the upstream and 2xx responses with no `Set-Cookie` are treated as failures.
|
|
21
|
+
- `createClientRefreshHandler(config)` — POST bridge for client-side JavaScript refresh. Returns 200 + propagated `Set-Cookie` on success, 401 empty body on any failure. Rejects non-POST methods with 405.
|
|
22
|
+
- `createLogoutHandler(config)` — POST logout handler with discriminated-union config: `mode: 'redirect'` requires `loginPath` and returns 302; `mode: 'status'` returns 200 empty body. Cookies are cleared unconditionally regardless of upstream response — the logout guarantee survives network failures.
|
|
23
|
+
- **Helpers**: `isBackgroundRequest`, `buildSilentRefreshUrl`, `parseSetCookieHeader` / `dedupeSetCookieHeaders` / `getSetCookieHeaders` (multi-domain white-label dedup by `(name, domain)` with last-writer-wins, CRLF-smuggling rejection, comma-split fallback for pre-Node 18.14 runtimes), `decodeJwtToken` / `verifyJwtToken` (HS256 pinning via `globalThis.crypto.subtle`; rejects `alg: none`, RS256, HS384/512, and whitespace-suffix bypass attempts), `isTokenExpired`, `getUserId`, `getUserRole`, `getTenantId`, `resolveSafeDestination`, and `SILENT_REFRESH_ROUTE` / `CLIENT_REFRESH_ROUTE` / `LOGOUT_ROUTE` constants.
|
|
24
|
+
- **Types**: `AuthProxyConfig`, `AuthProxyInstance`, `ResolvedAuthProxyConfig`, `ProtectedRoutePattern`, `SilentRefreshHandler` / `SilentRefreshHandlerConfig`, `ClientRefreshHandler` / `ClientRefreshHandlerConfig`, `LogoutHandler` / `LogoutHandlerConfig` (discriminated union) / `LogoutHandlerRedirectConfig` / `LogoutHandlerStatusConfig`, `DecodedToken`, `JwtHeader`, `ParsedSetCookie`, `HeadersLike`, `RequestWithHeaders`, `RequestWithUrl`.
|
|
25
|
+
- **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.
|
|
26
|
+
|
|
27
|
+
**React subpath (`@bymax-one/nest-auth/react`)**
|
|
28
|
+
- `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).
|
|
29
|
+
- `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()`.
|
|
30
|
+
- `useSession()` — reactive snapshot: `{ user, status, isLoading, refresh, lastValidation }` read from context (the `refresh` method triggers an ad-hoc revalidation).
|
|
31
|
+
- `useAuthStatus()` — lightweight selector returning just the `AuthStatus` string for components that only need to branch on it.
|
|
32
|
+
- `AuthContext`, `AuthContextValue`, `AuthStatus`, `AuthProviderProps` types exported from the subpath barrel.
|
|
33
|
+
|
|
34
|
+
**Client subpath (`@bymax-one/nest-auth/client`)**
|
|
35
|
+
- `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
|
|
36
|
+
- `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
|
|
37
|
+
- `AuthFetch`, `AuthFetchConfig`, `AuthClient`, `AuthClientConfig`, `LoginInput`, `RegisterInput`, `ResetPasswordInput` types exported from the subpath barrel
|
|
38
|
+
|
|
39
|
+
**Shared subpath (`@bymax-one/nest-auth/shared`)**
|
|
40
|
+
- `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
|
|
41
|
+
- `AuthResponseCode` type — `AuthErrorCode | (string & {})` union so consumers get autocomplete on known codes while preserving flexibility for non-auth Nest exceptions (e.g. `ValidationPipe` 400s)
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
|
|
45
|
+
- `AuthErrorResponse.code` and `AuthClientError.code` retyped from plain `string` to `AuthResponseCode`, enabling exhaustive narrowing on `AUTH_ERROR_CODES` values at consumer call sites
|
|
46
|
+
- `parseJsonOrThrow` inside `createAuthClient` now throws `AuthClientError` on an empty 2xx body instead of silently returning `undefined` cast as `T`; void endpoints continue to route through `expectNoContent`
|
|
47
|
+
- `AuthResult.accessToken` and `PlatformAuthResult.accessToken` JSDoc now carries a `@warning` block explicitly forbidding persistent storage (`localStorage`, `sessionStorage`, `IndexedDB`) in bearer mode — consumers must hold the token in memory only
|
|
48
|
+
- `AuthFetch` JSDoc now documents that `Request` objects carrying stream bodies are unsupported when a refresh-retry may occur (the retry would fail with `body already used`)
|
|
49
|
+
- `onSessionExpired` callback errors are now surfaced via `console.warn` instead of being silently swallowed, aiding consumer debugging without breaking the fetch contract
|
|
50
|
+
|
|
51
|
+
### Security
|
|
52
|
+
|
|
53
|
+
- Split `tsconfig.json` into a root config (used for editors, client, react, nextjs) and a dedicated `tsconfig.server.json` (lib `ES2022` only, no `DOM`) so server-side code cannot silently typecheck against browser globals like `window`, `document`, or `localStorage`; `pnpm typecheck` now runs both configs
|
|
54
|
+
- **JWT algorithm pinning** in `verifyJwtToken` (HS256 only) blocks `alg: none`, RS256→HS256 confusion, `alg: 'HS256 '` whitespace bypass, and the `HS384`/`HS512` downgrade attempts before any key material is imported. Empty-string secrets fail closed instead of silently degrading to decode-only mode
|
|
55
|
+
- **Anti-redirect-loop defence-in-depth** via two independent guards (the `_r` counter rides on the DESTINATION so it survives the silent-refresh round-trip; `reason=expired` breaks the loop even when the counter is attacker-reset to 0)
|
|
56
|
+
- **Open-redirect defence** in `createSilentRefreshHandler` rejects `redirect` query params that do not start with `/`, start with `//`, contain CR/LF/NUL/backslash, or resolve cross-origin
|
|
57
|
+
- **Header-spoofing defence** — `buildSanitizedRequestHeaders` deletes the configured `userHeaders.*` slots AND a hardcoded baseline (`x-user-id`, `x-user-role`, `x-tenant-id`, `x-tenant-domain`) from the inbound request before any handler runs, so a client-sent `x-user-id: admin` never reaches server components on any response path (public, protected, unmatched, or silent-refresh redirect)
|
|
58
|
+
- **Cookie-smuggling defence** — `parseSetCookieHeader` rejects inputs containing CR/LF (response-header splitting); `assertSafeCookieName`/`assertSafeCookiePath` validate consumer-configured cookie names and paths at factory time against RFC 6265 token grammar and attribute-terminator characters (`;`)
|
|
59
|
+
- **Factory-time validation** throws on absolute-URL `loginPath` / `redirectPath`, relative `apiBase`, mid-pattern protected-route wildcards, and segment-0 catch-alls, preventing misconfigurations from manifesting as silent runtime behaviour
|
|
60
|
+
- **Cache-Control: no-store, no-cache** on every 401 and redirect response prevents CDN poisoning (a cached 401 or expired-session redirect replayed for an authenticated user)
|
|
61
|
+
|
|
62
|
+
### Tests
|
|
63
|
+
|
|
64
|
+
- **221 tests** in the `nextjs` subpath across 10 suites covering the proxy pipeline (redirect-loop prevention, RBAC, status blocking, background-request handling, identity-header sanitisation), the three route handlers (silent-refresh, client-refresh, logout) including open-redirect vectors and method guards, the JWT helpers (algorithm-confusion attacks, UTF-8 validity, base64url alphabet, Web-Crypto failure-path mocks), the cookie helpers (RFC 6265 token coverage, legacy comma-split, CRLF rejection, length bounds), and all validators
|
|
65
|
+
- Co-located `*.spec.ts` per helper; every `it()` carries a dedicated English comment explaining the security vector or correctness invariant under test
|
|
66
|
+
- New `createAuthFetch.spec.ts` and `createAuthClient.spec.ts` covering refresh interception, timeout, header merge, prototype-pollution guards, MFA handshake, error body parsing, and retry semantics
|
|
67
|
+
- New `routes.spec.ts` giving `buildAuthRefreshSkipSuffixes` 100% statement/branch/function coverage (default prefix, custom prefix, slash normalization, empty-prefix branch, unprefixed proxy routes)
|
|
68
|
+
- New `barrel.spec.ts` asserting the `shared` subpath public surface
|
|
69
|
+
- React subpath specs cover the `loading → authenticated / unauthenticated` state machine, revalidation loop, `onSessionExpired` firing policy (transition-only, not on mount or explicit logout), MFA challenge short-circuit, and the three hook selectors
|
|
70
|
+
- Existing `error-codes.spec.ts` drift guard between `server` and `shared` `AUTH_ERROR_CODES`
|
|
71
|
+
|
|
72
|
+
## [1.0.0] - 2026-04-16
|
|
73
|
+
|
|
74
|
+
### Added
|
|
75
|
+
|
|
76
|
+
#### Phase 1 — Foundation and Infrastructure (NEST-001 to NEST-042)
|
|
77
|
+
|
|
78
|
+
**Scaffold and tooling**
|
|
79
|
+
- `package.json` with scope `@bymax-one`, peer dependencies (NestJS 11, ioredis, class-validator), zero direct runtime dependencies
|
|
80
|
+
- `tsconfig.json` and `tsconfig.build.json` with `strict: true`, ES2022 target, decorator support
|
|
81
|
+
- `tsconfig.jest.json` for ts-jest compilation
|
|
82
|
+
- ESLint flat config (`eslint.config.mjs`) with `@typescript-eslint`, `eslint-plugin-import`, `eslint-plugin-security`, `eslint-plugin-prettier`
|
|
83
|
+
- Prettier configuration (`.prettierrc`)
|
|
84
|
+
- Jest configuration (`jest.config.ts`) with ts-jest, 80% global coverage threshold, 95% for `crypto/` and `guards/`
|
|
85
|
+
- tsup build configuration (`tsup.config.ts`) for 5 subpaths with dual ESM+CJS output and `.d.ts` declarations
|
|
86
|
+
- Source directory structure: `server/{interfaces,config,services,controllers,guards,decorators,redis,dto,crypto,errors,oauth,constants,providers,hooks,utils}`, `shared`, `client`, `react`, `nextjs`
|
|
87
|
+
- MIT License, `.gitignore`, `AGENTS.md`, `CLAUDE.md`
|
|
88
|
+
|
|
89
|
+
**Interfaces**
|
|
90
|
+
- `BymaxAuthModuleOptions` — full module configuration interface with 15 optional groups (jwt, password, tokenDelivery, cookies, mfa, sessions, bruteForce, passwordReset, emailVerification, platform, invitations, roles, blockedStatuses, oauth, controllers)
|
|
91
|
+
- `AuthUser` and `SafeAuthUser` — user entity interfaces (15 fields) with credential-free safe variant
|
|
92
|
+
- `IUserRepository` — data access interface with 11 methods (findById, findByEmail, create, updatePassword, updateMfa, updateLastLogin, updateStatus, updateEmailVerified, findByOAuthId, linkOAuth, createWithOAuth)
|
|
93
|
+
- `AuthPlatformUser` and `IPlatformUserRepository` — platform admin entity and repository interfaces
|
|
94
|
+
- `IEmailProvider` — email delivery interface with 7 methods (OTP, reset, MFA notifications, session alert, invitation), each with optional `locale` parameter
|
|
95
|
+
- `IAuthHooks` — lifecycle hook interface with 12 optional hooks (beforeRegister, afterRegister, beforeLogin, afterLogin, afterLogout, afterMfaEnabled, afterMfaDisabled, onNewSession, afterEmailVerified, afterPasswordReset, onOAuthLogin, afterInvitationAccepted)
|
|
96
|
+
- `HookContext` — sanitized request context passed to all hooks (ip, userAgent, sanitizedHeaders, optional userId/email/tenantId)
|
|
97
|
+
- `BeforeRegisterResult` — hook result type with `allowed`, `reason`, and `modifiedData` fields
|
|
98
|
+
- `DashboardJwtPayload`, `PlatformJwtPayload`, `MfaTempPayload` — JWT payload interfaces
|
|
99
|
+
- `AuthResult`, `PlatformAuthResult`, `MfaChallengeResult`, `RotatedTokenResult` — service result types
|
|
100
|
+
- `AuthenticatedRequest` and `PlatformAuthenticatedRequest` — Express Request extensions with typed `user` payload
|
|
101
|
+
- `OAuthProviderPlugin` — native OAuth2 plugin interface (no Passport)
|
|
102
|
+
- `OAuthProfile` and `OAuthLoginResult` — OAuth profile and hook result types
|
|
103
|
+
|
|
104
|
+
**Constants and configuration**
|
|
105
|
+
- 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`
|
|
106
|
+
- `DEFAULT_OPTIONS` — all default values (jwt.accessExpiresIn `'15m'`, refreshExpiresInDays `7`, tokenDelivery `'cookie'`, bruteForce 5 attempts / 900s window, etc.)
|
|
107
|
+
- `resolveOptions()` — startup function that merges consumer options with defaults, validates all security invariants, and produces `ResolvedOptions` with no optional fields
|
|
108
|
+
- Throttle configurations (`THROTTLE_CONFIGS`) per endpoint category
|
|
109
|
+
|
|
110
|
+
**Crypto utilities** (`src/server/crypto/`)
|
|
111
|
+
- `sha256(input)` — deterministic SHA-256 hex digest via `node:crypto`
|
|
112
|
+
- `hmacSha256(input, secret)` — keyed HMAC-SHA256 hex digest for low-entropy inputs (composite keys with email addresses)
|
|
113
|
+
- `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)`
|
|
114
|
+
- `generateSecureToken()` — cryptographically random opaque token via `node:crypto.randomBytes`
|
|
115
|
+
|
|
116
|
+
**Error handling** (`src/server/errors/`)
|
|
117
|
+
- `AUTH_ERROR_CODES` — typed string union of all 30+ error codes with Portuguese end-user messages
|
|
118
|
+
- `AuthException` — NestJS `HttpException` subclass carrying structured `{ code, message, details? }` response body
|
|
119
|
+
|
|
120
|
+
**Redis layer** (`src/server/redis/`)
|
|
121
|
+
- `AuthRedisService` — typed wrapper around ioredis with automatic namespace prefixing; exposes `get`, `set`, `del`, `setnx`, `incr`, `expire`, `ttl`, `sadd`, `srem`, `smembers`, `sismember`, `eval`, `getdel`, `incrWithFixedTtl`
|
|
122
|
+
- `AuthRedisModule` — internal NestJS module registering `AuthRedisService`
|
|
123
|
+
|
|
124
|
+
**Services** (`src/server/services/`)
|
|
125
|
+
- `PasswordService` — scrypt-based password hashing and constant-time comparison; configurable cost factor, block size, and parallelization
|
|
126
|
+
- `BruteForceService` — fixed-window rate limiting via atomic `incrWithFixedTtl` Lua script; lockout with `getRemainingLockoutSeconds`
|
|
127
|
+
- `TokenManagerService` — JWT issuance (`issueTokens`, `issueMfaTempToken`), token rotation (`reissueTokens`), revocation blacklist via Redis `rv:{jti}` keys, raw refresh token storage via `rt:{sha256(token)}`
|
|
128
|
+
- `TokenDeliveryService` — cookie/bearer/both delivery modes; multi-domain support via `resolveDomains` callback; `extractAccessToken`, `extractRefreshToken`, `clearAuthSession`
|
|
129
|
+
|
|
130
|
+
**Utilities** (`src/server/utils/`)
|
|
131
|
+
- `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
|
|
132
|
+
- `sleep(ms)` — Promise-based delay for timing normalization in anti-enumeration flows
|
|
133
|
+
- `hasRole(userRole, requiredRole, hierarchy)` — recursive role hierarchy checker supporting denormalized role trees
|
|
134
|
+
|
|
135
|
+
**NoOp fallback providers**
|
|
136
|
+
- `NoOpEmailProvider` — silent no-op implementation of `IEmailProvider` (registered when consumer does not supply one)
|
|
137
|
+
- `NoOpAuthHooks` — silent no-op implementation of `IAuthHooks` (registered when consumer does not supply one)
|
|
138
|
+
|
|
139
|
+
**Phase 1 barrel export** (`src/server/index.ts`) — all interfaces, types, constants, error codes, and injectable tokens
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
#### Phase 2 — Core Authentication (NEST-043 to NEST-064)
|
|
144
|
+
|
|
145
|
+
**Guards** (`src/server/guards/`)
|
|
146
|
+
- `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
|
|
147
|
+
- `RolesGuard` — hierarchical role guard using denormalized `roles.hierarchy`; reads `@Roles()` metadata via `Reflector`; throws `INSUFFICIENT_ROLE` (403) on failure
|
|
148
|
+
- `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
|
|
149
|
+
- `assertTokenType` utility — reusable guard helper that throws `TOKEN_INVALID` when the JWT `type` claim does not match the expected value
|
|
150
|
+
|
|
151
|
+
**Decorators** (`src/server/decorators/`)
|
|
152
|
+
- `@CurrentUser(property?)` — param decorator extracting `request.user` or a specific property from it
|
|
153
|
+
- `@Roles(...roles)` — metadata decorator setting `ROLES_KEY` for `RolesGuard`
|
|
154
|
+
- `@Public()` — metadata decorator setting `IS_PUBLIC_KEY` to skip `JwtAuthGuard`
|
|
155
|
+
|
|
156
|
+
**DTOs** (`src/server/dto/`)
|
|
157
|
+
- `RegisterDto` — `email`, `password` (8–128 chars), `name` (2+ chars), `tenantId`; all with class-validator decorators
|
|
158
|
+
- `LoginDto` — `email`, `password` (no `@MinLength` — deliberate anti-enumeration), `tenantId`
|
|
159
|
+
|
|
160
|
+
**Services** (`src/server/services/`)
|
|
161
|
+
- `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)
|
|
162
|
+
- `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
|
|
163
|
+
|
|
164
|
+
**Controllers** (`src/server/controllers/`)
|
|
165
|
+
- `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
|
|
166
|
+
|
|
167
|
+
**Module**
|
|
168
|
+
- `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)
|
|
169
|
+
|
|
170
|
+
**Phase 2 barrel export** — adds `BymaxAuthModule`, `AuthService`, `JwtAuthGuard`, `RolesGuard`, `UserStatusGuard`, `CurrentUser`, `Roles`, `ROLES_KEY`, `Public`, `IS_PUBLIC_KEY`, `RegisterDto`, `LoginDto`
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
#### Phase 3 — Multi-Factor Authentication (TOTP)
|
|
175
|
+
|
|
176
|
+
**Crypto utilities** (`src/server/crypto/totp.ts`)
|
|
177
|
+
- `generateTotpSecret()` — generates a cryptographically random 20-byte TOTP secret via `node:crypto.randomBytes`; returns both raw `Buffer` and `base32`-encoded string
|
|
178
|
+
- `buildTotpUri(secret, account, issuer)` — constructs a standard `otpauth://totp/` URI for QR code generation
|
|
179
|
+
- `verifyTotp(secret, code, window)` — validates a 6-digit TOTP code within a configurable step window (±1 by default) using HMAC-SHA1 per RFC 6238
|
|
180
|
+
- `generateHotp(secret, counter)` — low-level HOTP generation (RFC 4226) used internally by `verifyTotp` and exposed for testing
|
|
181
|
+
- `fromBase32(input)` / `toBase32(buf)` — pure Base32 encode/decode without external dependencies; `fromBase32` strips whitespace, hyphens, and padding before decoding
|
|
182
|
+
|
|
183
|
+
**Services** (`src/server/services/mfa.service.ts`)
|
|
184
|
+
- `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)
|
|
185
|
+
- `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
|
|
186
|
+
- `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
|
|
187
|
+
- `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
|
|
188
|
+
|
|
189
|
+
**Guards** (`src/server/guards/mfa-required.guard.ts`)
|
|
190
|
+
- `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)
|
|
191
|
+
|
|
192
|
+
**Decorators** (`src/server/decorators/skip-mfa.decorator.ts`)
|
|
193
|
+
- `@SkipMfa()` — metadata decorator that marks an endpoint as exempt from `MfaRequiredGuard`; used on `POST /mfa/challenge` and any other pre-MFA routes
|
|
194
|
+
|
|
195
|
+
**DTOs** (`src/server/dto/`)
|
|
196
|
+
- `MfaChallengeDto` — `mfaTempToken` (string) + `code` (string); `@MaxLength(14)` as defence-in-depth before regex
|
|
197
|
+
- `MfaVerifyDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`
|
|
198
|
+
- `MfaDisableDto` — 6-digit TOTP code; `@MaxLength(6)` + `@Matches(/^\d{6}$/)`; JSDoc explains why recovery codes are not accepted
|
|
199
|
+
|
|
200
|
+
**Controllers** (`src/server/controllers/mfa.controller.ts`)
|
|
201
|
+
- `POST /mfa/setup` — initiates TOTP setup; returns secret, QR URI, and plain recovery codes (shown once); idempotent within 10-minute window; dashboard users only
|
|
202
|
+
- `POST /mfa/verify-enable` — submits the first TOTP code to permanently activate MFA; returns 204 No Content
|
|
203
|
+
- `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
|
|
204
|
+
- `POST /mfa/disable` — disables MFA for dashboard or platform users; derived `context` from `user.type` JWT claim; returns 204 No Content
|
|
205
|
+
|
|
206
|
+
**Redis additions** (`src/server/redis/auth-redis.service.ts`)
|
|
207
|
+
- `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
|
|
208
|
+
- `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
|
|
209
|
+
|
|
210
|
+
**Module integration** (`src/server/bymax-auth.module.ts`)
|
|
211
|
+
- `controllers.mfa: true` option conditionally registers `MfaController`; startup validation throws if `controllers.mfa: true` is set without the `mfa` configuration group
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
#### Phase 4 — Sessions & Password Reset
|
|
216
|
+
|
|
217
|
+
**Services** (`src/server/services/`)
|
|
218
|
+
- `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
|
|
219
|
+
- `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
|
|
220
|
+
|
|
221
|
+
**Controllers** (`src/server/controllers/`)
|
|
222
|
+
- `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`
|
|
223
|
+
- `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
|
|
224
|
+
|
|
225
|
+
**DTOs** (`src/server/dto/`)
|
|
226
|
+
- `ForgotPasswordDto` — `email` (normalized lowercase) + `tenantId`
|
|
227
|
+
- `ResetPasswordDto` — `email`, `newPassword` (8–128 chars), exactly one of `token` / `otp` / `verifiedToken`, `tenantId`
|
|
228
|
+
- `VerifyOtpDto` — `email`, `otp` (4–8 chars), `tenantId`
|
|
229
|
+
- `ResendOtpDto` — `email` + `tenantId`
|
|
230
|
+
|
|
231
|
+
**Configuration** (`BymaxAuthModuleOptions`)
|
|
232
|
+
- `sessions.enabled`, `sessions.defaultMaxSessions` (default 5), `sessions.maxSessionsResolver`, `sessions.evictionStrategy` (`'fifo'`)
|
|
233
|
+
- `passwordReset.method` (`'token'` | `'otp'`, default `'token'`), `passwordReset.tokenTtlSeconds` (default 3600), `passwordReset.otpTtlSeconds` (default 600), `passwordReset.otpLength` (default 6)
|
|
234
|
+
|
|
235
|
+
**Module integration** (`src/server/bymax-auth.module.ts`)
|
|
236
|
+
- `controllers.sessions: true` opt-in gate with startup cross-validation: throws if `sessions.enabled` is not `true` in the factory return value
|
|
237
|
+
- `controllers.passwordReset` opt-out gate (enabled by default); `PasswordResetService` only registered when controller is active
|
|
238
|
+
- `SessionService` always registered unconditionally — `AuthService.login()` and `AuthService.refresh()` call session methods regardless of whether the sessions controller is exposed
|
|
239
|
+
|
|
240
|
+
**Phase 4 barrel export** — adds `SessionService`, `PasswordResetService`, `ForgotPasswordDto`, `ResetPasswordDto`, `VerifyOtpDto`, `ResendOtpDto`, and `ActiveSessionInfo` type
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
#### Phase 5 — Platform Authentication, OAuth & Invitations
|
|
245
|
+
|
|
246
|
+
**Services**
|
|
247
|
+
- `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)
|
|
248
|
+
- `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
|
|
249
|
+
- `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`
|
|
250
|
+
|
|
251
|
+
**Guards** (`src/server/guards/`)
|
|
252
|
+
- `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()`
|
|
253
|
+
- `PlatformRolesGuard` — enforces role-based access on platform routes via `@PlatformRoles()` metadata; requires fully denormalized `roles.platformHierarchy`; denies access by default when hierarchy is missing
|
|
254
|
+
|
|
255
|
+
**Decorators** (`src/server/decorators/`)
|
|
256
|
+
- `@PlatformRoles(...roles)` — metadata decorator under `PLATFORM_ROLES_KEY` symbol; declares required platform role(s) for a route handler
|
|
257
|
+
|
|
258
|
+
**Controllers**
|
|
259
|
+
- `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
|
|
260
|
+
- `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
|
|
261
|
+
- `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)
|
|
262
|
+
|
|
263
|
+
**DTOs** (`src/server/dto/`)
|
|
264
|
+
- `PlatformLoginDto` — `email` (normalized lowercase) + `password` (12–128 chars)
|
|
265
|
+
- `CreateInvitationDto` — `email`, `role`, optional `tenantName` (max 128 chars)
|
|
266
|
+
- `AcceptInvitationDto` — `token` (exactly 64 hex chars), `name` (2–100 chars), `password` (8–128 chars)
|
|
267
|
+
- `OAuthInitiateQueryDto` — `tenantId` (1–128 chars)
|
|
268
|
+
- `OAuthCallbackQueryDto` — `code` (32–2048 chars), `state` (max 128 chars)
|
|
269
|
+
|
|
270
|
+
**OAuth module** (`src/server/oauth/`)
|
|
271
|
+
- `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`
|
|
272
|
+
- `OAUTH_PLUGINS` — Symbol injection token for the `OAuthProviderPlugin[]` array; internal to the library (not exported in public API)
|
|
273
|
+
|
|
274
|
+
**Configuration** (`BymaxAuthModuleOptions`)
|
|
275
|
+
- `platform.enabled` (default `false`); requires `roles.platformHierarchy`
|
|
276
|
+
- `oauth.google` — `clientId`, `clientSecret`, `callbackUrl` (required), `scope` (optional, default `['openid', 'email', 'profile']`)
|
|
277
|
+
- `invitations.enabled` (default `false`), `invitations.tokenTtlSeconds` (default 172800 — 48 hours)
|
|
278
|
+
- `roles.platformHierarchy` — required when `platform.enabled: true`
|
|
279
|
+
|
|
280
|
+
**Module integration** (`src/server/bymax-auth.module.ts`)
|
|
281
|
+
- `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`
|
|
282
|
+
- `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
|
|
283
|
+
- `controllers.invitations: true` opt-in gate with startup cross-validation: requires `invitations.enabled: true`
|
|
284
|
+
- `OAuthService` exported individually (not `OAUTH_PLUGINS` — internal token not part of the public integration surface)
|
|
285
|
+
|
|
286
|
+
**Phase 5 barrel export** — adds `PlatformAuthService`, `OAuthService`, `InvitationService`, `JwtPlatformGuard`, `PlatformRolesGuard`, `PlatformRoles`, `PLATFORM_ROLES_KEY`, `PlatformLoginDto`, `CreateInvitationDto`, `AcceptInvitationDto`, `SafeAuthPlatformUser`, `IPlatformUserRepository`, `OAuthProfile`, `OAuthProviderPlugin`
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
#### Phase 6 — Integration, Polish, and Publication (NEST-122 to NEST-151)
|
|
291
|
+
|
|
292
|
+
**Additional guards** (3)
|
|
293
|
+
- `WsJwtGuard` — WebSocket dashboard JWT guard (header-only, soft peer-dep on `@nestjs/websockets`, runtime check via dynamic import)
|
|
294
|
+
- `SelfOrAdminGuard` — self-access or admin override with strict SHA-256 session-hash validation; documents multi-tenant ownership limitation
|
|
295
|
+
- `OptionalAuthGuard` — extends `JwtAuthGuard`, allows unauthenticated access while validating tokens when present
|
|
296
|
+
|
|
297
|
+
**E2E test suite** (`test/e2e/`)
|
|
298
|
+
- Full auth flow (bearer + cookie modes)
|
|
299
|
+
- MFA flow (setup, verify, challenge with TOTP and recovery codes)
|
|
300
|
+
- Sessions flow (3-device login, list, revoke single, revoke all-except-current)
|
|
301
|
+
- Password reset flow (token method + OTP method)
|
|
302
|
+
- Invitations flow (admin creates, invitee accepts, login)
|
|
303
|
+
- OAuth flow (mocked Google plugin, create/link actions, CSRF state)
|
|
304
|
+
- FIFO session eviction (sessions.defaultMaxSessions exceeded → oldest evicted)
|
|
305
|
+
- Refresh concurrency (Promise.all on /refresh, grace window served distinct rotated tokens, original invalidated after grace expiry)
|
|
306
|
+
- Security scenarios (brute-force lockout, blacklist, missing jti, MFA cross-context token rejection, OTP cooldown)
|
|
307
|
+
|
|
308
|
+
**Security audits**
|
|
309
|
+
- Password & crypto audit — scrypt parameters, AES-256-GCM, recovery code hashing, opaque refresh tokens, `crypto.timingSafeEqual` (PASS)
|
|
310
|
+
- Token & session audit — refresh rotation grace window, blacklist, HttpOnly+SameSite cookies, algorithm pinning HS256, SHA-256 Redis keys (PASS)
|
|
311
|
+
- 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
|
|
312
|
+
|
|
313
|
+
**Documentation**
|
|
314
|
+
- README.md — install, configuration, IUserRepository + IEmailProvider reference implementations with XSS warning, endpoints table, guards/decorators table, security checklist, throttler version note
|
|
315
|
+
- JSDoc completion across all public services, guards, and decorators
|
|
316
|
+
|
|
317
|
+
**Test infrastructure**
|
|
318
|
+
- Jest E2E config (`jest.e2e.config.ts`)
|
|
319
|
+
- ioredis-mock + supertest test harness
|
|
320
|
+
- Shared bootstrap helper (`test/e2e/setup.ts`) with mock repositories, email capture, and in-memory Redis
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
### Fixed
|
|
325
|
+
|
|
326
|
+
#### Phase 6 — Bug fixes
|
|
327
|
+
- `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'`)
|
|
328
|
+
- `self-or-admin.guard.ts` (during initial implementation): replaced `ForbiddenException` wrapping `AuthException` with direct `AuthException` throw for correct error response shape
|
|
329
|
+
- `ws-jwt.guard.ts` (during initial implementation): replaced `require.resolve` with dynamic `await import()` for ESM compatibility
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
### Security
|
|
334
|
+
|
|
335
|
+
- **Grace pointer survivorship fix** — `rotateFromPrimary` and `rotateFromGrace` now add grace pointer keys (`rp:{hash}`) to the `sess:{userId}` Redis SET so that `invalidateUserSessions` (called on MFA enable/disable) deletes them atomically, preventing stale refresh tokens from surviving MFA state changes
|
|
336
|
+
- **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
|
|
337
|
+
- **`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
|
|
338
|
+
- **`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
|
|
339
|
+
- **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
|
|
340
|
+
- **Atomic resend cooldown** — GET+SET TOCTOU race in `resendVerificationEmail` replaced with atomic `SET NX EX` (`setnx`) preventing duplicate OTP sends under concurrent requests
|
|
341
|
+
- **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
|
|
342
|
+
- **`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
|
|
343
|
+
- **Algorithm pinning from options** — `JwtAuthGuard` now reads `algorithms: [this.options.jwt.algorithm]` instead of hardcoding `['HS256']`, ensuring the algorithm is validated once at startup and consistent across the full JWT lifecycle
|
|
344
|
+
- **Atomic OTP attempt increment** — `incrementAttempts` now uses a single Lua `EVAL` (GET+SET with preserved TTL) instead of separate `TTL` + `SET EX` calls, eliminating a race window between reads and writes
|
|
345
|
+
- **OTP key deleted on max-attempt exhaustion** — `verify()` now calls `redis.del(key)` when `attempts >= MAX_ATTEMPTS` before throwing `OTP_MAX_ATTEMPTS`, preventing further probing after lockout
|
|
346
|
+
- **`refreshCookiePath` validation is now a hard error** — mismatched `routePrefix` without explicit `refreshCookiePath` previously logged a warning; now throws at startup to prevent misconfigured cookie paths reaching production
|
|
347
|
+
- **`validateRefreshGraceWindowSeconds`** — startup validation added: throws if `refreshGraceWindowSeconds >= refreshExpiresInDays * 86400` to prevent a grace window larger than the token's lifetime
|
|
348
|
+
- **Anti-enumeration timing normalization** — `initiateReset` and `resendOtp` apply a 300ms minimum floor via `sleep()` so response time cannot reveal whether an email is registered
|
|
349
|
+
- **Single-use token enforcement** — password-reset tokens, OTP `verifiedToken`, OAuth CSRF state, and invitation tokens all consumed atomically via `redis.getdel()`, preventing concurrent redemption races
|
|
350
|
+
- **Session ownership verification** — `revokeSession` performs an SISMEMBER check before deletion; throws `SESSION_NOT_FOUND` for sessions not owned by the requesting user, preventing cross-user revocation
|
|
351
|
+
- **OAuth CSRF protection** — state nonce is 64 hex chars (256 bits), stored under `os:{sha256(state)}` and consumed in a single atomic `getdel()` call; provider format validated before the state is touched to prevent probe-and-consume attacks
|
|
352
|
+
- **Platform token type isolation** — `JwtPlatformGuard` throws `PLATFORM_AUTH_REQUIRED` (not the generic `TOKEN_INVALID`) when a dashboard-context token is submitted to a platform route, enabling clients to distinguish wrong-context from expired/invalid token errors
|
|
353
|
+
- **Tenant spoofing prevention** — `InvitationController` extracts `tenantId` exclusively from the authenticated JWT payload; body field is absent from `CreateInvitationDto`, making tenant injection structurally impossible
|
|
354
|
+
- **Invitation role re-validation on acceptance** — `acceptInvitation` re-validates the stored role against the live `roles.hierarchy` after consuming the token, preventing privilege escalation via Redis tampering between invite creation and acceptance
|
|
355
|
+
- **Platform brute-force HMAC identifiers** — `PlatformAuthService` uses `hmacSha256(email, jwt.secret)` as the brute-force counter key, consistent with dashboard pattern; no PII stored in Redis key segments
|
|
356
|
+
|
|
357
|
+
---
|
|
358
|
+
|
|
359
|
+
### Tests
|
|
360
|
+
|
|
361
|
+
- 561 tests across 34 co-located spec files through Phase 3; Phase 4 and Phase 5 add spec files for `session.service`, `password-reset.service`, `platform-auth.service`, `oauth.service`, `invitation.service`, `jwt-platform.guard`, and `platform-roles.guard`
|
|
362
|
+
- **100% coverage** on all metrics (Statements, Branches, Functions, Lines) across every source file
|
|
363
|
+
- Per-directory coverage thresholds enforced: 95% for `crypto/` and `guards/`, 80% global
|
|
364
|
+
- Every `it()` block has an English comment explaining the branch under test
|
|
365
|
+
- All spec files have a file-level JSDoc docblock describing strategy, mocks, and special setup
|
|
366
|
+
- Phase 3 integration smoke test (`mfa-integration.spec.ts`) validates: full setup→enable→challenge flow, idempotency, recovery codes, anti-replay, brute-force lockout, counter namespacing, platform context, session invalidation, disable TOTP-only enforcement, and `@SkipMfa()` guard bypass
|
|
367
|
+
- Phase 4 session tests cover: `createSession` FIFO eviction, `listSessions` `isCurrent` marking, `revokeSession` ownership check, `revokeAllExceptCurrent` current-session preservation, `rotateSession` atomic rename, and stale member cleanup
|
|
368
|
+
- Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
|
|
369
|
+
- Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bymax One
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|