8000 refactor: create common package in libs by sairanjit · Pull Request #1167 · credebl/platform · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

refactor: create common package in libs #1167

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

Merged
merged 9 commits into from
Apr 4, 2025
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
8 changes: 3 additions & 5 deletions libs/aws/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
"main": "src/index",
"types": "src/index",
"version": "0.0.1",
"files": ["dist"],
"license": "Apache-2.0",
"publishConfig": {
"access": "public"
},
"files": [
"dist"
],
"scripts": {
"build": "pnpm run clean && pnpm run compile",
"clean": "rimraf ../../dist/libs/aws",
Expand Down
38 changes: 38 additions & 0 deletions libs/common/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@credebl/common",
"main": "src/index",
"types": "src/index",
"version": "0.0.1",
"files": [
"dist"
],
"scripts": {
"build": "pnpm run clean && pnpm run compile",
"clean": "rimraf ../../dist/libs/common",
"compile": "tsc -p tsconfig.build.json",
"test": "jest"
},
"dependencies": {
"@nestjs/axios": "^3.0.0",
"@nestjs/common": "^10.2.7",
"@nestjs/core": "^10.1.3",
"@nestjs/testing": "^10.1.3",
"@nestjs/microservices": "^10.1.3",
"@nestjs/swagger": "^7.1.6",
"@prisma/client": "^5.1.1",
"@sendgrid/mail": "^7.7.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"crypto-js": "^4.1.1",
"dotenv": "^16.0.3",
"nats": "^2.15.1",
"rxjs": "^7.8.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/crypto-js": "^4.1.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^4.4.0",
"typescript": "^5.1.6"
}
}
46 changes: 23 additions & 23 deletions libs/common/src/NATSClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import { ClientProxy, NatsRecordBuilder } from '@nestjs/microservices';
import { map } from 'rxjs/operators';
import * as nats from 'nats';
import { firstValueFrom } from 'rxjs';
import ContextStorageService, { ContextStorageServiceKey } from '@credebl/context/contextStorageService.interface';
import ContextStorageService, { ContextStorageServiceKey } from '../../context/src/contextStorageService.interface';
import { v4 } from 'uuid';

