@nathapp/nestjs-microservices 1.0.0-rc.7 → 1.0.0-rc.8

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.
@@ -6,4 +6,5 @@ export declare class HttpServiceAdapter implements MicroServiceAdapter {
6
6
  private readonly jwtProvider;
7
7
  constructor(options: HttpOption);
8
8
  execute(request: MicroServiceRequest): Promise<any>;
9
+ private isValidHttpUrl;
9
10
  }
@@ -13,6 +13,9 @@ class HttpServiceAdapter {
13
13
  if (jwtOptions) {
14
14
  this.jwtProvider = new auth_1.JwtProvider(jwtOptions);
15
15
  }
16
+ if (!this.isValidHttpUrl(url)) {
17
+ throw Error(`Invalid Url: ${url}`);
18
+ }
16
19
  this.axiosClient = axios_1.default.create({
17
20
  baseURL: url,
18
21
  timeout: requestTimeout,
@@ -20,6 +23,7 @@ class HttpServiceAdapter {
20
23
  }
21
24
  async execute(request) {
22
25
  const { payload, overrides, method } = request;
26
+ const { url, requestTimeout } = this.options.options;
23
27
  let bearer = this.jwtProvider ? this.jwtProvider.sign(payload || {}) : null;
24
28
  let headers = {};
25
29
  if (overrides && overrides.headers) {
@@ -29,28 +33,44 @@ class HttpServiceAdapter {
29
33
  headers["Authorization"] = `Bearer ${bearer}`;
30
34
  }
31
35
  try {
32
- const response = await this.axiosClient.post(method, payload);
33
- const { url, requestTimeout } = this.options.options;
36
+ const response = await this.axiosClient.post(method, payload, { headers });
34
37
  if (!response) {
35
- this.logger.error(`Connection Error - url: ${url}},method ${method}, timeout: ${requestTimeout}`);
38
+ this.logger.error(`Connection Error - url: ${url},method ${method}, timeout: ${requestTimeout}`);
36
39
  throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
37
40
  }
38
- if (200 != response.status) {
39
- this.logger.error(`Invalid response - status: ${response.status}, url: ${url}},method ${method}, timeout: ${requestTimeout}`);
41
+ if (200 != response.status && 201 != response.status) {
42
+ this.logger.error(`Invalid response - status: ${response.status}, url: ${url},method ${method}, timeout: ${requestTimeout}`);
40
43
  throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
41
44
  }
42
45
  const result = response.data;
43
46
  if ("0" != result.ret) {
44
- this.logger.error(`Failed response - ret: ${result.ret}, url: ${url}},method ${method}, timeout: ${requestTimeout}`);
47
+ this.logger.error(`Failed response - ret: ${result.ret}, url: ${url},method ${method}, timeout: ${requestTimeout}`);
45
48
  this.logger.error(`Failed response message: ${result.msg}`);
46
- throw new nestjs_common_1.AppException(result.ret);
49
+ if (result.ret) {
50
+ throw new nestjs_common_1.AppException(result.ret);
51
+ }
52
+ else {
53
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNKNOWN_ERROR);
54
+ }
47
55
  }
48
56
  return result.data;
49
57
  }
50
58
  catch (error) {
59
+ if (!(error instanceof nestjs_common_1.AppException)) {
60
+ this.logger.error(`Unknown Exception Error - url: ${url},method ${method}, timeout: ${requestTimeout}`);
61
+ }
51
62
  this.logger.error(error);
52
63
  throw error;
53
64
  }
54
65
  }
66
+ isValidHttpUrl(url) {
67
+ try {
68
+ const newUrl = new URL(url);
69
+ return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';
70
+ }
71
+ catch (err) {
72
+ return false;
73
+ }
74
+ }
55
75
  }
56
76
  exports.HttpServiceAdapter = HttpServiceAdapter;
@@ -1,2 +1,3 @@
1
1
  export declare const MICRO_SERVICES_KEY = "MicroServices";
2
2
  export declare const MsProtected: () => import("@nestjs/common").CustomDecorator<string>;
3
+ export declare const MsPayload: (...dataOrPipes: unknown[]) => ParameterDecorator;
@@ -1,7 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MsProtected = exports.MICRO_SERVICES_KEY = void 0;
3
+ exports.MsPayload = exports.MsProtected = exports.MICRO_SERVICES_KEY = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
+ const common_2 = require("@nestjs/common");
5
6
  exports.MICRO_SERVICES_KEY = "MicroServices";
6
7
  const MsProtected = () => (0, common_1.SetMetadata)(exports.MICRO_SERVICES_KEY, true);
7
8
  exports.MsProtected = MsProtected;
9
+ exports.MsPayload = (0, common_2.createParamDecorator)((data, ctx) => {
10
+ const request = ctx.switchToHttp().getRequest();
11
+ const user = request.user;
12
+ return user ? request.body : {};
13
+ });
@@ -0,0 +1,11 @@
1
+ import { ExecutionContext } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ declare const JwtMsAuthGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>;
4
+ export declare class JwtMsAuthGuard extends JwtMsAuthGuard_base {
5
+ private reflector;
6
+ private readonly logger;
7
+ constructor(reflector: Reflector);
8
+ canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>;
9
+ handleRequest(err: any, user: any, info: any): any;
10
+ }
11
+ export {};
@@ -0,0 +1,66 @@
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 JwtMsAuthGuard_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.JwtMsAuthGuard = void 0;
14
+ const nestjs_auth_1 = require("@nathapp/nestjs-auth");
15
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
16
+ const common_1 = require("@nestjs/common");
17
+ const core_1 = require("@nestjs/core");
18
+ const passport_1 = require("@nestjs/passport");
19
+ const decorator_1 = require("../decorator");
20
+ let JwtMsAuthGuard = JwtMsAuthGuard_1 = class JwtMsAuthGuard extends (0, passport_1.AuthGuard)(nestjs_auth_1.JWT_STRATEGY_NAME) {
21
+ constructor(reflector) {
22
+ super();
23
+ this.reflector = reflector;
24
+ this.logger = new common_1.Logger(JwtMsAuthGuard_1.name);
25
+ }
26
+ canActivate(context) {
27
+ const handler = context.getHandler();
28
+ const clazz = context.getClass();
29
+ const isPublic = this.reflector.getAllAndOverride(nestjs_auth_1.IS_PUBLIC_KEY, [
30
+ handler,
31
+ clazz,
32
+ ]);
33
+ const RefreshToken = this.reflector.getAllAndOverride(nestjs_auth_1.REFRESH_TOKEN, [
34
+ handler,
35
+ clazz,
36
+ ]);
37
+ const IsMicroServiceProtected = this.reflector.getAllAndOverride(decorator_1.MICRO_SERVICES_KEY, [
38
+ handler,
39
+ clazz,
40
+ ]);
41
+ if (isPublic) {
42
+ this.logger.verbose(`has isPublic decorator, class: ${clazz.name}, method: ${handler.name}`);
43
+ return true;
44
+ }
45
+ if (RefreshToken) {
46
+ this.logger.verbose(`has RefreshToken decorator, class: ${clazz.name}, method: ${handler.name}`);
47
+ return true;
48
+ }
49
+ if (IsMicroServiceProtected) {
50
+ this.logger.verbose(`has MsProtected decorator, class: ${clazz.name}, method: ${handler.name}`);
51
+ return true;
52
+ }
53
+ return super.canActivate(context);
54
+ }
55
+ handleRequest(err, user, info) {
56
+ if (err || !user) {
57
+ throw err || new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
58
+ }
59
+ return user;
60
+ }
61
+ };
62
+ JwtMsAuthGuard = JwtMsAuthGuard_1 = __decorate([
63
+ (0, common_1.Injectable)(),
64
+ __metadata("design:paramtypes", [core_1.Reflector])
65
+ ], JwtMsAuthGuard);
66
+ exports.JwtMsAuthGuard = JwtMsAuthGuard;
@@ -1,4 +1,5 @@
1
1
  import { HttpClientsModuleOptionsFactory, JwtClientsModuleOptionsFactory } from "./micro-service-clients-module-factory";
2
2
  import { ServiceClientProvider, ServiceClientProviderOptions, ClientsModuleOptions, ClientsModuleOptionsFactory, ServiceClientsProviderAsyncOptions, ClientsModuleAsyncOptions } from "./micro-service-clients-module.interface";
3
+ import { MicroServiceClientsModule } from "./micro-service-clients.module";
3
4
  import { DefaultMicroServiceModuleOptionsFactory, MicroServiceModule, MicroServiceModuleOptionsFactory } from "./micro-service.module";
4
- export { MicroServiceModule, ServiceClientProvider, ServiceClientProviderOptions, ClientsModuleOptions, ClientsModuleOptionsFactory, ServiceClientsProviderAsyncOptions, ClientsModuleAsyncOptions, JwtClientsModuleOptionsFactory, HttpClientsModuleOptionsFactory, MicroServiceModuleOptionsFactory, DefaultMicroServiceModuleOptionsFactory, };
5
+ export { MicroServiceModule, ServiceClientProvider, ServiceClientProviderOptions, ClientsModuleOptions, ClientsModuleOptionsFactory, ServiceClientsProviderAsyncOptions, ClientsModuleAsyncOptions, JwtClientsModuleOptionsFactory, HttpClientsModuleOptionsFactory, MicroServiceModuleOptionsFactory, DefaultMicroServiceModuleOptionsFactory, MicroServiceClientsModule, };
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultMicroServiceModuleOptionsFactory = exports.HttpClientsModuleOptionsFactory = exports.JwtClientsModuleOptionsFactory = exports.MicroServiceModule = void 0;
3
+ exports.MicroServiceClientsModule = exports.DefaultMicroServiceModuleOptionsFactory = exports.HttpClientsModuleOptionsFactory = exports.JwtClientsModuleOptionsFactory = exports.MicroServiceModule = void 0;
4
4
  const micro_service_clients_module_factory_1 = require("./micro-service-clients-module-factory");
5
5
  Object.defineProperty(exports, "HttpClientsModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_clients_module_factory_1.HttpClientsModuleOptionsFactory; } });
6
6
  Object.defineProperty(exports, "JwtClientsModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_clients_module_factory_1.JwtClientsModuleOptionsFactory; } });
7
+ const micro_service_clients_module_1 = require("./micro-service-clients.module");
8
+ Object.defineProperty(exports, "MicroServiceClientsModule", { enumerable: true, get: function () { return micro_service_clients_module_1.MicroServiceClientsModule; } });
7
9
  const micro_service_module_1 = require("./micro-service.module");
8
10
  Object.defineProperty(exports, "DefaultMicroServiceModuleOptionsFactory", { enumerable: true, get: function () { return micro_service_module_1.DefaultMicroServiceModuleOptionsFactory; } });
9
11
  Object.defineProperty(exports, "MicroServiceModule", { enumerable: true, get: function () { return micro_service_module_1.MicroServiceModule; } });
@@ -3,8 +3,8 @@ import { ClientsModuleOptionsFactory, ServiceClientProvider } from ".";
3
3
  import { HttpOption } from "../adapter";
4
4
  export declare abstract class JwtClientsModuleOptionsFactory implements ClientsModuleOptionsFactory {
5
5
  createClientOptions(): Promise<ServiceClientProvider> | ServiceClientProvider;
6
- abstract createJwtMicroServiceOptions(jwtOption: JwtOptions): Promise<ServiceClientProvider> | ServiceClientProvider;
7
- createJwtOptions(): JwtOptions;
6
+ protected abstract createJwtMicroServiceOptions(jwtOption: JwtOptions): Promise<ServiceClientProvider> | ServiceClientProvider;
7
+ protected createJwtOptions(): JwtOptions;
8
8
  }
9
9
  export declare class HttpClientsModuleOptionsFactory extends JwtClientsModuleOptionsFactory {
10
10
  private readonly options;
@@ -12,5 +12,5 @@ export declare class HttpClientsModuleOptionsFactory extends JwtClientsModuleOpt
12
12
  url: string;
13
13
  requestTimeout?: number;
14
14
  });
15
- createJwtMicroServiceOptions(jwtOption: JwtOptions): HttpOption | Promise<HttpOption>;
15
+ protected createJwtMicroServiceOptions(jwtOption: JwtOptions): HttpOption | Promise<HttpOption>;
16
16
  }
@@ -14,10 +14,6 @@ const defaultOptions = {};
14
14
  let MicroServiceClientsModule = MicroServiceClientsModule_1 = class MicroServiceClientsModule {
15
15
  static register(options) {
16
16
  options = this.sanitizeModuleOptions(options);
17
- const clientsOptionsProvider = {
18
- provide: options.name,
19
- useValue: options,
20
- };
21
17
  const clientsOptions = options.clients;
22
18
  const clients = (clientsOptions || []).map(item => ({
23
19
  provide: item.name,
@@ -26,16 +22,12 @@ let MicroServiceClientsModule = MicroServiceClientsModule_1 = class MicroService
26
22
  return {
27
23
  module: MicroServiceClientsModule_1,
28
24
  global: options.isGlobal,
29
- providers: [clientsOptionsProvider, ...clients],
30
- exports: [clientsOptionsProvider, ...clients],
25
+ providers: clients,
26
+ exports: clients,
31
27
  };
32
28
  }
33
29
  static registerAsync(options) {
34
30
  options = this.sanitizeModuleOptions(options);
35
- const clientsOptionsProvider = {
36
- provide: options.name,
37
- useValue: options,
38
- };
39
31
  const clientsOptions = options.clients;
40
32
  const providers = clientsOptions.reduce((accProviders, item) => accProviders
41
33
  .concat(this.createAsyncProviders(item))
@@ -47,8 +39,8 @@ let MicroServiceClientsModule = MicroServiceClientsModule_1 = class MicroService
47
39
  module: MicroServiceClientsModule_1,
48
40
  global: options.isGlobal,
49
41
  imports,
50
- providers: [clientsOptionsProvider, ...providers],
51
- exports: [clientsOptionsProvider, ...providers],
42
+ providers: providers,
43
+ exports: providers,
52
44
  };
53
45
  }
54
46
  static sanitizeModuleOptions(options) {
@@ -1,8 +1,8 @@
1
1
  import { DynamicModule, ModuleMetadata, Type } from '@nestjs/common';
2
2
  import { JwtOptions, StrategyProvider } from '@nathapp/nestjs-auth';
3
3
  export declare class MicroServiceModule {
4
- static Register(options: MicroServiceModuleOptions): DynamicModule;
5
- static RegisterAsync(options: MicroServiceModuleAsyncOptions): DynamicModule;
4
+ static register(options: MicroServiceModuleOptions): DynamicModule;
5
+ static registerAsync(options: MicroServiceModuleAsyncOptions): DynamicModule;
6
6
  private static sanitizeMSModuleOptions;
7
7
  private static createStrategyProvider;
8
8
  private static createAsyncOptionsProviders;
@@ -18,7 +18,7 @@ const defaultOptions = {
18
18
  logging: true,
19
19
  };
20
20
  let MicroServiceModule = MicroServiceModule_1 = class MicroServiceModule {
21
- static Register(options) {
21
+ static register(options) {
22
22
  options = this.sanitizeMSModuleOptions(options);
23
23
  const msOptions = {
24
24
  provide: constant_1.MICROSERVICE_OPTIONS,
@@ -32,7 +32,7 @@ let MicroServiceModule = MicroServiceModule_1 = class MicroServiceModule {
32
32
  exports: [constant_1.MICROSERVICE_OPTIONS, strategyProvider],
33
33
  };
34
34
  }
35
- static RegisterAsync(options) {
35
+ static registerAsync(options) {
36
36
  options = this.sanitizeMSModuleOptions(options);
37
37
  const asyncOptionsProviders = this.createAsyncOptionsProviders(options);
38
38
  const strategyProvider = this.createStrategyProvider(options);
@@ -4,6 +4,7 @@ exports.MicroServiceJwtStrategyProvider = exports.MicroServiceStrategyProvider =
4
4
  const nestjs_auth_1 = require("@nathapp/nestjs-auth");
5
5
  const nestjs_common_1 = require("@nathapp/nestjs-common");
6
6
  const common_1 = require("@nestjs/common");
7
+ const util_1 = require("util");
7
8
  class MicroServiceStrategyProvider extends nestjs_auth_1.JwtStrategyProvider {
8
9
  }
9
10
  exports.MicroServiceStrategyProvider = MicroServiceStrategyProvider;
@@ -17,7 +18,13 @@ class MicroServiceJwtStrategyProvider extends MicroServiceStrategyProvider {
17
18
  if (req.method == "GET") {
18
19
  throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.UNAUTHORIZED);
19
20
  }
21
+ const omitExpPayload = payload;
22
+ delete omitExpPayload.iat;
23
+ delete omitExpPayload.exp;
20
24
  this.logger.verbose(`MS JwtStrategyProvider: body: ${JSON.stringify(req.body)}, payload: ${JSON.stringify(payload)}`);
25
+ if (!(0, util_1.isDeepStrictEqual)(req.body, omitExpPayload)) {
26
+ throw new nestjs_common_1.AppException(nestjs_common_1.CommonExceptionCode.FORBIDDEN);
27
+ }
21
28
  return payload;
22
29
  }
23
30
  }
@@ -1,9 +1,9 @@
1
1
  import { Strategy } from "passport-jwt";
2
- import { MicroServiceJwtStrategyProvider } from "./microservice-jwt-strategy-provider";
2
+ import { MicroServiceStrategyProvider } from "./microservice-jwt-strategy-provider";
3
3
  declare const MicroServiceJwtStrategy_base: new (...args: any[]) => Strategy;
4
4
  export declare class MicroServiceJwtStrategy extends MicroServiceJwtStrategy_base {
5
5
  private readonly strategyProvider;
6
- constructor(strategyProvider: MicroServiceJwtStrategyProvider, name?: string);
6
+ constructor(strategyProvider: MicroServiceStrategyProvider);
7
7
  validate(arg1: any, arg2: any): Promise<any>;
8
8
  }
9
9
  export {};
@@ -16,7 +16,7 @@ const common_1 = require("@nestjs/common");
16
16
  const constant_1 = require("../constant");
17
17
  const microservice_jwt_strategy_provider_1 = require("./microservice-jwt-strategy-provider");
18
18
  let MicroServiceJwtStrategy = class MicroServiceJwtStrategy extends (0, passport_1.PassportStrategy)(passport_jwt_1.Strategy, constant_1.MICROSERVICE_STRATEGY_NAME) {
19
- constructor(strategyProvider, name) {
19
+ constructor(strategyProvider) {
20
20
  super({
21
21
  jwtFromRequest: strategyProvider.jwtFromRequestFunction,
22
22
  ignoreExpiration: strategyProvider.ignoreExpiration,
@@ -24,7 +24,6 @@ let MicroServiceJwtStrategy = class MicroServiceJwtStrategy extends (0, passport
24
24
  passReqToCallback: strategyProvider.passReqToCallback,
25
25
  });
26
26
  this.strategyProvider = strategyProvider;
27
- this.name = name || this.name;
28
27
  }
29
28
  async validate(arg1, arg2) {
30
29
  const req = this.strategyProvider.passReqToCallback ? arg1 : {};
@@ -34,6 +33,6 @@ let MicroServiceJwtStrategy = class MicroServiceJwtStrategy extends (0, passport
34
33
  };
35
34
  MicroServiceJwtStrategy = __decorate([
36
35
  (0, common_1.Injectable)(),
37
- __metadata("design:paramtypes", [microservice_jwt_strategy_provider_1.MicroServiceJwtStrategyProvider, String])
36
+ __metadata("design:paramtypes", [microservice_jwt_strategy_provider_1.MicroServiceStrategyProvider])
38
37
  ], MicroServiceJwtStrategy);
39
38
  exports.MicroServiceJwtStrategy = MicroServiceJwtStrategy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-microservices",
3
- "version": "1.0.0-rc.7",
3
+ "version": "1.0.0-rc.8",
4
4
  "description": "nestjs-microservices",
5
5
  "scripts": {
6
6
  "build": "rimraf dist && tsc -p tsconfig.json",