@nathapp/nestjs-microservices 2.1.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/adapter/http-fetch-service.adapter.d.ts +1 -0
  2. package/dist/adapter/http-fetch-service.adapter.js +13 -4
  3. package/dist/adapter/http-fetch-service.adapter.js.map +1 -1
  4. package/dist/adapter/http-service.adapter.d.ts +1 -0
  5. package/dist/adapter/http-service.adapter.js +13 -3
  6. package/dist/adapter/http-service.adapter.js.map +1 -1
  7. package/dist/adapter/micro-service.adapter.d.ts +3 -0
  8. package/dist/adapter/nestjs-micro-service.adapter.js +1 -1
  9. package/dist/adapter/nestjs-micro-service.adapter.js.map +1 -1
  10. package/dist/constant/index.d.ts +4 -0
  11. package/dist/constant/index.js +5 -1
  12. package/dist/constant/index.js.map +1 -1
  13. package/dist/decorator/micro-service-permission.decorator.d.ts +1 -0
  14. package/dist/decorator/micro-service-permission.decorator.js +8 -0
  15. package/dist/decorator/micro-service-permission.decorator.js.map +1 -0
  16. package/dist/guard/jwt-ms-auth.guard.d.ts +1 -1
  17. package/dist/guard/jwt-ms-auth.guard.js +9 -9
  18. package/dist/guard/jwt-ms-auth.guard.js.map +1 -1
  19. package/dist/guard/micro-service.guard.js +1 -1
  20. package/dist/guard/micro-service.guard.js.map +1 -1
  21. package/dist/guard/ms-permission.guard.d.ts +7 -0
  22. package/dist/guard/ms-permission.guard.js +41 -0
  23. package/dist/guard/ms-permission.guard.js.map +1 -0
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +2 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/interface/index.d.ts +1 -0
  28. package/dist/interface/index.js +18 -0
  29. package/dist/interface/index.js.map +1 -0
  30. package/dist/interface/service-identity.interface.d.ts +24 -0
  31. package/dist/interface/service-identity.interface.js +3 -0
  32. package/dist/interface/service-identity.interface.js.map +1 -0
  33. package/dist/module/micro-service.module.d.ts +5 -0
  34. package/dist/module/micro-service.module.js +33 -4
  35. package/dist/module/micro-service.module.js.map +1 -1
  36. package/dist/provider/index.d.ts +2 -0
  37. package/dist/provider/index.js +19 -0
  38. package/dist/provider/index.js.map +1 -0
  39. package/dist/provider/service-identity.provider.d.ts +10 -0
  40. package/dist/provider/service-identity.provider.js +64 -0
  41. package/dist/provider/service-identity.provider.js.map +1 -0
  42. package/dist/provider/service-permission-registry.d.ts +7 -0
  43. package/dist/provider/service-permission-registry.js +35 -0
  44. package/dist/provider/service-permission-registry.js.map +1 -0
  45. package/dist/strategy/microservice-jwt-strategy-provider.d.ts +4 -0
  46. package/dist/strategy/microservice-jwt-strategy-provider.js +49 -0
  47. package/dist/strategy/microservice-jwt-strategy-provider.js.map +1 -1
  48. package/docs/20260215-fix-plan-service-identity-jwt.md +253 -0
  49. package/docs/20260215-review-microservices-enterprise.md +234 -0
  50. package/package.json +5 -5
