@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.
Files changed (151) hide show
  1. package/CLAUDE.md +29 -0
  2. package/README.md +134 -0
  3. package/dist/config/index.d.ts +4 -4
  4. package/dist/config/index.js.map +1 -1
  5. package/dist/config/server-security.config.d.ts +1 -0
  6. package/dist/config/server-security.config.js +19 -2
  7. package/dist/config/server-security.config.js.map +1 -1
  8. package/dist/decorator/index.d.ts +2 -2
  9. package/dist/decorator/index.js.map +1 -1
  10. package/dist/entities/base-entity.d.ts +3 -0
  11. package/dist/entities/base-entity.js +8 -0
  12. package/dist/entities/base-entity.js.map +1 -0
  13. package/dist/entities/index.d.ts +1 -0
  14. package/dist/entities/index.js +18 -0
  15. package/dist/entities/index.js.map +1 -0
  16. package/dist/exception/app.exception.d.ts +4 -3
  17. package/dist/exception/app.exception.js +1 -1
  18. package/dist/exception/app.exception.js.map +1 -1
  19. package/dist/exception/default-i18n-validation-exception.filter.js +1 -1
  20. package/dist/exception/default-i18n-validation-exception.filter.js.map +1 -1
  21. package/dist/exception/exception.constants.d.ts +1 -0
  22. package/dist/exception/exception.constants.js +5 -0
  23. package/dist/exception/exception.constants.js.map +1 -0
  24. package/dist/exception/exception.module.d.ts +7 -0
  25. package/dist/exception/exception.module.js +41 -0
  26. package/dist/exception/exception.module.js.map +1 -0
  27. package/dist/exception/exceptions/auth.exception.d.ts +4 -0
  28. package/dist/exception/exceptions/auth.exception.js +12 -0
  29. package/dist/exception/exceptions/auth.exception.js.map +1 -0
  30. package/dist/exception/exceptions/forbidden-app.exception.d.ts +4 -0
  31. package/dist/exception/exceptions/forbidden-app.exception.js +12 -0
  32. package/dist/exception/exceptions/forbidden-app.exception.js.map +1 -0
  33. package/dist/exception/exceptions/index.d.ts +6 -0
  34. package/dist/exception/exceptions/index.js +16 -0
  35. package/dist/exception/exceptions/index.js.map +1 -0
  36. package/dist/exception/exceptions/internal-app.exception.d.ts +4 -0
  37. package/dist/exception/exceptions/internal-app.exception.js +12 -0
  38. package/dist/exception/exceptions/internal-app.exception.js.map +1 -0
  39. package/dist/exception/exceptions/not-found-app.exception.d.ts +4 -0
  40. package/dist/exception/exceptions/not-found-app.exception.js +12 -0
  41. package/dist/exception/exceptions/not-found-app.exception.js.map +1 -0
  42. package/dist/exception/exceptions/throttle-app.exception.d.ts +4 -0
  43. package/dist/exception/exceptions/throttle-app.exception.js +12 -0
  44. package/dist/exception/exceptions/throttle-app.exception.js.map +1 -0
  45. package/dist/exception/exceptions/validation-app.exception.d.ts +4 -0
  46. package/dist/exception/exceptions/validation-app.exception.js +12 -0
  47. package/dist/exception/exceptions/validation-app.exception.js.map +1 -0
  48. package/dist/exception/global-exception.filter.d.ts +8 -54
  49. package/dist/exception/global-exception.filter.js +45 -163
  50. package/dist/exception/global-exception.filter.js.map +1 -1
  51. package/dist/exception/handler/app-exception.handler.d.ts +7 -0
  52. package/dist/exception/handler/app-exception.handler.js +44 -0
  53. package/dist/exception/handler/app-exception.handler.js.map +1 -0
  54. package/dist/exception/handler/bad-request.handler.d.ts +6 -0
  55. package/dist/exception/handler/bad-request.handler.js +30 -0
  56. package/dist/exception/handler/bad-request.handler.js.map +1 -0
  57. package/dist/exception/handler/exception-handler.interface.d.ts +14 -0
  58. package/dist/exception/handler/exception-handler.interface.js +3 -0
  59. package/dist/exception/handler/exception-handler.interface.js.map +1 -0
  60. package/dist/exception/handler/forbidden.handler.d.ts +6 -0
  61. package/dist/exception/handler/forbidden.handler.js +27 -0
  62. package/dist/exception/handler/forbidden.handler.js.map +1 -0
  63. package/dist/exception/handler/index.d.ts +11 -0
  64. package/dist/exception/handler/index.js +38 -0
  65. package/dist/exception/handler/index.js.map +1 -0
  66. package/dist/exception/handler/microservice.handler.d.ts +6 -0
  67. package/dist/exception/handler/microservice.handler.js +27 -0
  68. package/dist/exception/handler/microservice.handler.js.map +1 -0
  69. package/dist/exception/handler/not-found.handler.d.ts +6 -0
  70. package/dist/exception/handler/not-found.handler.js +27 -0
  71. package/dist/exception/handler/not-found.handler.js.map +1 -0
  72. package/dist/exception/handler/throttler.handler.d.ts +6 -0
  73. package/dist/exception/handler/throttler.handler.js +33 -0
  74. package/dist/exception/handler/throttler.handler.js.map +1 -0
  75. package/dist/exception/handler/unknown.handler.d.ts +6 -0
  76. package/dist/exception/handler/unknown.handler.js +35 -0
  77. package/dist/exception/handler/unknown.handler.js.map +1 -0
  78. package/dist/exception/handler/username-not-found.handler.d.ts +6 -0
  79. package/dist/exception/handler/username-not-found.handler.js +28 -0
  80. package/dist/exception/handler/username-not-found.handler.js.map +1 -0
  81. package/dist/exception/index.d.ts +7 -4
  82. package/dist/exception/index.js +12 -3
  83. package/dist/exception/index.js.map +1 -1
  84. package/dist/exception/micro-service.exception.js +1 -1
  85. package/dist/exception/micro-service.exception.js.map +1 -1
  86. package/dist/exception/user-not-found.exception.js +1 -1
  87. package/dist/http/index.d.ts +3 -3
  88. package/dist/index.d.ts +2 -1
  89. package/dist/index.js +2 -1
  90. package/dist/index.js.map +1 -1
  91. package/dist/interceptor/serializable.interceptor.d.ts +4 -2
  92. package/dist/interceptor/serializable.interceptor.js +75 -18
  93. package/dist/interceptor/serializable.interceptor.js.map +1 -1
  94. package/dist/ip/index.d.ts +3 -2
  95. package/dist/ip/index.js +4 -1
  96. package/dist/ip/index.js.map +1 -1
  97. package/dist/ip/request-ip.d.ts +4 -2
  98. package/dist/ip/request-ip.js +92 -30
  99. package/dist/ip/request-ip.js.map +1 -1
  100. package/dist/ip/trusted-proxy-presets.d.ts +3 -0
  101. package/dist/ip/trusted-proxy-presets.js +114 -0
  102. package/dist/ip/trusted-proxy-presets.js.map +1 -0
  103. package/dist/module/configurable-module.builder.js +3 -1
  104. package/dist/module/configurable-module.builder.js.map +1 -1
  105. package/dist/module/index.d.ts +5 -5
  106. package/dist/module/index.js.map +1 -1
  107. package/dist/pagination/index.d.ts +1 -0
  108. package/dist/pagination/index.js +18 -0
  109. package/dist/pagination/index.js.map +1 -0
  110. package/dist/pagination/page.d.ts +39 -0
  111. package/dist/pagination/page.js +87 -0
  112. package/dist/pagination/page.js.map +1 -0
  113. package/dist/serialize/localize.string.js.map +1 -1
  114. package/dist/utils/package-utils.js +3 -0
  115. package/dist/utils/package-utils.js.map +1 -1
  116. package/dist/validation/index.d.ts +1 -0
  117. package/dist/validation/index.js +1 -0
  118. package/dist/validation/index.js.map +1 -1
  119. package/dist/validation/validators.d.ts +3 -0
  120. package/dist/validation/validators.js +29 -0
  121. package/dist/validation/validators.js.map +1 -0
  122. package/docs/20260214-coverage-plan.md +52 -0
  123. package/docs/20260214-fix-plan-common-bugs.md +90 -0
  124. package/docs/20260214-fix-plan-common-cleanup.md +119 -0
  125. package/docs/20260214-fix-plan-exception-redesign.md +274 -0
  126. package/docs/20260214-fix-plan-nestjs-prisma.md +454 -0
  127. package/docs/20260214-fix-plan-pagination-move-and-rename.md +148 -0
  128. package/docs/20260214-review-common.md +426 -0
  129. package/docs/20260215-fix-plan-review-enhancements.md +110 -0
  130. package/docs/20260215-fix-plan-trust-proxy-presets.md +227 -0
  131. package/docs/20260215-review-nestjs-common.md +1015 -0
  132. package/docs/trust-proxy-security.md +475 -0
  133. package/package.json +1 -1
  134. package/dist/exception/app-exception.filter.d.ts +0 -9
  135. package/dist/exception/app-exception.filter.js +0 -52
  136. package/dist/exception/app-exception.filter.js.map +0 -1
  137. package/dist/i18n/i18n.constants.d.ts +0 -0
  138. package/dist/i18n/i18n.constants.js +0 -1
  139. package/dist/i18n/i18n.constants.js.map +0 -1
  140. package/dist/middleware/index.d.ts +0 -4
  141. package/dist/middleware/index.js +0 -14
  142. package/dist/middleware/index.js.map +0 -1
  143. package/dist/middleware/log.provider.d.ts +0 -38
  144. package/dist/middleware/log.provider.js +0 -147
  145. package/dist/middleware/log.provider.js.map +0 -1
  146. package/dist/middleware/logger-option.factory.d.ts +0 -17
  147. package/dist/middleware/logger-option.factory.js +0 -73
  148. package/dist/middleware/logger-option.factory.js.map +0 -1
  149. package/dist/middleware/logger.middleware.d.ts +0 -8
  150. package/dist/middleware/logger.middleware.js +0 -97
  151. package/dist/middleware/logger.middleware.js.map +0 -1
