Skip to content

Commit

Permalink
replace ErdnestConfigService with MxnestConfigService (#237)
Browse files Browse the repository at this point in the history
* replace ErdnestConfigService with MxnestConfigService

* make cache service optional for native auth guard

* throw error if is not native auth error

* throw error if is not native auth error

* remove empty lines

* remove unused import

* increment version

* updated lerna version

* updated depdendencies

---------

Co-authored-by: tanghel <[email protected]>
  • Loading branch information
andreigiura and tanghel authored Oct 17, 2024
1 parent 93c9450 commit b89ff93
Show file tree
Hide file tree
Showing 21 changed files with 71 additions and 72 deletions.
2 changes: 1 addition & 1 deletion lerna.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "node_modules/lerna/schemas/lerna-schema.json",
"useWorkspaces": true,
"version": "3.7.8",
"version": "4.0.0",
"packages": [
"packages/*"
],
Expand Down
24 changes: 12 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions packages/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ It also provides some [NestJS Decorators](https://docs.nestjs.com/custom-decorat
## Configuration

The authentication guards need 2 parameters on instantiation.
The fist parameter needs to be an instance of a class implementing the `ErdnestConfigService` interface.
The fist parameter needs to be an instance of a class implementing the `MxnestConfigService` interface.
The second one, needs to be an instance of a [Caching service](https://www.npmjs.com/package/@multiversx/sdk-nestjs-cache)


```typescript
import { Injectable } from "@nestjs/common";
import { ApiConfigService } from "./api.config.service";
import { ErdnestConfigService } from "@multiversx/sdk-nestjs-common";
import { MxnestConfigService } from "@multiversx/sdk-nestjs-common";

@Injectable()
export class SdkNestjsConfigServiceImpl implements ErdnestConfigService {
export class SdkNestjsConfigServiceImpl implements MxnestConfigService {
constructor(
private readonly apiConfigService: ApiConfigService,
) { }
Expand Down Expand Up @@ -80,12 +80,12 @@ You can register it as a provider, and the DI mechanism of NestJS will handle in

```typescript
import { Module } from '@nestjs/common';
import { ERDNEST_CONFIG_SERVICE } from "@multiversx/sdk-nestjs-common";
import { MXNEST_CONFIG_SERVICE } from "@multiversx/sdk-nestjs-common";

@Module({
providers: [
{
provide: ERDNEST_CONFIG_SERVICE,
provide: MXNEST_CONFIG_SERVICE,
useClass: SdkNestjsConfigServiceImpl,
},
],
Expand Down Expand Up @@ -136,7 +136,7 @@ In this case, the guard is method-scoped. Only `createProject` benefits from the

### Native Auth Admin Guard

`NativeAuthAdminGuard` allows only specific addresses to be authenticated. The addresses are defined in the [config](#configuration) file and are passed to the guard via the ErdnestConfigService.
`NativeAuthAdminGuard` allows only specific addresses to be authenticated. The addresses are defined in the [config](#configuration) file and are passed to the guard via the MxnestConfigService.

*This guard cannot be used by itself. It always has to be paired with a `NativeAuthGuard`*

Expand Down Expand Up @@ -166,7 +166,7 @@ export class UsersController {

### JWT Admin Guard

`JwtAdminGuard` relies on the same mechanism, only specific addresses can be authenticated. The addresses are defined in the [config](#configuration) file and are passed to the guard via the ErdnestConfigService.
`JwtAdminGuard` relies on the same mechanism, only specific addresses can be authenticated. The addresses are defined in the [config](#configuration) file and are passed to the guard via the MxnestConfigService.

*There is one caveat: when creating the JWT, the client must include an `address` field in the payload, before signing it.*

Expand Down
8 changes: 4 additions & 4 deletions packages/auth/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@multiversx/sdk-nestjs-auth",
"version": "3.7.8",
"version": "4.0.0",
"description": "Multiversx SDK Nestjs auth package",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down Expand Up @@ -38,9 +38,9 @@
"jsonwebtoken": "^9.0.0"
},
"peerDependencies": {
"@multiversx/sdk-nestjs-cache": "^3.7.2",
"@multiversx/sdk-nestjs-common": "^3.7.2",
"@multiversx/sdk-nestjs-monitoring": "^3.7.2",
"@multiversx/sdk-nestjs-cache": "^4.0.0",
"@multiversx/sdk-nestjs-common": "^4.0.0",
"@multiversx/sdk-nestjs-monitoring": "^4.0.0",
"@nestjs/common": "^10.x"
},
"publishConfig": {
Expand Down
8 changes: 4 additions & 4 deletions packages/auth/src/jwt.admin.guard.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Injectable, CanActivate, ExecutionContext, Inject } from '@nestjs/common';
import { ExecutionContextUtils, ErdnestConfigService, ERDNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';
import { ExecutionContextUtils, MxnestConfigService, MXNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';

@Injectable()
export class JwtAdminGuard implements CanActivate {
constructor(
@Inject(ERDNEST_CONFIG_SERVICE)
private readonly erdnestConfigService: ErdnestConfigService
@Inject(MXNEST_CONFIG_SERVICE)
private readonly mxnestConfigService: MxnestConfigService
) { }

// eslint-disable-next-line require-await
Expand All @@ -14,7 +14,7 @@ export class JwtAdminGuard implements CanActivate {
): Promise<boolean> {


const admins = this.erdnestConfigService.getSecurityAdmins();
const admins = this.mxnestConfigService.getSecurityAdmins();
if (!admins) {
return false;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/auth/src/jwt.authenticate.guard.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Injectable, CanActivate, ExecutionContext, Inject } from '@nestjs/common';
import { verify } from 'jsonwebtoken';
import { PerformanceProfiler } from '@multiversx/sdk-nestjs-monitoring';
import { ErdnestConfigService, ERDNEST_CONFIG_SERVICE, DecoratorUtils, ExecutionContextUtils } from '@multiversx/sdk-nestjs-common';
import { MxnestConfigService, MXNEST_CONFIG_SERVICE, DecoratorUtils, ExecutionContextUtils } from '@multiversx/sdk-nestjs-common';
import { NoAuthOptions } from './decorators/no.auth';

@Injectable()
export class JwtAuthenticateGuard implements CanActivate {
constructor(
@Inject(ERDNEST_CONFIG_SERVICE)
private readonly erdnestConfigService: ErdnestConfigService
@Inject(MXNEST_CONFIG_SERVICE)
private readonly mxnestConfigService: MxnestConfigService
) { }

async canActivate(
Expand All @@ -31,7 +31,7 @@ export class JwtAuthenticateGuard implements CanActivate {
const profiler = new PerformanceProfiler();

try {
const jwtSecret = this.erdnestConfigService.getJwtSecret();
const jwtSecret = this.mxnestConfigService.getJwtSecret();

request.jwt = await new Promise((resolve, reject) => {
verify(jwt, jwtSecret, (err: any, decoded: any) => {
Expand Down
8 changes: 4 additions & 4 deletions packages/auth/src/jwt.or.native.auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { Injectable, CanActivate, ExecutionContext, Inject, Optional } from '@nestjs/common';
import { CacheService } from '@multiversx/sdk-nestjs-cache';
import { ErdnestConfigService, ERDNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';
import { MxnestConfigService, MXNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';
import { JwtAuthenticateGuard } from './jwt.authenticate.guard';
import { NativeAuthGuard } from './native.auth.guard';

@Injectable()
export class JwtOrNativeAuthGuard implements CanActivate {
constructor(
@Inject(ERDNEST_CONFIG_SERVICE) private readonly erdnestConfigService: ErdnestConfigService,
@Inject(MXNEST_CONFIG_SERVICE) private readonly mxnestConfigService: MxnestConfigService,
@Optional() private readonly cacheService?: CacheService,
) { }

async canActivate(context: ExecutionContext): Promise<boolean> {
const jwtGuard = new JwtAuthenticateGuard(this.erdnestConfigService);
const nativeAuthGuard = new NativeAuthGuard(this.erdnestConfigService, this.cacheService);
const jwtGuard = new JwtAuthenticateGuard(this.mxnestConfigService);
const nativeAuthGuard = new NativeAuthGuard(this.mxnestConfigService, this.cacheService);

try {
const result = await jwtGuard.canActivate(context);
Expand Down
12 changes: 6 additions & 6 deletions packages/auth/src/native.auth.admin.guard.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import { Injectable, CanActivate, ExecutionContext, Inject } from '@nestjs/common';
import { ExecutionContextUtils, ErdnestConfigService, ERDNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';
import { ExecutionContextUtils, MxnestConfigService, MXNEST_CONFIG_SERVICE } from '@multiversx/sdk-nestjs-common';

/**
* This Guard allows only specific addresses to be authenticated.
*
* The addresses are defined in the config file and are passed to the guard via the ErdnestConfigService.
* The addresses are defined in the config file and are passed to the guard via the MxnestConfigService.
*
* @return {boolean} `canActivate` returns true if the address is in the list of admins and uses a valid Native-Auth token.
*
* @param {CachingService} CachingService - Dependency of `NativeAuthGuard`
* @param {ErdnestConfigService} ErdnestConfigService - Dependency of `NativeAuthGuard`. Also used to get the list of admins (`getSecurityAdmins`).
* @param {MxnestConfigService} MxnestConfigService - Dependency of `NativeAuthGuard`. Also used to get the list of admins (`getSecurityAdmins`).
*/
@Injectable()
export class NativeAuthAdminGuard implements CanActivate {
constructor(
@Inject(ERDNEST_CONFIG_SERVICE)
private readonly erdnestConfigService: ErdnestConfigService
@Inject(MXNEST_CONFIG_SERVICE)
private readonly mxnestConfigService: MxnestConfigService
) { }

canActivate(context: ExecutionContext): boolean {
const admins = this.erdnestConfigService.getSecurityAdmins();
const admins = this.mxnestConfigService.getSecurityAdmins();
if (!admins) {
return false;
}
Expand Down
21 changes: 10 additions & 11 deletions packages/auth/src/native.auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable, CanActivate, ExecutionContext, Optional, Inject, Logger } from '@nestjs/common';
import { CacheService } from '@multiversx/sdk-nestjs-cache';
import { NativeAuthError, NativeAuthServer } from '@multiversx/sdk-native-auth-server';
import { DecoratorUtils, ErdnestConfigService, ERDNEST_CONFIG_SERVICE, UrlUtils, ExecutionContextUtils } from '@multiversx/sdk-nestjs-common';
import { DecoratorUtils, MxnestConfigService, MXNEST_CONFIG_SERVICE, UrlUtils, ExecutionContextUtils } from '@multiversx/sdk-nestjs-common';
import { PerformanceProfiler } from '@multiversx/sdk-nestjs-monitoring';
import { NativeAuthInvalidOriginError } from './errors/native.auth.invalid.origin.error';
import { NoAuthOptions } from './decorators';
Expand All @@ -17,13 +17,13 @@ export class NativeAuthGuard implements CanActivate {
private readonly authServer: NativeAuthServer;

constructor(
@Inject(ERDNEST_CONFIG_SERVICE) erdnestConfigService: ErdnestConfigService,
@Inject(MXNEST_CONFIG_SERVICE) mxnestConfigService: MxnestConfigService,
@Optional() cacheService?: CacheService,
) {
const nativeAuthServerConfig: NativeAuthServerConfig = {
apiUrl: erdnestConfigService.getApiUrl(),
maxExpirySeconds: erdnestConfigService.getNativeAuthMaxExpirySeconds(),
acceptedOrigins: erdnestConfigService.getNativeAuthAcceptedOrigins(),
apiUrl: mxnestConfigService.getApiUrl(),
maxExpirySeconds: mxnestConfigService.getNativeAuthMaxExpirySeconds(),
acceptedOrigins: mxnestConfigService.getNativeAuthAcceptedOrigins(),
cache: {
getValue: async function <T>(key: string): Promise<T | undefined> {
if (key === 'block:timestamp:latest') {
Expand All @@ -35,20 +35,19 @@ export class NativeAuthGuard implements CanActivate {
if (cacheService) {
return await cacheService.get<T>(key);
}

throw new Error('CacheService is not available in the context');
return undefined;
},
setValue: async function <T>(key: string, value: T, ttl: number): Promise<void> {
if (cacheService) {
return await cacheService.set<T>(key, value, ttl);
}

throw new Error('CacheService is not available in the context');
return undefined;
},
},
};

const acceptedOrigins = erdnestConfigService.getNativeAuthAcceptedOrigins();
const acceptedOrigins = mxnestConfigService.getNativeAuthAcceptedOrigins();
const shouldAllowAllOrigins = acceptedOrigins && acceptedOrigins.length === 1 && acceptedOrigins[0] === '*';
if (shouldAllowAllOrigins) {
nativeAuthServerConfig.isOriginAccepted = () => true; // allow all origins
Expand Down Expand Up @@ -130,9 +129,9 @@ export class NativeAuthGuard implements CanActivate {
request.res.set('X-Native-Auth-Error-Message', message);
request.res.set('X-Native-Auth-Duration', profiler.duration);
}
return false;
}

return false;
throw error;
}
}
}
8 changes: 4 additions & 4 deletions packages/cache/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@multiversx/sdk-nestjs-cache",
"version": "3.7.8",
"version": "4.0.0",
"description": "Multiversx SDK Nestjs cache package",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down Expand Up @@ -40,9 +40,9 @@
"uuid": "^8.3.2"
},
"peerDependencies": {
"@multiversx/sdk-nestjs-common": "^3.7.2",
"@multiversx/sdk-nestjs-monitoring": "^3.7.2",
"@multiversx/sdk-nestjs-redis": "^3.7.2",
"@multiversx/sdk-nestjs-common": "^4.0.0",
"@multiversx/sdk-nestjs-monitoring": "^4.0.0",
"@multiversx/sdk-nestjs-redis": "^4.0.0",
"@nestjs/common": "^10.x",
"@nestjs/core": "^10.x"
},
Expand Down
4 changes: 2 additions & 2 deletions packages/common/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@multiversx/sdk-nestjs-common",
"version": "3.7.8",
"version": "4.0.0",
"description": "Multiversx SDK Nestjs common package",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down Expand Up @@ -40,7 +40,7 @@
"winston": "^3.7.2"
},
"peerDependencies": {
"@multiversx/sdk-nestjs-monitoring": "^3.7.2",
"@multiversx/sdk-nestjs-monitoring": "^4.0.0",
"@nestjs/common": "^10.x",
"@nestjs/config": "^3.x",
"@nestjs/core": "^10.x",
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/common/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from './base.config.service';
export * from './base.config.utils';
export * from './erdnest.config.service';
export * from './mxnest.config.service';
export * from './configuration.loader.error';
export * from './configuration.loader.schema.expander';
export * from './configuration.loader.schema.type';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export interface ErdnestConfigService {
export interface MxnestConfigService {
getSecurityAdmins(): string[];

getJwtSecret(): string;
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export * from './utils/file.utils';
export * from './utils/locker';
export * from './utils/logger.initializer';
export * from './utils/match.utils';
export * from './utils/erdnest.constants';
export * from './utils/mxnest.constants';
export * from './utils/number.utils';
export * from './utils/url.utils';
export * from './utils/origin.logger';
Expand Down
1 change: 0 additions & 1 deletion packages/common/src/utils/erdnest.constants.ts

This file was deleted.

1 change: 1 addition & 0 deletions packages/common/src/utils/mxnest.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const MXNEST_CONFIG_SERVICE = 'MxnestConfigService';
Loading

0 comments on commit b89ff93

Please sign in to comment.