Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hsstud 145 #63

Merged
merged 7 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ import { AppAuthSecretService } from './services/app-auth-passord.service';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy, JwtStrategyApp } from './strategy/jwt.strategy';
import { AppAuthApiKeyService } from './services/app-auth-apikey.service';
import { WhitelistCorsMiddleware } from './middlewares/cors.middleware';
import { WhitelistAppCorsMiddleware } from './middlewares/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
MongooseModule.forFeature([{ name: App.name, schema: AppSchema }]),
HidWalletModule,
EdvModule,

JwtModule.register({}),
],
providers: [
Expand All @@ -41,16 +41,15 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
JwtStrategy,
JwtStrategyApp,
AppAuthApiKeyService,

],
controllers: [AppAuthController, AppOAuthController],

exports: [AppAuthService, AppRepository,AppAuthApiKeyService],
exports: [AppAuthService, AppRepository, AppAuthApiKeyService],
})
export class AppAuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(WhitelistCorsMiddleware)
.apply(WhitelistAppCorsMiddleware)
.forRoutes(AppAuthController, AppOAuthController);
consumer
.apply(TrimMiddleware)
Expand Down
3 changes: 3 additions & 0 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { PaginationDto } from 'src/utils/pagination.dto';
import { AppSecretHeader } from '../decorator/app-sercret.decorator';
import { TransformResponseInterceptor } from '../interceptors/transformResponse.interseptor';
import { JwtGuard } from '../guard/jwt.guard';
import { SanitizeUrl } from 'src/utils/customDecorator/urlSanitiser.decorator';

@UseFilters(AllExceptionsFilter)
@Controller('app')
Expand Down Expand Up @@ -124,6 +125,7 @@ export class AppAuthController {
}