@@ -0,0 +1,475 @@
1
+ # Trust Proxy Security Guide
2
+
3
+ ## Overview
4
+
5
+ Trust proxy configuration controls whether your application trusts `X-Forwarded-For` and related headers to determine the real client IP address. **Misconfiguration can lead to critical security vulnerabilities**, including IP spoofing, authentication bypass, and rate limiting evasion.
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [What is Trust Proxy?](#what-is-trust-proxy)
10
+ 2. [Security Risks](#security-risks)
11
+ 3. [Secure Configuration](#secure-configuration)
12
+ 4. [Preset Configurations](#preset-configurations)
13
+ 5. [Verification Steps](#verification-steps)
14
+ 6. [OWASP Guidelines](#owasp-guidelines)
15
+ 7. [Troubleshooting](#troubleshooting)
16
+
17
+ ---
18
+
19
+ ## What is Trust Proxy?
20
+
21
+ When your application runs behind a reverse proxy, load balancer, or CDN, the direct TCP connection comes from the proxy—not the real client. Proxies add headers like `X-Forwarded-For` to preserve the original client IP.
22
+
23
+ **Example:**
24
+
25
+ ```
26
+ Client (203.0.113.42) → Cloudflare → AWS ALB → Your App (sees 10.0.1.5 as socket IP)
27
+ ```
28
+
29
+ Without trust proxy, your app sees `10.0.1.5` (the ALB's internal IP).
30
+ With trust proxy **correctly configured**, your app extracts `203.0.113.42` from `X-Forwarded-For`.
31
+
32
+ ---
33
+
34
+ ## Security Risks
35
+
36
+ ### 1. IP Spoofing via Forged Headers
37
+
38
+ **Attack:** An attacker sends a request with a fake `X-Forwarded-For` header:
39
+
40
+ ```http
41
+ GET /admin HTTP/1.1
42
+ X-Forwarded-For: 192.168.1.1
43
+ ```
44
+
45
+ If your app trusts this header **without validating the direct connection source**, the attacker can:
46
+ - **Bypass IP-based access control** (e.g., admin panels restricted to `192.168.1.0/24`)
47
+ - **Evade rate limiting** by rotating fake IPs
48
+ - **Manipulate audit logs** to frame another IP address
49
+ - **Exploit geo-based restrictions** (e.g., claim to be from a different country)
50
+
51
+ ### 2. Fail-Open vs Fail-Closed
52
+
53
+ | Configuration | Behavior | Risk |
54
+ |--------------|----------|------|
55
+ | **Fail-Open** (trust all headers) | Trusts `X-Forwarded-For` from ANY source | **CRITICAL** — allows IP spoofing |
56
+ | **Fail-Closed** (trust only verified proxies) | Rejects headers unless direct connection is from trusted proxy | **SECURE** — default in `@nathapp/nestjs-common` 3.x |
57
+
58
+ **Breaking Change in 3.0.0:**
59
+ Previous versions defaulted to **fail-open** (trusted all headers). Version 3.x defaults to **fail-closed** (rejects all headers unless explicitly configured).
60
+
61
+ ---
62
+
63
+ ## Secure Configuration
64
+
65
+ ### Default (Fail-Closed)
66
+
67
+ ```typescript
68
+ import { configureTrustProxy } from '@nathapp/nestjs-common';
69
+
70
+ // DEFAULT: Trust proxy disabled (always uses socket.remoteAddress)
71
+ // No configuration needed for apps NOT behind a proxy
72
+ ```
73
+
74
+ ### Explicit Trust Proxy Configuration
75
+
76
+ ```typescript
77
+ import { configureTrustProxy } from '@nathapp/nestjs-common';
78
+
79
+ // Option 1: Trust specific proxy IPs/CIDRs
80
+ configureTrustProxy({
81
+ enabled: true,
82
+ trustedProxies: [
83
+ '10.0.0.0/8', // AWS ALB internal network
84
+ '172.16.0.0/12', // Private network
85
+ '192.168.1.100', // Specific proxy IP
86
+ ],
87
+ }, 'AppFactory');
88
+
89
+ // Option 2: Use well-known provider presets
90
+ configureTrustProxy({
91
+ enabled: true,
92
+ providers: ['cloudflare', 'aws-alb'],
93
+ }, 'AppFactory');
94
+
95
+ // Option 3: Combine custom + providers
96
+ configureTrustProxy({
97
+ enabled: true,
98
+ trustedProxies: ['10.0.1.0/24'],
99
+ providers: 'cloudflare',
100
+ }, 'AppFactory');
101
+ ```
102
+
103
+ ### Environment Variable Override
104
+
105
+ ```bash
106
+ # Override trustedProxies via environment variable
107
+ TRUSTED_PROXIES="10.0.0.0/8,172.16.0.0/12"
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Preset Configurations
113
+
114
+ `@nathapp/nestjs-common` provides presets for common infrastructure providers. These presets are maintained and updated automatically.
115
+
116
+ ### Supported Providers
117
+
118
+ | Provider | Description | Use Case |
119
+ |----------|-------------|----------|
120
+ | `cloudflare` | Cloudflare CDN IP ranges | Apps behind Cloudflare |
121
+ | `aws-alb` | AWS Application Load Balancer private ranges | Apps on AWS with ALB |
122
+ | `aws-cloudfront` | AWS CloudFront edge IPs | Apps behind CloudFront |
123
+ | `gcp` | Google Cloud Platform load balancer ranges | Apps on GCP |
124
+ | `digitalocean` | DigitalOcean App Platform proxies | Apps on DigitalOcean |
125
+ | `alibaba` | Alibaba Cloud load balancer ranges | Apps on Alibaba Cloud |
126
+ | `loopback` | Localhost (`127.0.0.0/8`, `::1/128`) | Development/testing |
127
+ | `private` | RFC 1918 private networks | Internal proxies |
128
+ | `link-local` | Link-local addresses (`169.254.0.0/16`) | AWS metadata service |
129
+
130
+ ### Example: AWS with Cloudflare
131
+
132
+ ```typescript
133
+ configureTrustProxy({
134
+ enabled: true,
135
+ providers: ['cloudflare', 'aws-alb'],
136
+ // Cloudflare sits in front, ALB is internal
137
+ }, 'AppFactory');
138
+ ```
139
+
140
+ ### Example: Nginx Reverse Proxy
141
+
142
+ ```typescript
143
+ configureTrustProxy({
144
+ enabled: true,
145
+ trustedProxies: ['10.0.1.5'], // Nginx server IP
146
+ }, 'AppFactory');
147
+ ```
148
+
149
+ ### Example: Development (localhost)
150
+
151
+ ```typescript
152
+ configureTrustProxy({
153
+ enabled: true,
154
+ providers: 'loopback',
155
+ }, 'AppFactory');
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Verification Steps
161
+
162
+ ### 1. Check Trust Proxy Configuration
163
+
164
+ ```typescript
165
+ import { isTrustProxyConfigured, getTrustProxySource } from '@nathapp/nestjs-common';
166
+
167
+ console.log('Trust proxy configured:', isTrustProxyConfigured());
168
+ console.log('Configured by:', getTrustProxySource());
169
+ ```
170
+
171
+ ### 2. Test Client IP Extraction
172
+
173
+ **Setup:**
174
+ ```typescript
175
+ import { getClientIp } from '@nathapp/nestjs-common';
176
+
177
+ @Controller('debug')
178
+ export class DebugController {
179
+ @Get('ip')
180
+ getIp(@Req() req: any) {
181
+ return {
182
+ clientIp: getClientIp(req),
183
+ socketIp: req.socket?.remoteAddress,
184
+ headers: {
185
+ 'x-forwarded-for': req.headers['x-forwarded-for'],
186
+ 'x-real-ip': req.headers['x-real-ip'],
187
+ 'cf-connecting-ip': req.headers['cf-connecting-ip'],
188
+ },
189
+ };
190
+ }
191
+ }
192
+ ```
193
+
194
+ **Test Case 1: Direct Connection (No Proxy)**
195
+ ```bash
196
+ curl http://localhost:3000/debug/ip
197
+ # Expected: clientIp matches socketIp
198
+ ```
199
+
200
+ **Test Case 2: Trusted Proxy**
201
+ ```bash
202
+ # Simulate Cloudflare proxy (assuming Cloudflare provider configured)
203
+ curl -H "X-Forwarded-For: 203.0.113.42, 104.16.0.1" \
204
+ -H "CF-Connecting-IP: 203.0.113.42" \
205
+ http://localhost:3000/debug/ip
206
+ # Expected: clientIp = 203.0.113.42 (if connection from Cloudflare IP)
207
+ ```
208
+
209
+ **Test Case 3: Untrusted Proxy (Attack Simulation)**
210
+ ```bash
211
+ # Attacker spoofs X-Forwarded-For from untrusted IP
212
+ curl -H "X-Forwarded-For: 192.168.1.1" \
213
+ http://localhost:3000/debug/ip
214
+ # Expected: clientIp = socketIp (header ignored)
215
+ ```
216
+
217
+ ### 3. Verify Rate Limiting
218
+
219
+ ```typescript
220
+ import { Throttle } from '@nestjs/throttler';
221
+
222
+ @Controller('api')
223
+ export class ApiController {
224
+ @Throttle({ default: { limit: 5, ttl: 60000 } })
225
+ @Get('limited')
226
+ limited() {
227
+ return { message: 'Success' };
228
+ }
229
+ }
230
+ ```
231
+
232
+ **Test:**
233
+ ```bash
234
+ # Send 6 requests with spoofed IP (should rate limit on socket IP)
235
+ for i in {1..6}; do
236
+ curl -H "X-Forwarded-For: 192.168.1.$i" http://localhost:3000/api/limited
237
+ done
238
+ # Expected: 6th request returns 429 (rate limited on real IP, not spoofed)
239
+ ```
240
+
241
+ ### 4. Audit Logs
242
+
243
+ ```bash
244
+ # Check application logs for trust proxy warnings
245
+ grep "Trust proxy" logs/app.log
246
+
247
+ # Expected warnings if misconfigured:
248
+ # - "Trust proxy enabled but no trustedProxies or providers configured"
249
+ # - "Trust proxy already configured by X. Now being overridden by Y"
250
+ ```
251
+
252
+ ---
253
+
254
+ ## OWASP Guidelines
255
+
256
+ ### OWASP Top 10 Relevance
257
+
258
+ | OWASP Category | Trust Proxy Risk |
259
+ |----------------|------------------|
260
+ | **A01: Broken Access Control** | IP-based access control bypass via spoofing |
261
+ | **A04: Insecure Design** | Fail-open defaults enable attacks |
262
+ | **A05: Security Misconfiguration** | Incorrect proxy trust settings |
263
+ | **A07: Identification/Authentication Failures** | IP-based authentication bypass |
264
+
265
+ ### OWASP Recommendations
266
+
267
+ 1. **Principle of Least Privilege:**
268
+ Only trust proxies that are **necessary and verified**. Do not trust all proxies by default.
269
+
270
+ 2. **Defense in Depth:**
271
+ Do not rely solely on IP-based restrictions. Use multi-factor authentication, API keys, and other controls.
272
+
273
+ 3. **Validation:**
274
+ Validate that the direct TCP connection originates from a trusted proxy before trusting `X-Forwarded-For`.
275
+
276
+ 4. **Fail-Closed:**
277
+ Default to **rejecting** forwarded headers unless explicitly configured.
278
+
279
+ 5. **Audit Logging:**
280
+ Log both `clientIp` (extracted) and `socketIp` (direct connection) for forensic analysis.
281
+
282
+ ### References
283
+
284
+ - [OWASP Cheat Sheet: HTTP Headers](https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html)
285
+ - [OWASP Top 10 2021](https://owasp.org/www-project-top-ten/)
286
+ - [Cloudflare: Restoring Visitor IPs](https://developers.cloudflare.com/fundamentals/reference/http-request-headers/#x-forwarded-for)
287
+ - [AWS ALB: X-Forwarded-For](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html)
288
+ - [RFC 7239: Forwarded HTTP Extension](https://datatracker.ietf.org/doc/html/rfc7239)
289
+
290
+ ---
291
+
292
+ ## Troubleshooting
293
+
294
+ ### Problem: `clientIp` is empty or wrong
295
+
296
+ **Cause:** Trust proxy disabled or misconfigured.
297
+
298
+ **Solution:**
299
+ 1. Verify trust proxy configuration:
300
+ ```typescript
301
+ console.log('Trust proxy configured:', isTrustProxyConfigured());
302
+ ```
303
+ 2. Add your proxy IPs to `trustedProxies` or use a provider preset.
304
+ 3. Check application logs for warnings.
305
+
306
+ ### Problem: Rate limiting not working correctly
307
+
308
+ **Cause:** Attacker spoofing `X-Forwarded-For` to evade rate limits.
309
+
310
+ **Solution:**
311
+ 1. Ensure trust proxy is **fail-closed** (default in 3.x).
312
+ 2. Verify `trustedProxies` only includes your actual proxies.
313
+ 3. Check rate limiter uses `getClientIp()` from `@nathapp/nestjs-common`.
314
+
315
+ ### Problem: "Trust proxy already configured by X" warning
316
+
317
+ **Cause:** Multiple modules calling `configureTrustProxy()`.
318
+
319
+ **Solution:**
320
+ 1. Configure trust proxy **once** during application bootstrap:
321
+ ```typescript
322
+ // main.ts or app.factory.ts
323
+ configureTrustProxy({ enabled: true, providers: 'cloudflare' }, 'AppFactory');
324
+ ```
325
+ 2. Remove duplicate configurations from other modules.
326
+
327
+ ### Problem: Breaking change from 2.x to 3.x
328
+
329
+ **Cause:** Version 3.x defaults to **fail-closed** (was fail-open in 2.x).
330
+
331
+ **Solution (if intentional trust-all behavior was used):**
332
+ ```typescript
333
+ // ONLY if you intentionally trusted all proxies in 2.x
334
+ // (NOT RECOMMENDED for production)
335
+ configureTrustProxy({
336
+ enabled: true,
337
+ providers: 'private', // Trust all private networks
338
+ }, 'AppFactory');
339
+ ```
340
+
341
+ **Recommended Migration:**
342
+ ```typescript
343
+ // Replace trust-all with explicit configuration
344
+ configureTrustProxy({
345
+ enabled: true,
346
+ trustedProxies: ['10.0.0.0/8'], // Your actual proxy network
347
+ }, 'AppFactory');
348
+ ```
349
+
350
+ ### Problem: Headers not trusted in development
351
+
352
+ **Cause:** Localhost connections not in trusted proxies.
353
+
354
+ **Solution:**
355
+ ```typescript
356
+ // Development configuration
357
+ if (process.env.NODE_ENV === 'development') {
358
+ configureTrustProxy({
359
+ enabled: true,
360
+ providers: 'loopback',
361
+ }, 'AppFactory');
362
+ }
363
+ ```
364
+
365
+ ---
366
+
367
+ ## Security Checklist
368
+
369
+ Before deploying to production:
370
+
371
+ - [ ] Trust proxy configuration is **fail-closed** (enabled with explicit trustedProxies or providers)
372
+ - [ ] `trustedProxies` list includes **only** your actual proxy IPs/CIDRs
373
+ - [ ] Provider presets match your infrastructure (e.g., `cloudflare` if using Cloudflare)
374
+ - [ ] Rate limiting uses `getClientIp()` and is tested against spoofing
375
+ - [ ] IP-based access control is **not the sole authentication mechanism**
376
+ - [ ] Audit logs include both `clientIp` and `socketIp` for forensic analysis
377
+ - [ ] Trust proxy warnings are monitored and resolved
378
+ - [ ] Configuration is centralized in one location (e.g., `main.ts`)
379
+
380
+ ---
381
+
382
+ ## Example Architectures
383
+
384
+ ### AWS ALB + Cloudflare
385
+
386
+ ```
387
+ Client → Cloudflare (CDN) → AWS ALB → EC2/ECS (App)
388
+ ```
389
+
390
+ **Configuration:**
391
+ ```typescript
392
+ configureTrustProxy({
393
+ enabled: true,
394
+ providers: ['cloudflare', 'aws-alb'],
395
+ }, 'AppFactory');
396
+ ```
397
+
398
+ **Header Flow:**
399
+ ```
400
+ X-Forwarded-For: <client-ip>, <cloudflare-ip>, <alb-ip>
401
+ ↑ Extracted as clientIp
402
+ ```
403
+
404
+ ### Nginx Reverse Proxy
405
+
406
+ ```
407
+ Client → Nginx → Node.js App
408
+ ```
409
+
410
+ **Configuration:**
411
+ ```typescript
412
+ configureTrustProxy({
413
+ enabled: true,
414
+ trustedProxies: ['10.0.1.5'], // Nginx IP
415
+ }, 'AppFactory');
416
+ ```
417
+
418
+ **Nginx Configuration:**
419
+ ```nginx
420
+ location / {
421
+ proxy_pass http://localhost:3000;
422
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
423
+ proxy_set_header X-Real-IP $remote_addr;
424
+ }
425
+ ```
426
+
427
+ ### Local Development (No Proxy)
428
+
429
+ ```
430
+ Client → Node.js App (localhost)
431
+ ```
432
+
433
+ **Configuration:**
434
+ ```typescript
435
+ // No trust proxy configuration needed
436
+ // Default fail-closed behavior uses socket.remoteAddress
437
+ ```
438
+
439
+ ---
440
+
441
+ ## Appendix: Header Priority
442
+
443
+ `getClientIp()` checks headers in this order (when trust proxy is enabled and validated):
444
+
445
+ 1. `x-client-ip` (Amazon EC2, Heroku)
446
+ 2. `true-client-ip` (Akamai, Cloudflare Enterprise)
447
+ 3. `cf-connecting-ip` (Cloudflare)
448
+ 4. `do-connecting-ip` (DigitalOcean)
449
+ 5. `fastly-client-ip` (Fastly, Firebase)
450
+ 6. `x-forwarded-for` (Standard, AWS ALB)
451
+ 7. `x-real-ip` (Nginx)
452
+ 8. `x-cluster-client-ip` (Rackspace, Riverbed)
453
+ 9. `x-forwarded`
454
+ 10. `forwarded-for`
455
+ 11. `forwarded` (RFC 7239)
456
+ 12. `x-appengine-user-ip` (Google App Engine)
457
+ 13. `cf-pseudo-ipv4` (Cloudflare IPv6 fallback)
458
+
459
+ **Fallback:** If no trusted headers found, returns `socket.remoteAddress`.
460
+
461
+ ---
462
+
463
+ ## Additional Resources
464
+
465
+ - **Cloudflare IP Ranges:** https://www.cloudflare.com/ips/
466
+ - **AWS IP Ranges:** https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html
467
+ - **GCP IP Ranges:** https://cloud.google.com/compute/docs/faq#find_ip_range
468
+ - **DigitalOcean IP Ranges:** https://docs.digitalocean.com/products/platform/
469
+ - **RFC 1918 (Private Networks):** https://datatracker.ietf.org/doc/html/rfc1918
470
+
471
+ ---
472
+
473
+ **Last Updated:** 2026-02-16
474
+ **Version:** 3.0.0-rc.4
475
+ **Maintainer:** @nathapp/nestjs team
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-common",
3
- "version": "2.1.4",
3
+ "version": "3.0.0-rc.4",
4
4
  "description": "NestJs Common Library",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -1,9 +0,0 @@
1
- import { ExceptionFilter, ArgumentsHost } from "@nestjs/common";
2
- import { I18nService } from "nestjs-i18n";
3
- import { AppException } from "./app.exception";
4
- export declare class AppExceptionFilter implements ExceptionFilter {
5
- private readonly i18n;
6
- private logger;
7
- constructor(i18n: I18nService);
8
- catch(exception: AppException, host: ArgumentsHost): Promise<void>;
9
- }
@@ -1,52 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- var __param = (this && this.__param) || function (paramIndex, decorator) {
12
- return function (target, key) { decorator(target, key, paramIndex); }
13
- };
14
- var AppExceptionFilter_1;
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.AppExceptionFilter = void 0;
17
- const common_1 = require("@nathapp/common");
18
- const common_2 = require("@nestjs/common");
19
- const nestjs_i18n_1 = require("nestjs-i18n");
20
- const app_exception_1 = require("./app.exception");
21
- let AppExceptionFilter = AppExceptionFilter_1 = class AppExceptionFilter {
22
- constructor(i18n) {
23
- this.i18n = i18n;
24
- this.logger = new common_2.Logger(AppExceptionFilter_1.name);
25
- }
26
- async catch(exception, host) {
27
- const ctx = host.switchToHttp();
28
- const response = ctx.getResponse();
29
- const statusCode = exception.getStatus();
30
- const prefix = exception.prefix || "exception";
31
- let message = exception.code + "";
32
- if (this.i18n) {
33
- message = await this.i18n.translate(`${prefix}.${exception.code}`, {
34
- lang: ctx.getRequest().i18nLang,
35
- args: exception.args,
36
- });
37
- }
38
- else {
39
- this.logger.warn("I18nModule was not register. will to resolve AppException Message");
40
- }
41
- response
42
- .status(statusCode)
43
- .json(common_1.JsonResponse.Error(exception.code, message));
44
- }
45
- };
46
- exports.AppExceptionFilter = AppExceptionFilter;
47
- exports.AppExceptionFilter = AppExceptionFilter = AppExceptionFilter_1 = __decorate([
48
- (0, common_2.Catch)(app_exception_1.AppException),
49
- __param(0, (0, common_2.Optional)()),
50
- __metadata("design:paramtypes", [nestjs_i18n_1.I18nService])
51
- ], AppExceptionFilter);
52
- //# sourceMappingURL=app-exception.filter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-exception.filter.js","sourceRoot":"","sources":["../../lib/exception/app-exception.filter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA+C;AAC/C,2CAMwB;AAExB,6CAA0C;AAC1C,mDAA+C;AAMxC,IAAM,kBAAkB,0BAAxB,MAAM,kBAAkB;IAE7B,YAEE,IAAkC;QAAjB,SAAI,GAAJ,IAAI,CAAa;QAH5B,WAAM,GAAG,IAAI,eAAM,CAAC,oBAAkB,CAAC,IAAI,CAAC,CAAC;IAGb,CAAC;IAEzC,KAAK,CAAC,KAAK,CAAC,SAAuB,EAAE,IAAmB;QACtD,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAY,CAAC;QAC7C,MAAM,UAAU,GAAG,SAAS,CAAC,SAAS,EAAE,CAAC;QAEzC,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,IAAI,WAAW,CAAC;QAC/C,IAAI,OAAO,GAAG,SAAS,CAAC,IAAI,GAAG,EAAE,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,OAAO,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,MAAM,IAAI,SAAS,CAAC,IAAI,EAAE,EAAE;gBACjE,IAAI,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC,QAAQ;gBAC/B,IAAI,EAAE,SAAS,CAAC,IAAI;aACrB,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,mEAAmE,CACpE,CAAC;QACJ,CAAC;QAED,QAAQ;aACL,MAAM,CAAC,UAAU,CAAC;aAClB,IAAI,CAAC,qBAAY,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACvD,CAAC;CACF,CAAA;AA5BY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,cAAK,EAAC,4BAAY,CAAC;IAIf,WAAA,IAAA,iBAAQ,GAAE,CAAA;qCACY,yBAAW;GAJzB,kBAAkB,CA4B9B"}
File without changes
@@ -1 +0,0 @@
1
- //# sourceMappingURL=i18n.constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"i18n.constants.js","sourceRoot":"","sources":["../../lib/i18n/i18n.constants.ts"],"names":[],"mappings":""}
@@ -1,4 +0,0 @@
1
- import { DefaultLogProvider, EnvLogProvider, LogProvider, LogRequest, LogResponse } from "./log.provider";
2
- import { DefaultLoggerOptionFactory, EnvLoggerOptionFactory, LoggerOptionFactory, LoggerOptions } from "./logger-option.factory";
3
- import { LoggerMiddleware } from "./logger.middleware";
4
- export { LoggerMiddleware, LogRequest, LogResponse, LogProvider, DefaultLogProvider, EnvLogProvider, LoggerOptions, LoggerOptionFactory, DefaultLoggerOptionFactory, EnvLoggerOptionFactory };
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EnvLoggerOptionFactory = exports.DefaultLoggerOptionFactory = exports.LoggerOptionFactory = exports.EnvLogProvider = exports.DefaultLogProvider = exports.LogProvider = exports.LoggerMiddleware = void 0;
4
- const log_provider_1 = require("./log.provider");
5
- Object.defineProperty(exports, "DefaultLogProvider", { enumerable: true, get: function () { return log_provider_1.DefaultLogProvider; } });
6
- Object.defineProperty(exports, "EnvLogProvider", { enumerable: true, get: function () { return log_provider_1.EnvLogProvider; } });
7
- Object.defineProperty(exports, "LogProvider", { enumerable: true, get: function () { return log_provider_1.LogProvider; } });
8
- const logger_option_factory_1 = require("./logger-option.factory");
9
- Object.defineProperty(exports, "DefaultLoggerOptionFactory", { enumerable: true, get: function () { return logger_option_factory_1.DefaultLoggerOptionFactory; } });
10
- Object.defineProperty(exports, "EnvLoggerOptionFactory", { enumerable: true, get: function () { return logger_option_factory_1.EnvLoggerOptionFactory; } });
11
- Object.defineProperty(exports, "LoggerOptionFactory", { enumerable: true, get: function () { return logger_option_factory_1.LoggerOptionFactory; } });
12
- const logger_middleware_1 = require("./logger.middleware");
13
- Object.defineProperty(exports, "LoggerMiddleware", { enumerable: true, get: function () { return logger_middleware_1.LoggerMiddleware; } });
14
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/middleware/index.ts"],"names":[],"mappings":";;;AAAA,iDAA0G;AAIzC,mGAJxD,iCAAkB,OAIwD;AAAE,+FAJxD,6BAAc,OAIwD;AAA/C,4FAJP,0BAAW,OAIO;AAH/D,mEAAiI;AAGQ,2GAHhI,kDAA0B,OAGgI;AAAE,uGAHhI,8CAAsB,OAGgI;AAAvE,oGAHvD,2CAAmB,OAGuD;AAFvI,2DAAuD;AAE9C,iGAFA,oCAAgB,OAEA"}
@@ -1,38 +0,0 @@
1
- import { LoggerOptionFactory, LoggerOptions } from "./logger-option.factory";
2
- export interface LogRequest {
3
- method: string;
4
- originalUrl: string;
5
- data?: any;
6
- userAgent: string;
7
- ip: string;
8
- }
9
- export interface LogResponse {
10
- method: string;
11
- originalUrl: string;
12
- data?: any;
13
- statusCode: number;
14
- responseTime: number;
15
- }
16
- export interface LogHeader {
17
- headers: Record<string, any>;
18
- }
19
- export declare class LogProvider {
20
- private logger;
21
- protected readonly _options: LoggerOptions;
22
- constructor(optionsFactory: LoggerOptionFactory);
23
- get options(): LoggerOptions;
24
- processOutput(data: any): any;
25
- protected censorSensitiveKeysData(sensitiveKeys: string[], data: any): any;
26
- logHeader(headers: LogHeader): void;
27
- logRequest(request: LogRequest): void;
28
- logResponse(response: LogResponse): void;
29
- private toPrintableOutput;
30
- private toPrintableOutputResponseBody;
31
- private parseJson;
32
- }
33
- export declare class DefaultLogProvider extends LogProvider {
34
- constructor();
35
- }
36
- export declare class EnvLogProvider extends LogProvider {
37
- constructor();
38
- }