@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.
- package/dist/adapter/http-fetch-service.adapter.d.ts +1 -0
- package/dist/adapter/http-fetch-service.adapter.js +13 -4
- package/dist/adapter/http-fetch-service.adapter.js.map +1 -1
- package/dist/adapter/http-service.adapter.d.ts +1 -0
- package/dist/adapter/http-service.adapter.js +13 -3
- package/dist/adapter/http-service.adapter.js.map +1 -1
- package/dist/adapter/micro-service.adapter.d.ts +3 -0
- package/dist/adapter/nestjs-micro-service.adapter.js +1 -1
- package/dist/adapter/nestjs-micro-service.adapter.js.map +1 -1
- package/dist/constant/index.d.ts +4 -0
- package/dist/constant/index.js +5 -1
- package/dist/constant/index.js.map +1 -1
- package/dist/decorator/micro-service-permission.decorator.d.ts +1 -0
- package/dist/decorator/micro-service-permission.decorator.js +8 -0
- package/dist/decorator/micro-service-permission.decorator.js.map +1 -0
- package/dist/guard/jwt-ms-auth.guard.d.ts +1 -1
- package/dist/guard/jwt-ms-auth.guard.js +9 -9
- package/dist/guard/jwt-ms-auth.guard.js.map +1 -1
- package/dist/guard/micro-service.guard.js +1 -1
- package/dist/guard/micro-service.guard.js.map +1 -1
- package/dist/guard/ms-permission.guard.d.ts +7 -0
- package/dist/guard/ms-permission.guard.js +41 -0
- package/dist/guard/ms-permission.guard.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/interface/index.d.ts +1 -0
- package/dist/interface/index.js +18 -0
- package/dist/interface/index.js.map +1 -0
- package/dist/interface/service-identity.interface.d.ts +24 -0
- package/dist/interface/service-identity.interface.js +3 -0
- package/dist/interface/service-identity.interface.js.map +1 -0
- package/dist/module/micro-service.module.d.ts +5 -0
- package/dist/module/micro-service.module.js +33 -4
- package/dist/module/micro-service.module.js.map +1 -1
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.js +19 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/provider/service-identity.provider.d.ts +10 -0
- package/dist/provider/service-identity.provider.js +64 -0
- package/dist/provider/service-identity.provider.js.map +1 -0
- package/dist/provider/service-permission-registry.d.ts +7 -0
- package/dist/provider/service-permission-registry.js +35 -0
- package/dist/provider/service-permission-registry.js.map +1 -0
- package/dist/strategy/microservice-jwt-strategy-provider.d.ts +4 -0
- package/dist/strategy/microservice-jwt-strategy-provider.js +49 -0
- package/dist/strategy/microservice-jwt-strategy-provider.js.map +1 -1
- package/docs/20260215-fix-plan-service-identity-jwt.md +253 -0
- package/docs/20260215-review-microservices-enterprise.md +234 -0
- package/package.json +5 -5
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ServiceIdentityOptions } from '../interface';
|
|
2
|
+
export declare const SERVICE_IDENTITY_OPTIONS = "SERVICE_IDENTITY_OPTIONS";
|
|
3
|
+
export declare class ServiceIdentityProvider {
|
|
4
|
+
private options;
|
|
5
|
+
private cachedToken;
|
|
6
|
+
constructor(options: ServiceIdentityOptions);
|
|
7
|
+
getToken(audience?: string): string;
|
|
8
|
+
signBody(body: any): string;
|
|
9
|
+
verifyBody(body: any, signature: string): boolean;
|
|
10
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ServiceIdentityProvider = exports.SERVICE_IDENTITY_OPTIONS = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const jwt = require("jsonwebtoken");
|
|
18
|
+
const crypto = require("crypto");
|
|
19
|
+
exports.SERVICE_IDENTITY_OPTIONS = 'SERVICE_IDENTITY_OPTIONS';
|
|
20
|
+
let ServiceIdentityProvider = class ServiceIdentityProvider {
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.cachedToken = null;
|
|
24
|
+
}
|
|
25
|
+
getToken(audience) {
|
|
26
|
+
if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 30000) {
|
|
27
|
+
return this.cachedToken.token;
|
|
28
|
+
}
|
|
29
|
+
const payload = {
|
|
30
|
+
iss: this.options.serviceId,
|
|
31
|
+
sub: 'service',
|
|
32
|
+
...(audience && { aud: audience }),
|
|
33
|
+
};
|
|
34
|
+
const algorithm = this.options.jwt.algorithm || 'HS256';
|
|
35
|
+
const signingKey = this.options.jwt.privateKey || this.options.jwt.secret;
|
|
36
|
+
const finalKey = (algorithm === 'RS256' || algorithm === 'ES256') && typeof signingKey === 'string'
|
|
37
|
+
? signingKey.trim()
|
|
38
|
+
: signingKey;
|
|
39
|
+
const token = jwt.sign(payload, finalKey, {
|
|
40
|
+
algorithm,
|
|
41
|
+
expiresIn: this.options.jwt.expiresIn || 300,
|
|
42
|
+
});
|
|
43
|
+
this.cachedToken = { token, expiresAt: Date.now() + ((this.options.jwt.expiresIn || 300) * 1000) };
|
|
44
|
+
return token;
|
|
45
|
+
}
|
|
46
|
+
signBody(body) {
|
|
47
|
+
var _a, _b;
|
|
48
|
+
const hmacSecret = ((_a = this.options.hmac) === null || _a === void 0 ? void 0 : _a.secret) || this.options.jwt.secret;
|
|
49
|
+
const algo = ((_b = this.options.hmac) === null || _b === void 0 ? void 0 : _b.algorithm) || 'sha256';
|
|
50
|
+
const serialized = body === undefined ? '' : (body === null ? 'null' : (typeof body === 'string' ? body : JSON.stringify(body)));
|
|
51
|
+
return crypto.createHmac(algo, hmacSecret).update(serialized).digest('hex');
|
|
52
|
+
}
|
|
53
|
+
verifyBody(body, signature) {
|
|
54
|
+
const expected = this.signBody(body);
|
|
55
|
+
return expected === signature;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
exports.ServiceIdentityProvider = ServiceIdentityProvider;
|
|
59
|
+
exports.ServiceIdentityProvider = ServiceIdentityProvider = __decorate([
|
|
60
|
+
(0, common_1.Injectable)(),
|
|
61
|
+
__param(0, (0, common_1.Inject)(exports.SERVICE_IDENTITY_OPTIONS)),
|
|
62
|
+
__metadata("design:paramtypes", [Object])
|
|
63
|
+
], ServiceIdentityProvider);
|
|
64
|
+
//# sourceMappingURL=service-identity.provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-identity.provider.js","sourceRoot":"","sources":["../../lib/provider/service-identity.provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAoD;AACpD,oCAAoC;AACpC,iCAAiC;AAGpB,QAAA,wBAAwB,GAAG,0BAA0B,CAAC;AAG5D,IAAM,uBAAuB,GAA7B,MAAM,uBAAuB;IAGlC,YAA8C,OAAuC;QAA/B,YAAO,GAAP,OAAO,CAAwB;QAF7E,gBAAW,GAAgD,IAAI,CAAC;IAEgB,CAAC;IAGzF,QAAQ,CAAC,QAAiB;QAExB,IAAI,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,WAAW,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;YACxE,OAAO,IAA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,IAAI,0CAAE,SAAS,KAAI,QAAQ,CAAC;QAEtD,MAAM,UAAU,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACjI,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC9E,CAAC;IAGD,UAAU,CAAC,IAAS,EAAE,SAAiB;QACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrC,OAAO,QAAQ,KAAK,SAAS,CAAC;IAChC,CAAC;CACF,CAAA;AAhDY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,mBAAU,GAAE;IAIE,WAAA,IAAA,eAAM,EAAC,gCAAwB,CAAC,CAAA;;GAHlC,uBAAuB,CAgDnC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ServicePermissionMap } from '../interface/service-identity.interface';
|
|
2
|
+
export declare class ServicePermissionRegistry {
|
|
3
|
+
private map;
|
|
4
|
+
constructor(map: ServicePermissionMap);
|
|
5
|
+
getPermissions(serviceId: string): string[];
|
|
6
|
+
hasPermission(serviceId: string, permission: string): boolean;
|
|
7
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ServicePermissionRegistry = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const constant_1 = require("../constant");
|
|
18
|
+
let ServicePermissionRegistry = class ServicePermissionRegistry {
|
|
19
|
+
constructor(map) {
|
|
20
|
+
this.map = map;
|
|
21
|
+
}
|
|
22
|
+
getPermissions(serviceId) {
|
|
23
|
+
return this.map[serviceId] || [];
|
|
24
|
+
}
|
|
25
|
+
hasPermission(serviceId, permission) {
|
|
26
|
+
return this.getPermissions(serviceId).includes(permission);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
exports.ServicePermissionRegistry = ServicePermissionRegistry;
|
|
30
|
+
exports.ServicePermissionRegistry = ServicePermissionRegistry = __decorate([
|
|
31
|
+
(0, common_1.Injectable)(),
|
|
32
|
+
__param(0, (0, common_1.Inject)(constant_1.SERVICE_PERMISSION_MAP)),
|
|
33
|
+
__metadata("design:paramtypes", [Object])
|
|
34
|
+
], ServicePermissionRegistry);
|
|
35
|
+
//# sourceMappingURL=service-permission-registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-permission-registry.js","sourceRoot":"","sources":["../../lib/provider/service-permission-registry.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAoD;AAEpD,0CAAqD;AAG9C,IAAM,yBAAyB,GAA/B,MAAM,yBAAyB;IACpC,YAAoD,GAAyB;QAAzB,QAAG,GAAH,GAAG,CAAsB;IAAG,CAAC;IAEjF,cAAc,CAAC,SAAiB;QAC9B,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAED,aAAa,CAAC,SAAiB,EAAE,UAAkB;QACjD,OAAO,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAC7D,CAAC;CACF,CAAA;AAVY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,mBAAU,GAAE;IAEE,WAAA,IAAA,eAAM,EAAC,iCAAsB,CAAC,CAAA;;GADhC,yBAAyB,CAUrC"}
|
|
@@ -7,7 +7,11 @@ export declare abstract class MicroServiceStrategyProvider extends JwtStrategyPr
|
|
|
7
7
|
}
|
|
8
8
|
export declare class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
|
|
9
9
|
private readonly logger;
|
|
10
|
+
private readonly hmacSecret;
|
|
10
11
|
constructor(options: JwtOptions);
|
|
11
12
|
validate<T>(req: Req, payload: any): Promise<T>;
|
|
13
|
+
private validateServiceIdentity;
|
|
14
|
+
private validateLegacy;
|
|
15
|
+
private getHeaderCaseInsensitive;
|
|
12
16
|
getStrategyOptions(): StrategyOptionsWithRequest | StrategyOptionsWithoutRequest;
|
|
13
17
|
}
|
|
@@ -6,6 +6,7 @@ const nestjs_common_1 = require("@nathapp/nestjs-common");
|
|
|
6
6
|
const common_1 = require("@nestjs/common");
|
|
7
7
|
const passport_jwt_1 = require("passport-jwt");
|
|
8
8
|
const util_1 = require("util");
|
|
9
|
+
const crypto = require("crypto");
|
|
9
10
|
const extractor_1 = require("./extractor");
|
|
10
11
|
class MicroServiceStrategyProvider extends nestjs_auth_1.JwtStrategyProvider {
|
|
11
12
|
}
|
|
@@ -14,9 +15,46 @@ class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
|
|
|
14
15
|
constructor(options) {
|
|
15
16
|
super(options);
|
|
16
17
|
this.logger = new common_1.Logger(MicroServiceJwtStrategyProvider.name);
|
|
18
|
+
this.hmacSecret = options.secret;
|
|
17
19
|
}
|
|
18
20
|
async validate(req, payload) {
|
|
19
21
|
this.logger.verbose(`MS JwtStrategyProvider: method: ${req.method}`);
|
|
22
|
+
if (payload.sub === 'service') {
|
|
23
|
+
return this.validateServiceIdentity(req, payload);
|
|
24
|
+
}
|
|
25
|
+
return this.validateLegacy(req, payload);
|
|
26
|
+
}
|
|
27
|
+
async validateServiceIdentity(req, payload) {
|
|
28
|
+
this.logger.verbose(`Service Identity Mode: validating token from ${payload.iss}`);
|
|
29
|
+
if (!payload.iss) {
|
|
30
|
+
this.logger.warn('Service identity token missing iss field');
|
|
31
|
+
throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
|
|
32
|
+
}
|
|
33
|
+
const now = Math.floor(Date.now() / 1000);
|
|
34
|
+
if (payload.exp && payload.exp < now) {
|
|
35
|
+
this.logger.warn(`Service identity token expired: exp=${payload.exp}, now=${now}`);
|
|
36
|
+
throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
|
|
37
|
+
}
|
|
38
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
39
|
+
const hmacHeader = this.getHeaderCaseInsensitive(req.headers, 'x-body-hmac');
|
|
40
|
+
if (!hmacHeader) {
|
|
41
|
+
this.logger.warn('Service identity token requires X-Body-HMAC header for non-GET requests');
|
|
42
|
+
throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.FORBIDDEN);
|
|
43
|
+
}
|
|
44
|
+
const algorithmHeader = this.getHeaderCaseInsensitive(req.headers, 'x-hmac-algorithm');
|
|
45
|
+
const hmacAlgorithm = algorithmHeader || 'sha256';
|
|
46
|
+
const bodyString = req.body === null ? 'null' : (typeof req.body === 'string' ? req.body : JSON.stringify(req.body));
|
|
47
|
+
const expectedHmac = crypto.createHmac(hmacAlgorithm, this.hmacSecret).update(bodyString).digest('hex');
|
|
48
|
+
if (hmacHeader !== expectedHmac) {
|
|
49
|
+
this.logger.warn('HMAC verification failed: body signature mismatch');
|
|
50
|
+
throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.FORBIDDEN);
|
|
51
|
+
}
|
|
52
|
+
this.logger.verbose('HMAC verification successful');
|
|
53
|
+
}
|
|
54
|
+
return payload;
|
|
55
|
+
}
|
|
56
|
+
async validateLegacy(req, payload) {
|
|
57
|
+
this.logger.verbose('Legacy Mode: JWT-payload validation');
|
|
20
58
|
if (req.method == "GET") {
|
|
21
59
|
throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
|
|
22
60
|
}
|
|
@@ -29,6 +67,17 @@ class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
|
|
|
29
67
|
}
|
|
30
68
|
return payload;
|
|
31
69
|
}
|
|
70
|
+
getHeaderCaseInsensitive(headers, key) {
|
|
71
|
+
if (!headers)
|
|
72
|
+
return undefined;
|
|
73
|
+
const lowerKey = key.toLowerCase();
|
|
74
|
+
for (const headerKey in headers) {
|
|
75
|
+
if (headerKey.toLowerCase() === lowerKey) {
|
|
76
|
+
return headers[headerKey];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
32
81
|
getStrategyOptions() {
|
|
33
82
|
const partialOptions = {
|
|
34
83
|
ignoreExpiration: this.ignoreExpiration,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microservice-jwt-strategy-provider.js","sourceRoot":"","sources":["../../lib/strategy/microservice-jwt-strategy-provider.ts"],"names":[],"mappings":";;;AAAA,sDAAwF;AACxF,0DAA2E;AAC3E,2CAAwC;AACxC,+CAAsH;AACtH,+BAAyC;AACzC,2CAA+C;AAE/C,M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AS,IAAI,OAAO,EAAE,CAAC;YAChC,IAAI,SAAS,CAAC,WAAW,EAAE,KAAK,QAAQ,EAAE,CAAC;gBACzC,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,kBAAkB;QAChB,MAAM,cAAc,GAA6B;YAC/C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;SACxC,CAAA;QAED,IAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC1B,OAAO;gBACL,GAAG,cAAc;gBACjB,cAAc,EAAE,yBAAU,CAAC,cAAc,CAAC,CAAC,4BAAgB,EAAE,IAAI,CAAC,sBAAsB,CAAC,CAAC;gBAC1F,WAAW,EAAE,IAAI,CAAC,iBAAoC;gBACtD,iBAAiB,EAAE,IAAI;aACxB,CAAA;QACH,CAAC;QAED,OAAO;YACL,GAAG,cAAc;YACjB,cAAc,EAAE,yBAAU,CAAC,cAAc,CAAC,CAAC,4BAAgB,EAAE,IAAI,CAAC,sBAAsB,CAAC,CAAC;YAC1F,WAAW,EAAE,IAAI,CAAC,iBAAoC;YACtD,iBAAiB,EAAE,KAAK;SACzB,CAAA;IACH,CAAC;CAEF;AArHD,0EAqHC"}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# Fix Plan: Service Identity JWT + HMAC + Service Permissions
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-15
|
|
4
|
+
**Branch:** feat/monorepo-enterprise-upgrade
|
|
5
|
+
**Package:** `packages/nestjs-microservices`
|
|
6
|
+
|
|
7
|
+
## Context
|
|
8
|
+
|
|
9
|
+
Replace the current "JWT-payload" pattern (signs entire request body as JWT) with a proper Service Identity JWT + HMAC body signature approach.
|
|
10
|
+
|
|
11
|
+
### Current Problems
|
|
12
|
+
- JWT contains full request body → few MB payloads = few MB tokens = doubled memory
|
|
13
|
+
- No service identity → can't do authorization
|
|
14
|
+
- Token not cacheable → new JWT per request
|
|
15
|
+
- No asymmetric key support
|
|
16
|
+
|
|
17
|
+
### Target Architecture
|
|
18
|
+
```
|
|
19
|
+
Headers:
|
|
20
|
+
Authorization: Bearer <service-identity-token> (~200 bytes, cached 5min)
|
|
21
|
+
X-Body-HMAC: sha256(body, shared-secret) (64 bytes, per-request)
|
|
22
|
+
Body: <original payload, untouched, any size>
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Design Requirements (from William)
|
|
26
|
+
1. Shared secret for now, per-service secrets designed for later
|
|
27
|
+
2. Must support asymmetric keys (RS256/ES256), not just HS256
|
|
28
|
+
3. `MS_JWT_SECRET` currently reuses nestjs-auth secret — keep backward compatible
|
|
29
|
+
4. Service permissions via decorator (`@MicroServicePermission('user:read')`)
|
|
30
|
+
5. Java interop (BigInt/RMQ) untouched
|
|
31
|
+
|
|
32
|
+
## Phase 1: Service Identity JWT + HMAC (Replace Payload-as-JWT)
|
|
33
|
+
|
|
34
|
+
### 1A: New Interfaces & Options
|
|
35
|
+
|
|
36
|
+
**File:** `lib/interface/service-identity.interface.ts` (NEW)
|
|
37
|
+
```typescript
|
|
38
|
+
export interface ServiceIdentityOptions {
|
|
39
|
+
/** Unique identifier for this service (e.g., 'notification-api') */
|
|
40
|
+
serviceId: string;
|
|
41
|
+
|
|
42
|
+
/** JWT signing options */
|
|
43
|
+
jwt: {
|
|
44
|
+
/** Shared secret (HS256) OR private key (RS256/ES256) */
|
|
45
|
+
secret: string;
|
|
46
|
+
/** Algorithm - default 'HS256' */
|
|
47
|
+
algorithm?: 'HS256' | 'RS256' | 'ES256';
|
|
48
|
+
/** Public key for asymmetric verification (RS256/ES256) */
|
|
49
|
+
publicKey?: string;
|
|
50
|
+
/** Token TTL in seconds - default 300 (5 min) */
|
|
51
|
+
expiresIn?: number;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** HMAC options for body integrity */
|
|
55
|
+
hmac?: {
|
|
56
|
+
/** HMAC secret - defaults to jwt.secret if not provided */
|
|
57
|
+
secret?: string;
|
|
58
|
+
/** Algorithm - default 'sha256' */
|
|
59
|
+
algorithm?: 'sha256' | 'sha384' | 'sha512';
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface ServiceIdentityPayload {
|
|
64
|
+
iss: string; // serviceId of caller
|
|
65
|
+
aud?: string; // serviceId of target (optional, for per-service auth later)
|
|
66
|
+
sub: 'service';
|
|
67
|
+
iat: number;
|
|
68
|
+
exp: number;
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**File:** `lib/interface/index.ts` — re-export new interfaces
|
|
73
|
+
|
|
74
|
+
### 1B: ServiceIdentityProvider (Token + HMAC Generation)
|
|
75
|
+
|
|
76
|
+
**File:** `lib/provider/service-identity.provider.ts` (NEW)
|
|
77
|
+
```typescript
|
|
78
|
+
@Injectable()
|
|
79
|
+
export class ServiceIdentityProvider {
|
|
80
|
+
private cachedToken: { token: string; expiresAt: number } | null = null;
|
|
81
|
+
|
|
82
|
+
constructor(@Inject(SERVICE_IDENTITY_OPTIONS) private options: ServiceIdentityOptions) {}
|
|
83
|
+
|
|
84
|
+
/** Get or create a cached service identity JWT */
|
|
85
|
+
getToken(audience?: string): string {
|
|
86
|
+
// Cache: reuse if >30s remaining
|
|
87
|
+
if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 30000) {
|
|
88
|
+
return this.cachedToken.token;
|
|
89
|
+
}
|
|
90
|
+
const payload: ServiceIdentityPayload = {
|
|
91
|
+
iss: this.options.serviceId,
|
|
92
|
+
sub: 'service',
|
|
93
|
+
...(audience && { aud: audience }),
|
|
94
|
+
};
|
|
95
|
+
const token = jwt.sign(payload, this.options.jwt.secret, {
|
|
96
|
+
algorithm: this.options.jwt.algorithm || 'HS256',
|
|
97
|
+
expiresIn: this.options.jwt.expiresIn || 300,
|
|
98
|
+
});
|
|
99
|
+
this.cachedToken = { token, expiresAt: Date.now() + ((this.options.jwt.expiresIn || 300) * 1000) };
|
|
100
|
+
return token;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Generate HMAC signature for request body */
|
|
104
|
+
signBody(body: any): string {
|
|
105
|
+
const hmacSecret = this.options.hmac?.secret || this.options.jwt.secret;
|
|
106
|
+
const algo = this.options.hmac?.algorithm || 'sha256';
|
|
107
|
+
const serialized = typeof body === 'string' ? body : JSON.stringify(body);
|
|
108
|
+
return crypto.createHmac(algo, hmacSecret).update(serialized).digest('hex');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 1C: Update HTTP Adapters to Use Service Identity
|
|
114
|
+
|
|
115
|
+
**File:** `lib/adapter/http-fetch-service.adapter.ts`
|
|
116
|
+
**File:** `lib/adapter/http-service.adapter.ts`
|
|
117
|
+
|
|
118
|
+
Changes:
|
|
119
|
+
- Inject `ServiceIdentityProvider` (optional, for backward compat)
|
|
120
|
+
- If provider exists: use `getToken()` for Authorization header + `signBody()` for `X-Body-HMAC` header
|
|
121
|
+
- If no provider: fall back to legacy `JwtProvider.sign(payload)` behavior
|
|
122
|
+
- Remove the payload-as-JWT signing when ServiceIdentityProvider is present
|
|
123
|
+
|
|
124
|
+
### 1D: Update Strategy/Validation (Server Side)
|
|
125
|
+
|
|
126
|
+
**File:** `lib/strategy/micro-service-jwt-strategy.provider.ts`
|
|
127
|
+
|
|
128
|
+
Changes:
|
|
129
|
+
- When token has `sub: 'service'` → validate as service identity token (check iss, aud, exp)
|
|
130
|
+
- Verify `X-Body-HMAC` header against request body
|
|
131
|
+
- When token does NOT have `sub: 'service'` → legacy mode (existing `isDeepStrictEqual` check)
|
|
132
|
+
- This ensures backward compatibility during migration
|
|
133
|
+
|
|
134
|
+
**File:** `lib/guard/jwt-ms-auth.guard.ts`
|
|
135
|
+
- Add `request.serviceIdentity = { serviceId: payload.iss }` to context for downstream use
|
|
136
|
+
|
|
137
|
+
### 1E: Update MicroServiceModule Options
|
|
138
|
+
|
|
139
|
+
**File:** `lib/module/micro-service.module.ts`
|
|
140
|
+
|
|
141
|
+
Changes to `MicroServiceModuleOptions`:
|
|
142
|
+
- Add optional `serviceIdentity: ServiceIdentityOptions` field
|
|
143
|
+
- When provided: register `ServiceIdentityProvider` + new strategy validation
|
|
144
|
+
- When not provided: legacy behavior (backward compat)
|
|
145
|
+
|
|
146
|
+
**File:** `lib/module/micro-service-clients.module.ts`
|
|
147
|
+
- Pass `ServiceIdentityProvider` to adapter factory when available
|
|
148
|
+
|
|
149
|
+
### 1F: Constants & Tokens
|
|
150
|
+
|
|
151
|
+
**File:** `lib/constant/index.ts` (or new file)
|
|
152
|
+
- `SERVICE_IDENTITY_OPTIONS` injection token
|
|
153
|
+
- `X_BODY_HMAC_HEADER = 'x-body-hmac'`
|
|
154
|
+
- `SERVICE_IDENTITY_METADATA` reflector key
|
|
155
|
+
|
|
156
|
+
## Phase 2: Service Permissions (Authorization)
|
|
157
|
+
|
|
158
|
+
### 2A: Permission Decorator
|
|
159
|
+
|
|
160
|
+
**File:** `lib/decorator/micro-service-permission.decorator.ts` (NEW)
|
|
161
|
+
```typescript
|
|
162
|
+
export const MS_PERMISSION_KEY = 'ms_permissions';
|
|
163
|
+
export const MicroServicePermission = (...permissions: string[]) =>
|
|
164
|
+
SetMetadata(MS_PERMISSION_KEY, permissions);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### 2B: MicroServicePermissionGuard
|
|
168
|
+
|
|
169
|
+
**File:** `lib/guard/ms-permission.guard.ts` (NEW)
|
|
170
|
+
```typescript
|
|
171
|
+
@Injectable()
|
|
172
|
+
export class MicroServicePermissionGuard implements CanActivate {
|
|
173
|
+
constructor(private reflector: Reflector) {}
|
|
174
|
+
|
|
175
|
+
canActivate(context: ExecutionContext): boolean {
|
|
176
|
+
const required = this.reflector.getAllAndOverride<string[]>(MS_PERMISSION_KEY, [
|
|
177
|
+
context.getHandler(),
|
|
178
|
+
context.getClass(),
|
|
179
|
+
]);
|
|
180
|
+
if (!required || required.length === 0) return true;
|
|
181
|
+
|
|
182
|
+
const request = context.switchToHttp().getRequest();
|
|
183
|
+
const serviceIdentity = request.serviceIdentity;
|
|
184
|
+
if (!serviceIdentity?.permissions) return false;
|
|
185
|
+
|
|
186
|
+
return required.every(p => serviceIdentity.permissions.includes(p));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### 2C: Service Permission Registry
|
|
192
|
+
|
|
193
|
+
**File:** `lib/provider/service-permission-registry.ts` (NEW)
|
|
194
|
+
```typescript
|
|
195
|
+
/** Maps serviceId → allowed permissions */
|
|
196
|
+
export interface ServicePermissionMap {
|
|
197
|
+
[serviceId: string]: string[];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
@Injectable()
|
|
201
|
+
export class ServicePermissionRegistry {
|
|
202
|
+
constructor(@Inject(SERVICE_PERMISSION_MAP) private map: ServicePermissionMap) {}
|
|
203
|
+
|
|
204
|
+
getPermissions(serviceId: string): string[] {
|
|
205
|
+
return this.map[serviceId] || [];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
hasPermission(serviceId: string, permission: string): boolean {
|
|
209
|
+
return this.getPermissions(serviceId).includes(permission);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Usage in MicroServiceModule:
|
|
215
|
+
```typescript
|
|
216
|
+
MicroServiceModule.forRoot({
|
|
217
|
+
serviceIdentity: { serviceId: 'auth-api', jwt: { secret: '...' } },
|
|
218
|
+
servicePermissions: {
|
|
219
|
+
'notification-api': ['user:read', 'auth:validate'],
|
|
220
|
+
'billing-api': ['user:read', 'payment:process'],
|
|
221
|
+
},
|
|
222
|
+
})
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### 2D: Wire Permissions into Strategy
|
|
226
|
+
|
|
227
|
+
**File:** `lib/strategy/micro-service-jwt-strategy.provider.ts`
|
|
228
|
+
- After validating service identity JWT, look up `iss` in `ServicePermissionRegistry`
|
|
229
|
+
- Attach permissions to `request.serviceIdentity.permissions`
|
|
230
|
+
|
|
231
|
+
### 2E: Update Module Registration
|
|
232
|
+
|
|
233
|
+
**File:** `lib/module/micro-service.module.ts`
|
|
234
|
+
- Add `servicePermissions?: ServicePermissionMap` to options
|
|
235
|
+
- Register `ServicePermissionRegistry` when provided
|
|
236
|
+
- Register `MicroServicePermissionGuard` as global guard (after JwtMsAuthGuard)
|
|
237
|
+
|
|
238
|
+
### 2F: Export New Public API
|
|
239
|
+
|
|
240
|
+
**File:** `lib/index.ts` (or relevant barrel export)
|
|
241
|
+
- Export: `ServiceIdentityOptions`, `ServiceIdentityPayload`, `ServiceIdentityProvider`
|
|
242
|
+
- Export: `MicroServicePermission`, `MicroServicePermissionGuard`, `ServicePermissionRegistry`
|
|
243
|
+
- Export: `X_BODY_HMAC_HEADER` constant
|
|
244
|
+
|
|
245
|
+
## Test Strategy
|
|
246
|
+
- Mode: two-session-tdd
|
|
247
|
+
- TDD targets: ServiceIdentityProvider, HMAC signing/verification, strategy validation (service identity mode), MicroServicePermissionGuard, ServicePermissionRegistry, backward compatibility with legacy JWT-payload mode
|
|
248
|
+
- Session 1 scope: test files only in `test/` directory
|
|
249
|
+
- Session 2 scope: implementation files only in `lib/` directory
|
|
250
|
+
|
|
251
|
+
## Commits
|
|
252
|
+
- Phase 1: `feat(nestjs-microservices): add service identity JWT + HMAC body signing`
|
|
253
|
+
- Phase 2: `feat(nestjs-microservices): add service-to-service permission authorization`
|