@Injectable()
export class NATSClient {
private readonly logger: Logger;
constructor(@Inject(ContextStorageServiceKey)
private readonly contextStorageService: ContextStorageService
) {
constructor(
@Inject(ContextStorageServiceKey)
private readonly contextStorageService: ContextStorageService
) {
this.logger = new Logger('NATSClient');
}

Expand All @@ -22,7 +23,7 @@ export class NATSClient {
this.logger.log(`Inside NATSClient for sendNats()`);
const pattern = { cmd };
const headers = nats.headers(1, this.contextStorageService.getContextId());
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();

return serviceProxy
.send<string>(pattern, record)
Expand All @@ -34,29 +35,28 @@ export class NATSClient {
.toPromise();
}

sendNatsMessage(serviceProxy: ClientProxy, cmd: string, payload: any): Promise<any> {
const pattern = { cmd };
const headers = nats.headers(1, this.contextStorageService.getContextId());
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();

sendNatsMessage(serviceProxy: ClientProxy, cmd: string, payload: any): Promise<any> {
const pattern = { cmd };
const headers = nats.headers(1, this.contextStorageService.getContextId());
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();

const result = serviceProxy.send<string>(pattern, record);
const result = serviceProxy.send<string>(pattern, record);

return firstValueFrom(result);
}
return firstValueFrom(result);
}

send<T>(serviceProxy: ClientProxy, pattern: object, payload: any): Promise<T> {
let contextId = this.contextStorageService.getContextId();
send<T>(serviceProxy: ClientProxy, pattern: object, payload: any): Promise<T> {
let contextId = this.contextStorageService.getContextId();

if (!contextId) {
contextId = v4();
}
if (!contextId) {
contextId = v4();
}

const headers = nats.headers(1, contextId);
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
const headers = nats.headers(1, contextId);
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();

const result = serviceProxy.send<T>(pattern, record);
const result = serviceProxy.send<T>(pattern, record);

return firstValueFrom(result);
return firstValueFrom(result);
}
}
} 8000
66 changes: 35 additions & 31 deletions libs/common/src/cast.helper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { DidMethod, JSONSchemaType, ledgerLessDIDType, ProofType, schemaRequestType, TemplateIdentifier } from '@credebl/enum/enum';
import {
DidMethod,
JSONSchemaType,
ledgerLessDIDType,
ProofType,
schemaRequestType,
TemplateIdentifier
} from '../../enum/src/enum';
import { ISchemaFields } from './interfaces/schema.interface';
import { BadRequestException, PipeTransform } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
Expand Down Expand Up @@ -82,19 +89,22 @@ export function isSafeString(value: string): boolean {
}

export const IsNotSQLInjection =
(validationOptions?: ValidationOptions): PropertyDecorator => (object: object, propertyName: string) => {
(validationOptions?: ValidationOptions): PropertyDecorator =>
(object: object, propertyName: string) => {
registerDecorator({
name: 'isNotSQLInjection',
target: object.constructor,
propertyName,
options: validationOptions,
validator: {
validate(value) {

// Check if the value is a string
if ('string' === typeof value) {
// Regex to check for SQL injection keywords at the start
const startInjectionRegex = new RegExp(`^\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC|FROM|WHERE|AND|OR)\\b`, 'i');
const startInjectionRegex = new RegExp(
`^\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC|FROM|WHERE|AND|OR)\\b`,
'i'
);

// Check if the SQL injection pattern is present at the start
if (startInjectionRegex.test(value)) {
Expand All @@ -110,7 +120,7 @@ export const IsNotSQLInjection =
}
});
};

@ValidatorConstraint({ name: 'customText', async: false })
export class ImageBase64Validator implements ValidatorConstraintInterface {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -167,7 +177,7 @@ export class EmptyStringParamPipe implements PipeTransform {
private constructor(paramName: string) {
this.paramName = paramName;
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
transform(value: string) {
const trimmedValue = value.trim();
Expand All @@ -194,7 +204,6 @@ export class EmptyStringParamPipe implements PipeTransform {
// });
// };


export function validateSchemaPayload(schemaPayload: ISchemaFields, schemaType: string): void {
const errors: string[] = [];

Expand Down Expand Up @@ -314,21 +323,19 @@ export class AgentSpinupValidator {
public static validate(agentSpinupDto): void {
this.validateWalletName(agentSpinupDto.walletName);
}

}

export const validateEmail = (email: string): boolean => {
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailRegex.test(email);
};


// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
export const createOobJsonldIssuancePayload = (JsonldCredentialDetails: IJsonldCredential, prettyVc: IPrettyVc) => {
const {credentialData, orgDid, orgId, schemaLedgerId, schemaName, isReuseConnection} = JsonldCredentialDetails;
const credentialSubject = { };
const { credentialData, orgDid, orgId, schemaLedgerId, schemaName, isReuseConnection } = JsonldCredentialDetails;
const credentialSubject = {};

const proofType = (orgDid?.includes(DidMethod.POLYGON)) ? ProofType.POLYGON_PROOFTYPE : ProofType.NO_LEDGER_PROOFTYPE;
const proofType = orgDid?.includes(DidMethod.POLYGON) ? ProofType.POLYGON_PROOFTYPE : ProofType.NO_LEDGER_PROOFTYPE;

for (const key in credentialData) {
if (credentialData.hasOwnProperty(key) && TemplateIdentifier.EMAIL_COLUMN !== key) {
Expand All @@ -339,41 +346,39 @@ export const createOobJsonldIssuancePayload = (JsonldCredentialDetails: IJsonldC
return {
credentialOffer: [
{
'emailId': `${credentialData.email_identifier}`,
'credential': {
emailId: `${credentialData.email_identifier}`,
credential: {
'@context': ['https://www.w3.org/2018/credentials/v1', `${schemaLedgerId}`],
'type': [
'VerifiableCredential',
`${schemaName}`
],
'issuer': {
'id': `${orgDid}`
type: ['VerifiableCredential', `${schemaName}`],
issuer: {
id: `${orgDid}`
},
'issuanceDate': new Date().toISOString(),
issuanceDate: new Date().toISOString(),
credentialSubject,
prettyVc
},
'options': {
options: {
proofType,
'proofPurpose': 'assertionMethod'
proofPurpose: 'assertionMethod'
}
}
],
'comment': 'string',
'protocolVersion': 'v2',
'credentialType': 'jsonld',
comment: 'string',
protocolVersion: 'v2',
credentialType: 'jsonld',
orgId,
isReuseConnection
};
};


@ValidatorConstraint({ name: 'isHostPortOrDomain', async: false })
export class IsHostPortOrDomainConstraint implements ValidatorConstraintInterface {
validate(value: string): boolean {
// Regular expression for validating URL with host:port or domain
const hostPortRegex = /^(http:\/\/|https:\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)):(?:\d{1,5})(\/[^\s]*)?$/;
const domainRegex = /^(http:\/\/|https:\/\/)?(?:localhost|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})(:\d{1,5})?(\/[^\s]*)?$/;
const hostPortRegex =
/^(http:\/\/|https:\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)):(?:\d{1,5})(\/[^\s]*)?$/;
const domainRegex =
/^(http:\/\/|https:\/\/)?(?:localhost|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})(:\d{1,5})?(\/[^\s]*)?$/;

return hostPortRegex.test(value) || domainRegex.test(value);
}
Expand All @@ -396,10 +401,9 @@ export function IsHostPortOrDomain(validationOptions?: ValidationOptions) {
}

export function checkDidLedgerAndNetwork(schemaType: string, did: string): boolean {

const cleanSchemaType = schemaType.trim().toLowerCase();
const cleanDid = did.trim().toLowerCase();

if (JSONSchemaType.POLYGON_W3C === cleanSchemaType) {
return cleanDid.includes(JSONSchemaType.POLYGON_W3C);
}
Expand Down
5 changes: 2 additions & 3 deletions libs/common/src/common.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import * as CryptoJS from 'crypto-js';
import { BadRequestException, HttpException, HttpStatus, Injectable, Logger, NotFoundException } from '@nestjs/common';

import { CommonConstants } from './common.constant';
import { HttpService } from '@nestjs/axios/dist';
import { HttpService } from '@nestjs/axios';
import * as dotenv from 'dotenv';
import { ResponseMessages } from './response-messages';
import { IFormattedResponse, IOptionalParams } from './interfaces/interface';
import { OrgAgentType } from '@credebl/enum/enum';
import { OrgAgentType } from '../../enum/src/enum';
import { RpcException } from '@nestjs/microservices';
dotenv.config();

Expand Down Expand Up @@ -236,7 +236,6 @@ export class CommonService {
}

/**
*
* This function is used to handle errors in apps with RpcException
*/
handleError(error): Promise<void> {
Expand Down
56 changes: 28 additions & 28 deletions libs/common/src/interfaces/cloud-wallet.interface.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import { CloudWalletType } from '@credebl/enum/enum';
import { CloudWalletType } from '../../../enum/src/enum';
import { $Enums } from '@prisma/client';

export class ICreateCloudWallet {
label: string;
connectionImageUrl?: string;
email?: string;
userId?: string;
}
label: string;
connectionImageUrl?: string;
email?: string;
userId?: string;
}

export interface ICloudWalletDetails {
label: string;
tenantId: string;
email?: string;
type: CloudWalletType;
createdBy: string;
lastChangedBy: string;
userId: string;
agentEndpoint?: string;
agentApiKey?: string;
key?: string;
connectionImageUrl?: string;
}
label: string;
tenantId: string;
email?: string;
type: CloudWalletType;
createdBy: string;
lastChangedBy: string;
userId: string;
agentEndpoint?: string;
agentApiKey?: string;
key?: string;
connectionImageUrl?: string;
}

export interface IStoredWalletDetails {
email: string,
connectionImageUrl: string,
createDateTime: Date,
id: string,
tenantId: string,
label: string,
lastChangedDateTime: Date
email: string;
connectionImageUrl: string;
createDateTime: Date;
id: string;
tenantId: string;
label: string;
lastChangedDateTime: Date;
}

export interface IReceiveInvitation {
Expand Down Expand Up @@ -96,8 +96,8 @@ export interface IStoreWalletInfo {
agentEndpoint: string;
type: CloudWalletType;
userId: string;
createdBy: string;
lastChangedBy: string
createdBy: string;
lastChangedBy: string;
}

export interface IGetStoredWalletInfo {
Expand Down Expand Up @@ -328,5 +328,5 @@ export interface IBasicMessageDetails {
userId?: string;
email?: string;
content: string;
connectionId: string
connectionId: string;
}
Loading
0