@nathapp/nestjs-common 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.
- package/CLAUDE.md +29 -0
- package/README.md +134 -0
- package/dist/config/index.d.ts +4 -4
- package/dist/config/index.js.map +1 -1
- package/dist/config/server-security.config.d.ts +1 -0
- package/dist/config/server-security.config.js +19 -2
- package/dist/config/server-security.config.js.map +1 -1
- package/dist/decorator/index.d.ts +2 -2
- package/dist/decorator/index.js.map +1 -1
- package/dist/entities/base-entity.d.ts +3 -0
- package/dist/entities/base-entity.js +8 -0
- package/dist/entities/base-entity.js.map +1 -0
- package/dist/entities/index.d.ts +1 -0
- package/dist/entities/index.js +18 -0
- package/dist/entities/index.js.map +1 -0
- package/dist/exception/app.exception.d.ts +4 -3
- package/dist/exception/app.exception.js +1 -1
- package/dist/exception/app.exception.js.map +1 -1
- package/dist/exception/default-i18n-validation-exception.filter.js +1 -1
- package/dist/exception/default-i18n-validation-exception.filter.js.map +1 -1
- package/dist/exception/exception.constants.d.ts +1 -0
- package/dist/exception/exception.constants.js +5 -0
- package/dist/exception/exception.constants.js.map +1 -0
- package/dist/exception/exception.module.d.ts +7 -0
- package/dist/exception/exception.module.js +41 -0
- package/dist/exception/exception.module.js.map +1 -0
- package/dist/exception/exceptions/auth.exception.d.ts +4 -0
- package/dist/exception/exceptions/auth.exception.js +12 -0
- package/dist/exception/exceptions/auth.exception.js.map +1 -0
- package/dist/exception/exceptions/forbidden-app.exception.d.ts +4 -0
- package/dist/exception/exceptions/forbidden-app.exception.js +12 -0
- package/dist/exception/exceptions/forbidden-app.exception.js.map +1 -0
- package/dist/exception/exceptions/index.d.ts +6 -0
- package/dist/exception/exceptions/index.js +16 -0
- package/dist/exception/exceptions/index.js.map +1 -0
- package/dist/exception/exceptions/internal-app.exception.d.ts +4 -0
- package/dist/exception/exceptions/internal-app.exception.js +12 -0
- package/dist/exception/exceptions/internal-app.exception.js.map +1 -0
- package/dist/exception/exceptions/not-found-app.exception.d.ts +4 -0
- package/dist/exception/exceptions/not-found-app.exception.js +12 -0
- package/dist/exception/exceptions/not-found-app.exception.js.map +1 -0
- package/dist/exception/exceptions/throttle-app.exception.d.ts +4 -0
- package/dist/exception/exceptions/throttle-app.exception.js +12 -0
- package/dist/exception/exceptions/throttle-app.exception.js.map +1 -0
- package/dist/exception/exceptions/validation-app.exception.d.ts +4 -0
- package/dist/exception/exceptions/validation-app.exception.js +12 -0
- package/dist/exception/exceptions/validation-app.exception.js.map +1 -0
- package/dist/exception/global-exception.filter.d.ts +8 -54
- package/dist/exception/global-exception.filter.js +45 -163
- package/dist/exception/global-exception.filter.js.map +1 -1
- package/dist/exception/handler/app-exception.handler.d.ts +7 -0
- package/dist/exception/handler/app-exception.handler.js +44 -0
- package/dist/exception/handler/app-exception.handler.js.map +1 -0
- package/dist/exception/handler/bad-request.handler.d.ts +6 -0
- package/dist/exception/handler/bad-request.handler.js +30 -0
- package/dist/exception/handler/bad-request.handler.js.map +1 -0
- package/dist/exception/handler/exception-handler.interface.d.ts +14 -0
- package/dist/exception/handler/exception-handler.interface.js +3 -0
- package/dist/exception/handler/exception-handler.interface.js.map +1 -0
- package/dist/exception/handler/forbidden.handler.d.ts +6 -0
- package/dist/exception/handler/forbidden.handler.js +27 -0
- package/dist/exception/handler/forbidden.handler.js.map +1 -0
- package/dist/exception/handler/index.d.ts +11 -0
- package/dist/exception/handler/index.js +38 -0
- package/dist/exception/handler/index.js.map +1 -0
- package/dist/exception/handler/microservice.handler.d.ts +6 -0
- package/dist/exception/handler/microservice.handler.js +27 -0
- package/dist/exception/handler/microservice.handler.js.map +1 -0
- package/dist/exception/handler/not-found.handler.d.ts +6 -0
- package/dist/exception/handler/not-found.handler.js +27 -0
- package/dist/exception/handler/not-found.handler.js.map +1 -0
- package/dist/exception/handler/throttler.handler.d.ts +6 -0
- package/dist/exception/handler/throttler.handler.js +33 -0
- package/dist/exception/handler/throttler.handler.js.map +1 -0
- package/dist/exception/handler/unknown.handler.d.ts +6 -0
- package/dist/exception/handler/unknown.handler.js +35 -0
- package/dist/exception/handler/unknown.handler.js.map +1 -0
- package/dist/exception/handler/username-not-found.handler.d.ts +6 -0
- package/dist/exception/handler/username-not-found.handler.js +28 -0
- package/dist/exception/handler/username-not-found.handler.js.map +1 -0
- package/dist/exception/index.d.ts +7 -4
- package/dist/exception/index.js +12 -3
- package/dist/exception/index.js.map +1 -1
- package/dist/exception/micro-service.exception.js +1 -1
- package/dist/exception/micro-service.exception.js.map +1 -1
- package/dist/exception/user-not-found.exception.js +1 -1
- package/dist/http/index.d.ts +3 -3
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/interceptor/serializable.interceptor.d.ts +4 -2
- package/dist/interceptor/serializable.interceptor.js +75 -18
- package/dist/interceptor/serializable.interceptor.js.map +1 -1
- package/dist/ip/index.d.ts +3 -2
- package/dist/ip/index.js +4 -1
- package/dist/ip/index.js.map +1 -1
- package/dist/ip/request-ip.d.ts +4 -2
- package/dist/ip/request-ip.js +92 -30
- package/dist/ip/request-ip.js.map +1 -1
- package/dist/ip/trusted-proxy-presets.d.ts +3 -0
- package/dist/ip/trusted-proxy-presets.js +114 -0
- package/dist/ip/trusted-proxy-presets.js.map +1 -0
- package/dist/module/configurable-module.builder.js +3 -1
- package/dist/module/configurable-module.builder.js.map +1 -1
- package/dist/module/index.d.ts +5 -5
- package/dist/module/index.js.map +1 -1
- package/dist/pagination/index.d.ts +1 -0
- package/dist/pagination/index.js +18 -0
- package/dist/pagination/index.js.map +1 -0
- package/dist/pagination/page.d.ts +39 -0
- package/dist/pagination/page.js +87 -0
- package/dist/pagination/page.js.map +1 -0
- package/dist/serialize/localize.string.js.map +1 -1
- package/dist/utils/package-utils.js +3 -0
- package/dist/utils/package-utils.js.map +1 -1
- package/dist/validation/index.d.ts +1 -0
- package/dist/validation/index.js +1 -0
- package/dist/validation/index.js.map +1 -1
- package/dist/validation/validators.d.ts +3 -0
- package/dist/validation/validators.js +29 -0
- package/dist/validation/validators.js.map +1 -0
- package/docs/20260214-coverage-plan.md +52 -0
- package/docs/20260214-fix-plan-common-bugs.md +90 -0
- package/docs/20260214-fix-plan-common-cleanup.md +119 -0
- package/docs/20260214-fix-plan-exception-redesign.md +274 -0
- package/docs/20260214-fix-plan-nestjs-prisma.md +454 -0
- package/docs/20260214-fix-plan-pagination-move-and-rename.md +148 -0
- package/docs/20260214-review-common.md +426 -0
- package/docs/20260215-fix-plan-review-enhancements.md +110 -0
- package/docs/20260215-fix-plan-trust-proxy-presets.md +227 -0
- package/docs/20260215-review-nestjs-common.md +1015 -0
- package/docs/trust-proxy-security.md +475 -0
- package/package.json +1 -1
- package/dist/exception/app-exception.filter.d.ts +0 -9
- package/dist/exception/app-exception.filter.js +0 -52
- package/dist/exception/app-exception.filter.js.map +0 -1
- package/dist/i18n/i18n.constants.d.ts +0 -0
- package/dist/i18n/i18n.constants.js +0 -1
- package/dist/i18n/i18n.constants.js.map +0 -1
- package/dist/middleware/index.d.ts +0 -4
- package/dist/middleware/index.js +0 -14
- package/dist/middleware/index.js.map +0 -1
- package/dist/middleware/log.provider.d.ts +0 -38
- package/dist/middleware/log.provider.js +0 -147
- package/dist/middleware/log.provider.js.map +0 -1
- package/dist/middleware/logger-option.factory.d.ts +0 -17
- package/dist/middleware/logger-option.factory.js +0 -73
- package/dist/middleware/logger-option.factory.js.map +0 -1
- package/dist/middleware/logger.middleware.d.ts +0 -8
- package/dist/middleware/logger.middleware.js +0 -97
- package/dist/middleware/logger.middleware.js.map +0 -1
|
@@ -0,0 +1,1015 @@
|
|
|
1
|
+
# Code Review: @nathapp/nestjs-common (Pre-3.0.0)
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-15
|
|
4
|
+
**Reviewer:** Subrina (Deep Review)
|
|
5
|
+
**Scope:** Full lib/ source (~2355 lines across 73 files)
|
|
6
|
+
**Branch:** feat/monorepo-enterprise-upgrade
|
|
7
|
+
|
|
8
|
+
## Executive Summary
|
|
9
|
+
|
|
10
|
+
**Grade: B+**
|
|
11
|
+
|
|
12
|
+
The `@nathapp/nestjs-common` package demonstrates solid architectural patterns with the new exception handler chain design being a standout improvement. Code quality is generally high with good separation of concerns and strong TypeScript usage. However, several critical issues around object mutation, security configurations, and type safety prevent an A grade. The package is production-ready with minor fixes required for enterprise deployment.
|
|
13
|
+
|
|
14
|
+
**Key Strengths:**
|
|
15
|
+
- Excellent exception handler chain pattern (ExceptionHandler interface + GlobalExceptionsFilter)
|
|
16
|
+
- Strong DI integration with ConfigurableModuleBuilder enhancements
|
|
17
|
+
- Comprehensive i18n support with validation
|
|
18
|
+
- Well-structured pagination and serialization utilities
|
|
19
|
+
|
|
20
|
+
**Critical Issues:**
|
|
21
|
+
- Object mutation in SerializableInterceptor (data corruption risk)
|
|
22
|
+
- Trust proxy security misconfiguration risks
|
|
23
|
+
- Type safety gaps in exception handling (`any` types)
|
|
24
|
+
- Static state in GlobalExceptionsFilter (testing concerns)
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 1. Enterprise Grade
|
|
29
|
+
|
|
30
|
+
### Findings
|
|
31
|
+
|
|
32
|
+
**BUG-1** | CRITICAL | `lib/interceptor/serializable.interceptor.ts:46-67`
|
|
33
|
+
**Object Mutation in transformObject**
|
|
34
|
+
The `transformObject` method directly mutates the input object via `obj[key] = ...` assignments. This violates immutability principles and can cause unexpected side effects when the same object is reused elsewhere in the application.
|
|
35
|
+
|
|
36
|
+
**Fix:**
|
|
37
|
+
```typescript
|
|
38
|
+
transformObject(obj: PlainLiteralObject, lang: string) {
|
|
39
|
+
const result = { ...obj }; // Create shallow copy
|
|
40
|
+
for (const [key, value] of Object.entries(result)) {
|
|
41
|
+
if (this.isObject(value)) {
|
|
42
|
+
if (value instanceof LocaleString) {
|
|
43
|
+
result[key] = this.transformLocaleString(value, lang);
|
|
44
|
+
} else if (value instanceof LocaleObject) {
|
|
45
|
+
const transformed = this.transformLocaleObject(value, lang);
|
|
46
|
+
if (transformed) {
|
|
47
|
+
result[key] = transformed;
|
|
48
|
+
} else {
|
|
49
|
+
delete result[key];
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
result[key] = this.transformObject(value, lang);
|
|
53
|
+
}
|
|
54
|
+
} else if (Array.isArray(value)) {
|
|
55
|
+
result[key] = value.map((item: PlainLiteralObject) =>
|
|
56
|
+
this.isObject(item) ? this.transformObject(item, lang) : item
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
**WARN-1** | HIGH | `lib/exception/global-exception.filter.ts:20-22, 33-39`
|
|
67
|
+
**Static State in GlobalExceptionsFilter**
|
|
68
|
+
The static `customHandlers` Map breaks NestJS DI principles and causes issues in testing (handlers persist across test runs). The `registerHandler` / `clearHandlers` pattern is not thread-safe and violates dependency injection.
|
|
69
|
+
|
|
70
|
+
**Fix:** Remove static handler registration. Use only DI-injected handlers from `ExceptionModule.forRoot({ handlers })`. If dynamic registration is truly needed, document it as deprecated and provide migration guide.
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
**WARN-2** | HIGH | `lib/ip/request-ip.ts:37-46`
|
|
75
|
+
**Module-Level State Not Thread-Safe**
|
|
76
|
+
Variables `trustProxyConfig`, `hasWarnedAboutTrustProxy`, `trustProxyConfiguredBy` use module-level mutable state. In Node.js worker threads or multi-threaded environments, this can cause race conditions.
|
|
77
|
+
|
|
78
|
+
**Fix:** Consider making trust proxy configuration immutable after first initialization, or use a singleton service with proper locking.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
**WARN-3** | MEDIUM | `lib/exception/app.exception.ts:6-15`
|
|
83
|
+
**Untyped Exception Arguments**
|
|
84
|
+
`AppException` constructor accepts `args?: any`, reducing type safety. Developers lose autocomplete and type checking when passing exception arguments.
|
|
85
|
+
|
|
86
|
+
**Fix:**
|
|
87
|
+
```typescript
|
|
88
|
+
export interface AppExceptionArgs {
|
|
89
|
+
[key: string]: string | number | boolean | undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export class AppException extends HttpException {
|
|
93
|
+
private _args?: AppExceptionArgs;
|
|
94
|
+
// ...
|
|
95
|
+
constructor(code: number, args?: AppExceptionArgs, prefix?: string, httpStatus?: number) {
|
|
96
|
+
// ...
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
**WARN-4** | MEDIUM | `lib/pagination/page.ts:62-72`
|
|
104
|
+
**Page Mutation in toInstance/toPlain**
|
|
105
|
+
Methods `toInstance()` and `toPlain()` mutate the Page object by deleting `transformOptions` and modifying `records`. This makes the Page object single-use and can surprise developers.
|
|
106
|
+
|
|
107
|
+
**Fix:** Return new Page instances instead of mutating, or clearly document the mutation behavior with JSDoc `@mutates`.
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
**INFO-1** | LOW | Multiple files
|
|
112
|
+
**Missing JSDoc Documentation**
|
|
113
|
+
Public APIs lack comprehensive JSDoc comments. Examples needed:
|
|
114
|
+
- `GlobalExceptionsFilter.catch()`
|
|
115
|
+
- `SerializableInterceptor` methods
|
|
116
|
+
- `ConfigurableModuleBuilder.externallyConfigured()`
|
|
117
|
+
- All exception classes
|
|
118
|
+
|
|
119
|
+
**Fix:** Add JSDoc with `@param`, `@returns`, `@throws`, and `@example` tags for all public APIs.
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
**INFO-2** | LOW | `lib/exception/handler/app-exception.handler.ts:27-43`
|
|
124
|
+
**Inconsistent HTTP Status Mapping**
|
|
125
|
+
`getStatusCodeFromErrorCode()` maps `CAPTCHA_ERROR`, `TWO_FACTOR_REQUIRED`, `TWO_FACTOR_INVALID` to 403, but these might be better suited for 400 (client error) depending on API design philosophy.
|
|
126
|
+
|
|
127
|
+
**Recommendation:** Document the rationale for 403 vs 400 for these cases, or make it configurable.
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
**WARN-5** | MEDIUM | `lib/exception/handler/throttler.handler.ts:9-13`
|
|
132
|
+
**Fragile instanceof Check**
|
|
133
|
+
Using `(exception as any).constructor?.name === 'ThrottlerException'` is fragile. If the class is minified or comes from a different package version, the name check will fail.
|
|
134
|
+
|
|
135
|
+
**Fix:**
|
|
136
|
+
```typescript
|
|
137
|
+
canHandle(exception: unknown): boolean {
|
|
138
|
+
if (!exception || typeof exception !== 'object') return false;
|
|
139
|
+
// Check for ThrottlerException characteristics instead of name
|
|
140
|
+
return exception instanceof Error &&
|
|
141
|
+
'getStatus' in exception &&
|
|
142
|
+
(exception as any).getStatus?.() === 429;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Or better: import and use `instanceof ThrottlerException` directly from `@nestjs/throttler` (add as optional peer dependency).
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 2. Extensibility
|
|
151
|
+
|
|
152
|
+
### Findings
|
|
153
|
+
|
|
154
|
+
**GOOD-1** | Excellent Exception Handler Chain Pattern
|
|
155
|
+
The `ExceptionHandler` interface with `canHandle()` + `handle()` methods and priority-ordered chain execution is a well-designed Chain of Responsibility pattern. External developers can easily add custom handlers via `ExceptionModule.forRoot({ handlers: [...] })`.
|
|
156
|
+
|
|
157
|
+
**Example:**
|
|
158
|
+
```typescript
|
|
159
|
+
@Injectable()
|
|
160
|
+
export class CustomPaymentExceptionHandler implements ExceptionHandler {
|
|
161
|
+
canHandle(exception: unknown): boolean {
|
|
162
|
+
return exception instanceof StripePaymentException;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async handle(exception: unknown, context: ExceptionContext): Promise<ExceptionResult> {
|
|
166
|
+
// Custom handling
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
ExceptionModule.forRoot({
|
|
171
|
+
handlers: [CustomPaymentExceptionHandler]
|
|
172
|
+
})
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
**GOOD-2** | ConfigurableModuleBuilder Enhancement
|
|
178
|
+
The `externallyConfigured()` method and `setExtras()` pattern provide excellent extensibility for creating reusable NestJS modules. The `Subject`-based module definition passing is creative.
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
**WARN-6** | MEDIUM | `lib/serialize/localize.string.ts:1-5`
|
|
183
|
+
**No Type Safety for Locale Keys**
|
|
184
|
+
`LocaleString` and `LocaleObject` use `[key: string]: T` index signatures without constraining locale keys. Developers can accidentally use invalid locale codes.
|
|
185
|
+
|
|
186
|
+
**Enhancement:**
|
|
187
|
+
```typescript
|
|
188
|
+
type SupportedLocale = 'en_US' | 'zh_CN' | 'ms_MY' | 'id_ID'; // etc.
|
|
189
|
+
|
|
190
|
+
export class LocaleString {
|
|
191
|
+
[key: string]: string; // Keep for runtime flexibility
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export type TypedLocaleString = Partial<Record<SupportedLocale, string>>;
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Provide typed factory functions:
|
|
198
|
+
```typescript
|
|
199
|
+
export function createLocaleString(locales: TypedLocaleString): LocaleString {
|
|
200
|
+
return locales as LocaleString;
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
**INFO-3** | LOW | `lib/interceptor/serializable.interceptor.ts`
|
|
207
|
+
**No Extension Points for Custom Serialization**
|
|
208
|
+
The `SerializableInterceptor` hard-codes transformation logic. External developers cannot easily inject custom serialization steps (e.g., for custom types beyond LocaleString/LocaleObject).
|
|
209
|
+
|
|
210
|
+
**Enhancement:** Add a `CustomSerializer` interface and allow injection:
|
|
211
|
+
```typescript
|
|
212
|
+
export interface CustomSerializer {
|
|
213
|
+
canHandle(value: any): boolean;
|
|
214
|
+
serialize(value: any, lang: string): any;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
@Injectable()
|
|
218
|
+
export class SerializableInterceptor extends ClassSerializerInterceptor {
|
|
219
|
+
constructor(
|
|
220
|
+
@Inject(REFLECTOR) protected readonly reflector: any,
|
|
221
|
+
@Optional() @Inject(CUSTOM_SERIALIZERS) private customSerializers?: CustomSerializer[],
|
|
222
|
+
@Optional() protected readonly defaultOptions: ClassSerializerInterceptorOptions = {},
|
|
223
|
+
) { super(reflector, defaultOptions); }
|
|
224
|
+
|
|
225
|
+
transformObject(obj: PlainLiteralObject, lang: string) {
|
|
226
|
+
// Check custom serializers first
|
|
227
|
+
for (const serializer of this.customSerializers || []) {
|
|
228
|
+
if (serializer.canHandle(obj)) {
|
|
229
|
+
return serializer.serialize(obj, lang);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
// ... existing logic
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
**GOOD-3** | Validation Constraint Extensibility
|
|
240
|
+
`BaseI18nValidatorConstraint` provides a clean base class for custom validators with i18n support. Good pattern.
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## 3. Security
|
|
245
|
+
|
|
246
|
+
### Findings
|
|
247
|
+
|
|
248
|
+
**SEC-1** | CRITICAL | `lib/ip/request-ip.ts:104-118, 130-157`
|
|
249
|
+
**Trust Proxy Default Configuration is Insecure**
|
|
250
|
+
When `trustProxyConfig.enabled = true` (default) and no `trustedProxies` list is provided, the system trusts ALL forwarded headers with just a console warning. This is a **security vulnerability** allowing IP spoofing.
|
|
251
|
+
|
|
252
|
+
**Attack Scenario:**
|
|
253
|
+
```
|
|
254
|
+
Attacker → (X-Forwarded-For: 192.168.1.1) → Your Server
|
|
255
|
+
Your server trusts the header → Attacker bypasses IP-based access controls
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
**Fix:**
|
|
259
|
+
```typescript
|
|
260
|
+
function shouldTrustProxyHeaders(req: any): boolean {
|
|
261
|
+
const trustedProxies = trustProxyConfig.trustedProxies ||
|
|
262
|
+
(process.env.TRUSTED_PROXIES?.split(',').filter(Boolean).map(p => p.trim()));
|
|
263
|
+
|
|
264
|
+
// BREAKING CHANGE: Fail-closed instead of fail-open
|
|
265
|
+
if (trustProxyConfig.enabled === false) {
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (!trustedProxies || trustedProxies.length === 0) {
|
|
270
|
+
// Log ERROR instead of WARN and return false
|
|
271
|
+
console.error(
|
|
272
|
+
'[nestjs-common] SECURITY: Trust proxy enabled without trustedProxies list. ' +
|
|
273
|
+
'Rejecting all forwarded headers. Configure trustedProxies to fix this.'
|
|
274
|
+
);
|
|
275
|
+
return false; // CHANGED from true
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const remoteAddr = getRemoteAddress(req);
|
|
279
|
+
if (!remoteAddr) return false;
|
|
280
|
+
|
|
281
|
+
return isIpTrusted(remoteAddr, trustedProxies);
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
**Documentation Required:**
|
|
286
|
+
Add a prominent security warning in README.md:
|
|
287
|
+
|
|
288
|
+
```markdown
|
|
289
|
+
## ⚠️ Security: Trust Proxy Configuration
|
|
290
|
+
|
|
291
|
+
**CRITICAL:** Before deploying to production, configure trust proxy settings:
|
|
292
|
+
|
|
293
|
+
\`\`\`typescript
|
|
294
|
+
// In main.ts or app bootstrap
|
|
295
|
+
import { configureTrustProxy } from '@nathapp/nestjs-common';
|
|
296
|
+
|
|
297
|
+
configureTrustProxy({
|
|
298
|
+
enabled: true,
|
|
299
|
+
trustedProxies: [
|
|
300
|
+
'10.0.0.0/8', // Your load balancer subnet
|
|
301
|
+
'172.16.0.1', // Specific proxy IP
|
|
302
|
+
]
|
|
303
|
+
}, 'AppBootstrap');
|
|
304
|
+
\`\`\`
|
|
305
|
+
|
|
306
|
+
**Default behavior:** If you don't configure this, all `X-Forwarded-*` headers are rejected for security.
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
---
|
|
310
|
+
|
|
311
|
+
**SEC-2** | HIGH | `lib/ip/request-ip.ts:204-208`
|
|
312
|
+
**X-Forwarded-For Parsing Accepts First IP Blindly**
|
|
313
|
+
The function `getClientIpFromXForwardedFor` returns the first valid IP in the header. But the first IP is client-controlled. Attackers can inject fake IPs.
|
|
314
|
+
|
|
315
|
+
**Correct Approach:**
|
|
316
|
+
Read `X-Forwarded-For` from right to left, stopping at the first untrusted IP:
|
|
317
|
+
```
|
|
318
|
+
X-Forwarded-For: <client>, <proxy1>, <proxy2>, <load-balancer>
|
|
319
|
+
^attacker controlled ^trusted
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
**Fix:**
|
|
323
|
+
```typescript
|
|
324
|
+
function getClientIpFromXForwardedFor(value: string, trustedProxyCount: number = 0): string | null {
|
|
325
|
+
if (!is.existy(value) || !is.string(value)) return null;
|
|
326
|
+
|
|
327
|
+
const ips = value.split(',').map(e => e.trim()).reverse(); // Read right-to-left
|
|
328
|
+
|
|
329
|
+
// Skip trusted proxies from the right
|
|
330
|
+
const clientIpIndex = Math.min(trustedProxyCount, ips.length - 1);
|
|
331
|
+
|
|
332
|
+
for (let i = clientIpIndex; i < ips.length; i++) {
|
|
333
|
+
let ip = ips[i];
|
|
334
|
+
if (ip.includes(':')) {
|
|
335
|
+
const [ipPart] = ip.split(':');
|
|
336
|
+
ip = ipPart;
|
|
337
|
+
}
|
|
338
|
+
if (is.ip(ip)) {
|
|
339
|
+
return ip;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
**SEC-3** | MEDIUM | `lib/serialize/localize.string.ts:30-43, 48-61`
|
|
350
|
+
**Unsafe JSON.parse in parseLocaleString/parseLocaleObject**
|
|
351
|
+
`JSON.parse(source)` can throw on malformed JSON, but errors are silently caught and `defaultValue` is used. In some contexts, silently accepting malformed data could mask injection attempts or data corruption.
|
|
352
|
+
|
|
353
|
+
**Fix:** Add validation and logging:
|
|
354
|
+
```typescript
|
|
355
|
+
export const parseLocaleString = (
|
|
356
|
+
source: string,
|
|
357
|
+
defaultValue: string = '',
|
|
358
|
+
defaultLocale = 'en_US'
|
|
359
|
+
): LocaleString => {
|
|
360
|
+
const result = new LocaleString();
|
|
361
|
+
|
|
362
|
+
try {
|
|
363
|
+
const parsed = JSON.parse(source);
|
|
364
|
+
|
|
365
|
+
// Validate parsed value is an object
|
|
366
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
367
|
+
console.warn(`[LocaleString] Invalid JSON structure, using default: ${source.substring(0, 50)}`);
|
|
368
|
+
result[defaultLocale] = defaultValue;
|
|
369
|
+
return result;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Validate all values are strings
|
|
373
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
374
|
+
if (typeof value === 'string') {
|
|
375
|
+
result[key] = value;
|
|
376
|
+
} else {
|
|
377
|
+
console.warn(`[LocaleString] Non-string value for key "${key}", skipping`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return result;
|
|
382
|
+
} catch (e) {
|
|
383
|
+
console.warn(`[LocaleString] JSON parse error: ${e instanceof Error ? e.message : 'unknown'}`);
|
|
384
|
+
result[defaultLocale] = defaultValue;
|
|
385
|
+
return result;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
---
|
|
391
|
+
|
|
392
|
+
**INFO-4** | LOW | `lib/decorator/client-info.decorator.ts:32-53`
|
|
393
|
+
**Header Injection Risk in Custom Headers**
|
|
394
|
+
The decorator reads custom headers (`country`, `os`, `app-id`) without validation. While not directly exploitable, downstream code might make assumptions about format.
|
|
395
|
+
|
|
396
|
+
**Recommendation:** Add basic validation:
|
|
397
|
+
```typescript
|
|
398
|
+
if (!isUndefinedOrNullOrEmpty(request.headers["app-id"])) {
|
|
399
|
+
const appId = request.headers["app-id"];
|
|
400
|
+
// Validate it's numeric and within reasonable range
|
|
401
|
+
if (typeof appId === 'string' && /^\d{1,10}$/.test(appId)) {
|
|
402
|
+
clientInfo.appId = appId;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
---
|
|
408
|
+
|
|
409
|
+
**WARN-7** | MEDIUM | `lib/config/server-security.config.ts:51-67`
|
|
410
|
+
**CORS Origins RegExp Parsing**
|
|
411
|
+
The regex parsing logic `value.match(/^\/(.+)\/([gimsuy]*)$/)` accepts any regex flags. Unsafe flags like `g` (global) on regex used for origin matching could cause unexpected behavior.
|
|
412
|
+
|
|
413
|
+
**Fix:**
|
|
414
|
+
```typescript
|
|
415
|
+
if (value.startsWith("/")) {
|
|
416
|
+
const match = value.match(/^\/(.+)\/([imsu]*)$/); // Remove g,y flags
|
|
417
|
+
if (match) {
|
|
418
|
+
return new RegExp(match[1], match[2]);
|
|
419
|
+
} else {
|
|
420
|
+
console.warn(`[CORS] Invalid regex pattern: ${value}`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
---
|
|
426
|
+
|
|
427
|
+
## 4. Memory & Performance
|
|
428
|
+
|
|
429
|
+
### Findings
|
|
430
|
+
|
|
431
|
+
**PERF-1** | MEDIUM | `lib/interceptor/serializable.interceptor.ts:46-67`
|
|
432
|
+
**Recursive Object Traversal Performance**
|
|
433
|
+
`transformObject` recursively walks the entire object tree. For deeply nested objects (e.g., 1000+ levels or circular references), this could cause:
|
|
434
|
+
- Stack overflow
|
|
435
|
+
- Slow response times (O(n) where n = total object properties)
|
|
436
|
+
|
|
437
|
+
**Fix:**
|
|
438
|
+
1. Add depth limit:
|
|
439
|
+
```typescript
|
|
440
|
+
transformObject(obj: PlainLiteralObject, lang: string, depth: number = 0) {
|
|
441
|
+
const MAX_DEPTH = 100;
|
|
442
|
+
if (depth > MAX_DEPTH) {
|
|
443
|
+
console.warn('[SerializableInterceptor] Max depth reached, stopping traversal');
|
|
444
|
+
return obj;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
448
|
+
// ... existing logic with depth + 1
|
|
449
|
+
}
|
|
450
|
+
return obj;
|
|
451
|
+
}
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
2. Add circular reference detection:
|
|
455
|
+
```typescript
|
|
456
|
+
private transformWithCircularCheck(obj: any, lang: string, seen = new WeakSet()) {
|
|
457
|
+
if (seen.has(obj)) {
|
|
458
|
+
console.warn('[SerializableInterceptor] Circular reference detected');
|
|
459
|
+
return obj;
|
|
460
|
+
}
|
|
461
|
+
seen.add(obj);
|
|
462
|
+
return this.transformObject(obj, lang, seen);
|
|
463
|
+
}
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
---
|
|
467
|
+
|
|
468
|
+
**PERF-2** | LOW | `lib/exception/global-exception.filter.ts:52-66`
|
|
469
|
+
**Linear Handler Search**
|
|
470
|
+
The filter iterates through all handlers in sequence for every exception. With many handlers (~20+), this becomes O(n) lookup per request.
|
|
471
|
+
|
|
472
|
+
**Optimization:** Use a Map for O(1) lookup:
|
|
473
|
+
```typescript
|
|
474
|
+
private handlerMap = new Map<string, ExceptionHandler>();
|
|
475
|
+
|
|
476
|
+
constructor(...) {
|
|
477
|
+
this.handlers = [...];
|
|
478
|
+
|
|
479
|
+
// Build fast lookup map
|
|
480
|
+
for (const handler of this.handlers) {
|
|
481
|
+
const exceptionTypes = handler.getSupportedExceptions?.() || [];
|
|
482
|
+
for (const type of exceptionTypes) {
|
|
483
|
+
this.handlerMap.set(type.name, handler);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async catch(exception: unknown, host: ArgumentsHost): Promise<void> {
|
|
489
|
+
// Fast path: check map first
|
|
490
|
+
const exceptionName = exception?.constructor?.name;
|
|
491
|
+
let handler = exceptionName ? this.handlerMap.get(exceptionName) : undefined;
|
|
492
|
+
|
|
493
|
+
// Fallback to linear search for canHandle() logic
|
|
494
|
+
if (!handler) {
|
|
495
|
+
handler = this.handlers.find(h => h.canHandle(exception));
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (handler) {
|
|
499
|
+
result = await handler.handle(exception, context);
|
|
500
|
+
}
|
|
501
|
+
// ...
|
|
502
|
+
}
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
*Note:* Current implementation is fine for <10 handlers. Optimize only if profiling shows bottleneck.
|
|
506
|
+
|
|
507
|
+
---
|
|
508
|
+
|
|
509
|
+
**PERF-3** | LOW | `lib/ip/request-ip.ts:295-306`
|
|
510
|
+
**O(n²) Header Priority Reordering**
|
|
511
|
+
The nested loop in `mw()` when setting `prioritize` option causes O(n²) complexity:
|
|
512
|
+
```typescript
|
|
513
|
+
for (const prioritizedHeader of configuration.prioritize) {
|
|
514
|
+
for (let i = 0; i < headerPriority.length; i++) { // O(n²)
|
|
515
|
+
if (prioritizedHeader === headerPriority[i]) {
|
|
516
|
+
headerPriority.splice(i, 1);
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
**Fix:** Use Set for O(n) lookup:
|
|
524
|
+
```typescript
|
|
525
|
+
if (configuration?.prioritize?.length) {
|
|
526
|
+
// Validation...
|
|
527
|
+
|
|
528
|
+
const prioritizeSet = new Set(configuration.prioritize);
|
|
529
|
+
headerPriority = [
|
|
530
|
+
...configuration.prioritize,
|
|
531
|
+
...headerPriority.filter(h => !prioritizeSet.has(h))
|
|
532
|
+
];
|
|
533
|
+
}
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
---
|
|
537
|
+
|
|
538
|
+
**WARN-8** | MEDIUM | `lib/module/configurable-module.builder.ts:93, 145`
|
|
539
|
+
**Memory Leak: moduleSubject Never Completes**
|
|
540
|
+
`InternalModuleClass.moduleSubject` is a Subject that's never completed. In applications with dynamic module loading/unloading, this prevents garbage collection.
|
|
541
|
+
|
|
542
|
+
**Fix:**
|
|
543
|
+
```typescript
|
|
544
|
+
static [self.staticMethodKey](options: ModuleOptions & ExtraModuleDefinitionOptions): DynamicModule {
|
|
545
|
+
// ... existing code
|
|
546
|
+
|
|
547
|
+
InternalModuleClass.moduleSubject.next(dynamicModule);
|
|
548
|
+
InternalModuleClass.moduleSubject.complete(); // ADD THIS
|
|
549
|
+
|
|
550
|
+
return dynamicModule;
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
However, this breaks `externallyConfigured()` if called multiple times. Consider:
|
|
555
|
+
```typescript
|
|
556
|
+
private static getOrCreateSubject(): Subject<DynamicModule> {
|
|
557
|
+
if (!this._moduleSubject) {
|
|
558
|
+
this._moduleSubject = new Subject<DynamicModule>();
|
|
559
|
+
}
|
|
560
|
+
return this._moduleSubject;
|
|
561
|
+
}
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
And complete it only on application shutdown via lifecycle hook.
|
|
565
|
+
|
|
566
|
+
---
|
|
567
|
+
|
|
568
|
+
**INFO-5** | LOW | `lib/exception/global-exception.filter.ts:79-84`
|
|
569
|
+
**No Translation Caching**
|
|
570
|
+
Every exception translates the error message via `i18nService.translate()`. For high-traffic applications, the same error codes are translated repeatedly.
|
|
571
|
+
|
|
572
|
+
**Enhancement:** Add LRU cache:
|
|
573
|
+
```typescript
|
|
574
|
+
private translationCache = new LRUCache<string, string>({ max: 500 });
|
|
575
|
+
|
|
576
|
+
async translate(code: number, lang: string, args?: any, prefix?: string): Promise<string> {
|
|
577
|
+
const cacheKey = `${prefix}:${code}:${lang}:${JSON.stringify(args)}`;
|
|
578
|
+
|
|
579
|
+
let cached = this.translationCache.get(cacheKey);
|
|
580
|
+
if (cached) return cached;
|
|
581
|
+
|
|
582
|
+
const key = `${prefix || this.exceptionPrefix}.${code}`;
|
|
583
|
+
if (!this.i18nService) {
|
|
584
|
+
return key;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const translated = await this.i18nService.translate(key, { lang, args });
|
|
588
|
+
this.translationCache.set(cacheKey, translated);
|
|
589
|
+
return translated;
|
|
590
|
+
}
|
|
591
|
+
```
|
|
592
|
+
|
|
593
|
+
*Note:* Only implement if profiling shows i18n translation is a bottleneck.
|
|
594
|
+
|
|
595
|
+
---
|
|
596
|
+
|
|
597
|
+
**INFO-6** | LOW | `lib/pagination/page.ts:100-110`
|
|
598
|
+
**Array Map Without Type Guard**
|
|
599
|
+
In `remap()`, the `mapFunc` is called on all records without checking if they're objects. If records contain primitives, this could cause issues.
|
|
600
|
+
|
|
601
|
+
**Enhancement:**
|
|
602
|
+
```typescript
|
|
603
|
+
public remap<E, S = any>(
|
|
604
|
+
mapFunc: mapFunction<E>,
|
|
605
|
+
cls?: ClassConstructor<E>,
|
|
606
|
+
extra?: S
|
|
607
|
+
): Page<E, S> {
|
|
608
|
+
const records = this.records.map((item, index, array) => {
|
|
609
|
+
// Validate item before mapping
|
|
610
|
+
if (item === null || item === undefined) {
|
|
611
|
+
console.warn(`[Page.remap] Null/undefined item at index ${index}`);
|
|
612
|
+
return item as unknown as E;
|
|
613
|
+
}
|
|
614
|
+
return mapFunc(item, index, array);
|
|
615
|
+
});
|
|
616
|
+
// ...
|
|
617
|
+
}
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
---
|
|
621
|
+
|
|
622
|
+
## 5. Enhancement Suggestions
|
|
623
|
+
|
|
624
|
+
### HIGH Priority
|
|
625
|
+
|
|
626
|
+
**ENH-1** | **Fix Object Mutation in SerializableInterceptor**
|
|
627
|
+
As detailed in BUG-1. This is critical for data integrity.
|
|
628
|
+
|
|
629
|
+
**ENH-2** | **Add Strict Type for AppException.args**
|
|
630
|
+
As detailed in WARN-3. Improve developer experience with type safety:
|
|
631
|
+
```typescript
|
|
632
|
+
export interface AppExceptionArgs {
|
|
633
|
+
[key: string]: string | number | boolean | undefined;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// Or for even stricter typing:
|
|
637
|
+
export type AppExceptionArgs<T extends Record<string, any> = Record<string, any>> = T;
|
|
638
|
+
|
|
639
|
+
export class AppException<T extends Record<string, any> = Record<string, any>> extends HttpException {
|
|
640
|
+
private _args?: T;
|
|
641
|
+
|
|
642
|
+
constructor(code: number, args?: T, prefix?: string, httpStatus?: number) {
|
|
643
|
+
super({ code, args, prefix }, httpStatus || 500);
|
|
644
|
+
this._args = args;
|
|
645
|
+
// ...
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
public get args(): T | undefined {
|
|
649
|
+
return this._args;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// Usage:
|
|
654
|
+
throw new AppException<{ username: string }>(
|
|
655
|
+
CommonExceptionCode.USER_NOT_FOUND,
|
|
656
|
+
{ username: 'john' }
|
|
657
|
+
);
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
**ENH-3** | **Document Trust Proxy Security**
|
|
661
|
+
Add comprehensive security documentation:
|
|
662
|
+
1. README.md section on trust proxy configuration
|
|
663
|
+
2. Example configurations for common deployment scenarios (AWS ALB, Cloudflare, nginx)
|
|
664
|
+
3. Migration guide from 2.x (if trust proxy behavior changed)
|
|
665
|
+
4. JSDoc on `configureTrustProxy()` with security warnings
|
|
666
|
+
|
|
667
|
+
**ENH-4** | **Fix Trust Proxy Default to Fail-Closed**
|
|
668
|
+
As detailed in SEC-1. This is a breaking change but necessary for security:
|
|
669
|
+
|
|
670
|
+
```typescript
|
|
671
|
+
// BREAKING CHANGE in 3.0.0 migration guide:
|
|
672
|
+
**Trust Proxy Behavior Change:**
|
|
673
|
+
- **2.x:** Trusts all X-Forwarded-* headers by default (insecure)
|
|
674
|
+
- **3.x:** Rejects all forwarded headers unless explicitly configured (secure)
|
|
675
|
+
|
|
676
|
+
**Migration:**
|
|
677
|
+
If your app is behind a proxy, add this to your bootstrap:
|
|
678
|
+
|
|
679
|
+
\`\`\`typescript
|
|
680
|
+
import { configureTrustProxy } from '@nathapp/nestjs-common';
|
|
681
|
+
|
|
682
|
+
configureTrustProxy({
|
|
683
|
+
enabled: true,
|
|
684
|
+
trustedProxies: ['10.0.0.0/8'] // Your proxy subnet
|
|
685
|
+
});
|
|
686
|
+
\`\`\`
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
### MEDIUM Priority
|
|
690
|
+
|
|
691
|
+
**ENH-5** | **Add Validation Helpers**
|
|
692
|
+
Create utility functions for common validation patterns:
|
|
693
|
+
```typescript
|
|
694
|
+
// lib/validation/validators.ts
|
|
695
|
+
export function isValidLocaleCode(code: string): boolean {
|
|
696
|
+
return /^[a-z]{2}_[A-Z]{2}$/.test(code);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
export function isValidAppId(appId: string): boolean {
|
|
700
|
+
return /^\d{1,10}$/.test(appId);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
export function sanitizeHeader(value: string, maxLength: number = 255): string {
|
|
704
|
+
return value.substring(0, maxLength).replace(/[^\w\-\.]/g, '');
|
|
705
|
+
}
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
**ENH-6** | **Add JSDoc Documentation**
|
|
709
|
+
Comprehensive JSDoc for all public APIs. Priority list:
|
|
710
|
+
1. `GlobalExceptionsFilter` - document handler priority, error result format
|
|
711
|
+
2. `ExceptionHandler` interface - document contract, provide examples
|
|
712
|
+
3. `SerializableInterceptor` - document behavior, locale resolution
|
|
713
|
+
4. `Page` - document mutation behavior in `toInstance()`/`toPlain()`
|
|
714
|
+
5. `ConfigurableModuleBuilder.externallyConfigured()` - document timeout behavior
|
|
715
|
+
6. All exception classes - document when to use each
|
|
716
|
+
|
|
717
|
+
**ENH-7** | **Add Unit Tests for Edge Cases**
|
|
718
|
+
Based on code review, these scenarios need test coverage:
|
|
719
|
+
1. `SerializableInterceptor`: Deeply nested objects (>50 levels)
|
|
720
|
+
2. `SerializableInterceptor`: Circular references
|
|
721
|
+
3. `SerializableInterceptor`: Arrays with mixed types
|
|
722
|
+
4. `GlobalExceptionsFilter`: Handler that throws exception
|
|
723
|
+
5. `request-ip`: IP spoofing attempts with various header combinations
|
|
724
|
+
6. `Page.remap()`: Null/undefined records
|
|
725
|
+
7. `LocaleString.parseLocaleString()`: Malformed JSON, non-object JSON
|
|
726
|
+
8. `ConfigurableModuleBuilder.externallyConfigured()`: Timeout scenarios
|
|
727
|
+
|
|
728
|
+
**ENH-8** | **Improve Error Messages**
|
|
729
|
+
Make error messages more actionable:
|
|
730
|
+
```typescript
|
|
731
|
+
// Before:
|
|
732
|
+
throw new Error('Expected to be configured by at least one Module but it was not configured');
|
|
733
|
+
|
|
734
|
+
// After:
|
|
735
|
+
throw new Error(
|
|
736
|
+
`Module ${this.name} was not configured within ${timeout}ms. ` +
|
|
737
|
+
`Ensure you have imported a module that calls ${this.name}.forRoot() or .forRootAsync() ` +
|
|
738
|
+
`before importing ${this.name}.externallyConfigured(). ` +
|
|
739
|
+
`Common fix: Move ${this.name}.forRoot() to AppModule imports array.`
|
|
740
|
+
);
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
**ENH-9** | **Add Performance Monitoring Utilities**
|
|
744
|
+
For enterprise deployments, add optional performance tracking:
|
|
745
|
+
```typescript
|
|
746
|
+
// lib/utils/performance.ts
|
|
747
|
+
export class PerformanceMonitor {
|
|
748
|
+
static trackExceptionHandling(exception: Error, duration: number) {
|
|
749
|
+
if (duration > 100) {
|
|
750
|
+
console.warn(`[Performance] Exception handling took ${duration}ms for ${exception.constructor.name}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
static trackSerialization(objectCount: number, duration: number) {
|
|
755
|
+
if (duration > 200) {
|
|
756
|
+
console.warn(`[Performance] Serialized ${objectCount} objects in ${duration}ms`);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
### LOW Priority
|
|
763
|
+
|
|
764
|
+
**ENH-10** | **Add Locale Type Constraints**
|
|
765
|
+
As detailed in WARN-6. Provide typed helpers for common locales.
|
|
766
|
+
|
|
767
|
+
**ENH-11** | **Add Custom Serializer Extension Point**
|
|
768
|
+
As detailed in INFO-3. Allow injecting custom serialization logic.
|
|
769
|
+
|
|
770
|
+
**ENH-12** | **Optimize Handler Lookup**
|
|
771
|
+
As detailed in PERF-2. Only needed if >20 handlers are common.
|
|
772
|
+
|
|
773
|
+
**ENH-13** | **Add Deprecation Warnings**
|
|
774
|
+
For deprecated APIs:
|
|
775
|
+
```typescript
|
|
776
|
+
/**
|
|
777
|
+
* @deprecated This exception will be removed in v4.0.0. Use AppException hierarchy instead.
|
|
778
|
+
* See migration guide: https://docs.nathapp.io/migration/v3-to-v4
|
|
779
|
+
*/
|
|
780
|
+
export class HttpMicroServiceException extends HttpException {
|
|
781
|
+
constructor(ret: number, message: string) {
|
|
782
|
+
console.warn(
|
|
783
|
+
'[DEPRECATED] HttpMicroServiceException is deprecated and will be removed in v4.0.0. ' +
|
|
784
|
+
'Use InternalAppException instead.'
|
|
785
|
+
);
|
|
786
|
+
super({ ret, message }, 500);
|
|
787
|
+
// ...
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
**ENH-14** | **Add Configuration Validation**
|
|
793
|
+
Validate trust proxy configuration on startup:
|
|
794
|
+
```typescript
|
|
795
|
+
export function configureTrustProxy(options: TrustProxyOptions, source?: string): void {
|
|
796
|
+
// Validation
|
|
797
|
+
if (options.trustedProxies) {
|
|
798
|
+
for (const proxy of options.trustedProxies) {
|
|
799
|
+
if (!proxy.includes('/') && !is.ip(proxy)) {
|
|
800
|
+
throw new Error(
|
|
801
|
+
`[TrustProxy] Invalid trusted proxy: "${proxy}". ` +
|
|
802
|
+
`Must be a valid IP address or CIDR notation (e.g., "10.0.0.0/8")`
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ... rest of function
|
|
809
|
+
}
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
**ENH-15** | **Add Request Context Tracking**
|
|
813
|
+
For better debugging:
|
|
814
|
+
```typescript
|
|
815
|
+
// lib/decorator/request-context.decorator.ts
|
|
816
|
+
export interface RequestContext {
|
|
817
|
+
requestId: string;
|
|
818
|
+
timestamp: Date;
|
|
819
|
+
ip: string;
|
|
820
|
+
userAgent: string;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
export const ReqContext = createParamDecorator(
|
|
824
|
+
(data: unknown, ctx: ExecutionContext): RequestContext => {
|
|
825
|
+
const request = ctx.switchToHttp().getRequest();
|
|
826
|
+
return {
|
|
827
|
+
requestId: request.id || randomUUID(),
|
|
828
|
+
timestamp: new Date(),
|
|
829
|
+
ip: getClientIp(request),
|
|
830
|
+
userAgent: request.headers['user-agent'] || 'unknown',
|
|
831
|
+
};
|
|
832
|
+
},
|
|
833
|
+
);
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
---
|
|
837
|
+
|
|
838
|
+
## Test Coverage Gaps
|
|
839
|
+
|
|
840
|
+
**Based on code analysis, the following scenarios need test coverage:**
|
|
841
|
+
|
|
842
|
+
### Critical Paths (High Priority)
|
|
843
|
+
|
|
844
|
+
1. **Exception Handler Chain**
|
|
845
|
+
- [ ] Handler order priority enforcement
|
|
846
|
+
- [ ] Handler that throws exception during `canHandle()`
|
|
847
|
+
- [ ] Handler that throws exception during `handle()`
|
|
848
|
+
- [ ] No handler matches exception (fallback to UnknownExceptionHandler)
|
|
849
|
+
- [ ] Multiple handlers match (first wins)
|
|
850
|
+
- [ ] Async vs sync handler execution
|
|
851
|
+
- [ ] I18n translation failure fallback
|
|
852
|
+
|
|
853
|
+
2. **SerializableInterceptor**
|
|
854
|
+
- [ ] Deeply nested object serialization (>50 levels)
|
|
855
|
+
- [ ] Circular reference detection
|
|
856
|
+
- [ ] Array with LocaleString/LocaleObject items
|
|
857
|
+
- [ ] Missing locale fallback to default
|
|
858
|
+
- [ ] StreamableFile passthrough
|
|
859
|
+
- [ ] Response is null/undefined
|
|
860
|
+
- [ ] Response is primitive (string, number)
|
|
861
|
+
|
|
862
|
+
3. **Trust Proxy & IP Detection**
|
|
863
|
+
- [ ] X-Forwarded-For with multiple IPs
|
|
864
|
+
- [ ] X-Forwarded-For with port numbers
|
|
865
|
+
- [ ] X-Forwarded-For with IPv6 addresses
|
|
866
|
+
- [ ] Trusted proxy IP validation (CIDR matching)
|
|
867
|
+
- [ ] Untrusted proxy attempting to spoof IP
|
|
868
|
+
- [ ] Missing socket.remoteAddress
|
|
869
|
+
- [ ] Fastify request unwrapping
|
|
870
|
+
- [ ] Cloudflare headers (CF-Connecting-IP, Cf-Pseudo-IPv4)
|
|
871
|
+
|
|
872
|
+
4. **Pagination**
|
|
873
|
+
- [ ] Page with zero total
|
|
874
|
+
- [ ] Page with negative current/size
|
|
875
|
+
- [ ] Page.remap() with null items
|
|
876
|
+
- [ ] Page.toInstance() with missing class
|
|
877
|
+
- [ ] Page navigation (hasNext, hasPrev) edge cases
|
|
878
|
+
|
|
879
|
+
### Important Paths (Medium Priority)
|
|
880
|
+
|
|
881
|
+
5. **ConfigurableModuleBuilder**
|
|
882
|
+
- [ ] externallyConfigured() timeout
|
|
883
|
+
- [ ] externallyConfigured() called before forRoot()
|
|
884
|
+
- [ ] Multiple modules using externallyConfigured()
|
|
885
|
+
- [ ] setExtras() with complex transformDefinition
|
|
886
|
+
- [ ] alwaysTransient option (CONFIGURABLE_MODULE_ID uniqueness)
|
|
887
|
+
|
|
888
|
+
6. **Locale Parsing**
|
|
889
|
+
- [ ] parseLocaleString with invalid JSON
|
|
890
|
+
- [ ] parseLocaleString with non-object JSON (array, null, primitive)
|
|
891
|
+
- [ ] parseLocaleString with non-string values
|
|
892
|
+
- [ ] parseLocaleObject with malformed data
|
|
893
|
+
- [ ] remapLocaleObject with throwing map function
|
|
894
|
+
|
|
895
|
+
7. **Validation**
|
|
896
|
+
- [ ] All `*WithI18n` validators with i18n service unavailable
|
|
897
|
+
- [ ] Match constraint with circular references
|
|
898
|
+
- [ ] I18nValidationExceptionFilter with nested errors
|
|
899
|
+
- [ ] DefaultI18nValidationExceptionFilter response format
|
|
900
|
+
|
|
901
|
+
### Edge Cases (Low Priority)
|
|
902
|
+
|
|
903
|
+
8. **HTTP Types**
|
|
904
|
+
- [ ] Request/Response type compatibility (Express vs Fastify)
|
|
905
|
+
|
|
906
|
+
9. **Config Validation**
|
|
907
|
+
- [ ] ServerSecurityConfig with invalid CORS regex
|
|
908
|
+
- [ ] ServerSecurityConfig with empty origins
|
|
909
|
+
- [ ] JoiUtil.validate with missing environment variables
|
|
910
|
+
|
|
911
|
+
10. **Logging**
|
|
912
|
+
- [ ] EmptyLogger suppresses all output
|
|
913
|
+
- [ ] getLoggerLevel with DEBUG_MODE variations
|
|
914
|
+
|
|
915
|
+
---
|
|
916
|
+
|
|
917
|
+
## Summary Table
|
|
918
|
+
|
|
919
|
+
| ID | Severity | Category | File | Description |
|
|
920
|
+
|----|----------|----------|------|-------------|
|
|
921
|
+
| BUG-1 | CRITICAL | Enterprise Grade | `interceptor/serializable.interceptor.ts:46` | Object mutation in transformObject |
|
|
922
|
+
| WARN-1 | HIGH | Enterprise Grade | `exception/global-exception.filter.ts:20` | Static state in GlobalExceptionsFilter |
|
|
923
|
+
| WARN-2 | HIGH | Enterprise Grade | `ip/request-ip.ts:37` | Module-level state not thread-safe |
|
|
924
|
+
| WARN-3 | MEDIUM | Enterprise Grade | `exception/app.exception.ts:6` | Untyped exception arguments (any) |
|
|
925
|
+
| WARN-4 | MEDIUM | Enterprise Grade | `pagination/page.ts:62` | Page mutation in toInstance/toPlain |
|
|
926
|
+
| INFO-1 | LOW | Enterprise Grade | Multiple | Missing JSDoc documentation |
|
|
927
|
+
| INFO-2 | LOW | Enterprise Grade | `exception/handler/app-exception.handler.ts:27` | Inconsistent HTTP status mapping |
|
|
928
|
+
| WARN-5 | MEDIUM | Enterprise Grade | `exception/handler/throttler.handler.ts:9` | Fragile instanceof check |
|
|
929
|
+
| GOOD-1 | ✓ | Extensibility | `exception/handler/*` | Excellent handler chain pattern |
|
|
930
|
+
| GOOD-2 | ✓ | Extensibility | `module/configurable-module.builder.ts` | Enhanced ConfigurableModuleBuilder |
|
|
931
|
+
| WARN-6 | MEDIUM | Extensibility | `serialize/localize.string.ts:1` | No type safety for locale keys |
|
|
932
|
+
| INFO-3 | LOW | Extensibility | `interceptor/serializable.interceptor.ts` | No custom serialization extension points |
|
|
933
|
+
| GOOD-3 | ✓ | Extensibility | `validation/i18n-validation.constraint.ts` | Good validator base class |
|
|
934
|
+
| SEC-1 | CRITICAL | Security | `ip/request-ip.ts:104` | Trust proxy trusts all by default |
|
|
935
|
+
| SEC-2 | HIGH | Security | `ip/request-ip.ts:204` | X-Forwarded-For parsing vulnerability |
|
|
936
|
+
| SEC-3 | MEDIUM | Security | `serialize/localize.string.ts:30` | Unsafe JSON.parse without validation |
|
|
937
|
+
| INFO-4 | LOW | Security | `decorator/client-info.decorator.ts:32` | Header injection risk in custom headers |
|
|
938
|
+
| WARN-7 | MEDIUM | Security | `config/server-security.config.ts:51` | CORS regex parsing accepts unsafe flags |
|
|
939
|
+
| PERF-1 | MEDIUM | Performance | `interceptor/serializable.interceptor.ts:46` | Recursive traversal without depth limit |
|
|
940
|
+
| PERF-2 | LOW | Performance | `exception/global-exception.filter.ts:52` | Linear handler search (O(n)) |
|
|
941
|
+
| PERF-3 | LOW | Performance | `ip/request-ip.ts:295` | O(n²) header priority reordering |
|
|
942
|
+
| WARN-8 | MEDIUM | Performance | `module/configurable-module.builder.ts:93` | Memory leak: Subject never completes |
|
|
943
|
+
| INFO-5 | LOW | Performance | `exception/global-exception.filter.ts:79` | No translation caching |
|
|
944
|
+
| INFO-6 | LOW | Performance | `pagination/page.ts:100` | Array map without type guard |
|
|
945
|
+
| ENH-1 | HIGH | Enhancement | `interceptor/serializable.interceptor.ts` | Fix object mutation |
|
|
946
|
+
| ENH-2 | HIGH | Enhancement | `exception/app.exception.ts` | Add strict type for args |
|
|
947
|
+
| ENH-3 | HIGH | Enhancement | Documentation | Document trust proxy security |
|
|
948
|
+
| ENH-4 | HIGH | Enhancement | `ip/request-ip.ts` | Fix trust proxy to fail-closed |
|
|
949
|
+
| ENH-5 | MEDIUM | Enhancement | New file | Add validation helpers |
|
|
950
|
+
| ENH-6 | MEDIUM | Enhancement | Multiple | Add JSDoc documentation |
|
|
951
|
+
| ENH-7 | MEDIUM | Enhancement | Tests | Add unit tests for edge cases |
|
|
952
|
+
| ENH-8 | MEDIUM | Enhancement | Multiple | Improve error messages |
|
|
953
|
+
| ENH-9 | MEDIUM | Enhancement | New file | Add performance monitoring |
|
|
954
|
+
| ENH-10 | LOW | Enhancement | `serialize/localize.string.ts` | Add locale type constraints |
|
|
955
|
+
| ENH-11 | LOW | Enhancement | `interceptor/serializable.interceptor.ts` | Custom serializer extension |
|
|
956
|
+
| ENH-12 | LOW | Enhancement | `exception/global-exception.filter.ts` | Optimize handler lookup |
|
|
957
|
+
| ENH-13 | LOW | Enhancement | `exception/micro-service.exception.ts` | Add deprecation warnings |
|
|
958
|
+
| ENH-14 | LOW | Enhancement | `ip/request-ip.ts` | Add configuration validation |
|
|
959
|
+
| ENH-15 | LOW | Enhancement | New file | Add request context tracking |
|
|
960
|
+
|
|
961
|
+
---
|
|
962
|
+
|
|
963
|
+
## Recommended Action Plan
|
|
964
|
+
|
|
965
|
+
### Phase 1: Critical Fixes (Before 3.0.0 Release)
|
|
966
|
+
1. **Fix BUG-1**: Object mutation in SerializableInterceptor
|
|
967
|
+
2. **Fix SEC-1**: Trust proxy default to fail-closed
|
|
968
|
+
3. **Fix SEC-2**: X-Forwarded-For parsing
|
|
969
|
+
4. **Add ENH-3**: Trust proxy security documentation
|
|
970
|
+
5. **Fix WARN-1**: Remove static state from GlobalExceptionsFilter
|
|
971
|
+
|
|
972
|
+
**Estimated Effort:** 2-3 days
|
|
973
|
+
|
|
974
|
+
### Phase 2: Type Safety & Developer Experience (3.0.1)
|
|
975
|
+
1. **Fix WARN-3**: Strict typing for AppException.args
|
|
976
|
+
2. **Add ENH-6**: JSDoc documentation for public APIs
|
|
977
|
+
3. **Add ENH-8**: Improve error messages
|
|
978
|
+
4. **Fix WARN-5**: instanceof check for ThrottlerException
|
|
979
|
+
|
|
980
|
+
**Estimated Effort:** 2 days
|
|
981
|
+
|
|
982
|
+
### Phase 3: Security Hardening (3.1.0)
|
|
983
|
+
1. **Fix SEC-3**: Validate parseLocaleString input
|
|
984
|
+
2. **Add ENH-5**: Validation helper utilities
|
|
985
|
+
3. **Add ENH-14**: Configuration validation
|
|
986
|
+
4. **Fix WARN-7**: CORS regex flag validation
|
|
987
|
+
|
|
988
|
+
**Estimated Effort:** 1 day
|
|
989
|
+
|
|
990
|
+
### Phase 4: Performance & Polish (3.2.0)
|
|
991
|
+
1. **Fix PERF-1**: Add depth limit to transformObject
|
|
992
|
+
2. **Fix WARN-8**: Complete moduleSubject properly
|
|
993
|
+
3. **Fix WARN-4**: Page immutability
|
|
994
|
+
4. **Add ENH-7**: Comprehensive test coverage
|
|
995
|
+
5. **Add ENH-9**: Performance monitoring utilities
|
|
996
|
+
|
|
997
|
+
**Estimated Effort:** 3 days
|
|
998
|
+
|
|
999
|
+
---
|
|
1000
|
+
|
|
1001
|
+
## Conclusion
|
|
1002
|
+
|
|
1003
|
+
The `@nathapp/nestjs-common` package is architecturally sound with excellent patterns like the exception handler chain and enhanced ConfigurableModuleBuilder. The code is production-ready **after addressing the critical security issues** (trust proxy configuration and IP detection).
|
|
1004
|
+
|
|
1005
|
+
**Key Takeaways:**
|
|
1006
|
+
- ✅ **Strengths**: Excellent exception handling architecture, strong DI integration, comprehensive i18n support
|
|
1007
|
+
- ⚠️ **Critical Issues**: Trust proxy security, object mutation, type safety gaps
|
|
1008
|
+
- 🎯 **Recommendation**: Fix critical issues (Phase 1) before 3.0.0 release, then incrementally improve in minor versions
|
|
1009
|
+
|
|
1010
|
+
**Overall Assessment:** With the recommended fixes, this package will be enterprise-grade and suitable for public release. The architecture is solid and extensible, making it a strong foundation for the NathApp ecosystem.
|
|
1011
|
+
|
|
1012
|
+
---
|
|
1013
|
+
|
|
1014
|
+
**Review completed:** 2026-02-15
|
|
1015
|
+
**Next review recommended:** After Phase 1 fixes implementation
|