@nathapp/nestjs-auth 2.1.4 → 3.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CLAUDE.md +29 -0
  2. package/dist/auth-provider.js.map +1 -1
  3. package/dist/auth.module.d.ts +17 -0
  4. package/dist/auth.module.js +109 -0
  5. package/dist/auth.module.js.map +1 -0
  6. package/dist/authentication/auth.module.d.ts +49 -0
  7. package/dist/authentication/auth.module.js +252 -0
  8. package/dist/authentication/auth.module.js.map +1 -0
  9. package/dist/authentication/index.d.ts +8 -0
  10. package/dist/authentication/index.js +25 -0
  11. package/dist/authentication/index.js.map +1 -0
  12. package/dist/authorization/authorization.module.d.ts +32 -0
  13. package/dist/authorization/authorization.module.js +145 -0
  14. package/dist/authorization/authorization.module.js.map +1 -0
  15. package/dist/authorization/index.d.ts +5 -0
  16. package/dist/authorization/index.js +22 -0
  17. package/dist/authorization/index.js.map +1 -0
  18. package/dist/casl/casl-ability-factory.js.map +1 -1
  19. package/dist/constant/jwt-constant.js.map +1 -1
  20. package/dist/constant/module-constant.js.map +1 -1
  21. package/dist/decorator/is-public.decorator.js.map +1 -1
  22. package/dist/decorator/permission.decorator.js.map +1 -1
  23. package/dist/decorator/principal.decorator.js.map +1 -1
  24. package/dist/decorator/refresh-token.decorator.js.map +1 -1
  25. package/dist/guard/jwt-auth.guard.js +1 -8
  26. package/dist/guard/jwt-auth.guard.js.map +1 -1
  27. package/dist/guard/jwt-refresh.guard.d.ts +1 -0
  28. package/dist/guard/jwt-refresh.guard.js +8 -2
  29. package/dist/guard/jwt-refresh.guard.js.map +1 -1
  30. package/dist/guard/permission-auth.guard.js +1 -1
  31. package/dist/guard/permission-auth.guard.js.map +1 -1
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +3 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/module/jwt-module.js.map +1 -1
  36. package/dist/permission/permission.provider.js +25 -3
  37. package/dist/permission/permission.provider.js.map +1 -1
  38. package/dist/strategy/base-jwt-strategy-provider.d.ts +19 -0
  39. package/dist/strategy/base-jwt-strategy-provider.js +54 -0
  40. package/dist/strategy/base-jwt-strategy-provider.js.map +1 -0
  41. package/dist/strategy/index.d.ts +4 -3
  42. package/dist/strategy/index.js +3 -1
  43. package/dist/strategy/index.js.map +1 -1
  44. package/dist/strategy/jwt-refresh-strategy-provider.d.ts +4 -17
  45. package/dist/strategy/jwt-refresh-strategy-provider.js +5 -38
  46. package/dist/strategy/jwt-refresh-strategy-provider.js.map +1 -1
  47. package/dist/strategy/jwt-refresh-strategy.js.map +1 -1
  48. package/dist/strategy/jwt-strategy-provider.d.ts +4 -18
  49. package/dist/strategy/jwt-strategy-provider.js +5 -38
  50. package/dist/strategy/jwt-strategy-provider.js.map +1 -1
  51. package/dist/strategy/jwt-strategy.js.map +1 -1
  52. package/dist/strategy/strategy-provider.d.ts +2 -10
  53. package/dist/strategy/strategy-provider.js.map +1 -1
  54. package/dist/strategy/type-interface.d.ts +11 -0
  55. package/dist/utils/utils.d.ts +1 -1
  56. package/dist/utils/utils.js +6 -6
  57. package/dist/utils/utils.js.map +1 -1
  58. package/docs/20260214-fix-plan-auth-module-split.md +148 -0
  59. package/docs/20260214-fix-plan-auth-security.md +130 -0
  60. package/docs/20260214-review-auth-enterprise.md +186 -0
  61. package/docs/20260214-review-auth.md +300 -0
  62. package/docs/20260215-review-auth-post-fix.md +519 -0
  63. package/package.json +3 -3
