@nathapp/nestjs-auth-2fa 2.1.5 → 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 (50) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +38 -0
  3. package/dist/decorator/index.d.ts +1 -0
  4. package/dist/decorator/index.js +18 -0
  5. package/dist/decorator/index.js.map +1 -0
  6. package/dist/decorator/two-factor.decorator.d.ts +7 -0
  7. package/dist/decorator/two-factor.decorator.js +14 -0
  8. package/dist/decorator/two-factor.decorator.js.map +1 -0
  9. package/dist/enum/index.d.ts +1 -0
  10. package/dist/enum/index.js +1 -0
  11. package/dist/enum/index.js.map +1 -1
  12. package/dist/enum/two-factor-policy.enum.d.ts +5 -0
  13. package/dist/enum/two-factor-policy.enum.js +10 -0
  14. package/dist/enum/two-factor-policy.enum.js.map +1 -0
  15. package/dist/enum/two-factor-type.enum.d.ts +4 -1
  16. package/dist/enum/two-factor-type.enum.js +4 -1
  17. package/dist/enum/two-factor-type.enum.js.map +1 -1
  18. package/dist/guard/base-two-factor.guard.d.ts +25 -0
  19. package/dist/guard/base-two-factor.guard.js +215 -0
  20. package/dist/guard/base-two-factor.guard.js.map +1 -0
  21. package/dist/guard/index.d.ts +1 -0
  22. package/dist/guard/index.js +1 -0
  23. package/dist/guard/index.js.map +1 -1
  24. package/dist/guard/two-factor-force.guard.d.ts +3 -10
  25. package/dist/guard/two-factor-force.guard.js +5 -50
  26. package/dist/guard/two-factor-force.guard.js.map +1 -1
  27. package/dist/guard/two-factor.guard.d.ts +4 -11
  28. package/dist/guard/two-factor.guard.js +8 -54
  29. package/dist/guard/two-factor.guard.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/module/two-factor-auth.interface.d.ts +17 -2
  34. package/dist/module/two-factor-auth.interface.js +8 -2
  35. package/dist/module/two-factor-auth.interface.js.map +1 -1
  36. package/dist/module/two-factor-auth.module.js +2 -1
  37. package/dist/module/two-factor-auth.module.js.map +1 -1
  38. package/dist/module/two-factor.provider.d.ts +1 -0
  39. package/dist/module/two-factor.provider.js +25 -2
  40. package/dist/module/two-factor.provider.js.map +1 -1
  41. package/dist/provider/two-factor-setting.provider.d.ts +13 -4
  42. package/dist/provider/two-factor-setting.provider.js +4 -0
  43. package/dist/provider/two-factor-setting.provider.js.map +1 -1
  44. package/dist/provider/two-factor.provider.d.ts +7 -8
  45. package/dist/provider/two-factor.provider.js +38 -5
  46. package/dist/provider/two-factor.provider.js.map +1 -1
  47. package/docs/20260215-fix-plan-auth-2fa-v3.md +165 -0
  48. package/docs/20260215-fix-plan-auth-2fa.md +179 -0
  49. package/docs/20260215-review-auth-2fa-deep.md +264 -0
  50. package/package.json +5 -5
