From 9e11f6443eaf4ecdbe1bb9917b84fb1a67ee3a6e Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Thu, 31 Jul 2025 12:17:29 +0530 Subject: [PATCH 01/15] feat: added logic for updated routes for agent Signed-off-by: Tipu_Singh --- .eslintrc.js | 4 +- .../AFJ/scripts/start_agent.sh | 9 +- .../src/agent-provisioning.service.ts | 31 ++- .../src/agent-service.service.ts | 220 ++++++++++-------- .../agent-service/agent-service.controller.ts | 2 +- apps/connection/src/connection.service.ts | 156 +++++-------- apps/issuance/src/issuance.service.ts | 103 +------- apps/verification/src/verification.service.ts | 164 +------------ .../src/client-registration.service.ts | 10 +- libs/common/src/common.constant.ts | 40 ++-- libs/common/src/common.utils.ts | 64 ++++- libs/common/src/nats.config.ts | 4 +- libs/common/src/response-messages/index.ts | 9 +- package.json | 0 14 files changed, 319 insertions(+), 497 deletions(-) mode change 100755 => 100644 package.json diff --git a/.eslintrc.js b/.eslintrc.js index f55a1efc2..253007eb5 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -14,7 +14,7 @@ module.exports = { ignorePatterns: ['.eslintrc.js'], rules: { 'prettier/prettier': 0, - 'no-console': 'error', + // 'no-console': 'error', //TODO: Uncomment this after testing // "@typescript-eslint/consistent-type-imports": "error", '@typescript-eslint/no-unused-vars': [ 'error' @@ -101,4 +101,4 @@ module.exports = { 'prefer-template': 'error', quotes: ['warn', 'single', { allowTemplateLiterals: true }] } -}; \ No newline at end of file +}; diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent.sh b/apps/agent-provisioning/AFJ/scripts/start_agent.sh index c18fd5c52..8a09b1247 100755 --- a/apps/agent-provisioning/AFJ/scripts/start_agent.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent.sh @@ -116,6 +116,10 @@ fi echo "-----$AGENT_ENDPOINT----" CONFIG_FILE="${PWD}/apps/agent-provisioning/AFJ/agent-config/${AGENCY}_${CONTAINER_NAME}.json" +echo "CONFIG_FILE = $CONFIG_FILE" +echo "AGENCY = $AGENCY" +echo "CONTAINER_NAME = $CONTAINER_NAME" + # Check if the file exists if [ -f "$CONFIG_FILE" ]; then # If it exists, remove the file @@ -154,7 +158,8 @@ cat <${CONFIG_FILE} "webhookUrl": "$WEBHOOK_HOST/wh/$AGENCY", "adminPort": $ADMIN_PORT, "tenancy": $TENANT, - "schemaFileServerURL": "$SCHEMA_FILE_SERVER_URL" + "schemaFileServerURL": "$SCHEMA_FILE_SERVER_URL", + "apiKey": "supersecret-that-too-16chars" } EOF @@ -238,7 +243,7 @@ if [ $? -eq 0 ]; then container_logs=$(docker logs $(docker ps -q --filter "name=${AGENCY}_${CONTAINER_NAME}")) # Extract the token from the logs using sed - token=$(echo "$container_logs" | sed -nE 's/.*API Token: ([^ ]+).*/\1/p') + token=$(echo "$container_logs" | sed -nE 's/.*** API Key: ([^ ]+).*/\1/p') # Print the extracted token echo "Token: $token" diff --git a/apps/agent-provisioning/src/agent-provisioning.service.ts b/apps/agent-provisioning/src/agent-provisioning.service.ts index 92d382358..796f5363b 100644 --- a/apps/agent-provisioning/src/agent-provisioning.service.ts +++ b/apps/agent-provisioning/src/agent-provisioning.service.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { RpcException } from '@nestjs/microservices'; import { IWalletProvision } from './interface/agent-provisioning.interfaces'; @@ -9,25 +10,39 @@ dotenv.config(); @Injectable() export class AgentProvisioningService { - - constructor( - private readonly logger: Logger - ) { } + constructor(private readonly logger: Logger) {} /** * Description: Wallet provision - * @param payload + * @param payload * @returns Get DID and verkey */ async walletProvision(payload: IWalletProvision): Promise { try { - - const { containerName, externalIp, orgId, seed, walletName, walletPassword, walletStorageHost, walletStoragePassword, walletStoragePort, walletStorageUser, webhookEndpoint, agentType, protocol, credoImage, tenant, indyLedger, inboundEndpoint } = payload; + console.log('walletProvision payload:', payload); + const { + containerName, + externalIp, + orgId, + seed, + walletName, + walletPassword, + walletStorageHost, + walletStoragePassword, + walletStoragePort, + walletStorageUser, + webhookEndpoint, + agentType, + protocol, + credoImage, + tenant, + indyLedger, + inboundEndpoint + } = payload; if (agentType === AgentType.AFJ) { // The wallet provision command is used to invoke a shell script const walletProvision = `${process.cwd() + process.env.AFJ_AGENT_SPIN_UP} ${orgId} "${externalIp}" "${walletName}" "${walletPassword}" ${seed} ${webhookEndpoint} ${walletStorageHost} ${walletStoragePort} ${walletStorageUser} ${walletStoragePassword} ${containerName} ${protocol} ${tenant} ${credoImage} "${indyLedger}" ${inboundEndpoint} ${process.env.SCHEMA_FILE_SERVER_URL} ${process.env.AGENT_HOST} ${process.env.AWS_ACCOUNT_ID} ${process.env.S3_BUCKET_ARN} ${process.env.CLUSTER_NAME} ${process.env.TESKDEFINITION_FAMILY}`; const spinUpResponse: object = new Promise(async (resolve) => { - await exec(walletProvision, async (err, stdout, stderr) => { this.logger.log(`shell script output: ${stdout}`); if (stderr) { diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 4a61dba6f..c26eac929 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -4,6 +4,7 @@ /* eslint-disable no-useless-catch */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable camelcase */ +/* eslint-disable no-console */ //TODO: remove after testing import { BadRequestException, ConflictException, @@ -78,6 +79,7 @@ import { from } from 'rxjs'; import { NATSClient } from '@credebl/common/NATSClient'; import { SignDataDto } from '../../api-gateway/src/agent-service/dto/agent-service.dto'; import { IVerificationMethod } from 'apps/organization/interfaces/organization.interface'; +import { getAgentUrl } from '@credebl/common/common.utils'; @Injectable() @WebSocketGateway() export class AgentServiceService { @@ -487,6 +489,7 @@ export class AgentServiceService { let ledgerIdData = []; try { + console.log('walletProvisionPayload::::::::::::::_agentSpinup', walletProvisionPayload); if (agentSpinupDto.method !== DidMethod.KEY && agentSpinupDto.method !== DidMethod.WEB) { const { network } = agentSpinupDto; const ledger = await ledgerName(network); @@ -524,9 +527,25 @@ export class AgentServiceService { socket.emit('did-publish-process-initiated', { clientId: agentSpinupDto.clientSocketId }); socket.emit('invitation-url-creation-started', { clientId: agentSpinupDto.clientSocketId }); } - - const encryptedToken = await this.tokenEncryption(agentDetails?.agentToken); - + const agentBaseWalletDetils = await this.commonService.httpPost( + `${process.env.API_GATEWAY_PROTOCOL}://${agentDetails.agentEndPoint}/agent/token`, + '', + { + headers: { + Accept: 'application/json', + Authorization: agentDetails?.agentToken + } + } + ); + console.log('agentBaseWalletToken::::::::::::::', agentBaseWalletDetils); + if (!agentBaseWalletDetils.token) { + throw new BadRequestException(ResponseMessages.agent.error.baseWalletToken, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); + } + const encryptedToken = await this.tokenEncryption(agentBaseWalletDetils.token); + console.log('agentDetails::::::::::::::', agentDetails); const agentPayload: IStoreOrgAgentDetails = { agentEndPoint, seed: agentSpinupDto.seed, @@ -543,6 +562,7 @@ export class AgentServiceService { did: agentSpinupDto.did, id: agentProcess?.id }; + console.log('agentPayload::::::::::::::', agentPayload); /** * Store organization agent details */ @@ -568,7 +588,7 @@ export class AgentServiceService { const getOrganization = await this.agentServiceRepository.getOrgDetails(orgData?.id); - await this._createConnectionInvitation(orgData?.id, user, getOrganization.name); + // await this._createConnectionInvitation(orgData?.id, user, getOrganization.name); if (agentSpinupDto.clientSocketId) { socket.emit('invitation-url-creation-success', { clientId: agentSpinupDto.clientSocketId }); } @@ -596,24 +616,27 @@ export class AgentServiceService { async _storeOrgAgentDetails(payload: IStoreOrgAgentDetails): Promise { try { - /** - * Get orgaization agent type and agent details - */ - const [agentDid, orgAgentTypeId] = await Promise.all([ - this._getAgentDid(payload), - this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.DEDICATED) - ]); - /** - * Get DID method by agent - */ - const getDidMethod = await this._getDidMethod(payload, agentDid); + // /** + // * Get orgaization agent type and agent details + // */ + // const [agentDid, orgAgentTypeId] = await Promise.all([ + // this._getAgentDid(payload), + // this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.DEDICATED) + // ]); + // /** + const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.DEDICATED); + console.log('orgAgentTypeId::::::::::::::', orgAgentTypeId); + // * Get DID method by agent + // */ + // const getDidMethod = await this._getDidMethod(payload, agentDid); /** * Organization storage data */ - const storeOrgAgentData = await this._buildStoreOrgAgentData(payload, getDidMethod, `${orgAgentTypeId}`); + const storeOrgAgentData = await this._buildStoreOrgAgentData(payload, `${orgAgentTypeId}`); /** * Store org agent details */ + console.log('storeOrgAgentData::::::::::::::', storeOrgAgentData); const storeAgentDid = await this.agentServiceRepository.storeOrgAgentDetails(storeOrgAgentData); return storeAgentDid; } catch (error) { @@ -622,39 +645,38 @@ export class AgentServiceService { } } - private async _getAgentDid(payload: IStoreOrgAgentDetails): Promise { - const { agentEndPoint, apiKey, ledgerId, seed, keyType, method, network, role, did } = payload; - const writeDid = 'write-did'; - const ledgerDetails = await this.agentServiceRepository.getGenesisUrl(ledgerId); - const agentDidWriteUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; - return this._retryAgentSpinup(agentDidWriteUrl, apiKey, writeDid, seed, keyType, method, network, role, did); - } - - private async _getDidMethod(payload: IStoreOrgAgentDetails, agentDid: object): Promise { - const { agentEndPoint, apiKey, seed, keyType, method, network, role } = payload; - const getDidDoc = 'get-did-doc'; - const getDidMethodUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_GET_DID}/${agentDid['did']}`; - return this._retryAgentSpinup( - getDidMethodUrl, - apiKey, - getDidDoc, - seed, - keyType, - method, - network, - role, - `${agentDid['did']}` - ); - } - - private _buildStoreOrgAgentData( - payload: IStoreOrgAgentDetails, - getDidMethod: object, - orgAgentTypeId: string - ): IStoreOrgAgentDetails { + // private async _getAgentDid(payload: IStoreOrgAgentDetails): Promise { + // const { agentEndPoint, apiKey, ledgerId, seed, keyType, method, network, role, did } = payload; + // const writeDid = 'write-did'; + // const ledgerDetails = await this.agentServiceRepository.getGenesisUrl(ledgerId); + // const agentDidWriteUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; + // console.log("agentDidWriteUrl::::::::::::::", agentDidWriteUrl); + // console.log("apiKey::::::::::::::", apiKey); + // return this._retryAgentSpinup(agentDidWriteUrl, apiKey, writeDid, seed, keyType, method, network, role, did); + // } + + // private async _getDidMethod(payload: IStoreOrgAgentDetails, agentDid: object): Promise { + // const { agentEndPoint, apiKey, seed, keyType, method, network, role } = payload; + // const getDidDoc = 'get-did-doc'; + // const getDidMethodUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_GET_DID}/${agentDid['did']}`; + // return this._retryAgentSpinup( + // getDidMethodUrl, + // apiKey, + // getDidDoc, + // seed, + // keyType, + // method, + // network, + // role, + // `${agentDid['did']}` + // ); + // } + + private _buildStoreOrgAgentData(payload: IStoreOrgAgentDetails, orgAgentTypeId: string): IStoreOrgAgentDetails { + console.log('payload::::::::::::::', payload); return { - did: getDidMethod['didDocument']?.id, - verkey: getDidMethod['didDocument']?.verificationMethod[0]?.publicKeyBase58, + did: 'NA', + verkey: 'NA', isDidPublic: true, agentSpinUpStatus: AgentSpinUpStatus.COMPLETED, walletName: payload.walletName, @@ -704,8 +726,10 @@ export class AgentServiceService { }; try { const getDcryptedToken = await this.commonService.decryptPassword(apiKey); + console.log('getDcryptedToken::::::::::::::', getDcryptedToken); return retry(async () => { if (agentApiState === 'write-did') { + console.log('Inside If::::::::::::', agentUrl); return this.commonService.httpPost( agentUrl, { seed, keyType, method, network, role, did }, @@ -777,7 +801,7 @@ export class AgentServiceService { const agentStatusResponse = { agentSpinupStatus: AgentSpinUpStatus.PROCESSED }; - + console.log('createTenant payload::::::::::::::', payload); const getOrgAgent = await this.agentServiceRepository.getAgentDetails(payload.orgId); if (AgentSpinUpStatus.COMPLETED === getOrgAgent?.agentSpinUpStatus) { @@ -824,6 +848,7 @@ export class AgentServiceService { } const ledgerList = (await this._getALlLedgerDetails()) as unknown as LedgerListResponse; + console.log('ledgerList::::::::::::::', ledgerList); const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); if (!isLedgerExist) { throw new BadRequestException(ResponseMessages.agent.error.invalidLedger, { @@ -832,18 +857,22 @@ export class AgentServiceService { }); } ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); + console.log('ledgerIdData::::::::::::::', ledgerIdData); const agentSpinUpStatus = AgentSpinUpStatus.PROCESSED; // Create and stored agent details agentProcess = await this.agentServiceRepository.createOrgAgent(agentSpinUpStatus, user?.id); + console.log('agentProcess::::::::::::::', agentProcess); // Get platform admin details const platformAdminSpinnedUp = await this.getPlatformAdminAndNotify(payload.clientSocketId); + console.log('platformAdminSpinnedUp::::::::::::::', platformAdminSpinnedUp); payload.endpoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; // Create tenant wallet and DID const tenantDetails = await this.createTenantAndNotify(payload, platformAdminSpinnedUp); + console.log('tenantDetails::::::::::::::', tenantDetails); if (!tenantDetails?.walletResponseDetails?.id || !tenantDetails?.DIDCreationOption?.did) { this.logger.error(`Error in getting wallet id and wallet did`); throw new NotFoundException(ResponseMessages.agent.error.notAbleToSpinUpAgent, { @@ -863,7 +892,10 @@ export class AgentServiceService { const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); // Get agent type details const agentTypeId = await this.agentServiceRepository.getAgentTypeId(AgentType.AFJ); - + this.logger.log( + 'tenantDetails.walletResponseDetails::::::::::::::', + tenantDetails.walletResponseDetails['token'] + ); const storeOrgAgentData: IStoreOrgAgentDetails = { did: tenantDetails.DIDCreationOption.did, isDidPublic: true, @@ -876,11 +908,13 @@ export class AgentServiceService { tenantId: tenantDetails.walletResponseDetails['id'], walletName: payload.label, ledgerId: ledgerIdData.map((item) => item.id), - id: agentProcess?.id + id: agentProcess?.id, + apiKey: await this.commonService.dataEncryption(tenantDetails.walletResponseDetails['token']) }; - + console.log('storeOrgAgentData::::::::::::::', storeOrgAgentData); // Get organization data const getOrganization = await this.agentServiceRepository.getOrgDetails(payload.orgId); + console.log('getOrganization::::::::::::::', getOrganization); this.notifyClientSocket('agent-spinup-process-completed', payload.clientSocketId); @@ -1150,21 +1184,23 @@ export class AgentServiceService { delete WalletSetupPayload.clientSocketId; delete WalletSetupPayload.orgId; delete WalletSetupPayload.ledgerId; + console.log('platformAdminSpinnedUp.org_agents[0]::::::::::::::', platformAdminSpinnedUp.org_agents[0]); const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); + console.log('getDcryptedToken::::::::::::::', getDcryptedToken); const walletResponseDetails = await this._createTenantWallet( walletLabel, platformAdminSpinnedUp.org_agents[0].agentEndPoint, getDcryptedToken ); - if (!walletResponseDetails && !walletResponseDetails.id) { + console.log('walletResponseDetails::::::::::::::', walletResponseDetails); + if (!walletResponseDetails && !walletResponseDetails.id && !walletResponseDetails.token) { throw new InternalServerErrorException('Error while creating the wallet'); } const didCreateOption = { didPayload: WalletSetupPayload, agentEndpoint: platformAdminSpinnedUp.org_agents[0].agentEndPoint, - apiKey: getDcryptedToken, - tenantId: walletResponseDetails.id + apiKey: walletResponseDetails.token }; const DIDCreationOption = await this._createDID(didCreateOption); if (!DIDCreationOption) { @@ -1203,10 +1239,10 @@ export class AgentServiceService { * @returns Get tanant status */ private async _createDID(didCreateOption): Promise { - const { didPayload, agentEndpoint, apiKey, tenantId } = didCreateOption; + const { didPayload, agentEndpoint, apiKey } = didCreateOption; // Invoke an API request from the agent to create multi-tenant agent const didDetails = await this.commonService.httpPost( - `${agentEndpoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${tenantId}`, + `${agentEndpoint}${CommonConstants.URL_AGENT_WRITE_DID}`, didPayload, { headers: { authorization: apiKey } } ); @@ -1584,14 +1620,7 @@ export class AgentServiceService { description: ResponseMessages.errorMessages.notFound }); } - const orgAgentType = await this.agentServiceRepository.getOrgAgentType(orgAgentDetails?.orgAgentTypeId); - - const url = this.getAgentUrl( - 'sign-data-from-agent', - orgAgentType.agent, - orgAgentDetails.agentEndPoint, - orgAgentDetails.tenantId - ); + const url = getAgentUrl(orgAgentDetails.agentEndPoint, CommonConstants.SIGN_DATA_FROM_AGENT); const { dataTypeToSign, credentialPayload, rawPayload, storeCredential } = data; @@ -1651,14 +1680,7 @@ export class AgentServiceService { description: ResponseMessages.errorMessages.notFound }); } - const orgAgentType = await this.agentServiceRepository.getOrgAgentType(orgAgentDetails?.orgAgentTypeId); - - const url = this.getAgentUrl( - 'verify-signed-data-from-agent', - orgAgentType.agent, - orgAgentDetails.agentEndPoint, - orgAgentDetails.tenantId - ); + const url = getAgentUrl(orgAgentDetails.agentEndPoint, CommonConstants.VERIFY_SIGNED_DATA_FROM_AGENT); // Invoke an API request from the agent to assess its current status const signedDataFromAgent = await this.commonService @@ -1822,9 +1844,8 @@ export class AgentServiceService { // Perform the deletion in a transaction return await this.prisma.$transaction(async (prisma) => { // Delete org agent and related records - const { orgDid, agentInvitation, deleteOrgAgent } = await this.agentServiceRepository.deleteOrgAgentByOrg( - orgId - ); + const { orgDid, agentInvitation, deleteOrgAgent } = + await this.agentServiceRepository.deleteOrgAgentByOrg(orgId); // Make the HTTP DELETE request const deleteWallet = await this.commonService.httpDelete(url, { @@ -1922,25 +1943,25 @@ export class AgentServiceService { async getOrgAgentApiKey(orgId: string): Promise { try { const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); - const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); - let apiKey; - if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { - const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( - CommonConstants.PLATFORM_ADMIN_ORG - ); - if (!platformAdminSpinnedUp) { - throw new InternalServerErrorException('Agent not able to spin-up'); - } - apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey; - } else { - apiKey = orgAgentApiKey?.apiKey; - } - - if (!apiKey) { + // const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); + // let apiKey; + // if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { + // const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( + // CommonConstants.PLATFORM_ADMIN_ORG + // ); + // if (!platformAdminSpinnedUp) { + // throw new InternalServerErrorException('Agent not able to spin-up'); + // } + // apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey; + // } else { + // apiKey = orgAgentApiKey?.apiKey; + // } + + if (!orgAgentApiKey?.apiKey) { throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); } - const decryptedToken = await this.commonService.decryptPassword(apiKey); + const decryptedToken = await this.commonService.decryptPassword(orgAgentApiKey?.apiKey); return decryptedToken; } catch (error) { this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); @@ -2026,7 +2047,9 @@ export class AgentServiceService { ): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); - + console.log('getApiKey::::::::::::::::::', getApiKey); + console.log('connectionPayload::::::::::::::::::', connectionPayload); + console.log('url::::::::::::::::::Agent service', url); const createConnectionInvitation = await this.commonService .httpPost(url, connectionPayload, { headers: { authorization: getApiKey } }) .then(async (response) => response); @@ -2072,12 +2095,13 @@ export class AgentServiceService { throw error; } } - + //TODO: need to discuss this with GHkrishna /** * Description: Fetch agent url * @param referenceId * @returns agent URL */ + //DONE getAgentUrl(agentMethodLabel: string, orgAgentType: string, agentEndPoint: string, tenantId: string): string { try { let url; @@ -2087,8 +2111,8 @@ export class AgentServiceService { orgAgentType === OrgAgentType.DEDICATED ? `${agentEndPoint}${CommonConstants.URL_AGENT_SIGN_DATA}` : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_SIGN_DATA}`.replace('#', tenantId) - : null; + ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_SIGN_DATA}`.replace('#', tenantId) + : null; break; } case 'verify-signed-data-from-agent': { @@ -2096,8 +2120,8 @@ export class AgentServiceService { orgAgentType === OrgAgentType.DEDICATED ? `${agentEndPoint}${CommonConstants.URL_AGENT_VERIFY_SIGNED_DATA}` : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_VERIFY_SIGNED_DATA}`.replace('#', tenantId) - : null; + ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_VERIFY_SIGNED_DATA}`.replace('#', tenantId) + : null; break; } default: { diff --git a/apps/api-gateway/src/agent-service/agent-service.controller.ts b/apps/api-gateway/src/agent-service/agent-service.controller.ts index 2bd780ecc..77bde4081 100644 --- a/apps/api-gateway/src/agent-service/agent-service.controller.ts +++ b/apps/api-gateway/src/agent-service/agent-service.controller.ts @@ -259,7 +259,7 @@ export class AgentController { @Res() res: Response ): Promise { createTenantDto.orgId = orgId; - + console.log(`**** Create tenant...${JSON.stringify(createTenantDto)}`); const tenantDetails = await this.agentService.createTenant(createTenantDto, user); const finalResponse: IResponse = { diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index 0efa7a8bf..7c30cb7ec 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -21,13 +21,18 @@ import { IUserRequest } from '@credebl/user-request/user-request.interface'; import { OrgAgentType, ConnectionProcessState } from '@credebl/enum/enum'; import { Cache } from 'cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; -import { IConnectionList, ICreateConnectionUrl, IDeletedConnectionsRecord } from '@credebl/common/interfaces/connection.interface'; +import { + IConnectionList, + ICreateConnectionUrl, + IDeletedConnectionsRecord +} from '@credebl/common/interfaces/connection.interface'; import { IConnectionDetailsById } from 'apps/api-gateway/src/interfaces/IConnectionSearch.interface'; import { IBasicMessage, IQuestionPayload } from './interfaces/messaging.interfaces'; import { RecordType, user } from '@prisma/client'; import { UserActivityRepository } from 'libs/user-activity/repositories'; import { agent_invitations } from '@prisma/client'; import { NATSClient } from '@credebl/common/NATSClient'; +import { getAgentUrl } from '@credebl/common/common.utils'; @Injectable() export class ConnectionService { constructor( @@ -37,7 +42,7 @@ export class ConnectionService { private readonly userActivityRepository: UserActivityRepository, private readonly logger: Logger, @Inject(CACHE_MANAGER) private readonly cacheService: Cache, - private readonly natsClient : NATSClient + private readonly natsClient: NATSClient ) {} /** @@ -98,7 +103,6 @@ export class ConnectionService { try { return await this.connectionRepository.getConnectionRecordsCount(orgId); } catch (error) { - this.logger.error( `[getConnectionRecords ] [NATS call]- error in get connection records count : ${JSON.stringify(error)}` ); @@ -332,43 +336,6 @@ export class ConnectionService { return this.natsCall(pattern, payload); } - /** - * Description: Fetch agent url - * @param referenceId - * @returns agent URL - */ - async getAgentUrl( - orgAgentType: string, - agentEndPoint: string, - tenantId?: string, - connectionInvitationFlag?: string - ): Promise { - try { - let url; - if ('connection-invitation' === connectionInvitationFlag) { - if (orgAgentType === OrgAgentType.DEDICATED) { - url = `${agentEndPoint}${CommonConstants.URL_CONN_INVITE}`; - } else if (orgAgentType === OrgAgentType.SHARED) { - url = `${agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_CONNECTION_INVITATION}`.replace('#', tenantId); - } else { - throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); - } - } else { - if (orgAgentType === OrgAgentType.DEDICATED) { - url = `${agentEndPoint}${CommonConstants.URL_CONN_LEGACY_INVITE}`; - } else if (orgAgentType === OrgAgentType.SHARED) { - url = `${agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_INVITATION}`.replace('#', tenantId); - } else { - throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); - } - } - return url; - } catch (error) { - this.logger.error(`Error in get agent url: ${JSON.stringify(error)}`); - throw error; - } - } - async getQuestionAnswerAgentUrl( label: string, orgAgentType: string, @@ -384,10 +351,10 @@ export class ConnectionService { orgAgentType === OrgAgentType.DEDICATED ? `${agentEndPoint}${CommonConstants.URL_SEND_QUESTION}`.replace('#', connectionId) : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_SEND_QUESTION}` - .replace('#', connectionId) - .replace('@', tenantId) - : null; + ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_SEND_QUESTION}` + .replace('#', connectionId) + .replace('@', tenantId) + : null; break; } @@ -396,8 +363,8 @@ export class ConnectionService { orgAgentType === OrgAgentType.DEDICATED ? `${agentEndPoint}${CommonConstants.URL_QUESTION_ANSWER_RECORD}` : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_QUESTION_ANSWER_RECORD}`.replace('#', tenantId) - : null; + ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_QUESTION_ANSWER_RECORD}`.replace('#', tenantId) + : null; break; } @@ -475,8 +442,7 @@ export class ConnectionService { message: customErrorMessage, error: ResponseMessages.errorMessages.conflict }); - } else - if (error?.response?.error?.reason) { + } else if (error?.response?.error?.reason) { throw new RpcException({ message: ResponseMessages.connection.error.connectionNotFound, statusCode: error?.response?.status, @@ -495,7 +461,6 @@ export class ConnectionService { ): Promise<{ response; }> { - const pattern = { cmd: 'agent-receive-invitation-url' }; const payload = { url, orgId, receiveInvitationUrl }; @@ -644,7 +609,6 @@ export class ConnectionService { */ async createConnectionInvitation(payload: ICreateOutOfbandConnectionInvitation): Promise { try { - const { alias, appendedAttachments, @@ -676,18 +640,17 @@ export class ConnectionService { let legacyinvitationDid; if (IsReuseConnection) { const data: agent_invitations[] = await this.connectionRepository.getInvitationDidByOrgId(orgId); - if (data && 0 < data.length) { - const [firstElement] = data; - legacyinvitationDid = firstElement?.invitationDid ?? undefined; - - this.logger.log('legacyinvitationDid:', legacyinvitationDid); + if (data && 0 < data.length) { + const [firstElement] = data; + legacyinvitationDid = firstElement?.invitationDid ?? undefined; + + this.logger.log('legacyinvitationDid:', legacyinvitationDid); } } const connectionInvitationDid = invitationDid ? invitationDid : legacyinvitationDid; this.logger.log('connectionInvitationDid:', connectionInvitationDid); - this.logger.log(`logoUrl:::, ${organisation.logoUrl}`); const connectionPayload = { multiUseInvitation: multiUseInvitation ?? true, @@ -705,15 +668,8 @@ export class ConnectionService { recipientKey: recipientKey || undefined, invitationDid: connectionInvitationDid || undefined }; - - const createConnectionInvitationFlag = 'connection-invitation'; - const orgAgentType = await this.connectionRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); - const url = await this.getAgentUrl( - orgAgentType, - agentEndPoint, - agentDetails?.tenantId, - createConnectionInvitationFlag - ); + const url = await getAgentUrl(agentEndPoint, CommonConstants.CONNECTION_INVITATION); + console.log('url:::::::::::::::::::', url); const createConnectionInvitation = await this._createOutOfBandConnectionInvitation(connectionPayload, url, orgId); const connectionInvitationUrl = createConnectionInvitation?.response?.invitationUrl; const shortenedUrl = await this.storeConnectionObjectAndReturnUrl( @@ -726,7 +682,7 @@ export class ConnectionService { shortenedUrl, agentId, orgId, - invitationsDid + invitationsDid ); const connectionStorePayload: ConnectionResponseDetail = { id: saveConnectionDetails.id, @@ -785,8 +741,7 @@ export class ConnectionService { response: string; }> { try { - return from(this.natsClient - .send(this.connectionServiceProxy, pattern, payload)) + return from(this.natsClient.send(this.connectionServiceProxy, pattern, payload)) .pipe( map((response) => ({ response @@ -824,49 +779,47 @@ export class ConnectionService { async deleteConnectionRecords(orgId: string, user: user): Promise { try { - const deleteConnections = await this.connectionRepository.deleteConnectionRecordsByOrgId(orgId); + const deleteConnections = await this.connectionRepository.deleteConnectionRecordsByOrgId(orgId); - if (0 === deleteConnections?.deleteConnectionRecords?.count) { - throw new NotFoundException(ResponseMessages.connection.error.connectionRecordNotFound); - } + if (0 === deleteConnections?.deleteConnectionRecords?.count) { + throw new NotFoundException(ResponseMessages.connection.error.connectionRecordNotFound); + } - const statusCounts = { - [ConnectionProcessState.START]: 0, - [ConnectionProcessState.COMPLETE]: 0, - [ConnectionProcessState.ABANDONED]: 0, - [ConnectionProcessState.INVITATION_SENT]: 0, - [ConnectionProcessState.INVITATION_RECEIVED]: 0, - [ConnectionProcessState.REQUEST_SENT]: 0, - [ConnectionProcessState.DECLIEND]: 0, - [ConnectionProcessState.REQUEST_RECEIVED]: 0, - [ConnectionProcessState.RESPONSE_SENT]: 0, - [ConnectionProcessState.RESPONSE_RECEIVED]: 0 - }; - - await Promise.all(deleteConnections.getConnectionRecords.map(async (record) => { - statusCounts[record.state]++; - })); - - const filteredStatusCounts = Object.fromEntries( - Object.entries(statusCounts).filter(entry => 0 < entry[1]) - ); + const statusCounts = { + [ConnectionProcessState.START]: 0, + [ConnectionProcessState.COMPLETE]: 0, + [ConnectionProcessState.ABANDONED]: 0, + [ConnectionProcessState.INVITATION_SENT]: 0, + [ConnectionProcessState.INVITATION_RECEIVED]: 0, + [ConnectionProcessState.REQUEST_SENT]: 0, + [ConnectionProcessState.DECLIEND]: 0, + [ConnectionProcessState.REQUEST_RECEIVED]: 0, + [ConnectionProcessState.RESPONSE_SENT]: 0, + [ConnectionProcessState.RESPONSE_RECEIVED]: 0 + }; - const deletedConnectionData = { - deletedConnectionsRecordsCount: deleteConnections?.deleteConnectionRecords?.count, - deletedRecordsStatusCount: filteredStatusCounts - }; + await Promise.all( + deleteConnections.getConnectionRecords.map(async (record) => { + statusCounts[record.state]++; + }) + ); - await this.userActivityRepository._orgDeletedActivity(orgId, user, deletedConnectionData, RecordType.CONNECTION); + const filteredStatusCounts = Object.fromEntries(Object.entries(statusCounts).filter((entry) => 0 < entry[1])); - return deleteConnections; + const deletedConnectionData = { + deletedConnectionsRecordsCount: deleteConnections?.deleteConnectionRecords?.count, + deletedRecordsStatusCount: filteredStatusCounts + }; + await this.userActivityRepository._orgDeletedActivity(orgId, user, deletedConnectionData, RecordType.CONNECTION); + + return deleteConnections; } catch (error) { - this.logger.error(`[deleteConnectionRecords] - error in deleting connection records: ${JSON.stringify(error)}`); - throw new RpcException(error.response ? error.response : error); + this.logger.error(`[deleteConnectionRecords] - error in deleting connection records: ${JSON.stringify(error)}`); + throw new RpcException(error.response ? error.response : error); } } - async sendBasicMesage(payload: IBasicMessage): Promise { const { content, orgId, connectionId } = payload; try { @@ -915,5 +868,4 @@ export class ConnectionService { // eslint-disable-next-line no-return-await return await this.natsCall(pattern, payload); } - } diff --git a/apps/issuance/src/issuance.service.ts b/apps/issuance/src/issuance.service.ts index 7030d2b0c..c315acab2 100644 --- a/apps/issuance/src/issuance.service.ts +++ b/apps/issuance/src/issuance.service.ts @@ -47,7 +47,6 @@ import { import { AutoAccept, IssuanceProcessState, - OrgAgentType, PromiseResult, SchemaType, TemplateIdentifier, @@ -63,7 +62,7 @@ import { parse as paParse } from 'papaparse'; import { v4 as uuidv4 } from 'uuid'; import { Cache } from 'cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; -import { convertUrlToDeepLinkUrl, paginator } from '@credebl/common/common.utils'; +import { convertUrlToDeepLinkUrl, getAgentUrl, paginator } from '@credebl/common/common.utils'; import { InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; import { FileUploadStatus, FileUploadType } from 'apps/api-gateway/src/enum'; @@ -185,8 +184,7 @@ export class IssuanceService { throw new NotFoundException(ResponseMessages.issuance.error.orgAgentTypeNotFound); } - const issuanceMethodLabel = 'create-offer'; - const url = await this.getAgentUrl(issuanceMethodLabel, orgAgentType, agentEndPoint, agentDetails?.tenantId); + const url = await getAgentUrl(agentEndPoint, CommonConstants.CREATE_OFFER); if (payload.credentialType === IssueCredentialType.JSONLD) { await validateAndUpdateIssuanceDates(credentialData); @@ -371,10 +369,7 @@ export class IssuanceService { throw new NotFoundException(ResponseMessages.issuance.error.agentEndPointNotFound); } - const orgAgentType = await this.issuanceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); - - const issuanceMethodLabel = 'create-offer-oob'; - const url = await this.getAgentUrl(issuanceMethodLabel, orgAgentType, agentEndPoint, agentDetails?.tenantId); + const url = await getAgentUrl(agentEndPoint, CommonConstants.CREATE_OFFER_OUT_OF_BAND); let issueData; if (credentialType === IssueCredentialType.INDY) { @@ -687,15 +682,7 @@ export class IssuanceService { throw new NotFoundException(ResponseMessages.issuance.error.agentEndPointNotFound); } - const orgAgentType = await this.issuanceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); - const issuanceMethodLabel = 'get-issue-credential-by-credential-id'; - const url = await this.getAgentUrl( - issuanceMethodLabel, - orgAgentType, - agentEndPoint, - agentDetails?.tenantId, - credentialRecordId - ); + const url = await getAgentUrl(agentEndPoint, CommonConstants.GET_OFFER_BY_CRED_ID, credentialRecordId); const createConnectionInvitation = await this._getIssueCredentialsbyCredentialRecordId(url, orgId); return createConnectionInvitation?.response; @@ -836,15 +823,8 @@ export class IssuanceService { if (!agentDetails) { throw new NotFoundException(ResponseMessages.issuance.error.agentEndPointNotFound); } - const orgAgentType = await this.issuanceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); - const issuanceMethodLabel = 'create-offer-oob'; - const url = await this.getAgentUrl( - issuanceMethodLabel, - orgAgentType, - agentDetails.agentEndPoint, - agentDetails.tenantId - ); + const url = await getAgentUrl(agentDetails.agentEndPoint, CommonConstants.CREATE_OFFER_OUT_OF_BAND); const organizationDetails = await this.issuanceRepository.getOrganization(orgId); if (!organizationDetails) { @@ -1131,79 +1111,6 @@ export class IssuanceService { } } - /** - * Description: Fetch agent url - * @param referenceId - * @returns agent URL - */ - async getAgentUrl( - issuanceMethodLabel: string, - orgAgentType: string, - agentEndPoint: string, - tenantId: string, - credentialRecordId?: string - ): Promise { - try { - let url; - switch (issuanceMethodLabel) { - case 'create-offer': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_ISSUE_CREATE_CRED_OFFER_AFJ}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_OFFER}`.replace('#', tenantId) - : null; - break; - } - - case 'create-offer-oob': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_OUT_OF_BAND_CREDENTIAL_OFFER}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_OFFER_OUT_OF_BAND}`.replace('#', tenantId) - : null; - break; - } - - case 'get-issue-credentials': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_ISSUE_GET_CREDS_AFJ}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CREDENTIALS}`.replace('#', tenantId) - : null; - break; - } - - case 'get-issue-credential-by-credential-id': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_ISSUE_GET_CREDS_AFJ_BY_CRED_REC_ID}/${credentialRecordId}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CREDENTIALS_BY_CREDENTIAL_ID}` - .replace('#', credentialRecordId) - .replace('@', tenantId) - : null; - break; - } - - default: { - break; - } - } - - if (!url) { - throw new NotFoundException(ResponseMessages.issuance.error.agentUrlNotFound); - } - - return url; - } catch (error) { - this.logger.error(`Error in get agent url: ${JSON.stringify(error)}`); - throw error; - } - } - async downloadBulkIssuanceCSVTemplate(orgId: string, templateDetails: TemplateDetailsInterface): Promise { try { let schemaResponse: SchemaDetails; diff --git a/apps/verification/src/verification.service.ts b/apps/verification/src/verification.service.ts index ed9b8b0c3..d2eceb264 100644 --- a/apps/verification/src/verification.service.ts +++ b/apps/verification/src/verification.service.ts @@ -27,7 +27,7 @@ import { import { VerificationRepository } from './repositories/verification.repository'; import { ATTRIBUTE_NAME_REGEX, CommonConstants } from '@credebl/common/common.constant'; import { RecordType, agent_invitations, org_agents, organisation, presentations, user } from '@prisma/client'; -import { AutoAccept, OrgAgentType, VerificationProcessState } from '@credebl/enum/enum'; +import { AutoAccept, VerificationProcessState } from '@credebl/enum/enum'; import { ResponseMessages } from '@credebl/common/response-messages'; import * as QRCode from 'qrcode'; import { OutOfBandVerification } from '../templates/out-of-band-verification.template'; @@ -46,11 +46,10 @@ import { ProofRequestLabel, ProofRequestType, ProofVersion, - ProtocolVersionType, - VerificationMethodLabel + ProtocolVersionType } from 'apps/api-gateway/src/verification/enum/verification.enum'; import { UserActivityService } from '@credebl/user-activity'; -import { convertUrlToDeepLinkUrl } from '@credebl/common/common.utils'; +import { convertUrlToDeepLinkUrl, getAgentUrl } from '@credebl/common/common.utils'; import { UserActivityRepository } from 'libs/user-activity/repositories'; import { ISchemaDetail } from '@credebl/common/interfaces/schema.interface'; import { NATSClient } from '@credebl/common/NATSClient'; @@ -226,15 +225,9 @@ export class VerificationService { async getProofPresentationById(proofId: string, orgId: string): Promise { try { const getAgentDetails = await this.verificationRepository.getAgentEndPoint(orgId); - - const verificationMethodLabel = 'get-proof-presentation-by-id'; - const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - const url = await this.getAgentUrl( - verificationMethodLabel, - orgAgentType, + const url = await getAgentUrl( getAgentDetails?.agentEndPoint, - getAgentDetails?.tenantId, - '', + CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID_FLAG, proofId ); @@ -288,15 +281,7 @@ export class VerificationService { try { const comment = requestProof.comment ? requestProof.comment : ''; const getAgentDetails = await this.verificationRepository.getAgentEndPoint(requestProof.orgId); - const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - const verificationMethodLabel = VerificationMethodLabel.REQUEST_PROOF; - const url = await this.getAgentUrl( - verificationMethodLabel, - orgAgentType, - getAgentDetails?.agentEndPoint, - getAgentDetails?.tenantId - ); - + const url = await getAgentUrl(getAgentDetails?.agentEndPoint, CommonConstants.REQUEST_PROOF); // Function to create a payload const createPayload = async (connectionId: string): Promise => { const proofRequestPayload = { @@ -417,18 +402,7 @@ export class VerificationService { async verifyPresentation(proofId: string, orgId: string): Promise { try { const getAgentData = await this.verificationRepository.getAgentEndPoint(orgId); - const orgAgentTypeData = await this.verificationRepository.getOrgAgentType(getAgentData?.orgAgentTypeId); - - const verificationMethod = 'accept-presentation'; - - const url = await this.getAgentUrl( - verificationMethod, - orgAgentTypeData, - getAgentData?.agentEndPoint, - getAgentData?.tenantId, - '', - proofId - ); + const url = await getAgentUrl(getAgentData?.agentEndPoint, CommonConstants.ACCEPT_PRESENTATION, proofId); const payload = { orgId, url }; const getProofPresentationById = await this._verifyPresentation(payload); @@ -506,13 +480,9 @@ export class VerificationService { outOfBandRequestProof['label'] = label; - const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - const verificationMethodLabel = 'create-request-out-of-band'; - const url = await this.getAgentUrl( - verificationMethodLabel, - orgAgentType, + const url = await getAgentUrl( getAgentDetails?.agentEndPoint, - getAgentDetails?.tenantId + CommonConstants.CREATE_OUT_OF_BAND_PROOF_PRESENTATION ); // Destructuring 'outOfBandRequestProof' to remove emailId, as it is not used while agent operation @@ -786,127 +756,13 @@ export class VerificationService { } } - /** - * Description: Fetch agent url - * @param referenceId - * @returns agent URL - */ - async getAgentUrl( - verificationMethodLabel: string, - orgAgentType: string, - agentEndPoint: string, - tenantId: string, - threadId?: string, - proofPresentationId?: string - ): Promise { - try { - let url; - switch (verificationMethodLabel) { - case 'get-proof-presentation': { - url = - orgAgentType === OrgAgentType.DEDICATED && threadId - ? `${agentEndPoint}${CommonConstants.URL_GET_PROOF_PRESENTATIONS}?threadId=${threadId}` - : orgAgentType === OrgAgentType.SHARED && threadId - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_PROOFS}?threadId=${threadId}`.replace( - '#', - tenantId - ) - : orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_GET_PROOF_PRESENTATIONS}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_PROOFS}`.replace('#', tenantId) - : null; - break; - } - - case 'get-proof-presentation-by-id': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID}`.replace('#', proofPresentationId) - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_PROOFS_BY_PRESENTATION_ID}` - .replace('#', proofPresentationId) - .replace('@', tenantId) - : null; - break; - } - - case 'request-proof': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_SEND_PROOF_REQUEST}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_REQUEST_PROOF}`.replace('#', tenantId) - : null; - break; - } - - case 'accept-presentation': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_VERIFY_PRESENTATION}`.replace('#', proofPresentationId) - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_ACCEPT_PRESENTATION}` - .replace('@', proofPresentationId) - .replace('#', tenantId) - : null; - break; - } - - case 'create-request-out-of-band': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_SEND_OUT_OF_BAND_CREATE_REQUEST}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_OUT_OF_BAND_CREATE_REQUEST}`.replace('#', tenantId) - : null; - break; - } - - case 'get-verified-proof': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_PROOF_FORM_DATA}`.replace('#', proofPresentationId) - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHAGENT_PROOF_FORM_DATA}` - .replace('@', proofPresentationId) - .replace('#', tenantId) - : null; - break; - } - - default: { - break; - } - } - - if (!url) { - throw new NotFoundException(ResponseMessages.verification.error.agentUrlNotFound); - } - - return url; - } catch (error) { - this.logger.error(`Error in get agent url: ${JSON.stringify(error)}`); - throw error; - } - } - async getVerifiedProofdetails(proofId: string, orgId: string): Promise { try { const getAgentDetails = await this.verificationRepository.getAgentEndPoint(orgId); - const verificationMethodLabel = 'get-verified-proof'; let credDefId; let schemaId; let certificate; - const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - const url = await this.getAgentUrl( - verificationMethodLabel, - orgAgentType, - getAgentDetails?.agentEndPoint, - getAgentDetails?.tenantId, - '', - proofId - ); + const url = await getAgentUrl(getAgentDetails?.agentEndPoint, CommonConstants.GET_VERIFIED_PROOF); const payload = { orgId, url }; diff --git a/libs/client-registration/src/client-registration.service.ts b/libs/client-registration/src/client-registration.service.ts index 51dbeb923..cfcc662bf 100644 --- a/libs/client-registration/src/client-registration.service.ts +++ b/libs/client-registration/src/client-registration.service.ts @@ -579,11 +579,13 @@ export class ClientRegistrationService { throw new BadRequestException(`Client ID and client secret are missing`); } - const decryptClientId = await this.commonService.decryptPassword(clientId); - const decryptClientSecret = await this.commonService.decryptPassword(clientSecret); + // const decryptClientId = await this.commonService.decryptPassword(clientId); + // const decryptClientSecret = await this.commonService.decryptPassword(clientSecret); - payload.client_id = decryptClientId; - payload.client_secret = decryptClientSecret; + // payload.client_id = decryptClientId; + // payload.client_secret = decryptClientSecret; + payload.client_id = 'adminClient'; + payload.client_secret = 'C03x3S4YaCggPJK6NfkTRNg1nVhZ9eBn'; payload.username = email; payload.password = password; diff --git a/libs/common/src/common.constant.ts b/libs/common/src/common.constant.ts index 1698f3f43..cc4f86517 100644 --- a/libs/common/src/common.constant.ts +++ b/libs/common/src/common.constant.ts @@ -23,8 +23,8 @@ export enum CommonConstants { URL_CONN_ACCEPT_CONNECTION_REQUEST = '/connections/#/accept-request', URL_CONN_REMOVE_CONNECTION_BY_ID = '/connections/#/remove', URL_CONN_METADATA = '/connections/#/metadata', - URL_CONN_LEGACY_INVITE = '/oob/create-legacy-invitation', - URL_CONN_INVITE = '/oob/create-invitation', + URL_CONN_LEGACY_INVITE = '/didcomm/oob/create-legacy-invitation', + URL_CONN_INVITE = '/didcomm/oob/create-invitation', URL_RECEIVE_INVITATION_URL = '/oob/receive-invitation-url', URL_RECEIVE_INVITATION = '/oob/receive-invitation', URL_CONN_INVITATION = '/url', @@ -67,12 +67,12 @@ export enum CommonConstants { URL_PUBLISH_REVOCATION = '/issue-credential/publish-revocations', URL_CREATE_ISSUE_CREDENTIAL_OUT_OF_BAND = '/issue-credential/create', URL_CREATE_OUT_OF_BAND_INVITATION = '/out-of-band/create-invitation', - URL_ISSUE_CREATE_CRED_OFFER_AFJ = '/credentials/create-offer', + URL_ISSUANCE_CREATE_OFFER = '/didcomm/credentials/create-offer', // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values URL_ISSUE_GET_CREDS_AFJ = '/credentials', // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values - URL_ISSUE_GET_CREDS_AFJ_BY_CRED_REC_ID = '/credentials', - URL_OUT_OF_BAND_CREDENTIAL_OFFER = '/credentials/create-offer-oob', + URL_ISSUE_GET_CREDS_BY_CRED_REC_ID = '/didcomm/credentials/#', + URL_OUT_OF_BAND_CREDENTIAL_OFFER = '/didcomm/credentials/create-offer-oob', URL_ACCEPT_CREDENTIALS = '/credentials/accept-offer', URL_SEND_QUESTION = '/question-answer/question/#', URL_QUESTION_ANSWER_RECORD = '/question-answer', @@ -125,12 +125,12 @@ export enum CommonConstants { URL_SHARED_AGENT_VERIFY_SIGNED_DATA = '/multi-tenancy/credential/verify/#', // PROOF SERVICES - URL_SEND_PROOF_REQUEST = '/proofs/request-proof', + URL_SEND_PROOF_REQUEST = '/didcomm/proofs/request-proof', URL_GET_PROOF_PRESENTATIONS = '/proofs', - URL_GET_PROOF_PRESENTATION_BY_ID = '/proofs/#', - URL_VERIFY_PRESENTATION = '/proofs/#/accept-presentation', - URL_SEND_OUT_OF_BAND_CREATE_REQUEST = '/proofs/create-request-oob', - URL_PROOF_FORM_DATA = '/proofs/#/form-data', + URL_GET_PROOF_PRESENTATION_BY_ID = '/didcomm/proofs/#', + URL_ACCEPT_PRESENTATION = '/didcomm/proofs/#/accept-presentation', + URL_CREATE_OUT_OF_BAND_CREATE_REQUEST = '/didcomm/proofs/create-request-oob', + URL_PROOF_FORM_DATA = '/didcomm//proofs/#/form-data', // server or agent URL_SERVER_STATUS = '/status', @@ -139,8 +139,8 @@ export enum CommonConstants { URL_AGENT_GET_ENDPOINT = '/agent', // sign data from agent - URL_AGENT_SIGN_DATA = '/credential/sign', - URL_AGENT_VERIFY_SIGNED_DATA = '/credential/verify', + URL_AGENT_SIGN_DATA = '/agent/credential/sign/#', + URL_AGENT_VERIFY_SIGNED_DATA = '/agent/credential/verify', // CREATE KEYS CREATE_POLYGON_SECP256k1_KEY = '/polygon/create-keys', @@ -395,7 +395,21 @@ export enum CommonConstants { //CLOUD WALLET RECEIVE_INVITATION_BY_URL = '/multi-tenancy/receive-invitation-url/', ACCEPT_OFFER = '/multi-tenancy/credentials/accept-offer/', - SEED_LENGTH = 32 + SEED_LENGTH = 32, + + //Agent URL flags + CONNECTION_INVITATION = 'connection-invitation', + LEGACY_INVITATION = 'legacy-invitation', + SIGN_DATA_FROM_AGENT = 'sign-data-from-agent', + VERIFY_SIGNED_DATA_FROM_AGENT = 'verify-signed-data-from-agent', + CREATE_OFFER = 'create-offer', + CREATE_OFFER_OUT_OF_BAND = 'create-offer-oob', + GET_OFFER_BY_CRED_ID = 'get-offer-by-cred-id', + URL_GET_PROOF_PRESENTATION_BY_ID_FLAG = 'get-proof-presentation-by-id', + REQUEST_PROOF = 'request-proof', + ACCEPT_PRESENTATION = 'accept-presentation', + CREATE_OUT_OF_BAND_PROOF_PRESENTATION = 'create-request-out-of-band', + GET_VERIFIED_PROOF = 'get-verified-proof' } export const MICRO_SERVICE_NAME = Symbol('MICRO_SERVICE_NAME'); export const ATTRIBUTE_NAME_REGEX = /\['(.*?)'\]/; diff --git a/libs/common/src/common.utils.ts b/libs/common/src/common.utils.ts index ed84515c3..a34fc9be5 100644 --- a/libs/common/src/common.utils.ts +++ b/libs/common/src/common.utils.ts @@ -5,11 +5,7 @@ import { CommonConstants } from './common.constant'; dotenv.config(); /* eslint-disable camelcase */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type -export function paginator( - items: T[], - current_page: number, - items_per_page: number -) { +export function paginator(items: T[], current_page: number, items_per_page: number) { const page: number = Number(current_page) || 1; const per_page: number = Number(items_per_page) || 10; const offset: number = (page - 1) * per_page; @@ -50,11 +46,10 @@ export function orderValues(key, order = 'asc') { }; } - export function convertUrlToDeepLinkUrl(url: string): string { - const deepLinkDomain = process.env.DEEPLINK_DOMAIN - if(!deepLinkDomain) { - throw new NotFoundException(ResponseMessages.shorteningUrl.error.deepLinkDomainNotFound) + const deepLinkDomain = process.env.DEEPLINK_DOMAIN; + if (!deepLinkDomain) { + throw new NotFoundException(ResponseMessages.shorteningUrl.error.deepLinkDomainNotFound); } const deepLinkUrl = deepLinkDomain.concat(url); return deepLinkUrl; @@ -63,11 +58,56 @@ export function convertUrlToDeepLinkUrl(url: string): string { export const networkNamespace = (did: string): string => { // Split the DID into segments using the colon as a delimiter const segments = did.split(':'); - const hasPolygon = segments.some(segment => segment.includes(CommonConstants.POLYGON)); - const hasTestnet = segments.some(segment => segment.includes(CommonConstants.TESTNET)); + const hasPolygon = segments.some((segment) => segment.includes(CommonConstants.POLYGON)); + const hasTestnet = segments.some((segment) => segment.includes(CommonConstants.TESTNET)); if (hasPolygon) { return hasTestnet ? `${segments[1]}:${segments[2]}` : `${segments[1]}:${CommonConstants.MAINNET}`; } return segments[1]; -}; \ No newline at end of file +}; + +export const getAgentUrl = async (agentEndPoint: string, urlFlag: string, paramId?: string): Promise => { + try { + if (!agentEndPoint) { + throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); + } + + const agentUrlMap: Map = new Map([ + [String(CommonConstants.CONNECTION_INVITATION), String(CommonConstants.URL_CONN_INVITE)], + [String(CommonConstants.LEGACY_INVITATION), String(CommonConstants.URL_CONN_LEGACY_INVITE)], + [String(CommonConstants.SIGN_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_SIGN_DATA)], + [String(CommonConstants.VERIFY_SIGNED_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_VERIFY_SIGNED_DATA)], + [String(CommonConstants.CREATE_OFFER), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], + [String(CommonConstants.CREATE_OFFER_OUT_OF_BAND), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], + [String(CommonConstants.GET_OFFER_BY_CRED_ID), String(CommonConstants.URL_ISSUE_GET_CREDS_BY_CRED_REC_ID)], + [ + String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID_FLAG), + String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID) + ], + [String(CommonConstants.REQUEST_PROOF), String(CommonConstants.URL_SEND_PROOF_REQUEST)], + [String(CommonConstants.ACCEPT_PRESENTATION), String(CommonConstants.URL_ACCEPT_PRESENTATION)], + [ + String(CommonConstants.CREATE_OUT_OF_BAND_PROOF_PRESENTATION), + String(CommonConstants.URL_CREATE_OUT_OF_BAND_CREATE_REQUEST) + ], + [String(CommonConstants.GET_VERIFIED_PROOF), String(CommonConstants.URL_PROOF_FORM_DATA)] + ]); + + const urlSuffix = agentUrlMap.get(urlFlag); + + if (!urlSuffix) { + throw new NotFoundException(ResponseMessages.common.error.invalidUrl); + } + // Add paramId as a path parameter if provided + const resolvedUrlPath = paramId ? urlSuffix.replace('#', paramId) : urlSuffix; + + const url = `${agentEndPoint}${resolvedUrlPath}`; + + console.debug(`Generated agent URL: ${url}`); + return url; + } catch (error) { + console.error(`Error in getAgentUrl: ${error instanceof Error ? error.message : JSON.stringify(error)}`); + throw error; + } +}; diff --git a/libs/common/src/nats.config.ts b/libs/common/src/nats.config.ts index 7fd1ff011..984459979 100644 --- a/libs/common/src/nats.config.ts +++ b/libs/common/src/nats.config.ts @@ -14,8 +14,8 @@ export const getNatsOptions = ( const baseOptions = { servers: `${process.env.NATS_URL}`.split(','), maxReconnectAttempts: NATSReconnects.maxReconnectAttempts, - reconnectTimeWait: NATSReconnects.reconnectTimeWait, - queue: serviceName + reconnectTimeWait: NATSReconnects.reconnectTimeWait + // queue: serviceName }; if (nkeySeed) { diff --git a/libs/common/src/response-messages/index.ts b/libs/common/src/response-messages/index.ts index 0c56ef999..59de1523c 100644 --- a/libs/common/src/response-messages/index.ts +++ b/libs/common/src/response-messages/index.ts @@ -270,7 +270,8 @@ export const ResponseMessages = { requiredEndorserDid: 'Role or endorser DID is required', requiredPrivateKey: 'Privatekey is required for polygon method', privateKeyLength: 'Private key must be exactly 64 characters long', - requiredSeed: 'Seed is required' + requiredSeed: 'Seed is required', + baseWalletToken: 'Error while fetching base wallet token' } }, connection: { @@ -491,5 +492,11 @@ export const ResponseMessages = { 'No subscribers for the requested message. Error while connecting to NATS, service might not be started', natsConnect: 'Empty response. There are no subscribers listening to that message' } + }, + common: { + error: { + invalidUrl: 'Please check the url suffix.', + invalidEndpoint: 'Invalid agent endpoint provided' + } } }; diff --git a/package.json b/package.json old mode 100755 new mode 100644 From 6bd5038a3fe389d7f55d89c6e7d45e99098742e6 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Thu, 31 Jul 2025 12:27:15 +0530 Subject: [PATCH 02/15] refactor: uncommented required code Signed-off-by: Tipu_Singh --- .../src/client-registration.service.ts | 10 ++++------ libs/common/src/nats.config.ts | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/libs/client-registration/src/client-registration.service.ts b/libs/client-registration/src/client-registration.service.ts index cfcc662bf..51dbeb923 100644 --- a/libs/client-registration/src/client-registration.service.ts +++ b/libs/client-registration/src/client-registration.service.ts @@ -579,13 +579,11 @@ export class ClientRegistrationService { throw new BadRequestException(`Client ID and client secret are missing`); } - // const decryptClientId = await this.commonService.decryptPassword(clientId); - // const decryptClientSecret = await this.commonService.decryptPassword(clientSecret); + const decryptClientId = await this.commonService.decryptPassword(clientId); + const decryptClientSecret = await this.commonService.decryptPassword(clientSecret); - // payload.client_id = decryptClientId; - // payload.client_secret = decryptClientSecret; - payload.client_id = 'adminClient'; - payload.client_secret = 'C03x3S4YaCggPJK6NfkTRNg1nVhZ9eBn'; + payload.client_id = decryptClientId; + payload.client_secret = decryptClientSecret; payload.username = email; payload.password = password; diff --git a/libs/common/src/nats.config.ts b/libs/common/src/nats.config.ts index 984459979..7fd1ff011 100644 --- a/libs/common/src/nats.config.ts +++ b/libs/common/src/nats.config.ts @@ -14,8 +14,8 @@ export const getNatsOptions = ( const baseOptions = { servers: `${process.env.NATS_URL}`.split(','), maxReconnectAttempts: NATSReconnects.maxReconnectAttempts, - reconnectTimeWait: NATSReconnects.reconnectTimeWait - // queue: serviceName + reconnectTimeWait: NATSReconnects.reconnectTimeWait, + queue: serviceName }; if (nkeySeed) { From bba059d66b01706abb03b1a4a0f4e82c653b035f Mon Sep 17 00:00:00 2001 From: Sahil Kamble Date: Thu, 31 Jul 2025 13:18:49 +0530 Subject: [PATCH 03/15] feat:added logic to get token from cloudwatch Signed-off-by: Sahil Kamble --- .../AFJ/scripts/start_agent_ecs.sh | 73 ++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh index 27f984451..5c458d110 100644 --- a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh @@ -37,7 +37,7 @@ random_string=$(generate_random_string) # Print the generated random string echo "Random String: $random_string" -SERVICE_NAME="${AGENCY}-${CONTAINER_NAME}-service-${random_string}" +SERVICE_NAME="${CONTAINER_NAME}-service" EXTERNAL_IP=$(echo "$2" | tr -d '[:space:]') ADMIN_PORT_FILE="$PWD/agent-provisioning/AFJ/port-file/last-admin-port.txt" INBOUND_PORT_FILE="$PWD/agent-provisioning/AFJ/port-file/last-inbound-port.txt" @@ -194,6 +194,14 @@ CONTAINER_DEFINITIONS=$( } ], "volumesFrom": [], + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/$TESKDEFINITION_FAMILY", + "awslogs-create-group": "true", + "awslogs-region": "ap-south-1", + "awslogs-stream-prefix": "ecs" + }, "ulimits": [] } ] @@ -262,6 +270,67 @@ if [ $? -eq 0 ]; then sleep 10 fi done +# Describe the ECS service and filter by service name +service_description=$(aws ecs describe-services --service $SERVICE_NAME --cluster $CLUSTER_NAME --region $AWS_PUBLIC_REGION) +echo "service_description=$service_description" + + +# Extract Task ID from the service description events +task_id=$(echo "$service_description" | jq -r '.services[0].events[] | select(.message | test("has started 1 tasks")) | .message | capture("\\(task (?[^)]+)\\)") | .id') +#echo "task_id=$task_id" + +# to fetch log group of container +............................................................. +log_group=/ecs/$TESKDEFINITION_FAMILY +echo "log_group=$log_group" + +# Get Log Stream Name +log_stream=ecs/$CONTAINER_NAME/$task_id + +echo "logstrem=$log_stream" + + +# Fetch logs +#echo "$(aws logs get-log-events --log-group-name "/ecs/$TESKDEFINITION_FAMILY/$CONTAINER_NAME" --log-stream-name "$log_stream" --region $AWS_PUBLIC_REGION)" + +# Check if the token folder exists, and create it if it doesn't +token_folder="$PWD/agent-provisioning/AFJ/token" +if [ ! -d "$token_folder" ]; then + mkdir -p "$token_folder" +fi + +# Set maximum retry attempts +RETRIES=3 + +# Loop to attempt retrieving token from logs +# Loop to attempt retrieving token from logs +for attempt in $(seq 1 $RETRIES); do + echo "Attempt $attempt: Checking service logs for token..." + + # Fetch logs and grep for API token + token=$(aws logs get-log-events \ + --log-group-name "$log_group" \ + --log-stream-name "$log_stream" \ + --region ap-southeast-1 \ + | grep -o 'API Token: [^ ]*' \ + | cut -d ' ' -f 3 +) + # echo "token=$token" + if [ -n "$token" ]; then + echo "Token found: $token" + # Write token to a file + echo "{\"token\": \"$token\"}" > "$PWD/agent-provisioning/AFJ/token/${AGENCY}_${CONTAINER_NAME}.json" + break # Exit loop if token is found + else + echo "Token not found in logs. Retrying..." + if [ $attempt -eq $RETRIES ]; then + echo "Reached maximum retry attempts. Token not found." + fi + fi + # Add a delay of 10 seconds between retries + sleep 10 +done + echo "Creating agent config" cat <${PWD}/agent-provisioning/AFJ/endpoints/${AGENCY}_${CONTAINER_NAME}.json @@ -273,7 +342,7 @@ EOF cat <${PWD}/agent-provisioning/AFJ/token/${AGENCY}_${CONTAINER_NAME}.json { - "token" : "" + "token" : "$token" } EOF From 7f9b0366ca17344a6a52036fd6fd442aab3d181c Mon Sep 17 00:00:00 2001 From: Sahil Kamble Date: Thu, 31 Jul 2025 15:54:17 +0530 Subject: [PATCH 04/15] feat: update credo image in taskdef Signed-off-by: Sahil Kamble --- apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh index 5c458d110..99736f3cc 100644 --- a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh @@ -153,7 +153,7 @@ CONTAINER_DEFINITIONS=$( [ { "name": "$CONTAINER_NAME", - "image": "${AFJ_IMAGE_URL}", + "image": "${AFJ_VERSION}", "cpu": 154, "memory": 307, "portMappings": [ From 93df85a4212b8ba49bf2e6a280282f6d979b194a Mon Sep 17 00:00:00 2001 From: Sahil Kamble Date: Thu, 31 Jul 2025 15:55:34 +0530 Subject: [PATCH 05/15] feat: change service name for testing Signed-off-by: Sahil Kamble --- apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh index 99736f3cc..52360b958 100644 --- a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh @@ -37,7 +37,7 @@ random_string=$(generate_random_string) # Print the generated random string echo "Random String: $random_string" -SERVICE_NAME="${CONTAINER_NAME}-service" +SERVICE_NAME="${CONTAINER_NAME}-service-test" EXTERNAL_IP=$(echo "$2" | tr -d '[:space:]') ADMIN_PORT_FILE="$PWD/agent-provisioning/AFJ/port-file/last-admin-port.txt" INBOUND_PORT_FILE="$PWD/agent-provisioning/AFJ/port-file/last-inbound-port.txt" From 372f8857b1adc65e55e981c04a9957815f723fbc Mon Sep 17 00:00:00 2001 From: Sahil Kamble Date: Thu, 31 Jul 2025 16:14:25 +0530 Subject: [PATCH 06/15] chore: WIP Signed-off-by: Sahil Kamble --- apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh index 52360b958..372552e82 100644 --- a/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent_ecs.sh @@ -312,7 +312,7 @@ for attempt in $(seq 1 $RETRIES); do --log-group-name "$log_group" \ --log-stream-name "$log_stream" \ --region ap-southeast-1 \ - | grep -o 'API Token: [^ ]*' \ + | grep -o '*** API Key: [^ ]*' \ | cut -d ' ' -f 3 ) # echo "token=$token" From 599badb3bc43f5a4abebe81b0557adc8e3285edf Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Thu, 31 Jul 2025 19:33:56 +0530 Subject: [PATCH 07/15] debug: added logs for agent details Signed-off-by: Tipu_Singh --- apps/agent-service/src/agent-service.service.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index c26eac929..9a9a0b2fe 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -147,9 +147,12 @@ export class AgentServiceService { ]); let orgData; + console.log('agentSpinupDto::::::', agentSpinupDto); + console.log(user?.userId, 'userId:::::::::::::::', user?.userId); if (!user?.userId && agentSpinupDto?.platformAdminEmail) { // Get Platform admin user by platform admin email platformAdminUser = await this.agentServiceRepository.getPlatfomAdminUser(agentSpinupDto?.platformAdminEmail); + console.log('platformAdminUser:::::::::::::::', platformAdminUser); userId = platformAdminUser?.id; } else { @@ -223,6 +226,8 @@ export class AgentServiceService { orgData ); + console.log('walletProvisionPayload:::::::::::::: prepareWalletProvisionPayload', walletProvisionPayload); + // Socket connection const socket: Socket = await this.initSocketConnection(`${process.env.SOCKET_HOST}`); this.emitAgentSpinupInitiatedEvent(agentSpinupDto, socket); @@ -422,7 +427,7 @@ export class AgentServiceService { credoImage: process.env.AFJ_VERSION || '', protocol: process.env.AGENT_PROTOCOL || '', tenant: agentSpinupDto.tenant || false, - apiKey: agentSpinupDto.apiKey + apiKey: process.env.AGENT_API_KEY }; return walletProvisionPayload; } From 6f59f025520a9ad39169cf6594921cc19cee56dd Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Fri, 1 Aug 2025 17:52:38 +0530 Subject: [PATCH 08/15] refactor:removed console logs Signed-off-by: Tipu_Singh --- .eslintrc.js | 2 +- .../AFJ/scripts/start_agent.sh | 7 +- .../src/agent-provisioning.service.ts | 6 +- .../src/agent-service.service.ts | 109 ------------------ .../agent-service/agent-service.controller.ts | 1 - apps/connection/src/connection.service.ts | 1 - libs/common/src/nats.config.ts | 4 +- 7 files changed, 10 insertions(+), 120 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 253007eb5..6b733d326 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -14,7 +14,7 @@ module.exports = { ignorePatterns: ['.eslintrc.js'], rules: { 'prettier/prettier': 0, - // 'no-console': 'error', //TODO: Uncomment this after testing + 'no-console': 'error', // "@typescript-eslint/consistent-type-imports": "error", '@typescript-eslint/no-unused-vars': [ 'error' diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent.sh b/apps/agent-provisioning/AFJ/scripts/start_agent.sh index 8a09b1247..d8541b58a 100755 --- a/apps/agent-provisioning/AFJ/scripts/start_agent.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent.sh @@ -19,7 +19,7 @@ AFJ_VERSION=${14} INDY_LEDGER=${15} INBOUND_ENDPOINT=${16} SCHEMA_FILE_SERVER_URL=${17} - +AGENT_API_KEY="${18}" ADMIN_PORT_FILE="$PWD/apps/agent-provisioning/AFJ/port-file/last-admin-port.txt" INBOUND_PORT_FILE="$PWD/apps/agent-provisioning/AFJ/port-file/last-inbound-port.txt" ADMIN_PORT=8001 @@ -119,6 +119,7 @@ CONFIG_FILE="${PWD}/apps/agent-provisioning/AFJ/agent-config/${AGENCY}_${CONTAIN echo "CONFIG_FILE = $CONFIG_FILE" echo "AGENCY = $AGENCY" echo "CONTAINER_NAME = $CONTAINER_NAME" +echo "AGENT_API_KEY= $AGENT_API_KEY" # Check if the file exists if [ -f "$CONFIG_FILE" ]; then @@ -126,7 +127,7 @@ if [ -f "$CONFIG_FILE" ]; then rm "$CONFIG_FILE" fi -cat <${CONFIG_FILE} +cat <"$CONFIG_FILE" { "label": "${AGENCY}_${CONTAINER_NAME}", "walletId": "$WALLET_NAME", @@ -159,7 +160,7 @@ cat <${CONFIG_FILE} "adminPort": $ADMIN_PORT, "tenancy": $TENANT, "schemaFileServerURL": "$SCHEMA_FILE_SERVER_URL", - "apiKey": "supersecret-that-too-16chars" + "apiKey": "$AGENT_API_KEY" } EOF diff --git a/apps/agent-provisioning/src/agent-provisioning.service.ts b/apps/agent-provisioning/src/agent-provisioning.service.ts index 796f5363b..99a1b92cd 100644 --- a/apps/agent-provisioning/src/agent-provisioning.service.ts +++ b/apps/agent-provisioning/src/agent-provisioning.service.ts @@ -19,7 +19,6 @@ export class AgentProvisioningService { */ async walletProvision(payload: IWalletProvision): Promise { try { - console.log('walletProvision payload:', payload); const { containerName, externalIp, @@ -37,11 +36,12 @@ export class AgentProvisioningService { credoImage, tenant, indyLedger, - inboundEndpoint + inboundEndpoint, + apiKey } = payload; if (agentType === AgentType.AFJ) { // The wallet provision command is used to invoke a shell script - const walletProvision = `${process.cwd() + process.env.AFJ_AGENT_SPIN_UP} ${orgId} "${externalIp}" "${walletName}" "${walletPassword}" ${seed} ${webhookEndpoint} ${walletStorageHost} ${walletStoragePort} ${walletStorageUser} ${walletStoragePassword} ${containerName} ${protocol} ${tenant} ${credoImage} "${indyLedger}" ${inboundEndpoint} ${process.env.SCHEMA_FILE_SERVER_URL} ${process.env.AGENT_HOST} ${process.env.AWS_ACCOUNT_ID} ${process.env.S3_BUCKET_ARN} ${process.env.CLUSTER_NAME} ${process.env.TESKDEFINITION_FAMILY}`; + const walletProvision = `${process.cwd() + process.env.AFJ_AGENT_SPIN_UP} ${orgId} "${externalIp}" "${walletName}" "${walletPassword}" ${seed} ${webhookEndpoint} ${walletStorageHost} ${walletStoragePort} ${walletStorageUser} ${walletStoragePassword} ${containerName} ${protocol} ${tenant} ${credoImage} "${indyLedger}" ${inboundEndpoint} ${process.env.SCHEMA_FILE_SERVER_URL} ${apiKey} ${process.env.AGENT_HOST} ${process.env.AWS_ACCOUNT_ID} ${process.env.S3_BUCKET_ARN} ${process.env.CLUSTER_NAME} ${process.env.TESKDEFINITION_FAMILY}`; const spinUpResponse: object = new Promise(async (resolve) => { await exec(walletProvision, async (err, stdout, stderr) => { this.logger.log(`shell script output: ${stdout}`); diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 9a9a0b2fe..69ab1700a 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -4,7 +4,6 @@ /* eslint-disable no-useless-catch */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable camelcase */ -/* eslint-disable no-console */ //TODO: remove after testing import { BadRequestException, ConflictException, @@ -147,12 +146,9 @@ export class AgentServiceService { ]); let orgData; - console.log('agentSpinupDto::::::', agentSpinupDto); - console.log(user?.userId, 'userId:::::::::::::::', user?.userId); if (!user?.userId && agentSpinupDto?.platformAdminEmail) { // Get Platform admin user by platform admin email platformAdminUser = await this.agentServiceRepository.getPlatfomAdminUser(agentSpinupDto?.platformAdminEmail); - console.log('platformAdminUser:::::::::::::::', platformAdminUser); userId = platformAdminUser?.id; } else { @@ -226,8 +222,6 @@ export class AgentServiceService { orgData ); - console.log('walletProvisionPayload:::::::::::::: prepareWalletProvisionPayload', walletProvisionPayload); - // Socket connection const socket: Socket = await this.initSocketConnection(`${process.env.SOCKET_HOST}`); this.emitAgentSpinupInitiatedEvent(agentSpinupDto, socket); @@ -494,7 +488,6 @@ export class AgentServiceService { let ledgerIdData = []; try { - console.log('walletProvisionPayload::::::::::::::_agentSpinup', walletProvisionPayload); if (agentSpinupDto.method !== DidMethod.KEY && agentSpinupDto.method !== DidMethod.WEB) { const { network } = agentSpinupDto; const ledger = await ledgerName(network); @@ -542,7 +535,6 @@ export class AgentServiceService { } } ); - console.log('agentBaseWalletToken::::::::::::::', agentBaseWalletDetils); if (!agentBaseWalletDetils.token) { throw new BadRequestException(ResponseMessages.agent.error.baseWalletToken, { cause: new Error(), @@ -550,7 +542,6 @@ export class AgentServiceService { }); } const encryptedToken = await this.tokenEncryption(agentBaseWalletDetils.token); - console.log('agentDetails::::::::::::::', agentDetails); const agentPayload: IStoreOrgAgentDetails = { agentEndPoint, seed: agentSpinupDto.seed, @@ -567,7 +558,6 @@ export class AgentServiceService { did: agentSpinupDto.did, id: agentProcess?.id }; - console.log('agentPayload::::::::::::::', agentPayload); /** * Store organization agent details */ @@ -621,19 +611,7 @@ export class AgentServiceService { async _storeOrgAgentDetails(payload: IStoreOrgAgentDetails): Promise { try { - // /** - // * Get orgaization agent type and agent details - // */ - // const [agentDid, orgAgentTypeId] = await Promise.all([ - // this._getAgentDid(payload), - // this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.DEDICATED) - // ]); - // /** const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.DEDICATED); - console.log('orgAgentTypeId::::::::::::::', orgAgentTypeId); - // * Get DID method by agent - // */ - // const getDidMethod = await this._getDidMethod(payload, agentDid); /** * Organization storage data */ @@ -641,7 +619,6 @@ export class AgentServiceService { /** * Store org agent details */ - console.log('storeOrgAgentData::::::::::::::', storeOrgAgentData); const storeAgentDid = await this.agentServiceRepository.storeOrgAgentDetails(storeOrgAgentData); return storeAgentDid; } catch (error) { @@ -650,35 +627,7 @@ export class AgentServiceService { } } - // private async _getAgentDid(payload: IStoreOrgAgentDetails): Promise { - // const { agentEndPoint, apiKey, ledgerId, seed, keyType, method, network, role, did } = payload; - // const writeDid = 'write-did'; - // const ledgerDetails = await this.agentServiceRepository.getGenesisUrl(ledgerId); - // const agentDidWriteUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; - // console.log("agentDidWriteUrl::::::::::::::", agentDidWriteUrl); - // console.log("apiKey::::::::::::::", apiKey); - // return this._retryAgentSpinup(agentDidWriteUrl, apiKey, writeDid, seed, keyType, method, network, role, did); - // } - - // private async _getDidMethod(payload: IStoreOrgAgentDetails, agentDid: object): Promise { - // const { agentEndPoint, apiKey, seed, keyType, method, network, role } = payload; - // const getDidDoc = 'get-did-doc'; - // const getDidMethodUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_GET_DID}/${agentDid['did']}`; - // return this._retryAgentSpinup( - // getDidMethodUrl, - // apiKey, - // getDidDoc, - // seed, - // keyType, - // method, - // network, - // role, - // `${agentDid['did']}` - // ); - // } - private _buildStoreOrgAgentData(payload: IStoreOrgAgentDetails, orgAgentTypeId: string): IStoreOrgAgentDetails { - console.log('payload::::::::::::::', payload); return { did: 'NA', verkey: 'NA', @@ -731,10 +680,8 @@ export class AgentServiceService { }; try { const getDcryptedToken = await this.commonService.decryptPassword(apiKey); - console.log('getDcryptedToken::::::::::::::', getDcryptedToken); return retry(async () => { if (agentApiState === 'write-did') { - console.log('Inside If::::::::::::', agentUrl); return this.commonService.httpPost( agentUrl, { seed, keyType, method, network, role, did }, @@ -806,7 +753,6 @@ export class AgentServiceService { const agentStatusResponse = { agentSpinupStatus: AgentSpinUpStatus.PROCESSED }; - console.log('createTenant payload::::::::::::::', payload); const getOrgAgent = await this.agentServiceRepository.getAgentDetails(payload.orgId); if (AgentSpinUpStatus.COMPLETED === getOrgAgent?.agentSpinUpStatus) { @@ -853,7 +799,6 @@ export class AgentServiceService { } const ledgerList = (await this._getALlLedgerDetails()) as unknown as LedgerListResponse; - console.log('ledgerList::::::::::::::', ledgerList); const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); if (!isLedgerExist) { throw new BadRequestException(ResponseMessages.agent.error.invalidLedger, { @@ -862,22 +807,18 @@ export class AgentServiceService { }); } ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); - console.log('ledgerIdData::::::::::::::', ledgerIdData); const agentSpinUpStatus = AgentSpinUpStatus.PROCESSED; // Create and stored agent details agentProcess = await this.agentServiceRepository.createOrgAgent(agentSpinUpStatus, user?.id); - console.log('agentProcess::::::::::::::', agentProcess); // Get platform admin details const platformAdminSpinnedUp = await this.getPlatformAdminAndNotify(payload.clientSocketId); - console.log('platformAdminSpinnedUp::::::::::::::', platformAdminSpinnedUp); payload.endpoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; // Create tenant wallet and DID const tenantDetails = await this.createTenantAndNotify(payload, platformAdminSpinnedUp); - console.log('tenantDetails::::::::::::::', tenantDetails); if (!tenantDetails?.walletResponseDetails?.id || !tenantDetails?.DIDCreationOption?.did) { this.logger.error(`Error in getting wallet id and wallet did`); throw new NotFoundException(ResponseMessages.agent.error.notAbleToSpinUpAgent, { @@ -916,10 +857,8 @@ export class AgentServiceService { id: agentProcess?.id, apiKey: await this.commonService.dataEncryption(tenantDetails.walletResponseDetails['token']) }; - console.log('storeOrgAgentData::::::::::::::', storeOrgAgentData); // Get organization data const getOrganization = await this.agentServiceRepository.getOrgDetails(payload.orgId); - console.log('getOrganization::::::::::::::', getOrganization); this.notifyClientSocket('agent-spinup-process-completed', payload.clientSocketId); @@ -1189,16 +1128,13 @@ export class AgentServiceService { delete WalletSetupPayload.clientSocketId; delete WalletSetupPayload.orgId; delete WalletSetupPayload.ledgerId; - console.log('platformAdminSpinnedUp.org_agents[0]::::::::::::::', platformAdminSpinnedUp.org_agents[0]); const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); - console.log('getDcryptedToken::::::::::::::', getDcryptedToken); const walletResponseDetails = await this._createTenantWallet( walletLabel, platformAdminSpinnedUp.org_agents[0].agentEndPoint, getDcryptedToken ); - console.log('walletResponseDetails::::::::::::::', walletResponseDetails); if (!walletResponseDetails && !walletResponseDetails.id && !walletResponseDetails.token) { throw new InternalServerErrorException('Error while creating the wallet'); } @@ -2052,9 +1988,6 @@ export class AgentServiceService { ): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); - console.log('getApiKey::::::::::::::::::', getApiKey); - console.log('connectionPayload::::::::::::::::::', connectionPayload); - console.log('url::::::::::::::::::Agent service', url); const createConnectionInvitation = await this.commonService .httpPost(url, connectionPayload, { headers: { authorization: getApiKey } }) .then(async (response) => response); @@ -2100,46 +2033,4 @@ export class AgentServiceService { throw error; } } - //TODO: need to discuss this with GHkrishna - /** - * Description: Fetch agent url - * @param referenceId - * @returns agent URL - */ - //DONE - getAgentUrl(agentMethodLabel: string, orgAgentType: string, agentEndPoint: string, tenantId: string): string { - try { - let url; - switch (agentMethodLabel) { - case 'sign-data-from-agent': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_AGENT_SIGN_DATA}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_SIGN_DATA}`.replace('#', tenantId) - : null; - break; - } - case 'verify-signed-data-from-agent': { - url = - orgAgentType === OrgAgentType.DEDICATED - ? `${agentEndPoint}${CommonConstants.URL_AGENT_VERIFY_SIGNED_DATA}` - : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHARED_AGENT_VERIFY_SIGNED_DATA}`.replace('#', tenantId) - : null; - break; - } - default: { - break; - } - } - if (!url) { - throw new NotFoundException(ResponseMessages.issuance.error.agentUrlNotFound); - } - return url; - } catch (error) { - this.logger.error(`Error in get agent url: ${JSON.stringify(error)}`); - throw error; - } - } } diff --git a/apps/api-gateway/src/agent-service/agent-service.controller.ts b/apps/api-gateway/src/agent-service/agent-service.controller.ts index 77bde4081..6ef12047c 100644 --- a/apps/api-gateway/src/agent-service/agent-service.controller.ts +++ b/apps/api-gateway/src/agent-service/agent-service.controller.ts @@ -259,7 +259,6 @@ export class AgentController { @Res() res: Response ): Promise { createTenantDto.orgId = orgId; - console.log(`**** Create tenant...${JSON.stringify(createTenantDto)}`); const tenantDetails = await this.agentService.createTenant(createTenantDto, user); const finalResponse: IResponse = { diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index 7c30cb7ec..3f11dde53 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -669,7 +669,6 @@ export class ConnectionService { invitationDid: connectionInvitationDid || undefined }; const url = await getAgentUrl(agentEndPoint, CommonConstants.CONNECTION_INVITATION); - console.log('url:::::::::::::::::::', url); const createConnectionInvitation = await this._createOutOfBandConnectionInvitation(connectionPayload, url, orgId); const connectionInvitationUrl = createConnectionInvitation?.response?.invitationUrl; const shortenedUrl = await this.storeConnectionObjectAndReturnUrl( diff --git a/libs/common/src/nats.config.ts b/libs/common/src/nats.config.ts index 7fd1ff011..984459979 100644 --- a/libs/common/src/nats.config.ts +++ b/libs/common/src/nats.config.ts @@ -14,8 +14,8 @@ export const getNatsOptions = ( const baseOptions = { servers: `${process.env.NATS_URL}`.split(','), maxReconnectAttempts: NATSReconnects.maxReconnectAttempts, - reconnectTimeWait: NATSReconnects.reconnectTimeWait, - queue: serviceName + reconnectTimeWait: NATSReconnects.reconnectTimeWait + // queue: serviceName }; if (nkeySeed) { From 04abe9786084dc4e17c07f93b1cebc583766c8aa Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Fri, 1 Aug 2025 17:55:44 +0530 Subject: [PATCH 09/15] refactor:removed commented code Signed-off-by: Tipu_Singh --- apps/agent-service/src/agent-service.service.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 69ab1700a..ef8d8d422 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -581,9 +581,6 @@ export class AgentServiceService { socket.emit('did-publish-process-completed', { clientId: agentSpinupDto.clientSocketId }); } - const getOrganization = await this.agentServiceRepository.getOrgDetails(orgData?.id); - - // await this._createConnectionInvitation(orgData?.id, user, getOrganization.name); if (agentSpinupDto.clientSocketId) { socket.emit('invitation-url-creation-success', { clientId: agentSpinupDto.clientSocketId }); } From ad0cfa3ed8ef4a69e291767b7c212bab6c725146 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 09:41:16 +0530 Subject: [PATCH 10/15] feat: added token for old wallet Signed-off-by: Tipu_Singh --- .../src/agent-service.service.ts | 84 ++++++++++++------- libs/common/src/common.constant.ts | 2 + libs/common/src/common.service.ts | 41 ++++++++- libs/common/src/nats.config.ts | 4 +- libs/common/src/response-messages/index.ts | 5 +- 5 files changed, 98 insertions(+), 38 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index ef8d8d422..de3c913cf 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -525,23 +525,17 @@ export class AgentServiceService { socket.emit('did-publish-process-initiated', { clientId: agentSpinupDto.clientSocketId }); socket.emit('invitation-url-creation-started', { clientId: agentSpinupDto.clientSocketId }); } - const agentBaseWalletDetils = await this.commonService.httpPost( - `${process.env.API_GATEWAY_PROTOCOL}://${agentDetails.agentEndPoint}/agent/token`, - '', - { - headers: { - Accept: 'application/json', - Authorization: agentDetails?.agentToken - } - } + const agentBaseWalletToken = await this.commonService.getBaseAgentToken( + agentDetails.gentEndPoint, + agentDetails?.agentToken ); - if (!agentBaseWalletDetils.token) { + if (!agentBaseWalletToken) { throw new BadRequestException(ResponseMessages.agent.error.baseWalletToken, { cause: new Error(), description: ResponseMessages.errorMessages.badRequest }); } - const encryptedToken = await this.tokenEncryption(agentBaseWalletDetils.token); + const encryptedToken = await this.tokenEncryption(agentBaseWalletToken); const agentPayload: IStoreOrgAgentDetails = { agentEndPoint, seed: agentSpinupDto.seed, @@ -835,10 +829,6 @@ export class AgentServiceService { const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); // Get agent type details const agentTypeId = await this.agentServiceRepository.getAgentTypeId(AgentType.AFJ); - this.logger.log( - 'tenantDetails.walletResponseDetails::::::::::::::', - tenantDetails.walletResponseDetails['token'] - ); const storeOrgAgentData: IStoreOrgAgentDetails = { did: tenantDetails.DIDCreationOption.did, isDidPublic: true, @@ -1881,25 +1871,33 @@ export class AgentServiceService { async getOrgAgentApiKey(orgId: string): Promise { try { const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); - // const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); - // let apiKey; - // if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { - // const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( - // CommonConstants.PLATFORM_ADMIN_ORG - // ); - // if (!platformAdminSpinnedUp) { - // throw new InternalServerErrorException('Agent not able to spin-up'); - // } - // apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey; - // } else { - // apiKey = orgAgentApiKey?.apiKey; - // } - - if (!orgAgentApiKey?.apiKey) { + const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); + let apiKey; + if ( + orgAgentApiKey?.orgAgentTypeId === orgAgentId && + (orgAgentApiKey.apiKey === '' || orgAgentApiKey.apiKey === null) + ) { + const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( + CommonConstants.PLATFORM_ADMIN_ORG + ); + if (!platformAdminSpinnedUp) { + throw new InternalServerErrorException(ResponseMessages.agent.error.notConfigured); + } + const tenantToken = await this.commonService.getTenantWalletToken( + orgAgentApiKey.agentEndPoint, + platformAdminSpinnedUp.org_agents[0]?.apiKey, + orgAgentApiKey.tenantId + ); + apiKey = tenantToken; + } else { + apiKey = orgAgentApiKey?.apiKey; + } + + if (!apiKey) { throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); } - const decryptedToken = await this.commonService.decryptPassword(orgAgentApiKey?.apiKey); + const decryptedToken = await this.commonService.decryptPassword(apiKey); return decryptedToken; } catch (error) { this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); @@ -1907,6 +1905,30 @@ export class AgentServiceService { } } + async getTenantToken(agentEndPoint: string, apiKey: string, tenantId: string): Promise { + try { + if (!agentEndPoint || !apiKey || !tenantId) { + throw new BadRequestException(ResponseMessages.agent.error.invalidTenantDetails, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); + } + const tenantWalletToken = await this.commonService.getTenantWalletToken(agentEndPoint, apiKey, tenantId); + if (!tenantWalletToken) { + throw new NotFoundException(ResponseMessages.agent.error.tenantWalletToken, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); + } + + //Add tenant wallet token to the database + return tenantWalletToken; + } catch (error) { + this.logger.error(`Error in getting org agent type : ${JSON.stringify(error)}`); + throw error; + } + } + async handleAgentSpinupStatusErrors(error: string): Promise { if (error && Object.keys(error).length === 0) { throw new InternalServerErrorException(ResponseMessages.agent.error.agentDown, { diff --git a/libs/common/src/common.constant.ts b/libs/common/src/common.constant.ts index cc4f86517..043cfa875 100644 --- a/libs/common/src/common.constant.ts +++ b/libs/common/src/common.constant.ts @@ -28,6 +28,8 @@ export enum CommonConstants { URL_RECEIVE_INVITATION_URL = '/oob/receive-invitation-url', URL_RECEIVE_INVITATION = '/oob/receive-invitation', URL_CONN_INVITATION = '/url', + URL_AGENT_TOKEN = '/agent/token', + URL_SHARED_WALLET_TOKEN = '/multi-tenancy/get-token/', // WALLET SERVICES URL_WALLET_CREATE_DID = '/wallet/did/create', diff --git a/libs/common/src/common.service.ts b/libs/common/src/common.service.ts index 68d251fce..327027046 100644 --- a/libs/common/src/common.service.ts +++ b/libs/common/src/common.service.ts @@ -326,10 +326,10 @@ export class CommonService { orgAgentType === OrgAgentType.DEDICATED ? `${agentEndPoint}${CommonConstants.URL_SEND_BASIC_MESSAGE}`.replace('#', connectionId) : orgAgentType === OrgAgentType.SHARED - ? `${agentEndPoint}${CommonConstants.URL_SHARED_SEND_BASIC_MESSAGE}` - .replace('#', connectionId) - .replace('@', tenantId) - : null; + ? `${agentEndPoint}${CommonConstants.URL_SHARED_SEND_BASIC_MESSAGE}` + .replace('#', connectionId) + .replace('@', tenantId) + : null; break; } @@ -347,4 +347,37 @@ export class CommonService { throw error; } } + + async getBaseAgentToken(agentEndPoint: string, apiKey: string): Promise { + const agentBaseWalletDetils = await this.httpPost( + `${process.env.API_GATEWAY_PROTOCOL}://${agentEndPoint}${CommonConstants.URL_AGENT_TOKEN}`, + '', + { + headers: { + Accept: 'application/json', + Authorization: apiKey + } + } + ); + if (200 !== agentBaseWalletDetils?.status) { + throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); + } + return agentBaseWalletDetils.token; + } + + async getTenantWalletToken(agentEndPoint: string, apiKey: string, tenantId: string): Promise { + const tenantWalletDetails = await this.httpPost( + `${process.env.API_GATEWAY_PROTOCOL}://${agentEndPoint}${CommonConstants.URL_SHARED_WALLET_TOKEN}${tenantId}`, + { + headers: { + Accept: 'application/json', + Authorization: apiKey + } + } + ); + if (200 !== tenantWalletDetails?.status) { + throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); + } + return tenantWalletDetails.token; + } } diff --git a/libs/common/src/nats.config.ts b/libs/common/src/nats.config.ts index 984459979..7fd1ff011 100644 --- a/libs/common/src/nats.config.ts +++ b/libs/common/src/nats.config.ts @@ -14,8 +14,8 @@ export const getNatsOptions = ( const baseOptions = { servers: `${process.env.NATS_URL}`.split(','), maxReconnectAttempts: NATSReconnects.maxReconnectAttempts, - reconnectTimeWait: NATSReconnects.reconnectTimeWait - // queue: serviceName + reconnectTimeWait: NATSReconnects.reconnectTimeWait, + queue: serviceName }; if (nkeySeed) { diff --git a/libs/common/src/response-messages/index.ts b/libs/common/src/response-messages/index.ts index 59de1523c..ffff07d8f 100644 --- a/libs/common/src/response-messages/index.ts +++ b/libs/common/src/response-messages/index.ts @@ -240,6 +240,7 @@ export const ResponseMessages = { ledgerNotFound: 'Ledgers not found', agentNotExists: 'Agent not spun up for this organization', agentDown: 'Agent is down or not spun up', + notConfigured: 'Agent is not configured properly', walletAlreadyCreated: 'Your wallet is already been created', walletAlreadyProcessing: 'Your wallet is already processing', notAbleToSpinp: 'Agent not able to spun up', @@ -271,7 +272,9 @@ export const ResponseMessages = { requiredPrivateKey: 'Privatekey is required for polygon method', privateKeyLength: 'Private key must be exactly 64 characters long', requiredSeed: 'Seed is required', - baseWalletToken: 'Error while fetching base wallet token' + baseWalletToken: 'Error while fetching base wallet token', + tenantWalletToken: 'Error while fetching tenant wallet token', + invalidTenantDetails: 'Invalid tenant details provided' } }, connection: { From 20f31360d637d10a862583ace69a5a5e59523145 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 16:25:08 +0530 Subject: [PATCH 11/15] refactor: cloud wallet urls and token changes Signed-off-by: Tipu_Singh --- .../src/agent-service.service.ts | 49 +++-- .../src/interface/agent-service.interface.ts | 31 +-- .../repositories/agent-service.repository.ts | 27 ++- apps/cloud-wallet/src/cloud-wallet.service.ts | 202 ++++++++---------- libs/common/src/common.constant.ts | 18 +- libs/common/src/common.service.ts | 4 +- libs/common/src/common.utils.ts | 69 +++--- libs/common/src/response-messages/index.ts | 2 +- 8 files changed, 207 insertions(+), 195 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index de3c913cf..cd4b7c0aa 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -54,7 +54,8 @@ import { IAgentStore, IAgentConfigure, OrgDid, - IBasicMessage + IBasicMessage, + WalletDetails } from './interface/agent-service.interface'; import { AgentSpinUpStatus, AgentType, DidMethod, Ledgers, OrgAgentType, PromiseResult } from '@credebl/enum/enum'; import { AgentServiceRepository } from './repositories/agent-service.repository'; @@ -79,6 +80,7 @@ import { NATSClient } from '@credebl/common/NATSClient'; import { SignDataDto } from '../../api-gateway/src/agent-service/dto/agent-service.dto'; import { IVerificationMethod } from 'apps/organization/interfaces/organization.interface'; import { getAgentUrl } from '@credebl/common/common.utils'; +import e = require('express'); @Injectable() @WebSocketGateway() export class AgentServiceService { @@ -1870,12 +1872,12 @@ export class AgentServiceService { async getOrgAgentApiKey(orgId: string): Promise { try { - const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); + const orgAgentDetails = await this.agentServiceRepository.getAgentApiKey(orgId); const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); - let apiKey; + let agentApiKey; if ( - orgAgentApiKey?.orgAgentTypeId === orgAgentId && - (orgAgentApiKey.apiKey === '' || orgAgentApiKey.apiKey === null) + orgAgentDetails?.orgAgentTypeId === orgAgentId && + (orgAgentDetails.apiKey === '' || orgAgentDetails.apiKey === null) ) { const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( CommonConstants.PLATFORM_ADMIN_ORG @@ -1883,21 +1885,29 @@ export class AgentServiceService { if (!platformAdminSpinnedUp) { throw new InternalServerErrorException(ResponseMessages.agent.error.notConfigured); } - const tenantToken = await this.commonService.getTenantWalletToken( - orgAgentApiKey.agentEndPoint, - platformAdminSpinnedUp.org_agents[0]?.apiKey, - orgAgentApiKey.tenantId - ); - apiKey = tenantToken; + const walletDetails: WalletDetails = { + agentEndPoint: platformAdminSpinnedUp.org_agents[0]?.agentEndPoint, + apiKey: platformAdminSpinnedUp.org_agents[0]?.apiKey, + tenantId: orgAgentDetails.tenantId, + orgId: orgAgentDetails.orgId + }; + const { apiKey } = await this.getTenantToken(walletDetails); + if (apiKey) { + throw new NotFoundException(ResponseMessages.agent.error.tenantWalletToken, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); + } + agentApiKey = apiKey; } else { - apiKey = orgAgentApiKey?.apiKey; + agentApiKey = orgAgentDetails?.apiKey; } - if (!apiKey) { + if (!agentApiKey) { throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); } - const decryptedToken = await this.commonService.decryptPassword(apiKey); + const decryptedToken = await this.commonService.decryptPassword(agentApiKey); return decryptedToken; } catch (error) { this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); @@ -1905,9 +1915,10 @@ export class AgentServiceService { } } - async getTenantToken(agentEndPoint: string, apiKey: string, tenantId: string): Promise { + async getTenantToken(walletDetails: WalletDetails): Promise { try { - if (!agentEndPoint || !apiKey || !tenantId) { + const { agentEndPoint, apiKey, tenantId, orgId } = walletDetails; + if (!agentEndPoint || !apiKey || !tenantId || !orgId) { throw new BadRequestException(ResponseMessages.agent.error.invalidTenantDetails, { cause: new Error(), description: ResponseMessages.errorMessages.badRequest @@ -1920,9 +1931,9 @@ export class AgentServiceService { description: ResponseMessages.errorMessages.notFound }); } - - //Add tenant wallet token to the database - return tenantWalletToken; + const EncryptedTenantToken = await this.tokenEncryption(tenantWalletToken); + const updatedTenantDetails = await this.agentServiceRepository.updateTenantToken(orgId, EncryptedTenantToken); + return updatedTenantDetails; } catch (error) { this.logger.error(`Error in getting org agent type : ${JSON.stringify(error)}`); throw error; diff --git a/apps/agent-service/src/interface/agent-service.interface.ts b/apps/agent-service/src/interface/agent-service.interface.ts index b4927f98c..4121cf4c3 100644 --- a/apps/agent-service/src/interface/agent-service.interface.ts +++ b/apps/agent-service/src/interface/agent-service.interface.ts @@ -643,16 +643,21 @@ export interface OrgDid { } export interface ILedgers { - id: string; - createDateTime: Date; - lastChangedDateTime: Date; - name: string; - networkType: string; - poolConfig: string; - isActive: boolean; - networkString: string; - nymTxnEndpoint: string; - indyNamespace: string; - networkUrl: string; - -} \ No newline at end of file + id: string; + createDateTime: Date; + lastChangedDateTime: Date; + name: string; + networkType: string; + poolConfig: string; + isActive: boolean; + networkString: string; + nymTxnEndpoint: string; + indyNamespace: string; + networkUrl: string; +} +export interface WalletDetails { + agentEndPoint: string; + apiKey: string; + tenantId: string; + orgId: string; +} diff --git a/apps/agent-service/src/repositories/agent-service.repository.ts b/apps/agent-service/src/repositories/agent-service.repository.ts index 4eb239932..6069be0f0 100644 --- a/apps/agent-service/src/repositories/agent-service.repository.ts +++ b/apps/agent-service/src/repositories/agent-service.repository.ts @@ -1,6 +1,6 @@ +/* eslint-disable camelcase */ import { PrismaService } from '@credebl/prisma-service'; import { ConflictException, Injectable, Logger } from '@nestjs/common'; -// eslint-disable-next-line camelcase import { Prisma, ledgerConfig, @@ -566,4 +566,29 @@ export class AgentServiceRepository { throw error; } } + + /** + * update tenant token + * @param orgId + * @param token + * @returns updated org_agents + * @throws NotFoundException if the orgId does not exist + * @throws Error if there is an issue updating the org_agents + */ + // eslint-disable-next-line camelcase + async updateTenantToken(orgId: string, token: string): Promise { + try { + return await this.prisma.org_agents.update({ + where: { + orgId + }, + data: { + apiKey: token + } + }); + } catch (error) { + this.logger.error(`[updateTenantToken] - Update tenant records details: ${JSON.stringify(error)}`); + throw error; + } + } } diff --git a/apps/cloud-wallet/src/cloud-wallet.service.ts b/apps/cloud-wallet/src/cloud-wallet.service.ts index 5dcd378c1..03ab2b50d 100644 --- a/apps/cloud-wallet/src/cloud-wallet.service.ts +++ b/apps/cloud-wallet/src/cloud-wallet.service.ts @@ -31,7 +31,7 @@ import { IConnectionDetailsById, ITenantDetail, ICredentialDetails, - ICreateConnection, + ICreateConnection, IConnectionInvitationResponse, GetAllCloudWalletConnections, IBasicMessage, @@ -61,13 +61,6 @@ export class CloudWalletService { const { agentEndpoint, apiKey, email, walletKey, userId } = configureBaseWalletPayload; try { - const getAgentInfo = await this.commonService.httpGet( - `${agentEndpoint}${CommonConstants.URL_AGENT_GET_ENDPOINT}` - ); - if (!getAgentInfo?.isInitialized) { - throw new BadRequestException(ResponseMessages.cloudWallet.error.notReachable); - } - const existingWalletInfo = await this.cloudWalletRepository.getCloudWalletInfo(email); if (existingWalletInfo) { throw new ConflictException(ResponseMessages.cloudWallet.error.agentAlreadyExist); @@ -99,24 +92,23 @@ export class CloudWalletService { /** * Create connection - * @param createConnection + * @param createConnection * @returns connection details */ async createConnection(createConnection: ICreateConnection): Promise { try { - const { userId, ...connectionPayload } = createConnection; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - delete connectionPayload.email; + delete connectionPayload.email; + const { agentEndpoint } = baseWalletDetails; - const { tenantId } = getTenant; - const { agentEndpoint } = baseWalletDetails; + const url = `${agentEndpoint}${CommonConstants.URL_CONN_INVITE}`; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CREATE_CONNECTION_INVITATION}/${tenantId}`; - - const createConnectionDetails = await this.commonService.httpPost(url, connectionPayload, { headers: { authorization: decryptedApiKey } }); - return createConnectionDetails; + const createConnectionDetails = await this.commonService.httpPost(url, connectionPayload, { + headers: { authorization: decryptedApiKey } + }); + return createConnectionDetails; } catch (error) { await this.commonService.handleError(error); throw error; @@ -132,12 +124,10 @@ export class CloudWalletService { const { proofRecordId, comment, filterByNonRevocationRequirements, filterByPresentationPreview, userId } = acceptProofRequest; try { - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${proofRecordId}${CommonConstants.CLOUD_WALLET_ACCEPT_PROOF_REQUEST}${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${proofRecordId}${CommonConstants.CLOUD_WALLET_ACCEPT_PROOF_REQUEST}`; const proofAcceptRequestPayload = { comment, filterByNonRevocationRequirements, @@ -162,12 +152,9 @@ export class CloudWalletService { async getProofById(proofPrsentationByIdPayload: IGetProofPresentationById): Promise { try { const { proofRecordId, userId } = proofPrsentationByIdPayload; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${proofRecordId}/${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${proofRecordId}}`; const getProofById = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); return getProofById; @@ -186,15 +173,9 @@ export class CloudWalletService { try { const { threadId, userId } = proofPresentationPayload; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${tenantId}${ - threadId ? `?threadId=${threadId}` : '' - }`; - + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_GET_PROOF_REQUEST}/${threadId ? `?threadId=${threadId}` : ''}`; const getProofById = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); return getProofById; } catch (error) { @@ -208,7 +189,7 @@ export class CloudWalletService { * @param userId * @returns cloud wallet info */ - async _commonCloudWalletInfo(userId: string): Promise<[CloudWallet, CloudWallet, string]> { + async _commonCloudWalletInfo(userId: string): Promise<[CloudWallet, string]> { const baseWalletDetails = await this.cloudWalletRepository.getCloudWalletDetails(CloudWalletType.BASE_WALLET); if (!baseWalletDetails) { @@ -223,14 +204,14 @@ export class CloudWalletService { } const getTenant = await this.cloudWalletRepository.getCloudSubWallet(userId); - + if (!getTenant || !getTenant?.tenantId) { throw new NotFoundException(ResponseMessages.cloudWallet.error.walletRecordNotFound); } const decryptedApiKey = await this.commonService.decryptPassword(getTenant?.agentApiKey); - return [baseWalletDetails, getTenant, decryptedApiKey]; + return [baseWalletDetails, decryptedApiKey]; } /** @@ -253,10 +234,13 @@ export class CloudWalletService { if (checkUserExist) { throw new ConflictException(ResponseMessages.cloudWallet.error.userExist); } - + const baseWalletDetails = await this.cloudWalletRepository.getCloudWalletDetails(CloudWalletType.BASE_WALLET); const { agentEndpoint, agentApiKey } = baseWalletDetails; + if (!agentEndpoint || !agentApiKey) { + throw new NotFoundException(ResponseMessages.cloudWallet.error.notFoundBaseWallet); + } const url = `${agentEndpoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`; const decryptedApiKey = await this.commonService.decryptPassword(agentApiKey); @@ -276,7 +260,7 @@ export class CloudWalletService { }); } - const walletKey = await this.commonService.dataEncryption(createCloudWalletResponse.config.walletConfig.key); + const walletKey = await this.commonService.dataEncryption(createCloudWalletResponse.config.walletConfig.token); if (!walletKey) { throw new BadRequestException(ResponseMessages.cloudWallet.error.encryptCloudWalletKey, { @@ -292,7 +276,7 @@ export class CloudWalletService { tenantId: createCloudWalletResponse.id, type: CloudWalletType.SUB_WALLET, userId, - agentApiKey, + agentApiKey: this.commonService.dataEncryption(createCloudWalletResponse.token), agentEndpoint, email, key: walletKey, @@ -321,12 +305,10 @@ export class CloudWalletService { if (!checkUserExist) { throw new ConflictException(ResponseMessages.cloudWallet.error.walletNotExist); } + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.RECEIVE_INVITATION_BY_URL}${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.RECEIVE_INVITATION_BY_URL}`; const checkCloudWalletAgentHealth = await this.commonService.checkAgentHealth(agentEndpoint, decryptedApiKey); @@ -366,12 +348,10 @@ export class CloudWalletService { if (!checkUserExist) { throw new ConflictException(ResponseMessages.cloudWallet.error.walletNotExist); } - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.ACCEPT_OFFER}${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.ACCEPT_OFFER}`; const checkCloudWalletAgentHealth = await this.commonService.checkAgentHealth(agentEndpoint, decryptedApiKey); @@ -411,12 +391,10 @@ export class CloudWalletService { if (!checkUserExist) { throw new ConflictException(ResponseMessages.cloudWallet.error.walletNotExist); } - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.URL_AGENT_WRITE_DID}`; const checkCloudWalletAgentHealth = await this.commonService.checkAgentHealth(agentEndpoint, decryptedApiKey); @@ -449,12 +427,11 @@ export class CloudWalletService { async getDidList(walletDetails: IWalletDetailsForDidList): Promise { try { const { userId } = walletDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - const { tenantId } = getTenant; const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_DID_LIST}${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.URL_AGENT_GET_DID}`; const didList = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); return didList; @@ -472,14 +449,14 @@ export class CloudWalletService { async getconnectionById(connectionDetails: IConnectionDetailsById): Promise { try { const { userId, connectionId } = connectionDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const { tenantId } = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CONNECTION_BY_ID}${connectionId}/${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CONNECTION_BY_ID}/${connectionId}`; - const connectionDetailResponse = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); + const connectionDetailResponse = await this.commonService.httpGet(url, { + headers: { authorization: decryptedApiKey } + }); return connectionDetailResponse; } catch (error) { await this.commonService.handleError(error); @@ -487,35 +464,36 @@ export class CloudWalletService { } } - /** + /** * Get connection list by tenant id * @param connectionDetails * @returns Connection Details */ - async getAllconnectionById(connectionDetails: GetAllCloudWalletConnections): Promise { - try { - const { userId, alias, myDid, outOfBandId, theirDid, theirLabel } = connectionDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - const urlOptions = { - alias, - myDid, - outOfBandId, - theirDid, - theirLabel - }; - const optionalParameter = await this.commonService.createDynamicUrl(urlOptions); - const { tenantId } = getTenant; - const { agentEndpoint } = baseWalletDetails; - - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CONNECTION_BY_ID}${tenantId}${optionalParameter}`; - - const connectionDetailList = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); - return connectionDetailList; - } catch (error) { - await this.commonService.handleError(error); - throw error; - } + async getAllconnectionById(connectionDetails: GetAllCloudWalletConnections): Promise { + try { + const { userId, alias, myDid, outOfBandId, theirDid, theirLabel } = connectionDetails; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); + const urlOptions = { + alias, + myDid, + outOfBandId, + theirDid, + theirLabel + }; + const optionalParameter = await this.commonService.createDynamicUrl(urlOptions); + const { agentEndpoint } = baseWalletDetails; + + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CONNECTION_BY_ID}${optionalParameter}`; + + const connectionDetailList = await this.commonService.httpGet(url, { + headers: { authorization: decryptedApiKey } + }); + return connectionDetailList; + } catch (error) { + await this.commonService.handleError(error); + throw error; } + } /** * Get credential list by tenant id @@ -525,20 +503,21 @@ export class CloudWalletService { async getCredentialListById(tenantDetails: ITenantDetail): Promise { try { const { userId, connectionId, state, threadId } = tenantDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const urlOptions = { connectionId, state, threadId }; - const {tenantId} = getTenant; - const optionalParameter = await this.commonService.createDynamicUrl(urlOptions); - + const optionalParameter = await this.commonService.createDynamicUrl(urlOptions); + const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CREDENTIAL}/${tenantId}${optionalParameter}`; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CREDENTIAL}${optionalParameter}`; - const credentialDetailResponse = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); + const credentialDetailResponse = await this.commonService.httpGet(url, { + headers: { authorization: decryptedApiKey } + }); return credentialDetailResponse; } catch (error) { await this.commonService.handleError(error); @@ -554,14 +533,13 @@ export class CloudWalletService { async getCredentialByRecord(credentialDetails: ICredentialDetails): Promise { try { const { userId, credentialRecordId } = credentialDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const {tenantId} = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CREDENTIAL}/${credentialRecordId}`; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_CREDENTIAL}/${credentialRecordId}${tenantId}`; - - const credentialDetailResponse = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); + const credentialDetailResponse = await this.commonService.httpGet(url, { + headers: { authorization: decryptedApiKey } + }); return credentialDetailResponse; } catch (error) { await this.commonService.handleError(error); @@ -577,14 +555,14 @@ export class CloudWalletService { async getBasicMessageByConnectionId(connectionDetails: IBasicMessage): Promise { try { const { userId, connectionId } = connectionDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const {tenantId} = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_BASIC_MESSAGE}${connectionId}/${tenantId}`; + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_BASIC_MESSAGE}${connectionId}`; - const basicMessageResponse = await this.commonService.httpGet(url, { headers: { authorization: decryptedApiKey } }); + const basicMessageResponse = await this.commonService.httpGet(url, { + headers: { authorization: decryptedApiKey } + }); return basicMessageResponse; } catch (error) { await this.commonService.handleError(error); @@ -592,23 +570,25 @@ export class CloudWalletService { } } - /** + /** * Send basic-message by connection id * @param messageDetails * @returns Basic message Details */ - async sendBasicMessage(messageDetails: IBasicMessageDetails): Promise { + async sendBasicMessage(messageDetails: IBasicMessageDetails): Promise { try { const { userId, connectionId, content } = messageDetails; - const [baseWalletDetails, getTenant, decryptedApiKey] = await this._commonCloudWalletInfo(userId); - - const {tenantId} = getTenant; + const [baseWalletDetails, decryptedApiKey] = await this._commonCloudWalletInfo(userId); const { agentEndpoint } = baseWalletDetails; - const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_BASIC_MESSAGE}${connectionId}/${tenantId}`; - const basicMessageResponse = await this.commonService.httpPost(url, {content}, { - headers: { authorization: decryptedApiKey } - }); + const url = `${agentEndpoint}${CommonConstants.CLOUD_WALLET_BASIC_MESSAGE}${connectionId}`; + const basicMessageResponse = await this.commonService.httpPost( + url, + { content }, + { + headers: { authorization: decryptedApiKey } + } + ); return basicMessageResponse; } catch (error) { await this.commonService.handleError(error); diff --git a/libs/common/src/common.constant.ts b/libs/common/src/common.constant.ts index 043cfa875..3aff75f98 100644 --- a/libs/common/src/common.constant.ts +++ b/libs/common/src/common.constant.ts @@ -132,7 +132,7 @@ export enum CommonConstants { URL_GET_PROOF_PRESENTATION_BY_ID = '/didcomm/proofs/#', URL_ACCEPT_PRESENTATION = '/didcomm/proofs/#/accept-presentation', URL_CREATE_OUT_OF_BAND_CREATE_REQUEST = '/didcomm/proofs/create-request-oob', - URL_PROOF_FORM_DATA = '/didcomm//proofs/#/form-data', + URL_PROOF_FORM_DATA = '/didcomm/proofs/#/form-data', // server or agent URL_SERVER_STATUS = '/status', @@ -357,13 +357,11 @@ export enum CommonConstants { CACHE_APIKEY_KEY = 'sharedApiKey', CACHE_TTL_SECONDS = 604800, - CLOUD_WALLET_GET_PROOF_REQUEST = '/multi-tenancy/proofs', - CLOUD_WALLET_CREATE_CONNECTION_INVITATION = '/multi-tenancy/create-invitation', - CLOUD_WALLET_ACCEPT_PROOF_REQUEST = '/accept-request/', - CLOUD_WALLET_DID_LIST = '/multi-tenancy/dids/', - CLOUD_WALLET_CONNECTION_BY_ID = '/multi-tenancy/connections/', - CLOUD_WALLET_CREDENTIAL = '/multi-tenancy/credentials', - CLOUD_WALLET_BASIC_MESSAGE = '/multi-tenancy/basic-messages/', + CLOUD_WALLET_GET_PROOF_REQUEST = '/didcomm/proofs', + CLOUD_WALLET_ACCEPT_PROOF_REQUEST = '/accept-request', + CLOUD_WALLET_CONNECTION_BY_ID = '/didcomm/connections', + CLOUD_WALLET_CREDENTIAL = '/didcomm/credentials', + CLOUD_WALLET_BASIC_MESSAGE = '/didcomm/basic-messages/', // Bulk-issuance BATCH_SIZE = 100, @@ -395,8 +393,8 @@ export enum CommonConstants { CLOUD_WALLET_SERVICE = 'cloud-wallet', //CLOUD WALLET - RECEIVE_INVITATION_BY_URL = '/multi-tenancy/receive-invitation-url/', - ACCEPT_OFFER = '/multi-tenancy/credentials/accept-offer/', + RECEIVE_INVITATION_BY_URL = '/didcomm/oob/receive-invitation-url', + ACCEPT_OFFER = '/didcomm/credentials/accept-offer', SEED_LENGTH = 32, //Agent URL flags diff --git a/libs/common/src/common.service.ts b/libs/common/src/common.service.ts index 327027046..364635720 100644 --- a/libs/common/src/common.service.ts +++ b/libs/common/src/common.service.ts @@ -359,7 +359,7 @@ export class CommonService { } } ); - if (200 !== agentBaseWalletDetils?.status) { + if (HttpStatus.OK !== agentBaseWalletDetils?.status) { throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); } return agentBaseWalletDetils.token; @@ -375,7 +375,7 @@ export class CommonService { } } ); - if (200 !== tenantWalletDetails?.status) { + if (HttpStatus.OK !== tenantWalletDetails?.status) { throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); } return tenantWalletDetails.token; diff --git a/libs/common/src/common.utils.ts b/libs/common/src/common.utils.ts index a34fc9be5..cfef3dc05 100644 --- a/libs/common/src/common.utils.ts +++ b/libs/common/src/common.utils.ts @@ -68,46 +68,39 @@ export const networkNamespace = (did: string): string => { }; export const getAgentUrl = async (agentEndPoint: string, urlFlag: string, paramId?: string): Promise => { - try { - if (!agentEndPoint) { - throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); - } - - const agentUrlMap: Map = new Map([ - [String(CommonConstants.CONNECTION_INVITATION), String(CommonConstants.URL_CONN_INVITE)], - [String(CommonConstants.LEGACY_INVITATION), String(CommonConstants.URL_CONN_LEGACY_INVITE)], - [String(CommonConstants.SIGN_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_SIGN_DATA)], - [String(CommonConstants.VERIFY_SIGNED_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_VERIFY_SIGNED_DATA)], - [String(CommonConstants.CREATE_OFFER), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], - [String(CommonConstants.CREATE_OFFER_OUT_OF_BAND), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], - [String(CommonConstants.GET_OFFER_BY_CRED_ID), String(CommonConstants.URL_ISSUE_GET_CREDS_BY_CRED_REC_ID)], - [ - String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID_FLAG), - String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID) - ], - [String(CommonConstants.REQUEST_PROOF), String(CommonConstants.URL_SEND_PROOF_REQUEST)], - [String(CommonConstants.ACCEPT_PRESENTATION), String(CommonConstants.URL_ACCEPT_PRESENTATION)], - [ - String(CommonConstants.CREATE_OUT_OF_BAND_PROOF_PRESENTATION), - String(CommonConstants.URL_CREATE_OUT_OF_BAND_CREATE_REQUEST) - ], - [String(CommonConstants.GET_VERIFIED_PROOF), String(CommonConstants.URL_PROOF_FORM_DATA)] - ]); - - const urlSuffix = agentUrlMap.get(urlFlag); + if (!agentEndPoint) { + throw new NotFoundException(ResponseMessages.common.error.invalidEndpoint); + } - if (!urlSuffix) { - throw new NotFoundException(ResponseMessages.common.error.invalidUrl); - } - // Add paramId as a path parameter if provided - const resolvedUrlPath = paramId ? urlSuffix.replace('#', paramId) : urlSuffix; + const agentUrlMap: Map = new Map([ + [String(CommonConstants.CONNECTION_INVITATION), String(CommonConstants.URL_CONN_INVITE)], + [String(CommonConstants.LEGACY_INVITATION), String(CommonConstants.URL_CONN_LEGACY_INVITE)], + [String(CommonConstants.SIGN_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_SIGN_DATA)], + [String(CommonConstants.VERIFY_SIGNED_DATA_FROM_AGENT), String(CommonConstants.URL_AGENT_VERIFY_SIGNED_DATA)], + [String(CommonConstants.CREATE_OFFER), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], + [String(CommonConstants.CREATE_OFFER_OUT_OF_BAND), String(CommonConstants.URL_ISSUANCE_CREATE_OFFER)], + [String(CommonConstants.GET_OFFER_BY_CRED_ID), String(CommonConstants.URL_ISSUE_GET_CREDS_BY_CRED_REC_ID)], + [ + String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID_FLAG), + String(CommonConstants.URL_GET_PROOF_PRESENTATION_BY_ID) + ], + [String(CommonConstants.REQUEST_PROOF), String(CommonConstants.URL_SEND_PROOF_REQUEST)], + [String(CommonConstants.ACCEPT_PRESENTATION), String(CommonConstants.URL_ACCEPT_PRESENTATION)], + [ + String(CommonConstants.CREATE_OUT_OF_BAND_PROOF_PRESENTATION), + String(CommonConstants.URL_CREATE_OUT_OF_BAND_CREATE_REQUEST) + ], + [String(CommonConstants.GET_VERIFIED_PROOF), String(CommonConstants.URL_PROOF_FORM_DATA)] + ]); - const url = `${agentEndPoint}${resolvedUrlPath}`; + const urlSuffix = agentUrlMap.get(urlFlag); - console.debug(`Generated agent URL: ${url}`); - return url; - } catch (error) { - console.error(`Error in getAgentUrl: ${error instanceof Error ? error.message : JSON.stringify(error)}`); - throw error; + if (!urlSuffix) { + throw new NotFoundException(ResponseMessages.common.error.invalidUrl); } + // Add paramId as a path parameter if provided + const resolvedUrlPath = paramId ? urlSuffix.replace('#', paramId) : urlSuffix; + + const url = `${agentEndPoint}${resolvedUrlPath}`; + return url; }; diff --git a/libs/common/src/response-messages/index.ts b/libs/common/src/response-messages/index.ts index ffff07d8f..04b7239e3 100644 --- a/libs/common/src/response-messages/index.ts +++ b/libs/common/src/response-messages/index.ts @@ -274,7 +274,7 @@ export const ResponseMessages = { requiredSeed: 'Seed is required', baseWalletToken: 'Error while fetching base wallet token', tenantWalletToken: 'Error while fetching tenant wallet token', - invalidTenantDetails: 'Invalid tenant details provided' + invalidTenantDetails: 'Invalid wallet details provided' } }, connection: { From ca4a01449b9d4634e21e4c7cfab61e447f220ef2 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 16:27:35 +0530 Subject: [PATCH 12/15] refactor: removed logs from shell scripts Signed-off-by: Tipu_Singh --- apps/agent-provisioning/AFJ/scripts/start_agent.sh | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/agent-provisioning/AFJ/scripts/start_agent.sh b/apps/agent-provisioning/AFJ/scripts/start_agent.sh index d8541b58a..e46a87073 100755 --- a/apps/agent-provisioning/AFJ/scripts/start_agent.sh +++ b/apps/agent-provisioning/AFJ/scripts/start_agent.sh @@ -116,11 +116,6 @@ fi echo "-----$AGENT_ENDPOINT----" CONFIG_FILE="${PWD}/apps/agent-provisioning/AFJ/agent-config/${AGENCY}_${CONTAINER_NAME}.json" -echo "CONFIG_FILE = $CONFIG_FILE" -echo "AGENCY = $AGENCY" -echo "CONTAINER_NAME = $CONTAINER_NAME" -echo "AGENT_API_KEY= $AGENT_API_KEY" - # Check if the file exists if [ -f "$CONFIG_FILE" ]; then # If it exists, remove the file From 104fdc7d40b63a27addd38de9e944e5c475a5ffe Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 20:16:14 +0530 Subject: [PATCH 13/15] refactor: resolve comment Signed-off-by: Tipu_Singh --- apps/agent-service/src/agent-service.service.ts | 3 +-- .../src/repositories/agent-service.repository.ts | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index cd4b7c0aa..bc8335b3f 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -80,7 +80,6 @@ import { NATSClient } from '@credebl/common/NATSClient'; import { SignDataDto } from '../../api-gateway/src/agent-service/dto/agent-service.dto'; import { IVerificationMethod } from 'apps/organization/interfaces/organization.interface'; import { getAgentUrl } from '@credebl/common/common.utils'; -import e = require('express'); @Injectable() @WebSocketGateway() export class AgentServiceService { @@ -1892,7 +1891,7 @@ export class AgentServiceService { orgId: orgAgentDetails.orgId }; const { apiKey } = await this.getTenantToken(walletDetails); - if (apiKey) { + if (!apiKey) { throw new NotFoundException(ResponseMessages.agent.error.tenantWalletToken, { cause: new Error(), description: ResponseMessages.errorMessages.notFound diff --git a/apps/agent-service/src/repositories/agent-service.repository.ts b/apps/agent-service/src/repositories/agent-service.repository.ts index 6069be0f0..f561694e5 100644 --- a/apps/agent-service/src/repositories/agent-service.repository.ts +++ b/apps/agent-service/src/repositories/agent-service.repository.ts @@ -1,6 +1,6 @@ -/* eslint-disable camelcase */ import { PrismaService } from '@credebl/prisma-service'; import { ConflictException, Injectable, Logger } from '@nestjs/common'; +/* eslint-disable camelcase */ import { Prisma, ledgerConfig, @@ -578,7 +578,7 @@ export class AgentServiceRepository { // eslint-disable-next-line camelcase async updateTenantToken(orgId: string, token: string): Promise { try { - return await this.prisma.org_agents.update({ + const updatedAgent = await this.prisma.org_agents.update({ where: { orgId }, @@ -586,6 +586,8 @@ export class AgentServiceRepository { apiKey: token } }); + + return updatedAgent; } catch (error) { this.logger.error(`[updateTenantToken] - Update tenant records details: ${JSON.stringify(error)}`); throw error; From 9c03260a99c1b1e41ec3ed6dc61b6207082eadf6 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 20:19:08 +0530 Subject: [PATCH 14/15] refactor: resolve comments for getOrgAgentApiKey Signed-off-by: Tipu_Singh --- apps/agent-service/src/agent-service.service.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index bc8335b3f..4799b5f02 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -1899,13 +1899,11 @@ export class AgentServiceService { } agentApiKey = apiKey; } else { + if (!orgAgentDetails?.apiKey) { + throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); + } agentApiKey = orgAgentDetails?.apiKey; } - - if (!agentApiKey) { - throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); - } - const decryptedToken = await this.commonService.decryptPassword(agentApiKey); return decryptedToken; } catch (error) { From 16cd22d3402f16a72c515b38e69dce67e570fb60 Mon Sep 17 00:00:00 2001 From: Tipu_Singh Date: Mon, 4 Aug 2025 23:42:54 +0530 Subject: [PATCH 15/15] refactor: agent service comments Signed-off-by: Tipu_Singh --- apps/agent-provisioning/src/agent-provisioning.service.ts | 1 - apps/agent-service/src/agent-service.service.ts | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/agent-provisioning/src/agent-provisioning.service.ts b/apps/agent-provisioning/src/agent-provisioning.service.ts index 99a1b92cd..f7d5f34c9 100644 --- a/apps/agent-provisioning/src/agent-provisioning.service.ts +++ b/apps/agent-provisioning/src/agent-provisioning.service.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-console */ import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { RpcException } from '@nestjs/microservices'; import { IWalletProvision } from './interface/agent-provisioning.interfaces'; diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 4799b5f02..648dfd947 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -621,8 +621,8 @@ export class AgentServiceService { private _buildStoreOrgAgentData(payload: IStoreOrgAgentDetails, orgAgentTypeId: string): IStoreOrgAgentDetails { return { - did: 'NA', - verkey: 'NA', + did: '', + verkey: '', isDidPublic: true, agentSpinUpStatus: AgentSpinUpStatus.COMPLETED, walletName: payload.walletName,