@@ -0,0 +1,519 @@
1
+ # Code Review: @nathapp/nestjs-auth (Post-Fix Re-Review)
2
+
3
+ **Date:** 2026-02-15
4
+ **Reviewer:** Subrina (Deep Review)
5
+ **Scope:** Full lib/ source (~1711 lines), test/ scan (~2700 lines)
6
+ **Branch:** feat/monorepo-enterprise-upgrade
7
+ **Version:** 2.1.5
8
+
9
+ ---
10
+
11
+ ## Executive Summary
12
+
13
+ **Grade Change: B- → A-** (significant improvement)
14
+
15
+ All three critical issues from the previous review have been **successfully fixed and tested**:
16
+ - ✅ **SEC-1 CRITICAL**: `@RefreshToken()` no longer bypasses `JwtAuthGuard`
17
+ - ✅ **BUG-4 HIGH**: Multi-CASL permissions now properly passed to provider
18
+ - ✅ **BUG-3 HIGH**: `isAuthority()` operator precedence corrected
19
+
20
+ Additionally, the codebase received a **major architectural improvement**:
21
+ - ✅ Module restructure: `AuthModule` now cleanly separates `AuthenticationModule` and `AuthorizationModule`
22
+ - ✅ `BaseJwtStrategyProvider` created to eliminate 80% code duplication
23
+ - ✅ All deprecated constants properly marked with `@deprecated`
24
+ - ✅ Comprehensive unit tests added for all three critical fixes
25
+
26
+ **Test Results:** 145 passing, 1 failing (non-critical IP binding test setup issue)
27
+
28
+ **Remaining Concerns:** Security gap in refresh token validation (SEC-2), some type safety issues, and minor code quality items.
29
+
30
+ ---
31
+
32
+ ## Previous Issues Scorecard
33
+
34
+ | ID | Issue | Previous Status | Current Status | Verified? | Evidence |
35
+ |---|---|---|---|---|---|
36
+ | **SEC-1** | `@RefreshToken()` bypasses JwtAuthGuard | 🔴 CRITICAL | ✅ **FIXED** | ✅ Yes | `jwt-auth.guard.ts` lines 27-30 removed bypass; test added (line 60-68 of spec) |
37
+ | **BUG-4** | Multi-CASL permission drops after first tuple | 🔴 HIGH | ✅ **FIXED** | ✅ Yes | `permission-auth.guard.ts` line 35 now passes full `requirePermission` array; test added (line 73-90 of spec) |
38
+ | **BUG-3** | `isAuthority()` operator precedence bug | 🔴 HIGH | ✅ **FIXED** | ✅ Yes | `utils.ts` line 12 now has correct parentheses: `'id' in val && (typeof val.id === 'string' || typeof val.id === 'number')`; test added (line 8-16 of spec) |
39
+ | **SEC-7** | No auth failure audit logging | 🟡 MEDIUM | ✅ **FIXED** | ✅ Yes | Both guards now log warnings on auth failure (jwt-auth.guard.ts line 38, jwt-refresh.guard.ts line 14) |
40
+ | **C2** | Duplicate `validate` signatures | 🟢 LOW | ✅ **FIXED** | ✅ Yes | `BaseJwtStrategyProvider` now has single abstract method |
41
+ | **C5** | Deprecated constants not marked | 🟢 LOW | ✅ **FIXED** | ✅ Yes | `jwt-constant.ts` and `module-constant.ts` have `@deprecated` JSDoc |
42
+ | **ARCH-1** | DRY violation in strategy providers | 🟡 MEDIUM | ✅ **FIXED** | ✅ Yes | `BaseJwtStrategyProvider` created (70 lines), eliminates ~80% duplication |
43
+ | **Module Restructure** | `NathAuthModule` → `AuthModule` | N/A | ✅ **COMPLETED** | ✅ Yes | `AuthModule` combines `AuthenticationModule` + `AuthorizationModule`; clean separation of concerns |
44
+
45
+ ### SEC-1 Fix Details
46
+
47
+ **Before (lib/guard/jwt-auth.guard.ts, removed code):**
48
+ ```typescript
49
+ const RefreshToken = this.reflector.getAllAndOverride<boolean>(REFRESH_TOKEN, [...]);
50
+ if (RefreshToken) {
51
+ return true; // ❌ Complete bypass - security hole
52
+ }
53
+ ```
54
+
55
+ **After:**
56
+ ```typescript
57
+ const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [handler, clazz]);
58
+ if (isPublic) {
59
+ this.logger.verbose(`has isPublic decorator...`);
60
+ return true; // ✅ Only @Public() bypasses auth
61
+ }
62
+ return super.canActivate(context); // ✅ All other requests go through Passport JWT validation
63
+ ```
64
+
65
+ **Impact:** `@RefreshToken()` endpoints now **require explicit `@UseGuards(JwtRefreshGuard)`** and **cannot bypass authentication**.
66
+
67
+ ### BUG-4 Fix Details
68
+
69
+ **Before (lib/guard/permission-auth.guard.ts):**
70
+ ```typescript
71
+ else if (isRequiredCaslPermission(firstPermission)) {
72
+ return this.permissionProvider.checkPermission(context, [firstPermission]); // ❌ Only first permission checked
73
+ }
74
+ ```
75
+
76
+ **After:**
77
+ ```typescript
78
+ else if (isRequiredCaslPermission(firstPermission)) {
79
+ return this.permissionProvider.checkPermission(context, requirePermission as RequiredCaslPermission[]); // ✅ All permissions checked
80
+ }
81
+ ```
82
+
83
+ **Impact:** `@RequiredPermission(['create', 'Invoice'], ['read', 'Invoice'])` now correctly requires **both** permissions (AND logic), not just the first.
84
+
85
+ ### BUG-3 Fix Details
86
+
87
+ **Before (lib/utils/utils.ts):**
88
+ ```typescript
89
+ return ('id' in val && typeof val.id === 'string' || typeof val.id === 'number') && 'name' in val && typeof val.name === 'string';
90
+ // ❌ Evaluated as: ('id' in val && typeof val.id === 'string') || (typeof val.id === 'number' && 'name' in val && ...)
91
+ ```
92
+
93
+ **After:**
94
+ ```typescript
95
+ return val != null && typeof val === 'object' && 'id' in val && (typeof val.id === 'string' || typeof val.id === 'number') && 'name' in val && typeof val.name === 'string';
96
+ // ✅ Correct precedence: id must be string OR number, AND name must be string
97
+ ```
98
+
99
+ **Impact:** `{ id: 'abc' }` (no `name` property) now correctly returns `false`.
100
+
101
+ ---
102
+
103
+ ## New Findings
104
+
105
+ ### Enterprise Grade
106
+
107
+ #### ✅ Strengths
108
+
109
+ | Area | Finding |
110
+ |---|---|
111
+ | **Module Architecture** | Clean 3-tier design: `AuthModule` → `AuthenticationModule` + `AuthorizationModule`. Excellent separation of concerns. |
112
+ | **Provider Abstraction** | All core components (`AuthProvider`, `PermissionProvider`, `CaslAbilityFactory`, `JwtStrategyProvider`) are fully swappable via DI. |
113
+ | **DRY Improvement** | `BaseJwtStrategyProvider` eliminates 80% duplication between access/refresh strategies (shared: constructor, options parsing, sign, verify). |
114
+ | **Test Coverage** | **145 passing tests** with specific regression tests for SEC-1, BUG-3, BUG-4. Critical paths well-covered. |
115
+ | **Error Handling** | Both guards throw `AppException` with appropriate codes (`UNAUTHORIZED`, `FORBIDDEN_BLACKLISTED`, `FORBIDDEN_IP_NOT_MATCH`). |
116
+ | **Logging** | Debug/verbose logging throughout, auth failures now logged (SEC-7 fix). |
117
+
118
+ #### ⚠️ Weaknesses
119
+
120
+ | # | Severity | Category | File | Description |
121
+ |---|---|---|---|---|
122
+ | **NEW-1** | 🔴 **HIGH** | Security | `jwt-refresh-strategy-provider.ts:25-35` | **Refresh token validation has ZERO server-side checks.** `DefaultJwtRefreshStrategyProvider.validate()` trusts JWT payload blindly—no revocation check, no blacklist check, no DB lookup. Long-lived refresh tokens can't be invalidated server-side. |
123
+ | **NEW-2** | 🟡 MEDIUM | Type Safety | Multiple files | **Pervasive `any` usage**: `jwtPayload: any` (15+ occurrences), `IPrincipal.extra: any`, `CaslPermissionSubject = any`, `handleRequest(err, user, info)` all untyped. |
124
+ | **NEW-3** | 🟡 MEDIUM | Type Safety | `strategy-provider.ts`, `base-jwt-strategy-provider.ts` | **Generic type parameter `T` in `validate<T>()` is unconstrained.** Should be `T extends IPrincipal`. |
125
+ | **NEW-4** | 🟡 MEDIUM | Error Handling | `permission.provider.ts:117` | **`checkPermission()` has implicit fallthrough.** When `permission` is neither string nor array, function returns `undefined` (falsy, so denies—correct behavior but implicit). Add explicit `else` clause. |
126
+ | **NEW-5** | 🟡 MEDIUM | Code Quality | `authentication/auth.module.ts:75-84` | **useClass handling creates multiple factory instances.** Each factory call `new FactoryClass()` instead of injecting singleton. Inefficient and breaks DI conventions. |
127
+ | **NEW-6** | 🟢 LOW | Test | `jwt-strategy-provider.spec.ts:143-171` | **1 failing test**: IP binding test expects `x-forwarded` header but `getClientIp` likely expects `x-forwarded-for`. Test setup issue, not production code bug. |
128
+ | **NEW-7** | 🟢 LOW | Code Quality | Multiple files | **TODO comments unresolved**: `jwt-strategy.ts:11` ("temporary mark as any"), `permission.provider.ts:96,99` (RPC/WS implementation). |
129
+ | **NEW-8** | 🟢 LOW | Documentation | All public methods | **No JSDoc on public API.** Abstract classes, providers, guards lack `@param`, `@returns`, `@throws` annotations. |
130
+
131
+ ---
132
+
133
+ ### Extensibility
134
+
135
+ #### ✅ Excellent Extensibility
136
+
137
+ The library provides clean extension points for all major components:
138
+
139
+ | Component | Extension Mechanism | Example Use Case |
140
+ |---|---|---|
141
+ | **AuthProvider** | Implement `AuthProvider` interface | Database-backed user lookup, LDAP integration, multi-tenant principal resolution |
142
+ | **PermissionProvider** | Extend `PermissionProvider` abstract class | Custom RBAC, ABAC, or graph-based permission systems |
143
+ | **CaslAbilityFactory** | Extend `BaseCaslAbilityFactory` | Fetch permissions from DB/Redis/external API |
144
+ | **JwtStrategyProvider** | Extend `JwtStrategyProvider` or `BaseJwtStrategyProvider` | Custom token validation, multi-tenant JWT secrets, external auth providers |
145
+ | **Module Options** | `forRoot()` / `forRootAsync()` with `useClass`/`useFactory`/`useExisting` | Full NestJS dynamic module patterns supported |
146
+
147
+ #### Sample Extension Code
148
+
149
+ ```typescript
150
+ // Custom auth provider with DB lookup
151
+ @Injectable()
152
+ export class DatabaseAuthProvider implements AuthProvider {
153
+ constructor(private readonly userRepo: UserRepository) {}
154
+
155
+ async getPrincipal(jwtPayload: any): Promise<IPrincipal> {
156
+ const user = await this.userRepo.findById(jwtPayload.sub);
157
+ if (!user) return null;
158
+ return {
159
+ id: user.id,
160
+ name: user.fullName,
161
+ blacklisted: user.isBlacklisted,
162
+ revoked: user.tokenRevoked,
163
+ authorities: user.roles.map(r => r.permissions).flat(),
164
+ };
165
+ }
166
+
167
+ async isDuplicateLogin(principal: IPrincipal, jwtPayload: any): Promise<boolean> {
168
+ const latestSession = await this.sessionRepo.findLatest(principal.id);
169
+ return latestSession?.tokenHash !== principal.hashToken;
170
+ }
171
+ }
172
+
173
+ // Usage in app
174
+ AuthModule.forRoot({
175
+ jwtOptions: { /* ... */ },
176
+ authProvider: DatabaseAuthProvider,
177
+ permissionProvider: CustomPermissionProvider,
178
+ caslAbilityFactory: DbCaslAbilityFactory,
179
+ });
180
+ ```
181
+
182
+ #### ⚠️ Extensibility Limitations
183
+
184
+ | Limitation | Impact | Workaround |
185
+ |---|---|---|
186
+ | **Cannot swap passport strategies** | Locked to `passport-jwt`. Can't use OAuth2, SAML, etc. via this module. | Implement separate auth module for OAuth2, use this module only for JWT-secured endpoints. |
187
+ | **No issuer/audience validation** | Cannot validate JWT `iss`/`aud` claims (previous review S1). | Manual validation in custom `AuthProvider.getPrincipal()`. |
188
+ | **~~CaslAbilityFactory not injectable in JwtStrategyProvider~~** | ✅ **Resolved by design** — module split separates AuthN (identity) from AuthZ (permissions). JWT validation should not need CASL; permission checks happen in `PermissionAuthGuard` afterwards. Edge case: import `AuthorizationModule` and inject manually. | N/A |
189
+
190
+ ---
191
+
192
+ ### Security
193
+
194
+ #### ✅ Strong Security Posture
195
+
196
+ | Security Control | Status | Notes |
197
+ |---|---|---|
198
+ | **JWT signature validation** | ✅ Enabled | passport-jwt handles, `ignoreExpiration: false` by default |
199
+ | **Token expiration** | ✅ Enabled | Default: `ignoreExpiration: false` |
200
+ | **Revocation check (access tokens)** | ✅ Implemented | `DefaultJwtStrategyProvider` checks `principal.revoked` |
201
+ | **Blacklist check (access tokens)** | ✅ Implemented | Checks `principal.blacklisted` when `checkBlacklisted: true` |
202
+ | **IP binding** | ✅ Implemented | `bindIp: true` validates request IP matches `principal.loginIP` |
203
+ | **Duplicate login detection** | ✅ Implemented | `allowDuplicateLogin: false` triggers `isDuplicateLogin()` check |
204
+ | **Auth failure logging** | ✅ Implemented | Both guards log failures (SEC-7 fix) |
205
+ | **@Public() bypass only** | ✅ Implemented | `@RefreshToken()` bypass removed (SEC-1 fix) |
206
+
207
+ #### 🔴 Critical Security Gaps
208
+
209
+ ##### **SEC-NEW-1: Refresh Token Validation Has Zero Server-Side Checks (HIGH)**
210
+
211
+ **File:** `lib/strategy/jwt-refresh-strategy-provider.ts` lines 25-35
212
+
213
+ **Issue:**
214
+ ```typescript
215
+ validate<T = IPrincipal>(req: Req, payload: any): Promise<T> {
216
+ const refreshToken = this.jwtFromRequestFunction(req);
217
+ return Promise.resolve({
218
+ id: payload.sub,
219
+ username: payload.username,
220
+ name: payload.name,
221
+ blacklisted: false, // ❌ Hardcoded to false
222
+ revoked: false, // ❌ Hardcoded to false
223
+ refreshToken,
224
+ authorities: payload.authorities || [],
225
+ } as T);
226
+ }
227
+ ```
228
+
229
+ **Impact:**
230
+ - Refresh tokens **cannot be revoked server-side** (user gets logged out but can still refresh their access token)
231
+ - Blacklisted users can refresh tokens
232
+ - No database/cache lookup means compromised long-lived refresh tokens remain valid until expiration (7h+ typically)
233
+ - Token rotation is impossible (can't track "latest valid refresh token")
234
+
235
+ **Recommended Fix:**
236
+ ```typescript
237
+ @Injectable()
238
+ export class DefaultJwtRefreshStrategyProvider extends JwtRefreshStrategyProvider {
239
+ constructor(
240
+ jwtOptions: JwtOptions,
241
+ private readonly authProvider: AuthProvider, // ← Inject AuthProvider
242
+ ) {
243
+ super(jwtOptions);
244
+ }
245
+
246
+ async validate<T = IPrincipal>(req: Req, payload: any): Promise<T> {
247
+ // Call authProvider.getPrincipal to perform server-side checks
248
+ const principal = await this.authProvider.getPrincipal(payload);
249
+
250
+ if (!principal) {
251
+ throw new AppException(CommonExceptionCode.UNAUTHORIZED);
252
+ }
253
+
254
+ // Check revocation (critical for refresh tokens)
255
+ if (principal.revoked) {
256
+ throw new AppException(CommonExceptionCode.UNAUTHORIZED);
257
+ }
258
+
259
+ // Optional: check blacklist
260
+ if (principal.blacklisted) {
261
+ throw new AppException(CommonExceptionCode.FORBIDDEN_BLACKLISTED);
262
+ }
263
+
264
+ const refreshToken = this.jwtFromRequestFunction(req);
265
+ return { ...principal, refreshToken } as T;
266
+ }
267
+ }
268
+ ```
269
+
270
+ **Effort:** Low (1-2 hours)
271
+ **Priority:** 🔴 **Must-have for production use**
272
+
273
+ ##### **SEC-NEW-2: No Issuer/Audience Claim Validation (MEDIUM)**
274
+
275
+ **Issue:** `JwtOptions` doesn't expose `issuer`/`audience` fields. passport-jwt supports `StrategyOptions.issuer` and `StrategyOptions.audience`, but `BaseJwtStrategyProvider.getStrategyOptions()` doesn't pass them through.
276
+
277
+ **Impact:** Cannot validate JWT `iss`/`aud` claims. If an attacker obtains a valid JWT from another service using the same secret, they can use it here (cross-service JWT replay attack).
278
+
279
+ **Fix:** Add to `JwtOptions` interface:
280
+ ```typescript
281
+ export interface JwtOptions {
282
+ // ... existing fields
283
+ issuer?: string;
284
+ audience?: string | string[];
285
+ }
286
+ ```
287
+
288
+ And in `BaseJwtStrategyProvider.getStrategyOptions()`:
289
+ ```typescript
290
+ return {
291
+ ...partialOptions,
292
+ jwtFromRequest: this.jwtFromRequestFunction,
293
+ secretOrKey: this.secretOrPublicKey,
294
+ ...(this.jwtOptions.issuer && { issuer: this.jwtOptions.issuer }),
295
+ ...(this.jwtOptions.audience && { audience: this.jwtOptions.audience }),
296
+ passReqToCallback: this.passReqToCallback,
297
+ };
298
+ ```
299
+
300
+ **Effort:** Low (30 min)
301
+ **Priority:** 🟡 Should-have for multi-service environments
302
+
303
+ ##### **SEC-NEW-3: ignoreExpiration Settable via Env Without Warning (LOW)**
304
+
305
+ **Issue:** `DefaultAuthenticationModuleOptionsFactory` reads `JWT_ACCESS_IGNORE_EXPIRATION=true` from env and applies it without warning. Production deployments could accidentally disable expiration checks.
306
+
307
+ **Fix:** Add a warning log in `DefaultJwtStrategyProvider.validate()`:
308
+ ```typescript
309
+ if (this.jwtOptions.ignoreExpiration && process.env.NODE_ENV === 'production') {
310
+ this.logger.warn('⚠️ JWT expiration is IGNORED in production! Set JWT_ACCESS_IGNORE_EXPIRATION=false');
311
+ }
312
+ ```
313
+
314
+ **Effort:** Trivial (5 min)
315
+ **Priority:** 🟢 Nice-to-have
316
+
317
+ ---
318
+
319
+ ### Memory & Performance
320
+
321
+ #### ✅ Efficient Design
322
+
323
+ | Aspect | Finding |
324
+ |---|---|
325
+ | **Guard Instantiation** | Guards are singleton services (NestJS DI). No per-request overhead. |
326
+ | **Strategy Providers** | Singleton services with pre-parsed JWT options. `JwtProvider` cached in constructor. |
327
+ | **JWT Verification** | Handled by native `jsonwebtoken` library (C bindings), highly optimized. |
328
+ | **CASL Ability Creation** | `CaslAbilityFactory.createForUser()` returns new ability per request (correct for stateless auth). |
329
+ | **No Memory Leaks** | No event listeners, timers, or persistent state in library code. |
330
+
331
+ #### ⚠️ Performance Concerns
332
+
333
+ | # | Issue | Impact | Mitigation |
334
+ |---|---|---|---|
335
+ | **PERF-1** | **CaslAbilityFactory creates ability on every request** | For CASL-based permissions, `createMongoAbility()` is called on every request (default behavior). For high-throughput APIs with complex permission trees, this adds latency (~0.5-2ms per request). | Cache abilities per user ID in Redis/memory with TTL. Or pre-compute abilities and store in JWT (careful: token size increases). |
336
+ | **PERF-2** | **Multiple strategy factory instantiations in async module setup** | `auth.module.ts` lines 75-84 create multiple `new FactoryClass()` instances instead of injecting singleton. Memory waste (minor) and breaks DI patterns. | Refactor to use proper DI: inject factory once, reuse instance. |
337
+ | **PERF-3** | **No test for refresh token flow overhead** | Refresh flow makes zero server-side checks (NEW-1), so it's fast but insecure. Once fixed, refresh validation will add DB/cache lookup latency. | After fixing NEW-1, profile refresh endpoint. Add Redis cache for principal lookup (sub-1ms). |
338
+
339
+ **Estimated Performance Profile:**
340
+ - **Access token validation:** ~1-3ms (JWT verify + DB lookup + CASL ability creation)
341
+ - **Refresh token validation (current):** ~0.5ms (JWT verify only, no DB—insecure)
342
+ - **Refresh token validation (after fix):** ~2-5ms (JWT verify + DB lookup for revocation check)
343
+
344
+ ---
345
+
346
+ ## Enhancement Suggestions
347
+
348
+ ### 🔴 Critical (Must-Have for Production)
349
+
350
+ | Priority | Enhancement | File | Effort | Impact |
351
+ |---|---|---|---|---|
352
+ | 1 | **Add server-side checks to refresh token validation** | `jwt-refresh-strategy-provider.ts` | Low (2h) | Enables revocation, blacklisting, token rotation for long-lived refresh tokens |
353
+ | 2 | **Define JwtPayload interface, replace `any` in providers** | `strategy/type-interface.ts` | Low (1h) | Type safety for JWT claims, prevents runtime errors, better IDE autocomplete |
354
+ | 3 | **Add issuer/audience validation** | `strategy/type-interface.ts`, `base-jwt-strategy-provider.ts` | Low (30min) | Prevents cross-service JWT replay attacks |
355
+ | 4 | **Fix useClass factory instantiation in AuthModule.forRootAsync** | `auth.module.ts:75-84` | Medium (2h) | Proper DI, avoids multiple factory instances, cleaner code |
356
+
357
+ ### 🟡 High-Value (Should-Have for 3.0)
358
+
359
+ | Priority | Enhancement | File | Effort | Impact |
360
+ |---|---|---|---|---|
361
+ | 5 | **Add tests for refresh token flow** | `test/guard/jwt-refresh.guard.spec.ts` (new) | Medium (3h) | Currently 0% coverage on refresh guards/strategies |
362
+ | 6 | **Add JSDoc to all public APIs** | All exported classes | Medium (4h) | DX: developers know what params are required, what exceptions are thrown |
363
+ | 7 | **Fix implicit fallthrough in checkPermission** | `permission.provider.ts:117` | Trivial (5min) | Explicit error handling, easier debugging |
364
+ | 8 | **Add production warning for ignoreExpiration** | `jwt-strategy-provider.ts` | Trivial (5min) | Prevents accidental security misconfig |
365
+ | 9 | **Constrain generic type `T` in validate methods** | `strategy-provider.ts` | Trivial (5min) | `validate<T extends IPrincipal>()` prevents type errors |
366
+ | 10 | **Fix failing IP binding test** | `jwt-strategy-provider.spec.ts:143` | Low (30min) | All tests should pass (145/146 passing currently) |
367
+
368
+ ### 🟢 Nice-to-Have (Future)
369
+
370
+ | Priority | Enhancement | Effort | Impact |
371
+ |---|---|---|---|
372
+ | 11 | **GraphQL execution context support** | Medium | Enables auth guards in GraphQL resolvers (currently TODO) |
373
+ | 12 | **WebSocket/gRPC context support** | Medium | Enables auth guards in WS/gRPC handlers (currently TODO) |
374
+ | 13 | **Optional "deny by default" mode for PermissionAuthGuard** | Low | Security hardening for high-security apps |
375
+ | 14 | **Structured audit log events** | Medium | Machine-parseable logs for SIEM integration |
376
+ | 15 | **Ability caching strategy** | Medium | Performance: cache CASL abilities in Redis with TTL |
377
+
378
+ ---
379
+
380
+ ## Summary Table
381
+
382
+ ### All Issues (Previous + New)
383
+
384
+ | ID | Severity | Category | File | Description | Status |
385
+ |---|---|---|---|---|---|
386
+ | **SEC-1** | 🔴 CRITICAL | Security | `jwt-auth.guard.ts` | `@RefreshToken()` bypasses JwtAuthGuard | ✅ **FIXED** |
387
+ | **BUG-3** | 🔴 HIGH | Logic | `utils.ts:12` | `isAuthority()` operator precedence bug | ✅ **FIXED** |
388
+ | **BUG-4** | 🔴 HIGH | Logic | `permission-auth.guard.ts:35` | Multi-CASL permissions drop after first tuple | ✅ **FIXED** |
389
+ | **NEW-1** | 🔴 **HIGH** | Security | `jwt-refresh-strategy-provider.ts:25-35` | Refresh token validation has zero server-side checks | ❌ **NEW ISSUE** |
390
+ | **ARCH-1** | 🟡 MEDIUM | DRY | Strategy providers | 80% code duplication | ✅ **FIXED** (BaseJwtStrategyProvider) |
391
+ | **SEC-7** | 🟡 MEDIUM | Security | Guards | No auth failure audit logging | ✅ **FIXED** |
392
+ | **NEW-2** | 🟡 MEDIUM | Type Safety | Multiple files | Pervasive `any` usage (15+ occurrences) | ❌ **NEW ISSUE** |
393
+ | **NEW-3** | 🟡 MEDIUM | Type Safety | `strategy-provider.ts` | Unconstrained generic `T` in validate | ❌ **NEW ISSUE** |
394
+ | **NEW-4** | 🟡 MEDIUM | Error Handling | `permission.provider.ts:117` | Implicit fallthrough when permission is invalid type | ❌ **NEW ISSUE** |
395
+ | **NEW-5** | 🟡 MEDIUM | Architecture | `auth.module.ts:75-84` | useClass creates multiple factory instances | ❌ **NEW ISSUE** |
396
+ | **SEC-NEW-2** | 🟡 MEDIUM | Security | `base-jwt-strategy-provider.ts` | No issuer/audience validation | ❌ **NEW ISSUE** |
397
+ | **C2** | 🟢 LOW | Code Quality | Strategy providers | Duplicate validate signatures | ✅ **FIXED** |
398
+ | **C5** | 🟢 LOW | Documentation | Constants | Deprecated constants not marked | ✅ **FIXED** |
399
+ | **NEW-6** | 🟢 LOW | Test | `jwt-strategy-provider.spec.ts:143` | 1 failing IP binding test | ❌ **NEW ISSUE** |
400
+ | **NEW-7** | 🟢 LOW | Code Quality | Multiple files | Unresolved TODO comments | ❌ **NEW ISSUE** |
401
+ | **NEW-8** | 🟢 LOW | Documentation | All public classes | No JSDoc on public API | ❌ **NEW ISSUE** |
402
+ | **SEC-NEW-3** | 🟢 LOW | Security | `jwt-strategy-provider.ts` | ignoreExpiration no production warning | ❌ **NEW ISSUE** |
403
+ | **PERF-1** | 🟢 LOW | Performance | `casl-ability-factory.ts` | Ability created on every request | 💡 **OBSERVATION** |
404
+ | **PERF-2** | 🟢 LOW | Performance | `auth.module.ts` | Multiple factory instantiations | ❌ **NEW ISSUE** |
405
+
406
+ ---
407
+
408
+ ## Test Coverage Analysis
409
+
410
+ ### What's Well-Tested ✅
411
+
412
+ | Component | Coverage | Notes |
413
+ |---|---|---|
414
+ | **JwtAuthGuard** | ~95% | Includes SEC-1 regression test (no @RefreshToken bypass) |
415
+ | **PermissionAuthGuard** | ~95% | Includes BUG-4 regression test (multi-CASL) |
416
+ | **Utils** | ~100% | Includes BUG-3 regression test (isAuthority precedence) |
417
+ | **DefaultJwtStrategyProvider** | ~90% | All validation paths (revoked, blacklisted, IP binding, duplicate login) |
418
+ | **DefaultPermissionProvider** | ~85% | String permissions, authority objects |
419
+ | **AuthenticationModule** | ~85% | forRoot, forRootAsync with useClass/useFactory/useExisting |
420
+ | **AuthorizationModule** | ~85% | Provider registration, DI |
421
+ | **AuthProvider (Simple)** | ~100% | Full coverage |
422
+ | **E2E** | ~90% | Full request lifecycle with guards, decorators |
423
+
424
+ ### What's NOT Tested ❌
425
+
426
+ | Component | Coverage | Risk | Recommendation |
427
+ |---|---|---|---|
428
+ | **JwtRefreshGuard** | **0%** | 🔴 HIGH | Add unit tests for handleRequest, canActivate |
429
+ | **JwtRefreshStrategy** | **0%** | 🔴 HIGH | Test arg routing (passReqToCallback) |
430
+ | **DefaultJwtRefreshStrategyProvider** | **0%** | 🔴 CRITICAL | Test validate logic (currently minimal, will be complex after NEW-1 fix) |
431
+ | **CASL path in DefaultPermissionProvider** | ~30% | 🟡 MEDIUM | Test CASL permission array validation (currently only tests string/authority) |
432
+ | **CaslAbilityFactory (both classes)** | **0%** | 🟡 MEDIUM | Test CASL permission extraction from JWT |
433
+ | **RPC/WebSocket context paths** | **0%** | 🟢 LOW | Test permission/auth checks in RPC/WS (currently TODO) |
434
+
435
+ **Overall Test Coverage Estimate:** ~75% (145 passing tests, 2700 lines of test code)
436
+
437
+ ---
438
+
439
+ ## Migration Notes (2.1.x → 3.0)
440
+
441
+ If the refresh token validation fix (NEW-1) is implemented, this is a **breaking change**:
442
+
443
+ ### Breaking Change: Refresh Token Validation Now Requires AuthProvider
444
+
445
+ **Before (2.1.x):**
446
+ ```typescript
447
+ // Refresh tokens were validated with zero server-side checks
448
+ // No AuthProvider needed for refresh strategy
449
+ ```
450
+
451
+ **After (3.0):**
452
+ ```typescript
453
+ // DefaultJwtRefreshStrategyProvider now requires AuthProvider injection
454
+ // Refresh tokens check revocation, blacklist server-side
455
+ // Apps MUST implement AuthProvider.getPrincipal() properly
456
+ ```
457
+
458
+ **Migration Steps:**
459
+ 1. Ensure your `AuthProvider` implementation supports lookup by JWT sub (user ID)
460
+ 2. Test refresh token flow in staging (verify revocation works)
461
+ 3. Document that refresh token revocation now works (inform users if previously didn't)
462
+
463
+ ### Non-Breaking Changes
464
+
465
+ - Module restructure (`AuthModule` vs `AuthenticationModule`/`AuthorizationModule`) is backward-compatible via exports
466
+ - `@RefreshToken()` removal is correct behavior (was a security bug)
467
+ - All other fixes are behavior corrections, not API changes
468
+
469
+ ---
470
+
471
+ ## Recommendations for Next Steps
472
+
473
+ ### Immediate (Before Merging to Main)
474
+
475
+ 1. ✅ **Fix NEW-1**: Add server-side validation to refresh token flow
476
+ - Inject `AuthProvider` into `DefaultJwtRefreshStrategyProvider`
477
+ - Call `authProvider.getPrincipal()` and check `revoked`/`blacklisted`
478
+ - Add tests for refresh guard/strategy
479
+
480
+ 2. ✅ **Fix NEW-6**: Fix failing IP binding test
481
+ - Update test to use `x-forwarded-for` header or adjust `getClientIp` expectations
482
+
483
+ 3. ✅ **Document breaking changes** in CHANGELOG.md
484
+
485
+ ### Pre-3.0 Release
486
+
487
+ 4. Define `JwtPayload` interface (NEW-2)
488
+ 5. Add JSDoc to all public APIs (NEW-8)
489
+ 6. Add issuer/audience validation (SEC-NEW-2)
490
+ 7. Fix useClass factory instantiation (NEW-5)
491
+ 8. Fill test coverage gaps (refresh flow, CASL)
492
+
493
+ ### Post-3.0 (Maintenance)
494
+
495
+ 9. Resolve TODO comments (GraphQL, RPC, WebSocket support)
496
+ 10. Consider CASL ability caching strategy for high-throughput apps
497
+ 11. Add structured audit log events for SIEM integration
498
+
499
+ ---
500
+
501
+ ## Conclusion
502
+
503
+ **The post-fix review shows significant progress.** All three critical security/logic bugs from the previous review are **fixed and tested**. The module restructure is clean, the DRY violation is resolved, and test coverage is solid for core flows.
504
+
505
+ **However, one critical security gap remains:** refresh token validation has zero server-side checks (NEW-1). This **must be fixed** before production use in any security-sensitive application.
506
+
507
+ **Recommended Timeline:**
508
+ - **Immediate (1-2 days):** Fix NEW-1 (refresh validation), fix failing test (NEW-6), define JwtPayload interface (NEW-2)
509
+ - **Pre-3.0 (1 week):** Add JSDoc, issuer/audience validation, fill test gaps
510
+ - **Post-3.0 (ongoing):** Performance optimizations, GraphQL/RPC support, CASL caching
511
+
512
+ **Final Grade:** **A-** (was B- before fixes)
513
+ **Blockers for Production:** NEW-1 (refresh token validation)
514
+ **Estimated Effort to Production-Ready:** ~8-10 hours of focused work
515
+
516
+ ---
517
+
518
+ *Review completed 2026-02-15 by Subrina (AI-assisted deep code review).*
519
+ *Next review recommended after 3.0 release and NEW-1 fix.*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-auth",
3
- "version": "2.1.4",
3
+ "version": "3.0.0-rc.4",
4
4
  "description": "nestjs-auth",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -26,12 +26,12 @@
26
26
  "lib": "lib"
27
27
  },
28
28
  "dependencies": {
29
- "@nathapp/nestjs-common": "^2.1.1",
29
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
30
30
  "passport-jwt": "^4.0.1"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@nathapp/auth": "^1.0.2",
34
- "@nathapp/nestjs-common": "^2.1.1",
34
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
35
35
  "@nestjs/passport": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
36
36
  "@casl/ability": "^6.7.1"
37
37
  }