@@ -0,0 +1,179 @@
1
+ # Fix Plan: nestjs-auth-2fa Enterprise Upgrade
2
+
3
+ **Date:** 2026-02-15
4
+ **Branch:** feat/monorepo-enterprise-upgrade
5
+ **Review:** 20260215-review-auth-2fa-deep.md
6
+
7
+ ---
8
+
9
+ ## Phase 1: Guard Base Class Extraction (BUG-1)
10
+
11
+ ### Fix 1: Extract BaseTwoFactorGuard
12
+ **Files:**
13
+ - `lib/guard/base-two-factor.guard.ts` (NEW)
14
+ - `lib/guard/two-factor.guard.ts` (REWRITE)
15
+ - `lib/guard/two-factor-force.guard.ts` (REWRITE)
16
+ - `lib/guard/index.ts` (UPDATE exports)
17
+
18
+ **Change:**
19
+ Create `BaseTwoFactorGuard` abstract class containing ALL shared logic:
20
+ - Constructor with same DI injection (options, providersMap, twoFactorProvider, twoFactorSettingProvider, reflector)
21
+ - `canActivate()` with shared flow: check enabled → check skip → get user → get settings → filter enabled → delegate to `handleNoEnabledMethods()` → policy routing
22
+ - All private methods: `getPolicy()`, `getAllowedTypes()`, `verifyAnyPolicy()`, `verifyAllPolicy()`, `verifySpecificPolicy()`, `getProviderForType()`, `getTwoFactorTokenFromRequest()`, `getTwoFactorTokensObjectFromRequest()`, `getFieldFromRequest()`
23
+ - Abstract method: `protected abstract handleNoEnabledMethods(): boolean | Promise<boolean>`
24
+
25
+ `TwoFactorGuard` becomes:
26
+ ```typescript
27
+ @Injectable()
28
+ export class TwoFactorGuard extends BaseTwoFactorGuard {
29
+ protected handleNoEnabledMethods(): boolean {
30
+ return true; // Allow access when no 2FA methods enabled
31
+ }
32
+ }
33
+ ```
34
+
35
+ `TwoFactorForceGuard` becomes:
36
+ ```typescript
37
+ @Injectable()
38
+ export class TwoFactorForceGuard extends BaseTwoFactorGuard {
39
+ protected handleNoEnabledMethods(): never {
40
+ throw new TwoFactorRequiredException();
41
+ }
42
+ }
43
+ ```
44
+
45
+ **Impact:** Eliminates ~240 lines of duplication. All future policy changes only need to be made once.
46
+
47
+ ## Phase 2: Security Fixes (SEC-1, SEC-3)
48
+
49
+ ### Fix 2: Timing-Safe TOTP Verification (SEC-1)
50
+ **File:** `lib/provider/two-factor.provider.ts`
51
+
52
+ **Change:**
53
+ Replace direct `authenticator.verify()` with timing-safe comparison that checks all window positions:
54
+
55
+ ```typescript
56
+ import * as crypto from 'crypto';
57
+
58
+ verify(token: string, context: TwoFactorVerifyContext): boolean {
59
+ if (!context.secret) {
60
+ throw new TwoFactorVerificationError('TOTP verification requires secret in context');
61
+ }
62
+
63
+ // Generate tokens for each window position
64
+ const window = this.options.window ?? 1;
65
+ let isValid = false;
66
+
67
+ for (let i = -window; i <= window; i++) {
68
+ const expected = this.authenticator.generate(context.secret, { timestamp: Date.now() + i * 30000 });
69
+ const tokenBuf = Buffer.from(token.padStart(6, '0'));
70
+ const expectedBuf = Buffer.from(expected.padStart(6, '0'));
71
+
72
+ if (tokenBuf.length === expectedBuf.length && crypto.timingSafeEqual(tokenBuf, expectedBuf)) {
73
+ isValid = true;
74
+ // Don't return early — continue checking all windows for constant time
75
+ }
76
+ }
77
+
78
+ return isValid;
79
+ }
80
+ ```
81
+
82
+ **Note:** Must check ALL window positions regardless of match to maintain constant-time behavior.
83
+
84
+ ### Fix 3: Clone Authenticator Per Instance (SEC-3)
85
+ **File:** `lib/provider/two-factor.provider.ts`
86
+
87
+ **Change:**
88
+ ```typescript
89
+ // Before:
90
+ const { authenticator } = loadPackage('otplib');
91
+ this.authenticator = authenticator;
92
+ this.authenticator.options = { window: this.options.window };
93
+
94
+ // After:
95
+ const otplib = loadPackage('otplib');
96
+ this.authenticator = otplib.authenticator.clone();
97
+ this.authenticator.options = { window: this.options.window };
98
+ ```
99
+
100
+ ## Phase 3: Medium Priority Fixes (BUG-2, TYPE-1, ENH-2, STYLE-2)
101
+
102
+ ### Fix 4: ExecutionContext Type Check (BUG-2)
103
+ **File:** `lib/guard/base-two-factor.guard.ts`
104
+
105
+ **Change:** Add context type check at the start of `canActivate()`:
106
+ ```typescript
107
+ const contextType = context.getType();
108
+ if (contextType !== 'http') {
109
+ this.logger.warn(`TwoFactorGuard only supports HTTP context, got: ${contextType}`);
110
+ throw new TwoFactorInvalidException();
111
+ }
112
+ ```
113
+
114
+ ### Fix 5: Fix Typo TWO_FACTORY → TWO_FACTOR (ENH-2)
115
+ **File:** `lib/module/two-factor-auth.interface.ts`
116
+
117
+ **Change:** Rename `TWO_FACTORY_SETTING_PROVIDER` → `TWO_FACTOR_SETTING_PROVIDER`. Check all usages first — if unused externally, safe to rename.
118
+
119
+ ### Fix 6: Fix dist/ Import (STYLE-2)
120
+ **File:** `lib/provider/two-factor-setting.provider.ts`
121
+
122
+ **Change:**
123
+ ```typescript
124
+ // Before:
125
+ import { IPrincipal } from "@nathapp/nestjs-auth/dist";
126
+ // After:
127
+ import { IPrincipal } from "@nathapp/nestjs-auth";
128
+ ```
129
+
130
+ ### Fix 7: Replace Key `any` Types (TYPE-1)
131
+ **Files:** `lib/module/two-factor-auth.interface.ts`, `lib/guard/base-two-factor.guard.ts`, `lib/provider/two-factor.provider.ts`
132
+
133
+ **Changes:**
134
+ - `TwoFactorProviderRegistration.options?: any` → `options?: Record<string, unknown>`
135
+ - `request: any` in guard methods → define minimal `TwoFactorRequest` interface
136
+ - `authenticator: any` / `qrcodePackage: any` → define minimal interfaces (IAuthenticator, IQrCode)
137
+
138
+ ## Phase 4: Documentation (SEC-2, STYLE-1)
139
+
140
+ ### Fix 8: Add Trust Boundary Documentation (SEC-2)
141
+ **File:** `lib/guard/base-two-factor.guard.ts`
142
+
143
+ Add `@design` remark and JSDoc:
144
+ ```typescript
145
+ /**
146
+ * @design Rate limiting is the consumer's responsibility. This guard does not
147
+ * track or limit verification attempts. Consumers MUST implement rate limiting
148
+ * (e.g., via @nathapp/nestjs-throttler) to prevent brute-force attacks on
149
+ * 6-digit TOTP codes.
150
+ */
151
+ ```
152
+
153
+ ### Fix 9: Add JSDoc to Guard Classes (STYLE-1)
154
+ **Files:** `lib/guard/base-two-factor.guard.ts`, `lib/guard/two-factor.guard.ts`, `lib/guard/two-factor-force.guard.ts`
155
+
156
+ Add class-level and method-level JSDoc explaining behavior differences.
157
+
158
+ ---
159
+
160
+ ## Test Strategy
161
+
162
+ - **Mode:** two-session-tdd
163
+ - **TDD targets:**
164
+ - Timing-safe TOTP verification (SEC-1)
165
+ - Base guard extraction — existing tests should pass without changes
166
+ - ExecutionContext type check (BUG-2)
167
+ - Authenticator clone isolation (SEC-3)
168
+ - **Test files:**
169
+ - `test/guard/two-factor.guard.spec.ts` (existing — must still pass)
170
+ - `test/guard/two-factor-force.guard.spec.ts` (existing — must still pass)
171
+ - `test/guard/two-factor-policy.guard.spec.ts` (existing — must still pass)
172
+ - `test/provider/otplib-provider.spec.ts` (update for timing-safe + clone)
173
+ - `test/guard/two-factor-context.spec.ts` (NEW — test WS/RPC rejection)
174
+
175
+ ## Commits
176
+ - Phase 1: `refactor(auth-2fa): extract BaseTwoFactorGuard to eliminate duplication`
177
+ - Phase 2: `fix(auth-2fa): timing-safe TOTP verification and per-instance authenticator`
178
+ - Phase 3: `fix(auth-2fa): context type check, typo fix, dist import, type safety`
179
+ - Phase 4: `docs(auth-2fa): add trust boundary docs and JSDoc to guards`
@@ -0,0 +1,264 @@
1
+ # Deep Code Review: @nathapp/nestjs-auth-2fa
2
+
3
+ **Date:** 2026-02-15
4
+ **Reviewer:** Subrina (AI)
5
+ **Version:** 2.1.5
6
+ **Files:** 16 (lib: ~932 LOC, test: ~2165 LOC)
7
+ **Baseline:** 106 tests, 9 suites passing
8
+
9
+ ---
10
+
11
+ ## Overall Grade: B+ (82/100)
12
+
13
+ Solid 2FA library with good architecture — multi-method support (TOTP, SMS, EMAIL, PASSKEY), pluggable provider system, flexible policy engine (ANY/ALL/SPECIFIC), and strong decorator-driven configuration. Test coverage is excellent at a 2.3:1 test-to-lib ratio. However, the package has a critical DRY violation (TwoFactorGuard and TwoFactorForceGuard are ~95% identical code), a security concern around TOTP timing attacks, several `any` types in public APIs, and a missing `ExecutionContext` type check that would break in non-HTTP transports.
14
+
15
+ ---
16
+
17
+ ## Findings
18
+
19
+ ### 🔴 CRITICAL
20
+
21
+ #### SEC-1: TOTP Verification Vulnerable to Timing Attacks
22
+ **Severity:** CRITICAL | **Category:** Security
23
+ ```typescript
24
+ // lib/provider/two-factor.provider.ts:46
25
+ verify(token: string, context: TwoFactorVerifyContext): boolean {
26
+ if (!context.secret) {
27
+ throw new Error('TOTP verification requires secret in context');
28
+ }
29
+ return this.authenticator.verify({ token, secret: context.secret });
30
+ }
31
+ ```
32
+ **Risk:** `otplib`'s `authenticator.verify()` internally uses `===` string comparison for the token check. This is susceptible to timing side-channel attacks where an attacker can measure response time differences to determine correct digits. For a 6-digit TOTP, this reduces the brute-force space significantly.
33
+ **Fix:** Use `crypto.timingSafeEqual` to compare tokens:
34
+ ```typescript
35
+ import * as crypto from 'crypto';
36
+
37
+ verify(token: string, context: TwoFactorVerifyContext): boolean {
38
+ if (!context.secret) {
39
+ throw new Error('TOTP verification requires secret in context');
40
+ }
41
+ const expected = this.authenticator.generate(context.secret);
42
+ const tokenBuf = Buffer.from(token.padStart(6, '0'));
43
+ const expectedBuf = Buffer.from(expected.padStart(6, '0'));
44
+ return tokenBuf.length === expectedBuf.length &&
45
+ crypto.timingSafeEqual(tokenBuf, expectedBuf);
46
+ }
47
+ ```
48
+ **Note:** The `window` option means multiple valid tokens exist. If using timingSafeEqual, need to check each window step individually with constant-time comparison.
49
+
50
+ #### BUG-1: Massive Code Duplication — TwoFactorGuard vs TwoFactorForceGuard
51
+ **Severity:** CRITICAL | **Category:** Code Quality / Bug Risk
52
+ ```
53
+ lib/guard/two-factor.guard.ts: 254 lines
54
+ lib/guard/two-factor-force.guard.ts: 256 lines
55
+ ```
56
+ **Risk:** These two files are ~95% identical. The ONLY difference is in `canActivate()` — `TwoFactorGuard` returns `true` when no 2FA methods are enabled, while `TwoFactorForceGuard` throws `TwoFactorRequiredException`. Every bug fix in one guard must be duplicated to the other — this has already led to inconsistencies and will continue to cause maintenance bugs.
57
+ **Fix:** Extract a base guard class with all shared logic, and override only the divergent behavior:
58
+ ```typescript
59
+ abstract class BaseTwoFactorGuard implements CanActivate {
60
+ // ... all shared code (getPolicy, getAllowedTypes, verify*, getProvider*, getField*)
61
+
62
+ protected abstract handleNoEnabledMethods(): boolean | never;
63
+
64
+ async canActivate(context: ExecutionContext): Promise<boolean> {
65
+ // ... shared logic ...
66
+ if (enabledSettings.length === 0) {
67
+ return this.handleNoEnabledMethods();
68
+ }
69
+ // ... shared policy routing ...
70
+ }
71
+ }
72
+
73
+ class TwoFactorGuard extends BaseTwoFactorGuard {
74
+ protected handleNoEnabledMethods(): boolean { return true; }
75
+ }
76
+
77
+ class TwoFactorForceGuard extends BaseTwoFactorGuard {
78
+ protected handleNoEnabledMethods(): never { throw new TwoFactorRequiredException(); }
79
+ }
80
+ ```
81
+
82
+ ---
83
+
84
+ ### 🟡 MEDIUM
85
+
86
+ #### SEC-2: No Rate Limiting on Verification Attempts
87
+ **Severity:** MEDIUM | **Category:** Security
88
+ ```typescript
89
+ // lib/guard/two-factor.guard.ts:120
90
+ // Try each enabled provider until one succeeds
91
+ for(const setting of enabledSettings) {
92
+ const provider = this.getProviderForType(setting.type);
93
+ try {
94
+ const result = await provider.verify(token, setting.context);
95
+ ```
96
+ **Risk:** There is no rate limiting on 2FA verification attempts. A 6-digit TOTP has only 1,000,000 possible values, and with a 30-second window (+ window=1 allowing 3 values), an attacker can brute-force the token with sufficient request throughput. This is a library (not an app), but it should either:
97
+ 1. Document that rate limiting is the consumer's responsibility, or
98
+ 2. Provide an optional built-in rate limiter hook
99
+ **Fix:** Add `@design` remark documenting this trust boundary, and add a JSDoc warning on the guard class.
100
+
101
+ #### BUG-2: `switchToHttp()` Without Transport Check
102
+ **Severity:** MEDIUM | **Category:** Bug
103
+ ```typescript
104
+ // lib/guard/two-factor.guard.ts:49
105
+ const request = context.switchToHttp().getRequest();
106
+ ```
107
+ **Risk:** If this guard is used on a WebSocket or RPC handler, `switchToHttp()` will return an object without proper `body`/`headers` properties, causing silent failures or cryptic errors.
108
+ **Fix:** Check context type before switching:
109
+ ```typescript
110
+ const contextType = context.getType();
111
+ if (contextType !== 'http') {
112
+ this.logger.warn(`TwoFactorGuard only supports HTTP context, got: ${contextType}`);
113
+ return true; // or throw, depending on security policy
114
+ }
115
+ ```
116
+
117
+ #### TYPE-1: `any` Types in Public API
118
+ **Severity:** MEDIUM | **Category:** Type Safety
119
+ **Locations:**
120
+ - `two-factor-auth.interface.ts:18` — `TwoFactorProviderRegistration.options?: any`
121
+ - `two-factor-auth.interface.ts:78` — `useFactory?: (...args: any[]) => ...`
122
+ - `two-factor-auth.interface.ts:80` — `inject?: any[]`
123
+ - `two-factor.guard.ts:216,225,234` — `request: any`, `getFieldFromRequest` returns `any`
124
+ - `two-factor.provider.ts:22` — `qrcodePackage: any`
125
+ - `two-factor.provider.ts:24` — `authenticator: any`
126
+
127
+ **Risk:** Public API consumers get no type guidance. Internal `any` for lazy-loaded packages is less critical but still reduces compile-time safety.
128
+ **Fix:**
129
+ - `TwoFactorProviderRegistration.options` → `Record<string, unknown>` or generic `<T>`
130
+ - `useFactory` inject → follows NestJS pattern (acceptable)
131
+ - `request` → define a minimal `TwoFactorRequest` interface
132
+ - `authenticator` / `qrcodePackage` → define minimal interfaces
133
+
134
+ #### ENH-1: `createTwoFactorProvidersMap` Bypasses DI
135
+ **Severity:** MEDIUM | **Category:** API Design
136
+ ```typescript
137
+ // lib/module/two-factor.provider.ts:24
138
+ for(const providerReg of options.providers) {
139
+ const providerInstance = new providerReg.provider(providerReg.options);
140
+ providersMap.set(providerReg.type, providerInstance);
141
+ }
142
+ ```
143
+ **Risk:** Provider instances are created with `new` instead of through NestJS DI. This means:
144
+ 1. Providers can't inject other services (e.g., a database service for SMS OTP)
145
+ 2. No lifecycle hooks (`OnModuleInit`, `OnModuleDestroy`)
146
+ 3. No request-scoped providers possible
147
+ **Fix:** Use `ModuleRef.create()` or register each provider through the module's providers array and inject them by token. This is an architectural limitation that should be documented if not fixed.
148
+
149
+ #### SEC-3: TOTP Authenticator Options Set Globally
150
+ **Severity:** MEDIUM | **Category:** Security
151
+ ```typescript
152
+ // lib/provider/two-factor.provider.ts:36
153
+ this.authenticator.options = { window: this.options.window };
154
+ ```
155
+ **Risk:** `otplib`'s authenticator is a singleton. If multiple `OtpLibTwoFactorAuthProvider` instances are created with different window settings, they will overwrite each other's configuration. The last one wins.
156
+ **Fix:** Use `authenticator.clone()` or create a per-instance authenticator:
157
+ ```typescript
158
+ const { authenticator: Authenticator } = loadPackage('otplib');
159
+ this.authenticator = Authenticator.clone();
160
+ this.authenticator.options = { window: this.options.window };
161
+ ```
162
+
163
+ #### ENH-2: Typo in Injection Token — `TWO_FACTORY_SETTING_PROVIDER`
164
+ **Severity:** MEDIUM | **Category:** Style / API
165
+ ```typescript
166
+ // lib/module/two-factor-auth.interface.ts:11
167
+ export const TWO_FACTORY_SETTING_PROVIDER = 'TWO_FACTORY_SETTING_PROVIDER';
168
+ ```
169
+ **Risk:** `FACTORY` should be `FACTOR`. This token appears to be unused currently, but if exported and consumed, it would be a confusing API. If it's consumed anywhere externally, renaming is a breaking change.
170
+ **Fix:** Check if it's used externally. If not, rename to `TWO_FACTOR_SETTING_PROVIDER`. If it is, deprecate and alias.
171
+
172
+ ---
173
+
174
+ ### 🟢 LOW
175
+
176
+ #### STYLE-1: Missing JSDoc on Guard Public APIs
177
+ **Severity:** LOW | **Category:** Documentation
178
+ The `TwoFactorGuard` and `TwoFactorForceGuard` classes lack JSDoc on the class itself and on `canActivate()`. Consumers need to understand the difference between "soft" and "force" guards.
179
+
180
+ #### STYLE-2: Import from `dist/` Path
181
+ **Severity:** LOW | **Category:** Build
182
+ ```typescript
183
+ // lib/provider/two-factor-setting.provider.ts:1
184
+ import { IPrincipal } from "@nathapp/nestjs-auth/dist";
185
+ ```
186
+ **Risk:** Importing from `/dist` is fragile — if the build output structure changes, this breaks. Should import from the package root.
187
+ **Fix:** `import { IPrincipal } from "@nathapp/nestjs-auth";`
188
+
189
+ #### ENH-3: `TwoFactorAuthOptions` Only Supports TOTP
190
+ **Severity:** LOW | **Category:** API Design
191
+ ```typescript
192
+ export type TwoFactorAuthOptions = TotpAuthOptions;
193
+ ```
194
+ **Risk:** The type alias suggests extensibility but currently only maps to TOTP. When SMS_OTP or EMAIL_OTP options are added, this type needs to become a discriminated union. Not a bug today, but a design limitation to note.
195
+
196
+ #### STYLE-3: Inconsistent Error Types
197
+ **Severity:** LOW | **Category:** API Design
198
+ - `OtpLibTwoFactorAuthProvider.verify()` throws generic `Error('TOTP verification requires secret in context')`
199
+ - Guards throw domain-specific `TwoFactorRequiredException` and `TwoFactorInvalidException`
200
+
201
+ The provider should also throw domain-specific exceptions for consistency.
202
+
203
+ #### ENH-4: No `OnModuleDestroy` Cleanup
204
+ **Severity:** LOW | **Category:** Memory
205
+ The `OtpLibTwoFactorAuthProvider` stores references to `otplib` and `qrcode` packages. While not a leak per se (they're singletons), documenting the lifecycle is good practice for a security library.
206
+
207
+ ---
208
+
209
+ ## Grading Rubric
210
+
211
+ | Dimension | Score | Rationale |
212
+ |:---|:---|:---|
213
+ | **Security** | 14/20 | TOTP timing attack risk, no rate limiting guidance, global authenticator state |
214
+ | **Reliability** | 17/20 | Good error handling in guards, missing HTTP context check, DI bypass for providers |
215
+ | **API Design** | 16/20 | Clean decorator pattern, flexible policies, but DI bypass and TOTP-only options type |
216
+ | **Code Quality** | 15/20 | Excellent test ratio (2.3:1), but massive guard duplication and `any` types |
217
+ | **Best Practices** | 20/20 | Proper use of NestJS patterns (ConfigurableModuleClass, Reflector, loadPackage) |
218
+
219
+ **Total Score: 82/100 (B+)**
220
+
221
+ ---
222
+
223
+ ## Priority Fix Order
224
+
225
+ | Priority | ID | Effort | Description |
226
+ |:---|:---|:---|:---|
227
+ | P0 | SEC-1 | M | Add timing-safe TOTP comparison |
228
+ | P0 | BUG-1 | M | Extract base guard class to eliminate duplication |
229
+ | P1 | SEC-3 | S | Clone authenticator per instance |
230
+ | P1 | BUG-2 | S | Add ExecutionContext type check |
231
+ | P1 | TYPE-1 | M | Replace `any` types in public API |
232
+ | P1 | ENH-1 | L | Document or fix DI bypass for provider instantiation |
233
+ | P2 | SEC-2 | S | Document rate limiting trust boundary |
234
+ | P2 | ENH-2 | S | Fix FACTORY→FACTOR typo |
235
+ | P2 | STYLE-2 | S | Fix dist/ import path |
236
+ | P3 | STYLE-1 | M | Add JSDoc to guards |
237
+ | P3 | ENH-3 | S | Document TwoFactorAuthOptions extensibility plan |
238
+ | P3 | STYLE-3 | S | Use domain-specific exceptions in provider |
239
+
240
+ ---
241
+
242
+ ## Test Coverage Assessment
243
+
244
+ **Strengths:**
245
+ - All three policies (ANY, ALL, SPECIFIC) thoroughly tested
246
+ - Multi-provider scenarios tested
247
+ - Decorator metadata tests
248
+ - Module registration (sync + async) tested
249
+ - OtpLib provider with mocked otplib
250
+
251
+ **Gaps:**
252
+ - No test for `switchToHttp()` on non-HTTP context (BUG-2)
253
+ - No timing attack validation (SEC-1)
254
+ - No test for concurrent provider instantiation with different windows (SEC-3)
255
+ - No test for malformed/missing request body fields (edge cases)
256
+
257
+ ---
258
+
259
+ ## Recommendations
260
+
261
+ 1. **Immediate (P0):** Fix SEC-1 (timing-safe comparison) and BUG-1 (guard deduplication). These are the two highest-value changes.
262
+ 2. **Before 3.0.0:** Address P1 items. SEC-3 (authenticator clone) is a subtle bug that will bite in production.
263
+ 3. **The guard duplication is the single biggest maintenance risk.** Every future policy change or bug fix must be applied twice. Extract the base class now to prevent divergence.
264
+ 4. **Document trust boundaries:** Rate limiting, encryption-at-rest, and transport restrictions should be clearly documented as consumer responsibilities.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-auth-2fa",
3
- "version": "2.1.5",
3
+ "version": "3.0.0-rc.4",
4
4
  "description": "nestjs-auth-2fa",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -30,12 +30,12 @@
30
30
  "lib": "lib"
31
31
  },
32
32
  "dependencies": {
33
- "@nathapp/nestjs-auth": "^2.1.5",
34
- "@nathapp/nestjs-common": "^2.1.5"
33
+ "@nathapp/nestjs-auth": "^3.0.0-rc.4",
34
+ "@nathapp/nestjs-common": "^3.0.0-rc.4"
35
35
  },
36
36
  "peerDependencies": {
37
- "@nathapp/nestjs-auth": "^2.1.5",
38
- "@nathapp/nestjs-common": "^2.1.5",
37
+ "@nathapp/nestjs-auth": "^3.0.0-rc.4",
38
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
39
39
  "otplib": "^12.0.1",
40
40
  "qrcode": "^1.5.4"
41
41
  },