@Post()
@SanitizeUrl()
@UseInterceptors(
MongooseClassSerializerInterceptor(createAppResponse, {
excludePrefixes: ['apiKeyPrefix', '_', '__'],
Expand Down Expand Up @@ -153,6 +155,7 @@ export class AppAuthController {
}),
)
@Put(':appId')
@SanitizeUrl()
@ApiResponse({
status: 200,
description: 'App updated',
Expand Down
24 changes: 20 additions & 4 deletions src/app-auth/middlewares/cors.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,36 @@ import {
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';

import { NextFunction, Request, Response } from 'express';
import { AppRepository } from 'src/app-auth/repositories/app.repository';
@Injectable()
export class WhitelistCorsMiddleware implements NestMiddleware {
export class WhitelistAppCorsMiddleware implements NestMiddleware {
constructor(private readonly appRepositiory: AppRepository) {}
async use(req: Request, res: Response, next: NextFunction) {
const whitelistedOrigins = process.env.WHITELISTED_CORS;
const apiSecretKey = req.headers['x-api-secret-key'] as string;
const origin = req.header('Origin');
if (!whitelistedOrigins.includes(origin)) {
if (whitelistedOrigins.includes(origin)) {
return next();
} else if (apiSecretKey !== '' && apiSecretKey != undefined) {
const apikeyIndex = apiSecretKey?.split('.')[0];
const appDetail = await this.appRepositiory.findOne({
apiKeyPrefix: apikeyIndex,
});
if (!appDetail) {
throw new UnauthorizedException(['access_denied']);
}
if (appDetail.whitelistedCors.includes('*')) {
return next();
}
if (!appDetail.whitelistedCors.includes(origin)) {
throw new UnauthorizedException(['Origin mismatch']);
}
return next();
} else {
throw new UnauthorizedException([
'This is CORS-enabled for a whitelisted domain.',
]);
}
next();
}
}
2 changes: 1 addition & 1 deletion src/app-auth/services/app-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class AppAuthService {
userId: string,
): Promise<createAppResponse> {
const { mnemonic, address } = await this.hidWalletService.generateWallet();
const appId=await this.appAuthApiKeyService.generateAppId()
const appId = await this.appAuthApiKeyService.generateAppId();
const edvId = 'hs:apiservice:edv:' + appId;
await this.edvService.init(edvId);
const document: EdvDocsDto = {
Expand Down
4 changes: 2 additions & 2 deletions src/credential/credential.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { HidWalletService } from 'src/hid-wallet/services/hid-wallet.service';
import { CredentialRepository } from './repository/credential.repository';
import { DidModule } from 'src/did/did.module';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
Expand All @@ -42,7 +42,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
})
export class CredentialModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WhitelistMiddleware).forRoutes(CredentialController);
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(CredentialController);
consumer
.apply(TrimMiddleware)
.exclude(
Expand Down
37 changes: 20 additions & 17 deletions src/did/controllers/did.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,31 +134,29 @@ export class DidController {
required: false,
})
create(@Body() createDidDto: CreateDidDto, @Req() req: any) {
const { options } = createDidDto;
const { options } = createDidDto;
const appDetail = req.user;
switch (options?.keyType) {
case IKeyType.EcdsaSecp256k1RecoveryMethod2020:{

case IKeyType.EcdsaSecp256k1RecoveryMethod2020: {
return this.didService.createByClientSpec(createDidDto, appDetail);

break;
}

case IKeyType.EcdsaSecp256k1VerificationKey2019:
{

throw new NotFoundException({
message: [`${options.keyType} is not supported`, `Feature coming soon`],
error: 'Not Supported',
status: 404,
});
}

case IKeyType.EcdsaSecp256k1VerificationKey2019: {
throw new NotFoundException({
message: [
`${options.keyType} is not supported`,
`Feature coming soon`,
],
error: 'Not Supported',
status: 404,
});
}

default:
return this.didService.create(createDidDto, appDetail);

}

}

@ApiCreatedResponse({
Expand All @@ -170,11 +168,16 @@ export class DidController {
description: 'Error occured at the time of creating did',
type: DidError,
})
@ApiHeader({
name: 'Authorization',
description: 'Bearer <access_token>',
required: false,
})
@Post('/register')
@UsePipes(ValidationPipe)
register(@Body() registerDidDto: RegisterDidDto,@Req() req:any){
register(@Body() registerDidDto: RegisterDidDto, @Req() req: any) {
const appDetail = req.user;
return this.didService.register(registerDidDto,appDetail)
return this.didService.register(registerDidDto, appDetail);
}

@UsePipes(ValidationPipe)
Expand Down
4 changes: 2 additions & 2 deletions src/did/did.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import { HidWalletModule } from 'src/hid-wallet/hid-wallet.module';
import { HidWalletService } from 'src/hid-wallet/services/hid-wallet.service';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
Expand Down Expand Up @@ -52,7 +52,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
})
export class DidModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WhitelistMiddleware).forRoutes(DidController);
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(DidController);
consumer
.apply(TrimMiddleware)
.exclude(
Expand Down
57 changes: 31 additions & 26 deletions src/did/dto/create-did.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,58 +15,63 @@ import {
import { RegistrationStatus } from '../schemas/did.schema';
import { DidDoc } from '../dto/update-did.dto';
import { IsDid } from 'src/utils/customDecorator/did.decorator';
import { Optional } from '@nestjs/common';

export enum IKeyType {
Ed25519VerificationKey2020 = 'Ed25519VerificationKey2020',
EcdsaSecp256k1VerificationKey2019 = 'EcdsaSecp256k1VerificationKey2019',
EcdsaSecp256k1RecoveryMethod2020 = 'EcdsaSecp256k1RecoveryMethod2020',
}


export class Options {
@ApiProperty({
description:
'Verification Method Keytype Ed25519VerificationKey2020 or EcdsaSecp256k1RecoveryMethod2020',
example: 'keyType:EcdsaSecp256k1RecoveryMethod2020',
name: 'keyType',
required: false,
})
@ValidateIf((o) => o.keyType !== undefined)
@IsEnum(IKeyType)
keyType: IKeyType;


@ApiProperty({
name:'chainId',
example:'0x1',
description:"Chain Id"
name: 'chainId',
example: '0x1',
description: 'Chain Id',
required: false,
})
@IsOptional()
@IsString()
chainId:string;
chainId?: string;

@ApiProperty({
name:'publicKey',
example:`z76tzt4XCb6FNqC3CPZvsxRfEDX5HHQc2VPux4DeZYndW`,
description:"Public Key extracted from keplr"
name: 'publicKey',
example: `z76tzt4XCb6FNqC3CPZvsxRfEDX5HHQc2VPux4DeZYndW`,
description: 'Public Key extracted from keplr',
required: false,
})

@IsOptional()
@Type(()=>Uint8Array || String)
publicKey?:Uint8Array | string;
@Type(() => Uint8Array || String)
publicKey?: Uint8Array | string;

@ApiProperty({
name:'address',
example:`0x01978e553Df0C54A63e2E063DFFe71c688d91C76`,
description:"Checksum address from web3 wallet"
name: 'walletAddress',
example: `0x01978e553Df0C54A63e2E063DFFe71c688d91C76`,
description: 'Checksum address from web3 wallet',
required: false,
})
@IsOptional()
@IsString()
address:string

walletAddress?: string;
@ApiProperty({
name: 'register',
example: true,
description: 'If set to true did will be registerd on blockchain',
required: false,
})
@IsOptional()
@IsBoolean()
register:boolean
register?: boolean;
}
export class CreateDidDto {
@ApiProperty({
Expand All @@ -91,13 +96,13 @@ export class CreateDidDto {
@ApiProperty({
name: 'options',
description: ' keyType used for verification',
required: false,
example: {
keyType: 'Ed25519VerificationKey2020',
chainId:'0x1',
publicKey:'z76tzt4XCb6FNqC3CPZvsxRfEDX5HHQc2VPux4DeZYndW',
address:'0x01978e553Df0C54A63e2E063DFFe71c688d91C76',
register:false

chainId: '0x1',
publicKey: 'z76tzt4XCb6FNqC3CPZvsxRfEDX5HHQc2VPux4DeZYndW',
walletAddress: '0x01978e553Df0C54A63e2E063DFFe71c688d91C76',
register: false,
},
})
@IsOptional()
Expand All @@ -106,7 +111,7 @@ export class CreateDidDto {
@ValidateNested({
each: true,
})
options: Options;
options?: Options;
}

export class TxnHash {
Expand Down Expand Up @@ -140,7 +145,7 @@ export class CreateDidResponse {
description: 'Transaction Has',
example: 'XYAIFLKFLKHSLFHKLAOHFOAIHG..........',
})
@IsString()
@IsString()
transactionHash: string;

@ApiProperty({
Expand Down
Loading