@@ -0,0 +1,234 @@
1
+ # Deep Review: nestjs-microservices — Enterprise Readiness Assessment
2
+
3
+ **Date:** 2026-02-15
4
+ **Branch:** feat/monorepo-enterprise-upgrade
5
+ **Reviewer:** Subrina (opus)
6
+ **Grade:** C+ (functional, significant architectural concerns for enterprise)
7
+
8
+ ## Summary
9
+
10
+ `@nathapp/nestjs-microservices` adds JWT-secured service-to-service communication (HTTP, gRPC) on top of `@nestjs/microservices`. The core idea — sign payloads as JWT to authenticate inter-service calls — is clever but has fundamental security limitations and significant code duplication.
11
+
12
+ **Lines:** ~4,766 (1,333 are copy-pasted Kafka types)
13
+ **Tests:** 43 passing (low coverage for a security-critical package)
14
+
15
+ ---
16
+
17
+ ## Architecture Analysis
18
+
19
+ ### What It Does Well
20
+ 1. **Unified adapter pattern** — `MicroServiceAdapter` abstracts HTTP/gRPC/RMQ/TCP behind a single interface
21
+ 2. **Factory pattern** — `MicroServiceAdapterFactory` + `ServiceClientFactory` cleanly create adapters per transport
22
+ 3. **Module structure** — `MicroServiceModule` (server auth) + `MicroServiceClientsModule` (client connections) is a clean separation
23
+ 4. **BigInt support** — Custom RMQ client/server using `json-bigint` for Java interop
24
+ 5. **Graceful shutdown** — `assignOnAppShutdownHook` hooks client cleanup to app lifecycle
25
+
26
+ ### Core Security Model: JWT-Signed Payloads
27
+
28
+ Current approach:
29
+ ```
30
+ Service A → signs request body as JWT → Service B verifies JWT, compares body to payload
31
+ ```
32
+
33
+ **How it works:**
34
+ - Client: `JwtProvider.sign(payload)` → puts token in `Authorization: Bearer` header
35
+ - Server: `MicroServiceJwtStrategy` verifies token, then `MicroServiceJwtStrategyProvider.validate()` does `isDeepStrictEqual(req.body, omitExpPayload)` to ensure body wasn't tampered
36
+
37
+ ---
38
+
39
+ ## Critical Issues
40
+
41
+ ### SEC-1 🔴 HIGH — Payload-as-JWT is Not Standard Service Auth
42
+
43
+ **Problem:** The JWT payload IS the request body. This means:
44
+ - Every request generates a new JWT (no caching, ~1ms overhead per call)
45
+ - Token contains the full request data (potentially large payloads = large tokens)
46
+ - The `isDeepStrictEqual(body, payload)` check is the only integrity guarantee
47
+ - No service identity — any service with the shared secret can call any endpoint
48
+ - No audience/issuer validation — tokens are interchangeable between services
49
+
50
+ **Enterprise standard:** mTLS or service identity tokens (OAuth2 client credentials, SPIFFE/SPIRE)
51
+
52
+ **Impact:** Works for trusted internal networks but breaks down with:
53
+ - Service mesh adoption (Istio/Linkerd already provide mTLS)
54
+ - Zero-trust architecture (need service identity, not just shared secrets)
55
+ - Large payloads (10MB request body = 10MB JWT = doubled memory)
56
+ - Audit trails (no service identity in tokens)
57
+
58
+ ### SEC-2 🔴 HIGH — Shared Secret Between All Services
59
+
60
+ **Problem:** All services share the same `MS_JWT_ACCESS_SECRET`. Compromise of one service compromises all inter-service communication.
61
+
62
+ **Enterprise standard:** Per-service credentials or certificate-based identity.
63
+
64
+ ### SEC-3 🟡 MED — JwtMsAuthGuard Still Has RefreshToken Bypass
65
+
66
+ **File:** `lib/guard/jwt-ms-auth.guard.ts:48-51`
67
+ ```typescript
68
+ if (RefreshToken) {
69
+ return true; // bypasses auth
70
+ }
71
+ ```
72
+ Same SEC-1 bug we fixed in `nestjs-auth`. The `@RefreshToken()` decorator bypasses `JwtMsAuthGuard`.
73
+
74
+ ### SEC-4 🟡 MED — No Rate Limiting on Service-to-Service Calls
75
+
76
+ No protection against a compromised service flooding another service.
77
+
78
+ ---
79
+
80
+ ## Code Quality Issues
81
+
82
+ ### BUG-1 🔴 HIGH — Infinite Recursion in NestJsMicroServiceAdapter.close()
83
+
84
+ **File:** `lib/adapter/nestjs-micro-service.adapter.ts:25`
85
+ ```typescript
86
+ close() {
87
+ this.close() // ← calls itself, not this.clientProxy.close()
88
+ }
89
+ ```
90
+ This is a stack overflow bug. Should be `this.clientProxy.close()`.
91
+
92
+ ### BUG-2 🟡 MED — Timeout Throws Inside setTimeout (Uncatchable)
93
+
94
+ **File:** `lib/adapter/http-fetch-service.adapter.ts:87-90`
95
+ ```typescript
96
+ const timeout = setTimeout(() => {
97
+ controller.abort();
98
+ throw new AppException(CommonExceptionCode.UNKNOWN_ERROR); // ← uncatchable!
99
+ }, requestTimeout);
100
+ ```
101
+ `throw` inside `setTimeout` is uncatchable — it crashes the process. The `abort()` signal should be sufficient; the fetch will throw `AbortError`.
102
+
103
+ ### DUP-1 🟡 MED — HttpServiceAdapter and HttpFetchServiceAdapter Are 90% Identical
104
+
105
+ ~340 lines of near-duplicate code. Only difference: one uses `axios`, other uses `fetch`. Should be extracted to a base class.
106
+
107
+ ### DUP-2 🟡 MED — CustomClientRMQ and CustomServerRMQ Are Forked from NestJS
108
+
109
+ ~770 lines forked from `@nestjs/microservices` with only `JSONbig.stringify/parse` changes. These will fall out of sync with upstream NestJS updates.
110
+
111
+ ### DUP-3 🟢 LOW — Kafka Interface File (1,333 lines)
112
+
113
+ Copy-pasted kafkajs types. Should use `import type` from kafkajs or `@types/kafkajs`.
114
+
115
+ ### STYLE-1 🟢 LOW — Inconsistent Error Messages
116
+
117
+ Mix of error styles: `"Connection Error - url:"`, `"Invalid response - status:"`, `"Failed response - ret:"`. Should use structured logging.
118
+
119
+ ### STYLE-2 🟢 LOW — `ret` / `msg` Convention
120
+
121
+ The `"0" != result.ret` check and `HttpMicroServiceException(result.ret, result.msg)` pattern suggests a legacy Java response format. Should be documented.
122
+
123
+ ---
124
+
125
+ ## Architecture Recommendations
126
+
127
+ ### Question 1: Is JWT-Signed-Payload the Right Pattern?
128
+
129
+ **Current (what you have):**
130
+ ```
131
+ Sign(body) → Bearer token → Verify + deepEqual(body, decoded)
132
+ ```
133
+
134
+ **Alternative approaches worth considering:**
135
+
136
+ | Approach | Pros | Cons |
137
+ |----------|------|------|
138
+ | **Current (JWT payload)** | Simple, self-contained | Large tokens, no service identity, no caching |
139
+ | **Service identity JWT** | Service identity, cacheable (short-lived), standard OAuth2 | Needs token issuer/refresh |
140
+ | **mTLS** | Zero-trust, no token management, service mesh native | Certificate management complexity |
141
+ | **API keys + HMAC** | Simple, low overhead, payload-agnostic | Key management, no standard |
142
+ | **HMAC signature header** | Payload integrity without embedding in JWT, low overhead | Custom protocol |
143
+
144
+ **My recommendation for your ecosystem:**
145
+
146
+ **Option A — Service Identity JWT (if staying with JWT):**
147
+ ```typescript
148
+ // Service A registers as "auth-api" with a shared secret
149
+ const token = jwt.sign({
150
+ iss: 'auth-api', // who I am
151
+ aud: 'notification-api', // who I'm calling
152
+ sub: 'service', // service-to-service
153
+ }, serviceSecret, { expiresIn: '5m' });
154
+
155
+ // Body integrity via HMAC header (separate from auth)
156
+ headers['X-Body-Signature'] = hmac(body, token);
157
+ ```
158
+
159
+ Benefits:
160
+ - Token is small (fixed size, ~200 bytes regardless of payload)
161
+ - Cacheable — reuse for 5 minutes
162
+ - Service identity for audit trails
163
+ - Can restrict which service calls which (audience check)
164
+ - Body integrity via HMAC (handles large payloads)
165
+
166
+ **Option B — mTLS (if moving to service mesh):**
167
+ Let the infrastructure handle auth. Remove JWT from inter-service calls entirely. Use service mesh (Istio) for mTLS + authorization policies.
168
+
169
+ ### Question 2: What Do You Actually Need?
170
+
171
+ Before recommending fixes, I need to understand:
172
+
173
+ 1. **Deployment topology**: Are services on the same k8s cluster? Same VPC? Internet-facing?
174
+ 2. **Trust model**: Do all services trust each other equally, or do you need per-service permissions?
175
+ 3. **Java interop**: The custom RMQ with `JSONbig` suggests Java services. Are you still interoperating with Java?
176
+ 4. **Service mesh plans**: Any plans for Istio/Linkerd?
177
+ 5. **Payload sizes**: How large are typical inter-service request bodies?
178
+
179
+ ---
180
+
181
+ ## Test Coverage Gaps
182
+
183
+ | Area | Tests | Coverage |
184
+ |------|-------|----------|
185
+ | HTTP adapters | ✅ Basic | Missing: timeout, error paths, large payloads |
186
+ | gRPC JWT proxy | ❌ None | Security-critical, zero tests |
187
+ | Custom RMQ client | ❌ None | 441 lines untested |
188
+ | Custom RMQ server | ❌ None | 327 lines untested |
189
+ | Guards | ❌ None | Security-critical, zero tests |
190
+ | Exception handling | ❌ None | gRPC error resolution untested |
191
+ | Module registration | ✅ Basic | Missing: error cases |
192
+ | Strategy/validation | ✅ Basic | Missing: edge cases (large payloads, expired tokens) |
193
+ | NestJsMicroServiceAdapter | ❌ None | Has the close() recursion bug |
194
+
195
+ **Estimated coverage:** ~25-30% (compared to 80%+ target)
196
+
197
+ ---
198
+
199
+ ## Improvement Phases (If Proceeding)
200
+
201
+ ### Phase 0: Critical Bugs (Do Now)
202
+ - Fix BUG-1: `close()` recursion
203
+ - Fix BUG-2: uncatchable setTimeout throw
204
+ - Fix SEC-3: RefreshToken bypass in JwtMsAuthGuard
205
+ - Add tests for guards and gRPC proxy
206
+
207
+ ### Phase 1: Code Cleanup
208
+ - Extract base class for HTTP adapters (eliminate DUP-1)
209
+ - Remove copied Kafka types (use `import type`)
210
+ - Standardize error handling/logging
211
+
212
+ ### Phase 2: Architecture Decision
213
+ - Decide: keep JWT-payload, move to service identity JWT, or plan for mTLS
214
+ - This decision affects Phase 3 significantly
215
+
216
+ ### Phase 3: Implement Chosen Pattern
217
+ - If service identity JWT: refactor token generation, add iss/aud/sub, add HMAC for body integrity
218
+ - If mTLS: simplify package, remove JWT from service calls, document mesh setup
219
+ - Either way: add per-service permissions
220
+
221
+ ---
222
+
223
+ ## Verdict
224
+
225
+ The package works for its current purpose (JWT-secured HTTP/gRPC in a trusted network with a shared secret). But it has:
226
+
227
+ 1. **A critical bug** (infinite recursion in close())
228
+ 2. **A security design that won't scale** to zero-trust/service mesh
229
+ 3. **Significant code duplication** (~1,100 lines of forked NestJS code)
230
+ 4. **Low test coverage** on security-critical paths
231
+
232
+ For enterprise grade: needs architectural decision on the auth model before investing in fixes. The current JWT-payload approach is a **v1 pragmatic solution** — fine for internal services that trust each other, but not suitable for enterprise multi-team environments.
233
+
234
+ **Recommended action:** Fix Phase 0 bugs, then discuss architecture direction before Phase 2+.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-microservices",
3
- "version": "2.1.5",
3
+ "version": "3.0.0",
4
4
  "description": "nestjs-microservices",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -36,16 +36,16 @@
36
36
  "lib": "lib"
37
37
  },
38
38
  "dependencies": {
39
- "@nathapp/nestjs-auth": "^2.1.5",
40
- "@nathapp/nestjs-common": "^2.1.5",
39
+ "@nathapp/nestjs-auth": "^3.0.0",
40
+ "@nathapp/nestjs-common": "^3.0.0",
41
41
  "json-bigint": "^1.0.0",
42
42
  "passport-jwt": "^4.0.1"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@grpc/grpc-js": "*",
46
46
  "@nathapp/auth": "^1.0.2",
47
- "@nathapp/nestjs-auth": "^2.1.5",
48
- "@nathapp/nestjs-common": "^2.1.5",
47
+ "@nathapp/nestjs-auth": "^3.0.0",
48
+ "@nathapp/nestjs-common": "^3.0.0",
49
49
  "@nestjs/microservices": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
50
50
  "@nestjs/passport": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
51
51
  "axios": "*",