diff --git a/packages/action-menu/src/ActionMenuApi.ts b/packages/action-menu/src/ActionMenuApi.ts index e63ac1f563..0024aab32c 100644 --- a/packages/action-menu/src/ActionMenuApi.ts +++ b/packages/action-menu/src/ActionMenuApi.ts @@ -8,7 +8,7 @@ import type { import { AgentContext, - AriesFrameworkError, + CredoError, ConnectionService, MessageSender, injectable, @@ -118,7 +118,7 @@ export class ActionMenuApi { role: ActionMenuRole.Requester, }) if (!actionMenuRecord) { - throw new AriesFrameworkError(`No active menu found for connection id ${options.connectionId}`) + throw new CredoError(`No active menu found for connection id ${options.connectionId}`) } const { message, record } = await this.actionMenuService.createPerform(this.agentContext, { diff --git a/packages/action-menu/src/repository/ActionMenuRecord.ts b/packages/action-menu/src/repository/ActionMenuRecord.ts index a6afce3db7..dec713d894 100644 --- a/packages/action-menu/src/repository/ActionMenuRecord.ts +++ b/packages/action-menu/src/repository/ActionMenuRecord.ts @@ -2,7 +2,7 @@ import type { ActionMenuRole } from '../ActionMenuRole' import type { ActionMenuState } from '../ActionMenuState' import type { TagsBase } from '@credo-ts/core' -import { AriesFrameworkError, BaseRecord, utils } from '@credo-ts/core' +import { CredoError, BaseRecord, utils } from '@credo-ts/core' import { Type } from 'class-transformer' import { ActionMenuSelection, ActionMenu } from '../models' @@ -88,7 +88,7 @@ export class ActionMenuRecord } if (!expectedStates.includes(this.state)) { - throw new AriesFrameworkError( + throw new CredoError( `Action Menu record is in invalid state ${this.state}. Valid states are: ${expectedStates.join(', ')}.` ) } @@ -96,7 +96,7 @@ export class ActionMenuRecord public assertRole(expectedRole: ActionMenuRole) { if (this.role !== expectedRole) { - throw new AriesFrameworkError(`Action Menu record has invalid role ${this.role}. Expected role ${expectedRole}.`) + throw new CredoError(`Action Menu record has invalid role ${this.role}. Expected role ${expectedRole}.`) } } } diff --git a/packages/action-menu/src/services/ActionMenuService.ts b/packages/action-menu/src/services/ActionMenuService.ts index 032de6bb07..d3810a9d90 100644 --- a/packages/action-menu/src/services/ActionMenuService.ts +++ b/packages/action-menu/src/services/ActionMenuService.ts @@ -9,7 +9,7 @@ import type { ActionMenuStateChangedEvent } from '../ActionMenuEvents' import type { ActionMenuProblemReportMessage } from '../messages' import type { AgentContext, InboundMessageContext, Logger, Query } from '@credo-ts/core' -import { AgentConfig, EventEmitter, AriesFrameworkError, injectable } from '@credo-ts/core' +import { AgentConfig, EventEmitter, CredoError, injectable } from '@credo-ts/core' import { ActionMenuEventTypes } from '../ActionMenuEvents' import { ActionMenuRole } from '../ActionMenuRole' @@ -118,7 +118,7 @@ export class ActionMenuService { const uniqueNames = new Set(options.menu.options.map((v) => v.name)) if (uniqueNames.size < options.menu.options.length) { - throw new AriesFrameworkError('Action Menu contains duplicated options') + throw new CredoError('Action Menu contains duplicated options') } // Create message @@ -226,7 +226,7 @@ export class ActionMenuService { const validSelection = record.menu?.options.some((item) => item.name === performedSelection.name) if (!validSelection) { - throw new AriesFrameworkError('Selection does not match valid actions') + throw new CredoError('Selection does not match valid actions') } const previousState = record.state @@ -277,7 +277,7 @@ export class ActionMenuService { const validSelection = record.menu?.options.some((item) => item.name === performMessage.name) if (!validSelection) { - throw new AriesFrameworkError('Selection does not match valid actions') + throw new CredoError('Selection does not match valid actions') } const previousState = record.state @@ -289,7 +289,7 @@ export class ActionMenuService { this.emitStateChangedEvent(agentContext, record, previousState) } else { - throw new AriesFrameworkError(`No Action Menu found with thread id ${messageContext.message.threadId}`) + throw new CredoError(`No Action Menu found with thread id ${messageContext.message.threadId}`) } } @@ -325,9 +325,7 @@ export class ActionMenuService { }) if (!actionMenuRecord) { - throw new AriesFrameworkError( - `Unable to process action menu problem: record not found for connection id ${connection.id}` - ) + throw new CredoError(`Unable to process action menu problem: record not found for connection id ${connection.id}`) } // Clear menu to restart flow return await this.clearMenu(agentContext, { actionMenuRecord }) diff --git a/packages/anoncreds/src/anoncreds-rs/AnonCredsRsHolderService.ts b/packages/anoncreds/src/anoncreds-rs/AnonCredsRsHolderService.ts index e6de1f51f0..21cebf5ec3 100644 --- a/packages/anoncreds/src/anoncreds-rs/AnonCredsRsHolderService.ts +++ b/packages/anoncreds/src/anoncreds-rs/AnonCredsRsHolderService.ts @@ -29,7 +29,7 @@ import type { JsonObject, } from '@hyperledger/anoncreds-shared' -import { AriesFrameworkError, JsonTransformer, TypedArrayEncoder, injectable, utils } from '@credo-ts/core' +import { CredoError, JsonTransformer, TypedArrayEncoder, injectable, utils } from '@credo-ts/core' import { Credential, CredentialRequest, @@ -110,7 +110,7 @@ export class AnonCredsRsHolderService implements AnonCredsHolderService { // Extract revocation status list for the given timestamp const revocationStatusList = revocationStatusLists[timestamp] if (!revocationStatusList) { - throw new AriesFrameworkError( + throw new CredoError( `Revocation status list for revocation registry ${revocationRegistryDefinitionId} and timestamp ${timestamp} not found in revocation status lists. All revocation status lists must be present.` ) } @@ -219,7 +219,7 @@ export class AnonCredsRsHolderService implements AnonCredsHolderService { const isLegacyIdentifier = credentialOffer.cred_def_id.match(unqualifiedCredentialDefinitionIdRegex) if (!isLegacyIdentifier && useLegacyProverDid) { - throw new AriesFrameworkError('Cannot use legacy prover_did with non-legacy identifiers') + throw new CredoError('Cannot use legacy prover_did with non-legacy identifiers') } createReturnObj = CredentialRequest.create({ entropy: !useLegacyProverDid || !isLegacyIdentifier ? anoncreds.generateNonce() : undefined, diff --git a/packages/anoncreds/src/anoncreds-rs/AnonCredsRsIssuerService.ts b/packages/anoncreds/src/anoncreds-rs/AnonCredsRsIssuerService.ts index 9b76cfce70..207089ccfa 100644 --- a/packages/anoncreds/src/anoncreds-rs/AnonCredsRsIssuerService.ts +++ b/packages/anoncreds/src/anoncreds-rs/AnonCredsRsIssuerService.ts @@ -22,7 +22,7 @@ import type { import type { AgentContext } from '@credo-ts/core' import type { CredentialDefinitionPrivate, JsonObject, KeyCorrectnessProof } from '@hyperledger/anoncreds-shared' -import { injectable, AriesFrameworkError } from '@credo-ts/core' +import { injectable, CredoError } from '@credo-ts/core' import { RevocationStatusList, RevocationRegistryDefinitionPrivate, @@ -281,7 +281,7 @@ export class AnonCredsRsIssuerService implements AnonCredsIssuerService { revocationRegistryIndex, ].filter((e) => e !== undefined) if (definedRevocationOptions.length > 0 && definedRevocationOptions.length < 3) { - throw new AriesFrameworkError( + throw new CredoError( 'Revocation requires all of revocationRegistryDefinitionId, revocationRegistryIndex and revocationStatusList' ) } diff --git a/packages/anoncreds/src/error/AnonCredsError.ts b/packages/anoncreds/src/error/AnonCredsError.ts index 2ddd0a6b0e..d5b5f3ac80 100644 --- a/packages/anoncreds/src/error/AnonCredsError.ts +++ b/packages/anoncreds/src/error/AnonCredsError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' -export class AnonCredsError extends AriesFrameworkError { +export class AnonCredsError extends CredoError { public constructor(message: string, { cause }: { cause?: Error } = {}) { super(message, { cause }) } diff --git a/packages/anoncreds/src/formats/AnonCredsCredentialFormatService.ts b/packages/anoncreds/src/formats/AnonCredsCredentialFormatService.ts index a63a6bd0a2..e58f156279 100644 --- a/packages/anoncreds/src/formats/AnonCredsCredentialFormatService.ts +++ b/packages/anoncreds/src/formats/AnonCredsCredentialFormatService.ts @@ -33,7 +33,7 @@ import { ProblemReportError, MessageValidator, CredentialFormatSpec, - AriesFrameworkError, + CredoError, Attachment, JsonEncoder, utils, @@ -93,7 +93,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService const anoncredsFormat = credentialFormats.anoncreds if (!anoncredsFormat) { - throw new AriesFrameworkError('Missing anoncreds payload in createProposal') + throw new CredoError('Missing anoncreds payload in createProposal') } // We want all properties except for `attributes` and `linkedAttachments` attributes. @@ -105,9 +105,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService try { MessageValidator.validateSync(proposal) } catch (error) { - throw new AriesFrameworkError( - `Invalid proposal supplied: ${anoncredsCredentialProposal} in AnonCredsFormatService` - ) + throw new CredoError(`Invalid proposal supplied: ${anoncredsCredentialProposal} in AnonCredsFormatService`) } const attachment = this.getFormatData(JsonTransformer.toJSON(proposal), format.attachmentId) @@ -152,13 +150,11 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService const attributes = anoncredsFormat?.attributes ?? credentialRecord.credentialAttributes if (!credentialDefinitionId) { - throw new AriesFrameworkError( - 'No credential definition id in proposal or provided as input to accept proposal method.' - ) + throw new CredoError('No credential definition id in proposal or provided as input to accept proposal method.') } if (!attributes) { - throw new AriesFrameworkError('No attributes in proposal or provided as input to accept proposal method.') + throw new CredoError('No attributes in proposal or provided as input to accept proposal method.') } const { format, attachment, previewAttributes } = await this.createAnonCredsOffer(agentContext, { @@ -188,7 +184,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService const anoncredsFormat = credentialFormats.anoncreds if (!anoncredsFormat) { - throw new AriesFrameworkError('Missing anoncreds credential format data') + throw new CredoError('Missing anoncreds credential format data') } const { format, attachment, previewAttributes } = await this.createAnonCredsOffer(agentContext, { @@ -276,7 +272,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService * Starting from a request is not supported for anoncreds credentials, this method only throws an error. */ public async createRequest(): Promise { - throw new AriesFrameworkError('Starting from a request is not supported for anoncreds credentials') + throw new CredoError('Starting from a request is not supported for anoncreds credentials') } /** @@ -299,7 +295,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService // Assert credential attributes const credentialAttributes = credentialRecord.credentialAttributes if (!credentialAttributes) { - throw new AriesFrameworkError( + throw new CredoError( `Missing required credential attribute values on credential record with id ${credentialRecord.id}` ) } @@ -308,10 +304,10 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService agentContext.dependencyManager.resolve(AnonCredsIssuerServiceSymbol) const credentialOffer = offerAttachment?.getDataAsJson() - if (!credentialOffer) throw new AriesFrameworkError('Missing anoncreds credential offer in createCredential') + if (!credentialOffer) throw new CredoError('Missing anoncreds credential offer in createCredential') const credentialRequest = requestAttachment.getDataAsJson() - if (!credentialRequest) throw new AriesFrameworkError('Missing anoncreds credential request in createCredential') + if (!credentialRequest) throw new CredoError('Missing anoncreds credential request in createCredential') // We check locally for credential definition info. If it supports revocation, we need to search locally for // an active revocation registry @@ -334,7 +330,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService } if (!revocationRegistryDefinitionId || !revocationRegistryIndex) { - throw new AriesFrameworkError( + throw new CredoError( 'Revocation registry definition id and revocation index are mandatory to issue AnonCreds revocable credentials' ) } @@ -343,7 +339,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService .getByRevocationRegistryDefinitionId(agentContext, revocationRegistryDefinitionId) if (revocationRegistryDefinitionPrivateRecord.state !== AnonCredsRevocationRegistryState.Active) { - throw new AriesFrameworkError( + throw new CredoError( `Revocation registry ${revocationRegistryDefinitionId} is in ${revocationRegistryDefinitionPrivateRecord.state} state` ) } @@ -354,7 +350,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService .getRevocationStatusList(agentContext, revocationRegistryDefinitionId, dateToTimestamp(new Date())) if (!revocationStatusListResult.revocationStatusList) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve revocation status list for ${revocationRegistryDefinitionId}: ${revocationStatusListResult.resolutionMetadata.error} ${revocationStatusListResult.resolutionMetadata.message}` ) @@ -399,15 +395,13 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService agentContext.dependencyManager.resolve(AnonCredsHolderServiceSymbol) if (!credentialRequestMetadata) { - throw new AriesFrameworkError( + throw new CredoError( `Missing required request metadata for credential exchange with thread id with id ${credentialRecord.id}` ) } if (!credentialRecord.credentialAttributes) { - throw new AriesFrameworkError( - 'Missing credential attributes on credential record. Unable to check credential attributes' - ) + throw new CredoError('Missing credential attributes on credential record. Unable to check credential attributes') } const anonCredsCredential = attachment.getDataAsJson() @@ -416,7 +410,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService .getRegistryForIdentifier(agentContext, anonCredsCredential.cred_def_id) .getCredentialDefinition(agentContext, anonCredsCredential.cred_def_id) if (!credentialDefinitionResult.credentialDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve credential definition ${anonCredsCredential.cred_def_id}: ${credentialDefinitionResult.resolutionMetadata.error} ${credentialDefinitionResult.resolutionMetadata.message}` ) } @@ -425,7 +419,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService .getRegistryForIdentifier(agentContext, anonCredsCredential.cred_def_id) .getSchema(agentContext, anonCredsCredential.schema_id) if (!schemaResult.schema) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve schema ${anonCredsCredential.schema_id}: ${schemaResult.resolutionMetadata.error} ${schemaResult.resolutionMetadata.message}` ) } @@ -438,7 +432,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService .getRevocationRegistryDefinition(agentContext, anonCredsCredential.rev_reg_id) if (!revocationRegistryResult.revocationRegistryDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve revocation registry definition ${anonCredsCredential.rev_reg_id}: ${revocationRegistryResult.resolutionMetadata.error} ${revocationRegistryResult.resolutionMetadata.message}` ) } @@ -605,7 +599,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService const { previewAttributes } = this.getCredentialLinkedAttachments(attributes, linkedAttachments) if (!previewAttributes) { - throw new AriesFrameworkError('Missing required preview attributes for anoncreds offer') + throw new CredoError('Missing required preview attributes for anoncreds offer') } await this.assertPreviewAttributesMatchSchemaAttributes(agentContext, offer, previewAttributes) @@ -620,7 +614,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService if (credentialDefinition.revocation) { if (!revocationRegistryDefinitionId || !revocationRegistryIndex) { - throw new AriesFrameworkError( + throw new CredoError( 'AnonCreds revocable credentials require revocationRegistryDefinitionId and revocationRegistryIndex' ) } @@ -656,7 +650,7 @@ export class AnonCredsCredentialFormatService implements CredentialFormatService const schemaResult = await registry.getSchema(agentContext, offer.schema_id) if (!schemaResult.schema) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve schema ${offer.schema_id} from registry: ${schemaResult.resolutionMetadata.error} ${schemaResult.resolutionMetadata.message}` ) } diff --git a/packages/anoncreds/src/formats/AnonCredsProofFormatService.ts b/packages/anoncreds/src/formats/AnonCredsProofFormatService.ts index 044fa339e4..4a324e26c5 100644 --- a/packages/anoncreds/src/formats/AnonCredsProofFormatService.ts +++ b/packages/anoncreds/src/formats/AnonCredsProofFormatService.ts @@ -35,14 +35,7 @@ import type { ProofFormatAutoRespondPresentationOptions, } from '@credo-ts/core' -import { - AriesFrameworkError, - Attachment, - AttachmentData, - JsonEncoder, - ProofFormatSpec, - JsonTransformer, -} from '@credo-ts/core' +import { CredoError, Attachment, AttachmentData, JsonEncoder, ProofFormatSpec, JsonTransformer } from '@credo-ts/core' import { AnonCredsProofRequest as AnonCredsProofRequestClass } from '../models/AnonCredsProofRequest' import { AnonCredsVerifierServiceSymbol, AnonCredsHolderServiceSymbol } from '../services' @@ -211,7 +204,7 @@ export class AnonCredsProofFormatService implements ProofFormatService { if (credentialsForRequest.predicates[attributeName].length === 0) { - throw new AriesFrameworkError('Unable to automatically select requested predicates.') + throw new CredoError('Unable to automatically select requested predicates.') } else { selectedCredentials.predicates[attributeName] = credentialsForRequest.predicates[attributeName][0] } @@ -468,7 +461,7 @@ export class AnonCredsProofFormatService implements ProofFormatService() if (!isUnqualifiedCredentialDefinitionId(credentialOffer.cred_def_id)) { - throw new AriesFrameworkError( - `${credentialOffer.cred_def_id} is not a valid legacy indy credential definition id` - ) + throw new CredoError(`${credentialOffer.cred_def_id} is not a valid legacy indy credential definition id`) } // Get credential definition const registry = registryService.getRegistryForIdentifier(agentContext, credentialOffer.cred_def_id) @@ -284,7 +280,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic * Starting from a request is not supported for indy credentials, this method only throws an error. */ public async createRequest(): Promise { - throw new AriesFrameworkError('Starting from a request is not supported for indy credentials') + throw new CredoError('Starting from a request is not supported for indy credentials') } /** @@ -307,7 +303,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic // Assert credential attributes const credentialAttributes = credentialRecord.credentialAttributes if (!credentialAttributes) { - throw new AriesFrameworkError( + throw new CredoError( `Missing required credential attribute values on credential record with id ${credentialRecord.id}` ) } @@ -316,10 +312,10 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic agentContext.dependencyManager.resolve(AnonCredsIssuerServiceSymbol) const credentialOffer = offerAttachment?.getDataAsJson() - if (!credentialOffer) throw new AriesFrameworkError('Missing indy credential offer in createCredential') + if (!credentialOffer) throw new CredoError('Missing indy credential offer in createCredential') const credentialRequest = requestAttachment.getDataAsJson() - if (!credentialRequest) throw new AriesFrameworkError('Missing indy credential request in createCredential') + if (!credentialRequest) throw new CredoError('Missing indy credential request in createCredential') const { credential, credentialRevocationId } = await anonCredsIssuerService.createCredential(agentContext, { credentialOffer, @@ -365,15 +361,13 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic agentContext.dependencyManager.resolve(AnonCredsHolderServiceSymbol) if (!credentialRequestMetadata) { - throw new AriesFrameworkError( + throw new CredoError( `Missing required request metadata for credential exchange with thread id with id ${credentialRecord.id}` ) } if (!credentialRecord.credentialAttributes) { - throw new AriesFrameworkError( - 'Missing credential attributes on credential record. Unable to check credential attributes' - ) + throw new CredoError('Missing credential attributes on credential record. Unable to check credential attributes') } const anonCredsCredential = attachment.getDataAsJson() @@ -382,7 +376,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic .getRegistryForIdentifier(agentContext, anonCredsCredential.cred_def_id) .getCredentialDefinition(agentContext, anonCredsCredential.cred_def_id) if (!credentialDefinitionResult.credentialDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve credential definition ${anonCredsCredential.cred_def_id}: ${credentialDefinitionResult.resolutionMetadata.error} ${credentialDefinitionResult.resolutionMetadata.message}` ) } @@ -391,7 +385,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic .getRegistryForIdentifier(agentContext, anonCredsCredential.cred_def_id) .getSchema(agentContext, anonCredsCredential.schema_id) if (!schemaResult.schema) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve schema ${anonCredsCredential.schema_id}: ${schemaResult.resolutionMetadata.error} ${schemaResult.resolutionMetadata.message}` ) } @@ -404,7 +398,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic .getRevocationRegistryDefinition(agentContext, anonCredsCredential.rev_reg_id) if (!revocationRegistryResult.revocationRegistryDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve revocation registry definition ${anonCredsCredential.rev_reg_id}: ${revocationRegistryResult.resolutionMetadata.error} ${revocationRegistryResult.resolutionMetadata.message}` ) } @@ -562,7 +556,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic const { previewAttributes } = this.getCredentialLinkedAttachments(attributes, linkedAttachments) if (!previewAttributes) { - throw new AriesFrameworkError('Missing required preview attributes for indy offer') + throw new CredoError('Missing required preview attributes for indy offer') } await this.assertPreviewAttributesMatchSchemaAttributes(agentContext, offer, previewAttributes) @@ -588,7 +582,7 @@ export class LegacyIndyCredentialFormatService implements CredentialFormatServic const schemaResult = await registry.getSchema(agentContext, offer.schema_id) if (!schemaResult.schema) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to resolve schema ${offer.schema_id} from registry: ${schemaResult.resolutionMetadata.error} ${schemaResult.resolutionMetadata.message}` ) } diff --git a/packages/anoncreds/src/formats/LegacyIndyProofFormatService.ts b/packages/anoncreds/src/formats/LegacyIndyProofFormatService.ts index 9b81f75c14..ce7a90ec2d 100644 --- a/packages/anoncreds/src/formats/LegacyIndyProofFormatService.ts +++ b/packages/anoncreds/src/formats/LegacyIndyProofFormatService.ts @@ -35,14 +35,7 @@ import type { ProofFormatAutoRespondPresentationOptions, } from '@credo-ts/core' -import { - AriesFrameworkError, - Attachment, - AttachmentData, - JsonEncoder, - ProofFormatSpec, - JsonTransformer, -} from '@credo-ts/core' +import { CredoError, Attachment, AttachmentData, JsonEncoder, ProofFormatSpec, JsonTransformer } from '@credo-ts/core' import { AnonCredsProofRequest as AnonCredsProofRequestClass } from '../models/AnonCredsProofRequest' import { AnonCredsVerifierServiceSymbol, AnonCredsHolderServiceSymbol } from '../services' @@ -211,7 +204,7 @@ export class LegacyIndyProofFormatService implements ProofFormatService { if (credentialsForRequest.predicates[attributeName].length === 0) { - throw new AriesFrameworkError('Unable to automatically select requested predicates.') + throw new CredoError('Unable to automatically select requested predicates.') } else { selectedCredentials.predicates[attributeName] = credentialsForRequest.predicates[attributeName][0] } @@ -469,14 +462,14 @@ export class LegacyIndyProofFormatService implements ProofFormatService > { - throw new AriesFrameworkError('Starting from a request is not supported for v1 issue credential protocol') + throw new CredoError('Starting from a request is not supported for v1 issue credential protocol') } public async processRequest( @@ -764,7 +760,7 @@ export class V1CredentialProtocol const requestAttachment = requestMessage.getRequestAttachmentById(INDY_CREDENTIAL_REQUEST_ATTACHMENT_ID) if (!requestAttachment) { - throw new AriesFrameworkError( + throw new CredoError( `Indy attachment with id ${INDY_CREDENTIAL_REQUEST_ATTACHMENT_ID} not found in request message` ) } @@ -820,7 +816,7 @@ export class V1CredentialProtocol const requestAttachment = requestMessage.getRequestAttachmentById(INDY_CREDENTIAL_REQUEST_ATTACHMENT_ID) if (!offerAttachment || !requestAttachment) { - throw new AriesFrameworkError( + throw new CredoError( `Missing data payload in offer or request attachment in credential Record ${credentialRecord.id}` ) } @@ -899,12 +895,12 @@ export class V1CredentialProtocol const issueAttachment = issueMessage.getCredentialAttachmentById(INDY_CREDENTIAL_ATTACHMENT_ID) if (!issueAttachment) { - throw new AriesFrameworkError('Missing indy credential attachment in processCredential') + throw new CredoError('Missing indy credential attachment in processCredential') } const requestAttachment = requestCredentialMessage?.getRequestAttachmentById(INDY_CREDENTIAL_REQUEST_ATTACHMENT_ID) if (!requestAttachment) { - throw new AriesFrameworkError('Missing indy credential request attachment in processCredential') + throw new CredoError('Missing indy credential request attachment in processCredential') } await this.indyCredentialFormat.processCredential(messageContext.agentContext, { @@ -1280,13 +1276,13 @@ export class V1CredentialProtocol if (formatKeys.length === 0) return if (formatKeys.length !== 1 || !formatKeys.includes('indy')) { - throw new AriesFrameworkError('Only indy credential format is supported for issue credential v1 protocol') + throw new CredoError('Only indy credential format is supported for issue credential v1 protocol') } } public getFormatServiceForRecordType(credentialRecordType: string) { if (credentialRecordType !== this.indyCredentialFormat.credentialRecordType) { - throw new AriesFrameworkError( + throw new CredoError( `Unsupported credential record type ${credentialRecordType} for v1 issue credential protocol (need ${this.indyCredentialFormat.credentialRecordType})` ) } diff --git a/packages/anoncreds/src/protocols/credentials/v1/__tests__/V1CredentialProtocolCred.test.ts b/packages/anoncreds/src/protocols/credentials/v1/__tests__/V1CredentialProtocolCred.test.ts index 22fd5f16bd..4c9b999d35 100644 --- a/packages/anoncreds/src/protocols/credentials/v1/__tests__/V1CredentialProtocolCred.test.ts +++ b/packages/anoncreds/src/protocols/credentials/v1/__tests__/V1CredentialProtocolCred.test.ts @@ -14,7 +14,7 @@ import { JsonEncoder, DidCommMessageRecord, DidCommMessageRole, - AriesFrameworkError, + CredoError, CredentialState, CredentialExchangeRecord, CredentialFormatSpec, @@ -145,7 +145,7 @@ const getAgentMessageMock = async (agentContext: AgentContext, options: { messag return credentialIssueMessage } - throw new AriesFrameworkError('Could not find message') + throw new CredoError('Could not find message') } // A record is deserialized to JSON when it's stored into the storage. We want to simulate this behaviour for `offer` diff --git a/packages/anoncreds/src/protocols/credentials/v1/handlers/V1IssueCredentialHandler.ts b/packages/anoncreds/src/protocols/credentials/v1/handlers/V1IssueCredentialHandler.ts index 4e9a5b73f7..9f674b6841 100644 --- a/packages/anoncreds/src/protocols/credentials/v1/handlers/V1IssueCredentialHandler.ts +++ b/packages/anoncreds/src/protocols/credentials/v1/handlers/V1IssueCredentialHandler.ts @@ -1,7 +1,7 @@ import type { V1CredentialProtocol } from '../V1CredentialProtocol' import type { MessageHandler, MessageHandlerInboundMessage, CredentialExchangeRecord } from '@credo-ts/core' -import { AriesFrameworkError, getOutboundMessageContext } from '@credo-ts/core' +import { CredoError, getOutboundMessageContext } from '@credo-ts/core' import { V1IssueCredentialMessage } from '../messages' @@ -41,7 +41,7 @@ export class V1IssueCredentialHandler implements MessageHandler { credentialRecord.id ) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No request message found for credential record with id '${credentialRecord.id}'`) } return getOutboundMessageContext(messageContext.agentContext, { diff --git a/packages/anoncreds/src/protocols/credentials/v1/handlers/V1RequestCredentialHandler.ts b/packages/anoncreds/src/protocols/credentials/v1/handlers/V1RequestCredentialHandler.ts index d48b8710fd..807438438a 100644 --- a/packages/anoncreds/src/protocols/credentials/v1/handlers/V1RequestCredentialHandler.ts +++ b/packages/anoncreds/src/protocols/credentials/v1/handlers/V1RequestCredentialHandler.ts @@ -1,7 +1,7 @@ import type { V1CredentialProtocol } from '../V1CredentialProtocol' import type { CredentialExchangeRecord, MessageHandler, MessageHandlerInboundMessage } from '@credo-ts/core' -import { AriesFrameworkError, getOutboundMessageContext } from '@credo-ts/core' +import { CredoError, getOutboundMessageContext } from '@credo-ts/core' import { V1RequestCredentialMessage } from '../messages' @@ -37,7 +37,7 @@ export class V1RequestCredentialHandler implements MessageHandler { credentialRecord.id ) if (!offerMessage) { - throw new AriesFrameworkError(`Could not find offer message for credential record with id ${credentialRecord.id}`) + throw new CredoError(`Could not find offer message for credential record with id ${credentialRecord.id}`) } const { message } = await this.credentialProtocol.acceptRequest(messageContext.agentContext, { diff --git a/packages/anoncreds/src/protocols/proofs/v1/V1ProofProtocol.ts b/packages/anoncreds/src/protocols/proofs/v1/V1ProofProtocol.ts index 10a1fadc6e..1c31f4f915 100644 --- a/packages/anoncreds/src/protocols/proofs/v1/V1ProofProtocol.ts +++ b/packages/anoncreds/src/protocols/proofs/v1/V1ProofProtocol.ts @@ -17,7 +17,7 @@ import { Protocol, ProofRepository, DidCommMessageRepository, - AriesFrameworkError, + CredoError, MessageValidator, ProofExchangeRecord, ProofState, @@ -111,7 +111,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const didCommMessageRepository = agentContext.dependencyManager.resolve(DidCommMessageRepository) if (!proofFormats.indy) { - throw new AriesFrameworkError('Missing indy proof format in v1 create proposal call.') + throw new CredoError('Missing indy proof format in v1 create proposal call.') } const presentationProposal = new V1PresentationPreview({ @@ -357,7 +357,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const didCommMessageRepository = agentContext.dependencyManager.resolve(DidCommMessageRepository) if (!proofFormats.indy) { - throw new AriesFrameworkError('Missing indy proof request data for v1 create request') + throw new CredoError('Missing indy proof request data for v1 create request') } // Create record @@ -419,9 +419,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const requestAttachment = proofRequestMessage.getRequestAttachmentById(INDY_PROOF_REQUEST_ATTACHMENT_ID) if (!requestAttachment) { - throw new AriesFrameworkError( - `Indy attachment with id ${INDY_PROOF_REQUEST_ATTACHMENT_ID} not found in request message` - ) + throw new CredoError(`Indy attachment with id ${INDY_PROOF_REQUEST_ATTACHMENT_ID} not found in request message`) } // proof record already exists, this means we are the message is sent as reply to a proposal we sent @@ -503,13 +501,13 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const didCommMessageRepository = agentContext.dependencyManager.resolve(DidCommMessageRepository) if (!proofRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connectionId found for proof record '${proofRecord.id}'. Connection-less verification does not support negotiation.` ) } if (!proofFormats.indy) { - throw new AriesFrameworkError('Missing indy proof format in v1 negotiate request call.') + throw new CredoError('Missing indy proof format in v1 negotiate request call.') } const presentationProposal = new V1PresentationPreview({ @@ -638,7 +636,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const indyProofRequest = requestMessage.indyProofRequest if (!requestAttachment || !indyProofRequest) { - throw new AriesFrameworkError( + throw new CredoError( `Missing indy attachment in request message for presentation with thread id ${proofRecord.threadId}` ) } @@ -698,7 +696,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< const indyProofRequest = requestMessage.indyProofRequest if (!requestAttachment || !indyProofRequest) { - throw new AriesFrameworkError( + throw new CredoError( `Missing indy attachment in request message for presentation with thread id ${proofRecord.threadId}` ) } @@ -1153,7 +1151,7 @@ export class V1ProofProtocol extends BaseProofProtocol implements ProofProtocol< if (formatKeys.length === 0) return if (formatKeys.length !== 1 || !formatKeys.includes('indy')) { - throw new AriesFrameworkError('Only indy proof format is supported for present proof v1 protocol') + throw new CredoError('Only indy proof format is supported for present proof v1 protocol') } } } diff --git a/packages/anoncreds/src/protocols/proofs/v1/handlers/V1PresentationHandler.ts b/packages/anoncreds/src/protocols/proofs/v1/handlers/V1PresentationHandler.ts index 70636b2a46..33c270f76c 100644 --- a/packages/anoncreds/src/protocols/proofs/v1/handlers/V1PresentationHandler.ts +++ b/packages/anoncreds/src/protocols/proofs/v1/handlers/V1PresentationHandler.ts @@ -1,7 +1,7 @@ import type { V1ProofProtocol } from '../V1ProofProtocol' import type { MessageHandler, MessageHandlerInboundMessage, ProofExchangeRecord } from '@credo-ts/core' -import { AriesFrameworkError, getOutboundMessageContext } from '@credo-ts/core' +import { CredoError, getOutboundMessageContext } from '@credo-ts/core' import { V1PresentationMessage } from '../messages' @@ -34,7 +34,7 @@ export class V1PresentationHandler implements MessageHandler { const requestMessage = await this.proofProtocol.findRequestMessage(messageContext.agentContext, proofRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for proof record with id '${proofRecord.id}'`) + throw new CredoError(`No request message found for proof record with id '${proofRecord.id}'`) } const { message } = await this.proofProtocol.acceptPresentation(messageContext.agentContext, { diff --git a/packages/anoncreds/src/services/tails/BasicTailsFileService.ts b/packages/anoncreds/src/services/tails/BasicTailsFileService.ts index 9454bb5a69..a184c5827c 100644 --- a/packages/anoncreds/src/services/tails/BasicTailsFileService.ts +++ b/packages/anoncreds/src/services/tails/BasicTailsFileService.ts @@ -2,7 +2,7 @@ import type { TailsFileService } from './TailsFileService' import type { AnonCredsRevocationRegistryDefinition } from '../../models' import type { AgentContext, FileSystem } from '@credo-ts/core' -import { AriesFrameworkError, InjectionSymbols, TypedArrayEncoder } from '@credo-ts/core' +import { CredoError, InjectionSymbols, TypedArrayEncoder } from '@credo-ts/core' export class BasicTailsFileService implements TailsFileService { private tailsDirectoryPath?: string @@ -28,7 +28,7 @@ export class BasicTailsFileService implements TailsFileService { revocationRegistryDefinition: AnonCredsRevocationRegistryDefinition } ): Promise<{ tailsFileUrl: string }> { - throw new AriesFrameworkError('BasicTailsFileService only supports tails file downloading') + throw new CredoError('BasicTailsFileService only supports tails file downloading') } public async getTailsFile( diff --git a/packages/anoncreds/src/updates/0.3.1-0.4/credentialDefinition.ts b/packages/anoncreds/src/updates/0.3.1-0.4/credentialDefinition.ts index 8eb57410ed..1efaa05cae 100644 --- a/packages/anoncreds/src/updates/0.3.1-0.4/credentialDefinition.ts +++ b/packages/anoncreds/src/updates/0.3.1-0.4/credentialDefinition.ts @@ -1,7 +1,7 @@ import type { AnonCredsCredentialDefinition } from '../../models' import type { BaseAgent } from '@credo-ts/core' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' import { AnonCredsCredentialDefinitionRepository } from '../../repository' import { AnonCredsRegistryService } from '../../services/registry/AnonCredsRegistryService' @@ -52,7 +52,7 @@ export async function migrateAnonCredsCredentialDefinitionRecordToV0_4 typeof value === 'string' @@ -162,7 +162,7 @@ export function assertAttributesMatch(schema: AnonCredsSchema, attributes: Crede .concat(schemaAttributes.filter((x) => !credAttributes.includes(x))) if (difference.length > 0) { - throw new AriesFrameworkError( + throw new CredoError( `The credential preview attributes do not match the schema attributes (difference is: ${difference}, needs: ${schemaAttributes})` ) } @@ -185,7 +185,7 @@ export function createAndLinkAttachmentsToPreview( attachments.forEach((linkedAttachment) => { if (credentialPreviewAttributeNames.includes(linkedAttachment.attributeName)) { - throw new AriesFrameworkError(`linkedAttachment ${linkedAttachment.attributeName} already exists in the preview`) + throw new CredoError(`linkedAttachment ${linkedAttachment.attributeName} already exists in the preview`) } else { newPreviewAttributes.push({ name: linkedAttachment.attributeName, diff --git a/packages/anoncreds/src/utils/getRevocationRegistries.ts b/packages/anoncreds/src/utils/getRevocationRegistries.ts index c23d662ce7..699a98070e 100644 --- a/packages/anoncreds/src/utils/getRevocationRegistries.ts +++ b/packages/anoncreds/src/utils/getRevocationRegistries.ts @@ -2,7 +2,7 @@ import type { AnonCredsProof, AnonCredsProofRequest, AnonCredsSelectedCredential import type { CreateProofOptions, VerifyProofOptions } from '../services' import type { AgentContext } from '@credo-ts/core' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' import { AnonCredsModuleConfig } from '../AnonCredsModuleConfig' import { AnonCredsRegistryService } from '../services' @@ -48,7 +48,7 @@ export async function getRevocationRegistriesForRequest( const revocationRegistryPromises = [] for (const { referent, selectedCredential, nonRevoked, type } of referentCredentials) { if (!selectedCredential.credentialInfo) { - throw new AriesFrameworkError( + throw new CredoError( `Credential for referent '${referent} does not have credential info for revocation state creation` ) } @@ -85,7 +85,7 @@ export async function getRevocationRegistriesForRequest( revocationRegistryId ) if (!revocationRegistryDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Could not retrieve revocation registry definition for revocation registry ${revocationRegistryId}: ${resolutionMetadata.message}` ) } @@ -112,7 +112,7 @@ export async function getRevocationRegistriesForRequest( await registry.getRevocationStatusList(agentContext, revocationRegistryId, timestampToFetch) if (!revocationStatusList) { - throw new AriesFrameworkError( + throw new CredoError( `Could not retrieve revocation status list for revocation registry ${revocationRegistryId}: ${statusListResolutionMetadata.message}` ) } @@ -180,7 +180,7 @@ export async function getRevocationRegistriesForProof(agentContext: AgentContext revocationRegistryId ) if (!revocationRegistryDefinition) { - throw new AriesFrameworkError( + throw new CredoError( `Could not retrieve revocation registry definition for revocation registry ${revocationRegistryId}: ${resolutionMetadata.message}` ) } @@ -197,7 +197,7 @@ export async function getRevocationRegistriesForProof(agentContext: AgentContext await registry.getRevocationStatusList(agentContext, revocationRegistryId, timestamp) if (!revocationStatusList) { - throw new AriesFrameworkError( + throw new CredoError( `Could not retrieve revocation status list for revocation registry ${revocationRegistryId}: ${statusListResolutionMetadata.message}` ) } diff --git a/packages/anoncreds/src/utils/hasDuplicateGroupNames.ts b/packages/anoncreds/src/utils/hasDuplicateGroupNames.ts index b1ccbf980c..8f1faf3549 100644 --- a/packages/anoncreds/src/utils/hasDuplicateGroupNames.ts +++ b/packages/anoncreds/src/utils/hasDuplicateGroupNames.ts @@ -1,6 +1,6 @@ import type { AnonCredsProofRequest } from '../models' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' function attributeNamesToArray(proofRequest: AnonCredsProofRequest) { // Attributes can contain either a `name` string value or an `names` string array. We reduce it to a single array @@ -22,8 +22,6 @@ export function assertNoDuplicateGroupsNamesInProofRequest(proofRequest: AnonCre const duplicates = predicates.filter((item) => attributes.indexOf(item) !== -1) if (duplicates.length > 0) { - throw new AriesFrameworkError( - `The proof request contains duplicate predicates and attributes: ${duplicates.toString()}` - ) + throw new CredoError(`The proof request contains duplicate predicates and attributes: ${duplicates.toString()}`) } } diff --git a/packages/anoncreds/src/utils/indyIdentifiers.ts b/packages/anoncreds/src/utils/indyIdentifiers.ts index 81cedef911..f18e558447 100644 --- a/packages/anoncreds/src/utils/indyIdentifiers.ts +++ b/packages/anoncreds/src/utils/indyIdentifiers.ts @@ -1,4 +1,4 @@ -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' const didIndyAnonCredsBase = /(did:indy:((?:[a-z][_a-z0-9-]*)(?::[a-z][_a-z0-9-]*)?):([1-9A-HJ-NP-Za-km-z]{21,22}))\/anoncreds\/v0/ @@ -80,7 +80,7 @@ export function parseIndyDid(did: string) { const [, namespace, namespaceIdentifier] = match return { namespace, namespaceIdentifier } } else { - throw new AriesFrameworkError(`${did} is not a valid did:indy did`) + throw new CredoError(`${did} is not a valid did:indy did`) } } diff --git a/packages/anoncreds/src/utils/revocationInterval.ts b/packages/anoncreds/src/utils/revocationInterval.ts index c6034a3f0b..fdf1036157 100644 --- a/packages/anoncreds/src/utils/revocationInterval.ts +++ b/packages/anoncreds/src/utils/revocationInterval.ts @@ -1,6 +1,6 @@ import type { AnonCredsNonRevokedInterval } from '../models' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' // This sets the `to` value to be required. We do this check in the `assertBestPracticeRevocationInterval` method, // and it makes it easier to work with the object in TS @@ -14,11 +14,11 @@ export function assertBestPracticeRevocationInterval( revocationInterval: AnonCredsNonRevokedInterval ): asserts revocationInterval is BestPracticeNonRevokedInterval { if (!revocationInterval.to) { - throw new AriesFrameworkError(`Presentation requests proof of non-revocation with no 'to' value specified`) + throw new CredoError(`Presentation requests proof of non-revocation with no 'to' value specified`) } if ((revocationInterval.from || revocationInterval.from === 0) && revocationInterval.to !== revocationInterval.from) { - throw new AriesFrameworkError( + throw new CredoError( `Presentation requests proof of non-revocation with an interval from: '${revocationInterval.from}' that does not match the interval to: '${revocationInterval.to}', as specified in Aries RFC 0441` ) } diff --git a/packages/anoncreds/tests/anoncredsSetup.ts b/packages/anoncreds/tests/anoncredsSetup.ts index e59a8be7e5..cb4fad2a34 100644 --- a/packages/anoncreds/tests/anoncredsSetup.ts +++ b/packages/anoncreds/tests/anoncredsSetup.ts @@ -20,7 +20,7 @@ import { CacheModule, InMemoryLruCache, Agent, - AriesFrameworkError, + CredoError, AutoAcceptCredential, CredentialEventTypes, CredentialsModule, @@ -489,9 +489,7 @@ async function registerSchema( testLogger.test(`created schema with id ${schemaState.schemaId}`, schema) if (schemaState.state !== 'finished') { - throw new AriesFrameworkError( - `Schema not created: ${schemaState.state === 'failed' ? schemaState.reason : 'Not finished'}` - ) + throw new CredoError(`Schema not created: ${schemaState.state === 'failed' ? schemaState.reason : 'Not finished'}`) } return schemaState @@ -510,7 +508,7 @@ async function registerCredentialDefinition( }) if (credentialDefinitionState.state !== 'finished') { - throw new AriesFrameworkError( + throw new CredoError( `Credential definition not created: ${ credentialDefinitionState.state === 'failed' ? credentialDefinitionState.reason : 'Not finished' }` @@ -530,7 +528,7 @@ async function registerRevocationRegistryDefinition( }) if (revocationRegistryDefinitionState.state !== 'finished') { - throw new AriesFrameworkError( + throw new CredoError( `Revocation registry definition not created: ${ revocationRegistryDefinitionState.state === 'failed' ? revocationRegistryDefinitionState.reason : 'Not finished' }` @@ -550,7 +548,7 @@ async function registerRevocationStatusList( }) if (revocationStatusListState.state !== 'finished') { - throw new AriesFrameworkError( + throw new CredoError( `Revocation status list not created: ${ revocationStatusListState.state === 'failed' ? revocationStatusListState.reason : 'Not finished' }` diff --git a/packages/anoncreds/tests/legacyAnonCredsSetup.ts b/packages/anoncreds/tests/legacyAnonCredsSetup.ts index 28303b83ae..53c0b2e6d0 100644 --- a/packages/anoncreds/tests/legacyAnonCredsSetup.ts +++ b/packages/anoncreds/tests/legacyAnonCredsSetup.ts @@ -16,7 +16,7 @@ import { CacheModule, InMemoryLruCache, Agent, - AriesFrameworkError, + CredoError, AutoAcceptCredential, CredentialEventTypes, CredentialsModule, @@ -451,9 +451,7 @@ async function registerSchema( testLogger.test(`created schema with id ${schemaState.schemaId}`, schema) if (schemaState.state !== 'finished') { - throw new AriesFrameworkError( - `Schema not created: ${schemaState.state === 'failed' ? schemaState.reason : 'Not finished'}` - ) + throw new CredoError(`Schema not created: ${schemaState.state === 'failed' ? schemaState.reason : 'Not finished'}`) } return schemaState @@ -472,7 +470,7 @@ async function registerCredentialDefinition( }) if (credentialDefinitionState.state !== 'finished') { - throw new AriesFrameworkError( + throw new CredoError( `Credential definition not created: ${ credentialDefinitionState.state === 'failed' ? credentialDefinitionState.reason : 'Not finished' }` diff --git a/packages/askar/src/AskarModule.ts b/packages/askar/src/AskarModule.ts index 561e0c2f85..c59450e122 100644 --- a/packages/askar/src/AskarModule.ts +++ b/packages/askar/src/AskarModule.ts @@ -1,7 +1,7 @@ import type { AskarModuleConfigOptions } from './AskarModuleConfig' import type { AgentContext, DependencyManager, Module } from '@credo-ts/core' -import { AgentConfig, AriesFrameworkError, InjectionSymbols } from '@credo-ts/core' +import { AgentConfig, CredoError, InjectionSymbols } from '@credo-ts/core' import { Store } from '@hyperledger/aries-askar-shared' import { AskarMultiWalletDatabaseScheme, AskarModuleConfig } from './AskarModuleConfig' @@ -27,7 +27,7 @@ export class AskarModule implements Module { dependencyManager.registerInstance(AskarModuleConfig, this.config) if (dependencyManager.isRegistered(InjectionSymbols.Wallet)) { - throw new AriesFrameworkError('There is an instance of Wallet already registered') + throw new CredoError('There is an instance of Wallet already registered') } else { dependencyManager.registerContextScoped(InjectionSymbols.Wallet, AskarWallet) @@ -38,7 +38,7 @@ export class AskarModule implements Module { } if (dependencyManager.isRegistered(InjectionSymbols.StorageService)) { - throw new AriesFrameworkError('There is an instance of StorageService already registered') + throw new CredoError('There is an instance of StorageService already registered') } else { dependencyManager.registerSingleton(InjectionSymbols.StorageService, AskarStorageService) } diff --git a/packages/askar/src/utils/assertAskarWallet.ts b/packages/askar/src/utils/assertAskarWallet.ts index 08763ee46a..40879c5468 100644 --- a/packages/askar/src/utils/assertAskarWallet.ts +++ b/packages/askar/src/utils/assertAskarWallet.ts @@ -1,6 +1,6 @@ import type { Wallet } from '@credo-ts/core' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' import { AskarWallet, AskarProfileWallet } from '../wallet' @@ -8,7 +8,7 @@ export function assertAskarWallet(wallet: Wallet): asserts wallet is AskarProfil if (!(wallet instanceof AskarProfileWallet) && !(wallet instanceof AskarWallet)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const walletClassName = (wallet as any).constructor?.name ?? 'unknown' - throw new AriesFrameworkError( + throw new CredoError( `Expected wallet to be instance of AskarProfileWallet or AskarWallet, found ${walletClassName}` ) } diff --git a/packages/askar/src/wallet/AskarBaseWallet.ts b/packages/askar/src/wallet/AskarBaseWallet.ts index 70796751e6..f2ba14a6f1 100644 --- a/packages/askar/src/wallet/AskarBaseWallet.ts +++ b/packages/askar/src/wallet/AskarBaseWallet.ts @@ -20,7 +20,7 @@ import { isValidPrivateKey, JsonEncoder, Buffer, - AriesFrameworkError, + CredoError, WalletError, Key, TypedArrayEncoder, @@ -69,7 +69,7 @@ export abstract class AskarBaseWallet implements Wallet { public get session() { if (!this._session) { - throw new AriesFrameworkError('No Wallet Session is opened') + throw new CredoError('No Wallet Session is opened') } return this._session @@ -142,7 +142,7 @@ export abstract class AskarBaseWallet implements Wallet { if (error instanceof WalletError) throw error if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError(`Error creating key with key type '${keyType}': ${error.message}`, { cause: error }) } @@ -241,7 +241,7 @@ export abstract class AskarBaseWallet implements Wallet { } } catch (error) { if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError(`Error signing data with verkey ${key.publicKeyBase58}. ${error.message}`, { cause: error }) } finally { @@ -292,7 +292,7 @@ export abstract class AskarBaseWallet implements Wallet { } catch (error) { askarKey?.handle.free() if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError(`Error verifying signature of data signed with verkey ${key.publicKeyBase58}`, { cause: error, @@ -360,7 +360,7 @@ export abstract class AskarBaseWallet implements Wallet { return new BigNumber(nonce).toString() } catch (error) { if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError('Error generating nonce', { cause: error }) } diff --git a/packages/askar/src/wallet/AskarWallet.ts b/packages/askar/src/wallet/AskarWallet.ts index 078c75f647..917eddd27e 100644 --- a/packages/askar/src/wallet/AskarWallet.ts +++ b/packages/askar/src/wallet/AskarWallet.ts @@ -4,7 +4,7 @@ import { WalletExportPathExistsError, WalletInvalidKeyError, WalletDuplicateError, - AriesFrameworkError, + CredoError, Logger, WalletError, InjectionSymbols, @@ -54,7 +54,7 @@ export class AskarWallet extends AskarBaseWallet { public get store() { if (!this._store) { - throw new AriesFrameworkError( + throw new CredoError( 'Wallet has not been initialized yet. Make sure to await agent.initialize() before using the agent.' ) } diff --git a/packages/bbs-signatures/src/signature-suites/BbsBlsSignature2020.ts b/packages/bbs-signatures/src/signature-suites/BbsBlsSignature2020.ts index 51d0c201e5..6722824f64 100644 --- a/packages/bbs-signatures/src/signature-suites/BbsBlsSignature2020.ts +++ b/packages/bbs-signatures/src/signature-suites/BbsBlsSignature2020.ts @@ -23,7 +23,7 @@ import type { import type { VerificationMethod, JsonObject, DocumentLoader, Proof } from '@credo-ts/core' import { - AriesFrameworkError, + CredoError, TypedArrayEncoder, SECURITY_CONTEXT_BBS_URL, SECURITY_CONTEXT_URL, @@ -336,9 +336,7 @@ export class BbsBlsSignature2020 extends LinkedDataProof { } if (!documentLoader) { - throw new AriesFrameworkError( - 'Missing custom document loader. This is required for resolving verification methods.' - ) + throw new CredoError('Missing custom document loader. This is required for resolving verification methods.') } const { document } = await documentLoader(verificationMethod) diff --git a/packages/bbs-signatures/src/signature-suites/BbsBlsSignatureProof2020.ts b/packages/bbs-signatures/src/signature-suites/BbsBlsSignatureProof2020.ts index 6874bc1bfb..779762b5d5 100644 --- a/packages/bbs-signatures/src/signature-suites/BbsBlsSignatureProof2020.ts +++ b/packages/bbs-signatures/src/signature-suites/BbsBlsSignatureProof2020.ts @@ -15,7 +15,7 @@ import type { DeriveProofOptions, VerifyProofOptions, CreateVerifyDataOptions, C import type { VerifyProofResult } from '../types/VerifyProofResult' import type { JsonObject, DocumentLoader, Proof } from '@credo-ts/core' -import { AriesFrameworkError, TypedArrayEncoder, SECURITY_CONTEXT_URL, vcLibraries } from '@credo-ts/core' +import { CredoError, TypedArrayEncoder, SECURITY_CONTEXT_URL, vcLibraries } from '@credo-ts/core' import { blsCreateProof, blsVerifyProof } from '@mattrglobal/bbs-signatures' import { Bls12381G2KeyPair } from '@mattrglobal/bls12381-key-pair' import { randomBytes } from '@stablelib/random' @@ -255,7 +255,7 @@ export class BbsBlsSignatureProof2020 extends LinkedDataProof { const proofValue = proof.proofValue if (typeof proofValue !== 'string') { - throw new AriesFrameworkError(`Expected proof.proofValue to be of type 'string', got ${typeof proof}`) + throw new CredoError(`Expected proof.proofValue to be of type 'string', got ${typeof proof}`) } // Verify the proof @@ -379,9 +379,7 @@ export class BbsBlsSignatureProof2020 extends LinkedDataProof { } if (!options.documentLoader) { - throw new AriesFrameworkError( - 'Missing custom document loader. This is required for resolving verification methods.' - ) + throw new CredoError('Missing custom document loader. This is required for resolving verification methods.') } const { document } = await options.documentLoader(verificationMethod) diff --git a/packages/cheqd/src/anoncreds/services/CheqdAnonCredsRegistry.ts b/packages/cheqd/src/anoncreds/services/CheqdAnonCredsRegistry.ts index a54f735ea9..0fbd45de8e 100644 --- a/packages/cheqd/src/anoncreds/services/CheqdAnonCredsRegistry.ts +++ b/packages/cheqd/src/anoncreds/services/CheqdAnonCredsRegistry.ts @@ -14,7 +14,7 @@ import type { } from '@credo-ts/anoncreds' import type { AgentContext } from '@credo-ts/core' -import { AriesFrameworkError, Buffer, Hasher, JsonTransformer, TypedArrayEncoder, utils } from '@credo-ts/core' +import { CredoError, Buffer, Hasher, JsonTransformer, TypedArrayEncoder, utils } from '@credo-ts/core' import { CheqdDidResolver, CheqdDidRegistrar } from '../../dids' import { cheqdSdkAnonCredsRegistryIdentifierRegex, parseCheqdDid } from '../utils/identifiers' @@ -321,9 +321,7 @@ export class CheqdAnonCredsRegistry implements AnonCredsRegistry { const statusListTimestamp = response.resourceMetadata?.created?.getUTCSeconds() if (!statusListTimestamp) { - throw new AriesFrameworkError( - `Unable to extract revocation status list timestamp from resource ${revocationRegistryId}` - ) + throw new CredoError(`Unable to extract revocation status list timestamp from resource ${revocationRegistryId}`) } return { diff --git a/packages/cheqd/src/dids/CheqdDidResolver.ts b/packages/cheqd/src/dids/CheqdDidResolver.ts index c943319daa..df5b1f2a69 100644 --- a/packages/cheqd/src/dids/CheqdDidResolver.ts +++ b/packages/cheqd/src/dids/CheqdDidResolver.ts @@ -2,7 +2,7 @@ import type { ParsedCheqdDid } from '../anoncreds/utils/identifiers' import type { Metadata } from '@cheqd/ts-proto/cheqd/resource/v2' import type { AgentContext, DidResolutionResult, DidResolver, ParsedDid } from '@credo-ts/core' -import { DidDocument, AriesFrameworkError, utils, JsonTransformer } from '@credo-ts/core' +import { DidDocument, CredoError, utils, JsonTransformer } from '@credo-ts/core' import { cheqdDidMetadataRegex, @@ -158,13 +158,13 @@ export class CheqdDidResolver implements DidResolver { const { did, id } = parsedDid if (!parsedDid.path) { - throw new AriesFrameworkError(`Missing path in did ${parsedDid.did}`) + throw new CredoError(`Missing path in did ${parsedDid.did}`) } const [, , resourceId] = parsedDid.path.split('/') if (!resourceId) { - throw new AriesFrameworkError(`Missing resource id in didUrl ${parsedDid.didUrl}`) + throw new CredoError(`Missing resource id in didUrl ${parsedDid.didUrl}`) } const metadata = await cheqdLedgerService.resolveResourceMetadata(did, id, resourceId) diff --git a/packages/cheqd/src/dids/didCheqdUtil.ts b/packages/cheqd/src/dids/didCheqdUtil.ts index 4dba81ba60..aad9a95b57 100644 --- a/packages/cheqd/src/dids/didCheqdUtil.ts +++ b/packages/cheqd/src/dids/didCheqdUtil.ts @@ -11,7 +11,7 @@ import { import { MsgCreateDidDocPayload, MsgDeactivateDidDocPayload } from '@cheqd/ts-proto/cheqd/did/v2' import { EnglishMnemonic as _ } from '@cosmjs/crypto' import { DirectSecp256k1HdWallet, DirectSecp256k1Wallet } from '@cosmjs/proto-signing' -import { DidDocument, AriesFrameworkError, JsonEncoder, TypedArrayEncoder, JsonTransformer } from '@credo-ts/core' +import { DidDocument, CredoError, JsonEncoder, TypedArrayEncoder, JsonTransformer } from '@credo-ts/core' export function validateSpecCompliantPayload(didDocument: DidDocument): SpecValidationResult { // id is required, validated on both compile and runtime @@ -115,7 +115,7 @@ export interface IDidDocOptions { export function getClosestResourceVersion(resources: Metadata[], date: Date) { const result = resources.sort(function (a, b) { - if (!a.created || !b.created) throw new AriesFrameworkError("Missing required property 'created' on resource") + if (!a.created || !b.created) throw new CredoError("Missing required property 'created' on resource") const distancea = Math.abs(date.getTime() - a.created.getTime()) const distanceb = Math.abs(date.getTime() - b.created.getTime()) return distancea - distanceb diff --git a/packages/cheqd/src/ledger/CheqdLedgerService.ts b/packages/cheqd/src/ledger/CheqdLedgerService.ts index 2f56cdfcd6..b8b245d483 100644 --- a/packages/cheqd/src/ledger/CheqdLedgerService.ts +++ b/packages/cheqd/src/ledger/CheqdLedgerService.ts @@ -4,7 +4,7 @@ import type { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2 import type { DirectSecp256k1HdWallet, DirectSecp256k1Wallet } from '@cosmjs/proto-signing' import { createCheqdSDK, DIDModule, ResourceModule, CheqdNetwork } from '@cheqd/sdk' -import { AriesFrameworkError, injectable } from '@credo-ts/core' +import { CredoError, injectable } from '@credo-ts/core' import { CheqdModuleConfig } from '../CheqdModuleConfig' import { parseCheqdDid } from '../anoncreds/utils/identifiers' @@ -43,7 +43,7 @@ export class CheqdLedgerService { modules: [DIDModule as unknown as AbstractCheqdSDKModule, ResourceModule as unknown as AbstractCheqdSDKModule], rpcUrl: network.rpcUrl, wallet: await network.cosmosPayerWallet.catch((error) => { - throw new AriesFrameworkError(`Error initializing cosmos payer wallet: ${error.message}`, { cause: error }) + throw new CredoError(`Error initializing cosmos payer wallet: ${error.message}`, { cause: error }) }), }) } diff --git a/packages/core/src/agent/Agent.ts b/packages/core/src/agent/Agent.ts index 891965b0a9..eb7d87cbaf 100644 --- a/packages/core/src/agent/Agent.ts +++ b/packages/core/src/agent/Agent.ts @@ -13,7 +13,7 @@ import { concatMap, takeUntil } from 'rxjs/operators' import { InjectionSymbols } from '../constants' import { SigningProviderToken } from '../crypto' import { JwsService } from '../crypto/JwsService' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { DependencyManager } from '../plugins' import { DidCommMessageRepository, StorageUpdateService, StorageVersionRepository } from '../storage' @@ -77,7 +77,7 @@ export class Agent extends BaseAge // Register possibly already defined services if (!dependencyManager.isRegistered(InjectionSymbols.Wallet)) { - throw new AriesFrameworkError( + throw new CredoError( "Missing required dependency: 'Wallet'. You can register it using the AskarModule, or implement your own." ) } @@ -85,7 +85,7 @@ export class Agent extends BaseAge dependencyManager.registerInstance(InjectionSymbols.Logger, agentConfig.logger) } if (!dependencyManager.isRegistered(InjectionSymbols.StorageService)) { - throw new AriesFrameworkError( + throw new CredoError( "Missing required dependency: 'StorageService'. You can register it using the AskarModule, or implement your own." ) } @@ -236,7 +236,7 @@ export class Agent extends BaseAge this.logger.debug(`Mediation invitation processed`, { outOfBandInvitation }) if (!newConnection) { - throw new AriesFrameworkError('No connection record to provision mediation.') + throw new CredoError('No connection record to provision mediation.') } return this.connections.returnWhenIsConnected(newConnection.id) diff --git a/packages/core/src/agent/BaseAgent.ts b/packages/core/src/agent/BaseAgent.ts index 3194e4c7d5..a1ed4131c7 100644 --- a/packages/core/src/agent/BaseAgent.ts +++ b/packages/core/src/agent/BaseAgent.ts @@ -7,7 +7,7 @@ import type { MessagePickupModule } from '../modules/message-pickup' import type { ProofsModule } from '../modules/proofs' import type { DependencyManager } from '../plugins' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { BasicMessagesApi } from '../modules/basic-messages' import { ConnectionsApi } from '../modules/connections' import { CredentialsApi } from '../modules/credentials' @@ -135,7 +135,7 @@ export abstract class BaseAgent | void diff --git a/packages/core/src/agent/MessageReceiver.ts b/packages/core/src/agent/MessageReceiver.ts index 2bfabd9342..65c0721873 100644 --- a/packages/core/src/agent/MessageReceiver.ts +++ b/packages/core/src/agent/MessageReceiver.ts @@ -7,7 +7,7 @@ import type { InboundTransport } from '../transport' import type { EncryptedMessage, PlaintextMessage } from '../types' import { InjectionSymbols } from '../constants' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { Logger } from '../logger' import { ConnectionService } from '../modules/connections' import { ProblemReportError, ProblemReportMessage, ProblemReportReason } from '../modules/problem-reports' @@ -97,7 +97,7 @@ export class MessageReceiver { } else if (this.isPlaintextMessage(inboundMessage)) { await this.receivePlaintextMessage(agentContext, inboundMessage, connection) } else { - throw new AriesFrameworkError('Unable to parse incoming message: unrecognized format') + throw new CredoError('Unable to parse incoming message: unrecognized format') } } finally { // Always end the session for the agent context after handling the message. @@ -279,7 +279,7 @@ export class MessageReceiver { ) { const messageType = parseMessageType(plaintextMessage['@type']) if (canHandleMessageType(ProblemReportMessage, messageType)) { - throw new AriesFrameworkError(`Not sending problem report in response to problem report: ${message}`) + throw new CredoError(`Not sending problem report in response to problem report: ${message}`) } const problemReportMessage = new ProblemReportMessage({ description: { diff --git a/packages/core/src/agent/MessageSender.ts b/packages/core/src/agent/MessageSender.ts index bcf23f93b8..1787f7ac02 100644 --- a/packages/core/src/agent/MessageSender.ts +++ b/packages/core/src/agent/MessageSender.ts @@ -11,7 +11,7 @@ import type { EncryptedMessage, OutboundPackage } from '../types' import { DID_COMM_TRANSPORT_QUEUE, InjectionSymbols } from '../constants' import { ReturnRouteTypes } from '../decorators/transport/TransportDecorator' -import { AriesFrameworkError, MessageSendingError } from '../error' +import { CredoError, MessageSendingError } from '../error' import { Logger } from '../logger' import { DidCommDocumentService } from '../modules/didcomm' import { DidKey, type DidDocument } from '../modules/dids' @@ -101,7 +101,7 @@ export class MessageSender { private async sendMessageToSession(agentContext: AgentContext, session: TransportSession, message: AgentMessage) { this.logger.debug(`Packing message and sending it via existing session ${session.type}...`) if (!session.keys) { - throw new AriesFrameworkError(`There are no keys for the given ${session.type} transport session.`) + throw new CredoError(`There are no keys for the given ${session.type} transport session.`) } const encryptedMessage = await this.envelopeService.packMessage(agentContext, message, session.keys) this.logger.debug('Sending message') @@ -144,7 +144,7 @@ export class MessageSender { ) if (this.outboundTransports.length === 0 && !queueService) { - throw new AriesFrameworkError('Agent has no outbound transport!') + throw new CredoError('Agent has no outbound transport!') } // Loop trough all available services and try to send the message @@ -192,7 +192,7 @@ export class MessageSender { errors, connection, }) - throw new AriesFrameworkError(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`) + throw new CredoError(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`) } public async sendMessage( @@ -398,12 +398,12 @@ export class MessageSender { const { agentContext, message, serviceParams, connection } = outboundMessageContext if (!serviceParams) { - throw new AriesFrameworkError('No service parameters found in outbound message context') + throw new CredoError('No service parameters found in outbound message context') } const { service, senderKey, returnRoute } = serviceParams if (this.outboundTransports.length === 0) { - throw new AriesFrameworkError('Agent has no outbound transport!') + throw new CredoError('Agent has no outbound transport!') } this.logger.debug(`Sending outbound message to service:`, { diff --git a/packages/core/src/agent/TransportService.ts b/packages/core/src/agent/TransportService.ts index bd42f892a5..de90b09984 100644 --- a/packages/core/src/agent/TransportService.ts +++ b/packages/core/src/agent/TransportService.ts @@ -5,7 +5,7 @@ import type { TransportSessionRemovedEvent, TransportSessionSavedEvent } from '. import type { EncryptedMessage } from '../types' import { DID_COMM_TRANSPORT_QUEUE } from '../constants' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { injectable } from '../plugins' import { TransportEventTypes } from '../transport' @@ -49,7 +49,7 @@ export class TransportService { public setConnectionIdForSession(sessionId: string, connectionId: string) { const session = this.findSessionById(sessionId) if (!session) { - throw new AriesFrameworkError(`Session not found with id ${sessionId}`) + throw new CredoError(`Session not found with id ${sessionId}`) } session.connectionId = connectionId this.saveSession(session) diff --git a/packages/core/src/agent/context/DefaultAgentContextProvider.ts b/packages/core/src/agent/context/DefaultAgentContextProvider.ts index c4b6d9e18d..7f9ec4d918 100644 --- a/packages/core/src/agent/context/DefaultAgentContextProvider.ts +++ b/packages/core/src/agent/context/DefaultAgentContextProvider.ts @@ -1,6 +1,6 @@ import type { AgentContextProvider } from './AgentContextProvider' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { injectable } from '../../plugins' import { AgentContext } from './AgentContext' @@ -21,7 +21,7 @@ export class DefaultAgentContextProvider implements AgentContextProvider { public async getAgentContextForContextCorrelationId(contextCorrelationId: string): Promise { if (contextCorrelationId !== this.agentContext.contextCorrelationId) { - throw new AriesFrameworkError( + throw new CredoError( `Could not get agent context for contextCorrelationId '${contextCorrelationId}'. Only contextCorrelationId '${this.agentContext.contextCorrelationId}' is supported.` ) } @@ -45,7 +45,7 @@ export class DefaultAgentContextProvider implements AgentContextProvider { public async endSessionForAgentContext(agentContext: AgentContext) { // Throw an error if the context correlation id does not match to prevent misuse. if (agentContext.contextCorrelationId !== this.agentContext.contextCorrelationId) { - throw new AriesFrameworkError( + throw new CredoError( `Could not end session for agent context with contextCorrelationId '${agentContext.contextCorrelationId}'. Only contextCorrelationId '${this.agentContext.contextCorrelationId}' is provided by this provider.` ) } diff --git a/packages/core/src/agent/getOutboundMessageContext.ts b/packages/core/src/agent/getOutboundMessageContext.ts index ee39cbf43c..8ff9ebd446 100644 --- a/packages/core/src/agent/getOutboundMessageContext.ts +++ b/packages/core/src/agent/getOutboundMessageContext.ts @@ -7,7 +7,7 @@ import type { BaseRecordAny } from '../storage/BaseRecord' import { Key } from '../crypto' import { ServiceDecorator } from '../decorators/service/ServiceDecorator' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { InvitationType, OutOfBandRepository, OutOfBandRole, OutOfBandService } from '../modules/oob' import { OutOfBandRecordMetadataKeys } from '../modules/oob/repository/outOfBandRecordMetadataTypes' import { RoutingService } from '../modules/routing' @@ -56,13 +56,13 @@ export async function getOutboundMessageContext( } if (!lastReceivedMessage) { - throw new AriesFrameworkError( + throw new CredoError( 'No connection record and no lastReceivedMessage was supplied. For connection-less exchanges the lastReceivedMessage is required.' ) } if (!associatedRecord) { - throw new AriesFrameworkError( + throw new CredoError( 'No associated record was supplied. This is required for connection-less exchanges to store the associated ~service decorator on the message.' ) } @@ -111,12 +111,10 @@ export async function getConnectionlessOutboundMessageContext( // These errors should not happen as they will be caught by the checks above. But if there's a path missed, // and to make typescript happy we add these checks. if (!ourService) { - throw new AriesFrameworkError( - `Could not determine our service for connection-less exchange for message ${message.id}.` - ) + throw new CredoError(`Could not determine our service for connection-less exchange for message ${message.id}.`) } if (!recipientService) { - throw new AriesFrameworkError( + throw new CredoError( `Could not determine recipient service for connection-less exchange for message ${message.id}.` ) } @@ -188,14 +186,14 @@ async function getServicesForMessage( } if (!recipientService) { - throw new AriesFrameworkError( + throw new CredoError( `Could not find a service to send the message to. Please make sure the connection has a service or provide a service to send the message to.` ) } // We have created the oob record with a message, that message should be provided here as well if (!lastSentMessage) { - throw new AriesFrameworkError('Must have lastSentMessage when out of band record has role Sender') + throw new CredoError('Must have lastSentMessage when out of band record has role Sender') } } else if (outOfBandRecord?.role === OutOfBandRole.Receiver) { // Extract recipientService from the oob record if not on a previous message @@ -207,7 +205,7 @@ async function getServicesForMessage( } if (lastSentMessage && !ourService) { - throw new AriesFrameworkError( + throw new CredoError( `Could not find a service to send the message to. Please make sure the connection has a service or provide a service to send the message to.` ) } @@ -219,7 +217,7 @@ async function getServicesForMessage( agentContext.config.logger.error( `No out of band record associated and missing our service for connection-less exchange for message ${message.id}, while previous message has already been sent.` ) - throw new AriesFrameworkError( + throw new CredoError( `No out of band record associated and missing our service for connection-less exchange for message ${message.id}, while previous message has already been sent.` ) } @@ -228,7 +226,7 @@ async function getServicesForMessage( agentContext.config.logger.error( `No out of band record associated and missing recipient service for connection-less exchange for message ${message.id}.` ) - throw new AriesFrameworkError( + throw new CredoError( `No out of band record associated and missing recipient service for connection-less exchange for message ${message.id}.` ) } diff --git a/packages/core/src/agent/models/InboundMessageContext.ts b/packages/core/src/agent/models/InboundMessageContext.ts index 8a6e800160..c205091fd9 100644 --- a/packages/core/src/agent/models/InboundMessageContext.ts +++ b/packages/core/src/agent/models/InboundMessageContext.ts @@ -3,7 +3,7 @@ import type { ConnectionRecord } from '../../modules/connections' import type { AgentMessage } from '../AgentMessage' import type { AgentContext } from '../context' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' export interface MessageContextParams { connection?: ConnectionRecord @@ -33,11 +33,11 @@ export class InboundMessageContext { /** * Assert the inbound message has a ready connection associated with it. * - * @throws {AriesFrameworkError} if there is no connection or the connection is not ready + * @throws {CredoError} if there is no connection or the connection is not ready */ public assertReadyConnection(): ConnectionRecord { if (!this.connection) { - throw new AriesFrameworkError(`No connection associated with incoming message ${this.message.type}`) + throw new CredoError(`No connection associated with incoming message ${this.message.type}`) } // Make sure connection is ready diff --git a/packages/core/src/agent/models/OutboundMessageContext.ts b/packages/core/src/agent/models/OutboundMessageContext.ts index de0eca1705..bb031594c1 100644 --- a/packages/core/src/agent/models/OutboundMessageContext.ts +++ b/packages/core/src/agent/models/OutboundMessageContext.ts @@ -8,7 +8,7 @@ import type { BaseRecord } from '../../storage/BaseRecord' import type { AgentMessage } from '../AgentMessage' import type { AgentContext } from '../context' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' export interface ServiceMessageParams { senderKey: Key @@ -50,11 +50,11 @@ export class OutboundMessageContext { /** * Assert the outbound message has a ready connection associated with it. * - * @throws {AriesFrameworkError} if there is no connection or the connection is not ready + * @throws {CredoError} if there is no connection or the connection is not ready */ public assertReadyConnection(): ConnectionRecord { if (!this.connection) { - throw new AriesFrameworkError(`No connection associated with outgoing message ${this.message.type}`) + throw new CredoError(`No connection associated with outgoing message ${this.message.type}`) } // Make sure connection is ready diff --git a/packages/core/src/agent/models/features/Feature.ts b/packages/core/src/agent/models/features/Feature.ts index 1a5b3e461c..00464ee77f 100644 --- a/packages/core/src/agent/models/features/Feature.ts +++ b/packages/core/src/agent/models/features/Feature.ts @@ -1,7 +1,7 @@ import { Expose } from 'class-transformer' import { IsString } from 'class-validator' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonTransformer } from '../../../utils/JsonTransformer' export interface FeatureOptions { @@ -32,7 +32,7 @@ export class Feature { */ public combine(feature: this) { if (feature.id !== this.id) { - throw new AriesFrameworkError('Can only combine with a feature with the same id') + throw new CredoError('Can only combine with a feature with the same id') } const obj1 = JsonTransformer.toJSON(this) diff --git a/packages/core/src/crypto/JwsService.ts b/packages/core/src/crypto/JwsService.ts index 8e68c997f7..53a0300660 100644 --- a/packages/core/src/crypto/JwsService.ts +++ b/packages/core/src/crypto/JwsService.ts @@ -5,7 +5,7 @@ import type { JwkJson } from './jose/jwk/Jwk' import type { AgentContext } from '../agent' import type { Buffer } from '../utils' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { injectable } from '../plugins' import { isJsonObject, JsonEncoder, TypedArrayEncoder } from '../utils' import { WalletError } from '../wallet/error' @@ -22,13 +22,13 @@ export class JwsService { // Make sure the options.key and jwk from protectedHeader are the same. if (jwk && (jwk.key.keyType !== options.key.keyType || !jwk.key.publicKey.equals(options.key.publicKey))) { - throw new AriesFrameworkError(`Protected header JWK does not match key for signing.`) + throw new CredoError(`Protected header JWK does not match key for signing.`) } // Validate the options.key used for signing against the jws options // We use keyJwk instead of jwk, as the user could also use kid instead of jwk if (keyJwk && !keyJwk.supportsSignatureAlgorithm(alg)) { - throw new AriesFrameworkError( + throw new CredoError( `alg '${alg}' is not a valid JWA signature algorithm for this jwk with keyType ${ keyJwk.keyType }. Supported algorithms are ${keyJwk.supportedSignatureAlgorithms.join(', ')}` @@ -96,8 +96,7 @@ export class JwsService { let payload: string if (typeof jws === 'string') { - if (!JWS_COMPACT_FORMAT_MATCHER.test(jws)) - throw new AriesFrameworkError(`Invalid JWS compact format for value '${jws}'.`) + if (!JWS_COMPACT_FORMAT_MATCHER.test(jws)) throw new CredoError(`Invalid JWS compact format for value '${jws}'.`) const [protectedHeader, _payload, signature] = jws.split('.') @@ -116,7 +115,7 @@ export class JwsService { } if (signatures.length === 0) { - throw new AriesFrameworkError('Unable to verify JWS, no signatures present in JWS.') + throw new CredoError('Unable to verify JWS, no signatures present in JWS.') } const signerKeys: Key[] = [] @@ -124,11 +123,11 @@ export class JwsService { const protectedJson = JsonEncoder.fromBase64(jws.protected) if (!isJsonObject(protectedJson)) { - throw new AriesFrameworkError('Unable to verify JWS, protected header is not a valid JSON object.') + throw new CredoError('Unable to verify JWS, protected header is not a valid JSON object.') } if (!protectedJson.alg || typeof protectedJson.alg !== 'string') { - throw new AriesFrameworkError('Unable to verify JWS, protected header alg is not provided or not a string.') + throw new CredoError('Unable to verify JWS, protected header alg is not provided or not a string.') } const jwk = await this.jwkFromJws({ @@ -141,7 +140,7 @@ export class JwsService { jwkResolver, }) if (!jwk.supportsSignatureAlgorithm(protectedJson.alg)) { - throw new AriesFrameworkError( + throw new CredoError( `alg '${protectedJson.alg}' is not a valid JWA signature algorithm for this jwk with keyType ${ jwk.keyType }. Supported algorithms are ${jwk.supportedSignatureAlgorithms.join(', ')}` @@ -180,10 +179,10 @@ export class JwsService { private buildProtected(options: JwsProtectedHeaderOptions) { if (!options.jwk && !options.kid) { - throw new AriesFrameworkError('Both JWK and kid are undefined. Please provide one or the other.') + throw new CredoError('Both JWK and kid are undefined. Please provide one or the other.') } if (options.jwk && options.kid) { - throw new AriesFrameworkError('Both JWK and kid are provided. Please only provide one of the two.') + throw new CredoError('Both JWK and kid are provided. Please only provide one of the two.') } return { @@ -203,21 +202,17 @@ export class JwsService { const { protectedHeader, jwkResolver, jws, payload } = options if (protectedHeader.jwk && protectedHeader.kid) { - throw new AriesFrameworkError( - 'Both JWK and kid are defined in the protected header. Only one of the two is allowed.' - ) + throw new CredoError('Both JWK and kid are defined in the protected header. Only one of the two is allowed.') } // Jwk if (protectedHeader.jwk) { - if (!isJsonObject(protectedHeader.jwk)) throw new AriesFrameworkError('JWK is not a valid JSON object.') + if (!isJsonObject(protectedHeader.jwk)) throw new CredoError('JWK is not a valid JSON object.') return getJwkFromJson(protectedHeader.jwk as JwkJson) } if (!jwkResolver) { - throw new AriesFrameworkError( - `jwkResolver is required when the JWS protected header does not contain a 'jwk' property.` - ) + throw new CredoError(`jwkResolver is required when the JWS protected header does not contain a 'jwk' property.`) } try { @@ -229,7 +224,7 @@ export class JwsService { return jwk } catch (error) { - throw new AriesFrameworkError(`Error when resolving JWK for JWS in jwkResolver. ${error.message}`, { + throw new CredoError(`Error when resolving JWK for JWS in jwkResolver. ${error.message}`, { cause: error, }) } diff --git a/packages/core/src/crypto/jose/jwk/transform.ts b/packages/core/src/crypto/jose/jwk/transform.ts index 145029984f..c2c553e9ad 100644 --- a/packages/core/src/crypto/jose/jwk/transform.ts +++ b/packages/core/src/crypto/jose/jwk/transform.ts @@ -2,7 +2,7 @@ import type { JwkJson, Jwk } from './Jwk' import type { Key } from '../../Key' import type { JwaSignatureAlgorithm } from '../jwa' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { KeyType } from '../../KeyType' import { JwaCurve, JwaKeyType } from '../jwa' @@ -42,7 +42,7 @@ export function getJwkFromKey(key: Key) { if (key.keyType === KeyType.K256) return K256Jwk.fromPublicKey(key.publicKey) - throw new AriesFrameworkError(`Cannot create JWK from key. Unsupported key with type '${key.keyType}'.`) + throw new CredoError(`Cannot create JWK from key. Unsupported key with type '${key.keyType}'.`) } export function getJwkClassFromJwaSignatureAlgorithm(alg: JwaSignatureAlgorithm | string) { diff --git a/packages/core/src/crypto/jose/jwt/Jwt.ts b/packages/core/src/crypto/jose/jwt/Jwt.ts index 33bb5c9178..71e90252ce 100644 --- a/packages/core/src/crypto/jose/jwt/Jwt.ts +++ b/packages/core/src/crypto/jose/jwt/Jwt.ts @@ -1,6 +1,6 @@ import type { Buffer } from '../../../utils' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonEncoder, TypedArrayEncoder } from '../../../utils' import { JwtPayload } from './JwtPayload' @@ -42,7 +42,7 @@ export class Jwt { public static fromSerializedJwt(serializedJwt: string) { if (typeof serializedJwt !== 'string' || !Jwt.format.test(serializedJwt)) { - throw new AriesFrameworkError(`Invalid JWT. '${serializedJwt}' does not match JWT regex`) + throw new CredoError(`Invalid JWT. '${serializedJwt}' does not match JWT regex`) } const [header, payload, signature] = serializedJwt.split('.') @@ -55,7 +55,7 @@ export class Jwt { serializedJwt, }) } catch (error) { - throw new AriesFrameworkError(`Invalid JWT. ${error instanceof Error ? error.message : JSON.stringify(error)}`) + throw new CredoError(`Invalid JWT. ${error instanceof Error ? error.message : JSON.stringify(error)}`) } } } diff --git a/packages/core/src/crypto/jose/jwt/JwtPayload.ts b/packages/core/src/crypto/jose/jwt/JwtPayload.ts index 26e5491d26..1a5cdb4ac8 100644 --- a/packages/core/src/crypto/jose/jwt/JwtPayload.ts +++ b/packages/core/src/crypto/jose/jwt/JwtPayload.ts @@ -1,4 +1,4 @@ -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' /** * The maximum allowed clock skew time in seconds. If an time based validation @@ -128,26 +128,26 @@ export class JwtPayload { // Validate nbf if (typeof this.nbf !== 'number' && typeof this.nbf !== 'undefined') { - throw new AriesFrameworkError(`JWT payload 'nbf' must be a number if provided. Actual type is ${typeof this.nbf}`) + throw new CredoError(`JWT payload 'nbf' must be a number if provided. Actual type is ${typeof this.nbf}`) } if (typeof this.nbf === 'number' && this.nbf > nowSkewedFuture) { - throw new AriesFrameworkError(`JWT not valid before ${this.nbf}`) + throw new CredoError(`JWT not valid before ${this.nbf}`) } // Validate iat if (typeof this.iat !== 'number' && typeof this.iat !== 'undefined') { - throw new AriesFrameworkError(`JWT payload 'iat' must be a number if provided. Actual type is ${typeof this.iat}`) + throw new CredoError(`JWT payload 'iat' must be a number if provided. Actual type is ${typeof this.iat}`) } if (typeof this.iat === 'number' && this.iat > nowSkewedFuture) { - throw new AriesFrameworkError(`JWT issued in the future at ${this.iat}`) + throw new CredoError(`JWT issued in the future at ${this.iat}`) } // Validate exp if (typeof this.exp !== 'number' && typeof this.exp !== 'undefined') { - throw new AriesFrameworkError(`JWT payload 'exp' must be a number if provided. Actual type is ${typeof this.exp}`) + throw new CredoError(`JWT payload 'exp' must be a number if provided. Actual type is ${typeof this.exp}`) } if (typeof this.exp === 'number' && this.exp < nowSkewedPast) { - throw new AriesFrameworkError(`JWT expired at ${this.exp}`) + throw new CredoError(`JWT expired at ${this.exp}`) } // NOTE: nonce and aud are not validated in here. We could maybe add @@ -172,37 +172,37 @@ export class JwtPayload { // Validate iss if (iss && typeof iss !== 'string') { - throw new AriesFrameworkError(`JWT payload iss must be a string`) + throw new CredoError(`JWT payload iss must be a string`) } // Validate sub if (sub && typeof sub !== 'string') { - throw new AriesFrameworkError(`JWT payload sub must be a string`) + throw new CredoError(`JWT payload sub must be a string`) } // Validate aud if (aud && typeof aud !== 'string' && !(Array.isArray(aud) && aud.every((aud) => typeof aud === 'string'))) { - throw new AriesFrameworkError(`JWT payload aud must be a string or an array of strings`) + throw new CredoError(`JWT payload aud must be a string or an array of strings`) } // Validate exp if (exp && (typeof exp !== 'number' || exp < 0)) { - throw new AriesFrameworkError(`JWT payload exp must be a positive number`) + throw new CredoError(`JWT payload exp must be a positive number`) } // Validate nbf if (nbf && (typeof nbf !== 'number' || nbf < 0)) { - throw new AriesFrameworkError(`JWT payload nbf must be a positive number`) + throw new CredoError(`JWT payload nbf must be a positive number`) } // Validate iat if (iat && (typeof iat !== 'number' || iat < 0)) { - throw new AriesFrameworkError(`JWT payload iat must be a positive number`) + throw new CredoError(`JWT payload iat must be a positive number`) } // Validate jti if (jti && typeof jti !== 'string') { - throw new AriesFrameworkError(`JWT payload jti must be a string`) + throw new CredoError(`JWT payload jti must be a string`) } const jwtPayload = new JwtPayload({ diff --git a/packages/core/src/crypto/signing-provider/SigningProviderError.ts b/packages/core/src/crypto/signing-provider/SigningProviderError.ts index 21bcf0650b..bf7cae040d 100644 --- a/packages/core/src/crypto/signing-provider/SigningProviderError.ts +++ b/packages/core/src/crypto/signing-provider/SigningProviderError.ts @@ -1,3 +1,3 @@ -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' -export class SigningProviderError extends AriesFrameworkError {} +export class SigningProviderError extends CredoError {} diff --git a/packages/core/src/crypto/signing-provider/SigningProviderRegistry.ts b/packages/core/src/crypto/signing-provider/SigningProviderRegistry.ts index c58664e66a..4395b1616c 100644 --- a/packages/core/src/crypto/signing-provider/SigningProviderRegistry.ts +++ b/packages/core/src/crypto/signing-provider/SigningProviderRegistry.ts @@ -1,7 +1,7 @@ import type { SigningProvider } from './SigningProvider' import type { KeyType } from '../KeyType' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { injectable, injectAll } from '../../plugins' export const SigningProviderToken = Symbol('SigningProviderToken') @@ -29,7 +29,7 @@ export class SigningProviderRegistry { const signingKeyProvider = this.signingKeyProviders.find((x) => x.keyType === keyType) if (!signingKeyProvider) { - throw new AriesFrameworkError(`No signing key provider for key type: ${keyType}`) + throw new CredoError(`No signing key provider for key type: ${keyType}`) } return signingKeyProvider diff --git a/packages/core/src/decorators/attachment/Attachment.ts b/packages/core/src/decorators/attachment/Attachment.ts index 3a91065b56..0e50069ae0 100644 --- a/packages/core/src/decorators/attachment/Attachment.ts +++ b/packages/core/src/decorators/attachment/Attachment.ts @@ -3,7 +3,7 @@ import type { JwsDetachedFormat, JwsFlattenedDetachedFormat, JwsGeneralFormat } import { Expose, Type } from 'class-transformer' import { IsDate, IsHash, IsInstance, IsInt, IsMimeType, IsOptional, IsString, ValidateNested } from 'class-validator' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { JsonValue } from '../../types' import { JsonEncoder } from '../../utils/JsonEncoder' import { uuid } from '../../utils/uuid' @@ -148,7 +148,7 @@ export class Attachment { } else if (this.data.json) { return this.data.json as T } else { - throw new AriesFrameworkError('No attachment data found in `json` or `base64` data fields.') + throw new CredoError('No attachment data found in `json` or `base64` data fields.') } } diff --git a/packages/core/src/decorators/signature/SignatureDecoratorUtils.ts b/packages/core/src/decorators/signature/SignatureDecoratorUtils.ts index dedbde2610..55eecf2538 100644 --- a/packages/core/src/decorators/signature/SignatureDecoratorUtils.ts +++ b/packages/core/src/decorators/signature/SignatureDecoratorUtils.ts @@ -1,7 +1,7 @@ import type { Wallet } from '../../wallet/Wallet' import { Key, KeyType } from '../../crypto' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { JsonEncoder } from '../../utils/JsonEncoder' import { TypedArrayEncoder } from '../../utils/TypedArrayEncoder' import { Buffer } from '../../utils/buffer' @@ -32,7 +32,7 @@ export async function unpackAndVerifySignatureDecorator( const isValid = await wallet.verify({ signature, data: signedData, key }) if (!isValid) { - throw new AriesFrameworkError('Signature is not valid') + throw new CredoError('Signature is not valid') } // TODO: return Connection instance instead of raw json diff --git a/packages/core/src/error/ClassValidationError.ts b/packages/core/src/error/ClassValidationError.ts index 051664b40b..8c766c7c7e 100644 --- a/packages/core/src/error/ClassValidationError.ts +++ b/packages/core/src/error/ClassValidationError.ts @@ -1,8 +1,8 @@ import type { ValidationError } from 'class-validator' -import { AriesFrameworkError } from './AriesFrameworkError' +import { CredoError } from './CredoError' -export class ClassValidationError extends AriesFrameworkError { +export class ClassValidationError extends CredoError { public validationErrors: ValidationError[] public validationErrorsToString() { diff --git a/packages/core/src/error/AriesFrameworkError.ts b/packages/core/src/error/CredoError.ts similarity index 74% rename from packages/core/src/error/AriesFrameworkError.ts rename to packages/core/src/error/CredoError.ts index bc7fc267b8..484f55b958 100644 --- a/packages/core/src/error/AriesFrameworkError.ts +++ b/packages/core/src/error/CredoError.ts @@ -1,8 +1,8 @@ import { BaseError } from './BaseError' -export class AriesFrameworkError extends BaseError { +export class CredoError extends BaseError { /** - * Create base AriesFrameworkError. + * Create base CredoError. * @param message the error message * @param cause the error that caused this error to be created */ diff --git a/packages/core/src/error/MessageSendingError.ts b/packages/core/src/error/MessageSendingError.ts index 6d0ddc46aa..eb511be5e9 100644 --- a/packages/core/src/error/MessageSendingError.ts +++ b/packages/core/src/error/MessageSendingError.ts @@ -1,8 +1,8 @@ import type { OutboundMessageContext } from '../agent/models' -import { AriesFrameworkError } from './AriesFrameworkError' +import { CredoError } from './CredoError' -export class MessageSendingError extends AriesFrameworkError { +export class MessageSendingError extends CredoError { public outboundMessageContext: OutboundMessageContext public constructor( message: string, diff --git a/packages/core/src/error/RecordDuplicateError.ts b/packages/core/src/error/RecordDuplicateError.ts index 60410a9d60..c7480b4bcb 100644 --- a/packages/core/src/error/RecordDuplicateError.ts +++ b/packages/core/src/error/RecordDuplicateError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from './AriesFrameworkError' +import { CredoError } from './CredoError' -export class RecordDuplicateError extends AriesFrameworkError { +export class RecordDuplicateError extends CredoError { public constructor(message: string, { recordType, cause }: { recordType: string; cause?: Error }) { super(`${recordType}: ${message}`, { cause }) } diff --git a/packages/core/src/error/RecordNotFoundError.ts b/packages/core/src/error/RecordNotFoundError.ts index 51d35a9f1e..914e721eb3 100644 --- a/packages/core/src/error/RecordNotFoundError.ts +++ b/packages/core/src/error/RecordNotFoundError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from './AriesFrameworkError' +import { CredoError } from './CredoError' -export class RecordNotFoundError extends AriesFrameworkError { +export class RecordNotFoundError extends CredoError { public constructor(message: string, { recordType, cause }: { recordType: string; cause?: Error }) { super(`${recordType}: ${message}`, { cause }) } diff --git a/packages/core/src/error/index.ts b/packages/core/src/error/index.ts index 45ebd04bd7..7eb55c0d1f 100644 --- a/packages/core/src/error/index.ts +++ b/packages/core/src/error/index.ts @@ -1,4 +1,4 @@ -export * from './AriesFrameworkError' +export * from './CredoError' export * from './RecordNotFoundError' export * from './RecordDuplicateError' export * from './ClassValidationError' diff --git a/packages/core/src/modules/cache/singleContextLruCache/SingleContextStorageLruCache.ts b/packages/core/src/modules/cache/singleContextLruCache/SingleContextStorageLruCache.ts index bdd17d49d1..0d46df0ae4 100644 --- a/packages/core/src/modules/cache/singleContextLruCache/SingleContextStorageLruCache.ts +++ b/packages/core/src/modules/cache/singleContextLruCache/SingleContextStorageLruCache.ts @@ -4,7 +4,7 @@ import type { Cache } from '../Cache' import { LRUMap } from 'lru_map' -import { AriesFrameworkError, RecordDuplicateError } from '../../../error' +import { CredoError, RecordDuplicateError } from '../../../error' import { SingleContextLruCacheRecord } from './SingleContextLruCacheRecord' import { SingleContextLruCacheRepository } from './SingleContextLruCacheRepository' @@ -163,7 +163,7 @@ export class SingleContextStorageLruCache implements Cache { } if (this._contextCorrelationId !== agentContext.contextCorrelationId) { - throw new AriesFrameworkError( + throw new CredoError( 'SingleContextStorageLruCache can not be used with multiple agent context instances. Register a custom cache implementation in the CacheModule.' ) } diff --git a/packages/core/src/modules/connections/ConnectionsApi.ts b/packages/core/src/modules/connections/ConnectionsApi.ts index fd1051bc06..9a42d491ff 100644 --- a/packages/core/src/modules/connections/ConnectionsApi.ts +++ b/packages/core/src/modules/connections/ConnectionsApi.ts @@ -9,7 +9,7 @@ import { MessageHandlerRegistry } from '../../agent/MessageHandlerRegistry' import { MessageSender } from '../../agent/MessageSender' import { OutboundMessageContext } from '../../agent/models' import { ReturnRouteTypes } from '../../decorators/transport/TransportDecorator' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { injectable } from '../../plugins' import { DidResolverService } from '../dids' import { DidRepository } from '../dids/repository' @@ -106,7 +106,7 @@ export class ConnectionsApi { const { protocol, label, alias, imageUrl, autoAcceptConnection, ourDid } = config if (ourDid && config.routing) { - throw new AriesFrameworkError(`'routing' is disallowed when defining 'ourDid'`) + throw new CredoError(`'routing' is disallowed when defining 'ourDid'`) } const routing = @@ -124,7 +124,7 @@ export class ConnectionsApi { }) } else if (protocol === HandshakeProtocol.Connections) { if (ourDid) { - throw new AriesFrameworkError('Using an externally defined did for connections protocol is unsupported') + throw new CredoError('Using an externally defined did for connections protocol is unsupported') } result = await this.connectionService.createRequest(this.agentContext, outOfBandRecord, { @@ -135,7 +135,7 @@ export class ConnectionsApi { autoAcceptConnection, }) } else { - throw new AriesFrameworkError(`Unsupported handshake protocol ${protocol}.`) + throw new CredoError(`Unsupported handshake protocol ${protocol}.`) } const { message, connectionRecord } = result @@ -158,15 +158,15 @@ export class ConnectionsApi { public async acceptRequest(connectionId: string): Promise { const connectionRecord = await this.connectionService.findById(this.agentContext, connectionId) if (!connectionRecord) { - throw new AriesFrameworkError(`Connection record ${connectionId} not found.`) + throw new CredoError(`Connection record ${connectionId} not found.`) } if (!connectionRecord.outOfBandId) { - throw new AriesFrameworkError(`Connection record ${connectionId} does not have out-of-band record.`) + throw new CredoError(`Connection record ${connectionId} does not have out-of-band record.`) } const outOfBandRecord = await this.outOfBandService.findById(this.agentContext, connectionRecord.outOfBandId) if (!outOfBandRecord) { - throw new AriesFrameworkError(`Out-of-band record ${connectionRecord.outOfBandId} not found.`) + throw new CredoError(`Out-of-band record ${connectionRecord.outOfBandId} not found.`) } // If the outOfBandRecord is reusable we need to use new routing keys for the connection, otherwise @@ -215,11 +215,11 @@ export class ConnectionsApi { let outboundMessageContext if (connectionRecord.protocol === HandshakeProtocol.DidExchange) { if (!connectionRecord.outOfBandId) { - throw new AriesFrameworkError(`Connection ${connectionRecord.id} does not have outOfBandId!`) + throw new CredoError(`Connection ${connectionRecord.id} does not have outOfBandId!`) } const outOfBandRecord = await this.outOfBandService.findById(this.agentContext, connectionRecord.outOfBandId) if (!outOfBandRecord) { - throw new AriesFrameworkError( + throw new CredoError( `OutOfBand record for connection ${connectionRecord.id} with outOfBandId ${connectionRecord.outOfBandId} not found!` ) } @@ -304,7 +304,7 @@ export class ConnectionsApi { const connection = await this.connectionService.getById(this.agentContext, connectionId) if (toDid && options.routing) { - throw new AriesFrameworkError(`'routing' is disallowed when defining 'toDid'`) + throw new CredoError(`'routing' is disallowed when defining 'toDid'`) } let routing = options.routing diff --git a/packages/core/src/modules/connections/DidExchangeProtocol.ts b/packages/core/src/modules/connections/DidExchangeProtocol.ts index 92eb8111d7..e6dd9218ca 100644 --- a/packages/core/src/modules/connections/DidExchangeProtocol.ts +++ b/packages/core/src/modules/connections/DidExchangeProtocol.ts @@ -12,7 +12,7 @@ import { JwsService } from '../../crypto/JwsService' import { JwaSignatureAlgorithm } from '../../crypto/jose/jwa' import { getJwkFromKey } from '../../crypto/jose/jwk' import { Attachment, AttachmentData } from '../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { Logger } from '../../logger' import { inject, injectable } from '../../plugins' import { TypedArrayEncoder, isDid, Buffer } from '../../utils' @@ -101,7 +101,7 @@ export class DidExchangeProtocol { mediatorId = (await getMediationRecordForDidDocument(agentContext, didDocument))?.id // Otherwise, create a did:peer based on the provided routing } else { - if (!routing) throw new AriesFrameworkError(`'routing' must be defined if 'ourDid' is not specified`) + if (!routing) throw new CredoError(`'routing' must be defined if 'ourDid' is not specified`) didDocument = await createPeerDidFromServices( agentContext, @@ -247,11 +247,11 @@ export class DidExchangeProtocol { const config = agentContext.dependencyManager.resolve(ConnectionsModuleConfig) if (!threadId) { - throw new AriesFrameworkError('Missing threadId on connection record.') + throw new CredoError('Missing threadId on connection record.') } if (!theirDid) { - throw new AriesFrameworkError('Missing theirDid on connection record.') + throw new CredoError('Missing theirDid on connection record.') } let services: ResolvedDidCommService[] = [] @@ -325,7 +325,7 @@ export class DidExchangeProtocol { const { connection: connectionRecord, message, agentContext } = messageContext if (!connectionRecord) { - throw new AriesFrameworkError('No connection record in message context.') + throw new CredoError('No connection record in message context.') } DidExchangeStateMachine.assertProcessMessageState(DidExchangeResponseMessage.type, connectionRecord) @@ -388,13 +388,11 @@ export class DidExchangeProtocol { const parentThreadId = outOfBandRecord.outOfBandInvitation.id if (!threadId) { - throw new AriesFrameworkError(`Connection record ${connectionRecord.id} does not have 'threadId' attribute.`) + throw new CredoError(`Connection record ${connectionRecord.id} does not have 'threadId' attribute.`) } if (!parentThreadId) { - throw new AriesFrameworkError( - `Connection record ${connectionRecord.id} does not have 'parentThreadId' attribute.` - ) + throw new CredoError(`Connection record ${connectionRecord.id} does not have 'parentThreadId' attribute.`) } const message = new DidExchangeCompleteMessage({ threadId, parentThreadId }) @@ -418,7 +416,7 @@ export class DidExchangeProtocol { const { connection: connectionRecord, message } = messageContext if (!connectionRecord) { - throw new AriesFrameworkError('No connection record in message context.') + throw new CredoError('No connection record in message context.') } DidExchangeStateMachine.assertProcessMessageState(DidExchangeCompleteMessage.type, connectionRecord) @@ -535,7 +533,7 @@ export class DidExchangeProtocol { } if (!didRotateAttachment.data.base64) { - throw new AriesFrameworkError('DID Rotate attachment is missing base64 property for signed did.') + throw new CredoError('DID Rotate attachment is missing base64 property for signed did.') } // JWS payload must be base64url encoded @@ -543,7 +541,7 @@ export class DidExchangeProtocol { const signedDid = TypedArrayEncoder.fromBase64(base64UrlPayload).toString() if (signedDid !== message.did) { - throw new AriesFrameworkError( + throw new CredoError( `DID Rotate attachment's did ${message.did} does not correspond to message did ${message.did}` ) } @@ -555,7 +553,7 @@ export class DidExchangeProtocol { }, jwkResolver: ({ jws: { header } }) => { if (typeof header.kid !== 'string' || !isDid(header.kid, 'key')) { - throw new AriesFrameworkError('JWS header kid must be a did:key DID.') + throw new CredoError('JWS header kid must be a did:key DID.') } const didKey = DidKey.fromDid(header.kid) @@ -621,7 +619,7 @@ export class DidExchangeProtocol { } if (!didDocumentAttachment.data.base64) { - throw new AriesFrameworkError('DID Document attachment is missing base64 property for signed did document.') + throw new CredoError('DID Document attachment is missing base64 property for signed did document.') } // JWS payload must be base64url encoded @@ -634,7 +632,7 @@ export class DidExchangeProtocol { }, jwkResolver: ({ jws: { header } }) => { if (typeof header.kid !== 'string' || !isDid(header.kid, 'key')) { - throw new AriesFrameworkError('JWS header kid must be a did:key DID.') + throw new CredoError('JWS header kid must be a did:key DID.') } const didKey = DidKey.fromDid(header.kid) diff --git a/packages/core/src/modules/connections/DidExchangeStateMachine.ts b/packages/core/src/modules/connections/DidExchangeStateMachine.ts index 3d7cd96088..9a962ce77e 100644 --- a/packages/core/src/modules/connections/DidExchangeStateMachine.ts +++ b/packages/core/src/modules/connections/DidExchangeStateMachine.ts @@ -1,7 +1,7 @@ import type { ConnectionRecord } from './repository' import type { ParsedMessageType } from '../../utils/messageType' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { canHandleMessageType } from '../../utils/messageType' import { DidExchangeRequestMessage, DidExchangeResponseMessage, DidExchangeCompleteMessage } from './messages' @@ -53,10 +53,10 @@ export class DidExchangeStateMachine { public static assertCreateMessageState(messageType: ParsedMessageType, record: ConnectionRecord) { const rule = this.createMessageStateRules.find((r) => canHandleMessageType(r.message, messageType)) if (!rule) { - throw new AriesFrameworkError(`Could not find create message rule for ${messageType}`) + throw new CredoError(`Could not find create message rule for ${messageType}`) } if (rule.state !== record.state || rule.role !== record.role) { - throw new AriesFrameworkError( + throw new CredoError( `Record with role ${record.role} is in invalid state ${record.state} to create ${messageType}. Expected state for role ${rule.role} is ${rule.state}.` ) } @@ -65,10 +65,10 @@ export class DidExchangeStateMachine { public static assertProcessMessageState(messageType: ParsedMessageType, record: ConnectionRecord) { const rule = this.processMessageStateRules.find((r) => canHandleMessageType(r.message, messageType)) if (!rule) { - throw new AriesFrameworkError(`Could not find create message rule for ${messageType}`) + throw new CredoError(`Could not find create message rule for ${messageType}`) } if (rule.state !== record.state || rule.role !== record.role) { - throw new AriesFrameworkError( + throw new CredoError( `Record with role ${record.role} is in invalid state ${record.state} to process ${messageType.messageTypeUri}. Expected state for role ${rule.role} is ${rule.state}.` ) } @@ -79,7 +79,7 @@ export class DidExchangeStateMachine { .concat(this.processMessageStateRules) .find((r) => canHandleMessageType(r.message, messageType) && r.role === record.role) if (!rule) { - throw new AriesFrameworkError( + throw new CredoError( `Could not find create message rule for messageType ${messageType.messageTypeUri}, state ${record.state} and role ${record.role}` ) } diff --git a/packages/core/src/modules/connections/handlers/ConnectionRequestHandler.ts b/packages/core/src/modules/connections/handlers/ConnectionRequestHandler.ts index db107c7d4d..659ccab8eb 100644 --- a/packages/core/src/modules/connections/handlers/ConnectionRequestHandler.ts +++ b/packages/core/src/modules/connections/handlers/ConnectionRequestHandler.ts @@ -7,7 +7,7 @@ import type { ConnectionService } from '../services/ConnectionService' import { TransportService } from '../../../agent/TransportService' import { OutboundMessageContext } from '../../../agent/models' -import { AriesFrameworkError } from '../../../error/AriesFrameworkError' +import { CredoError } from '../../../error/CredoError' import { tryParseDid } from '../../dids/domain/parse' import { ConnectionRequestMessage } from '../messages' import { HandshakeProtocol } from '../models' @@ -38,7 +38,7 @@ export class ConnectionRequestHandler implements MessageHandler { const { agentContext, connection, recipientKey, senderKey, message, sessionId } = messageContext if (!recipientKey || !senderKey) { - throw new AriesFrameworkError('Unable to process connection request without senderVerkey or recipientKey') + throw new CredoError('Unable to process connection request without senderVerkey or recipientKey') } const parentThreadId = message.thread?.parentThreadId @@ -54,18 +54,16 @@ export class ConnectionRequestHandler implements MessageHandler { : await this.outOfBandService.findCreatedByRecipientKey(agentContext, recipientKey) if (!outOfBandRecord) { - throw new AriesFrameworkError(`Out-of-band record for recipient key ${recipientKey.fingerprint} was not found.`) + throw new CredoError(`Out-of-band record for recipient key ${recipientKey.fingerprint} was not found.`) } if (connection && !outOfBandRecord.reusable) { - throw new AriesFrameworkError( - `Connection record for non-reusable out-of-band ${outOfBandRecord.id} already exists.` - ) + throw new CredoError(`Connection record for non-reusable out-of-band ${outOfBandRecord.id} already exists.`) } const receivedDidRecord = await this.didRepository.findReceivedDidByRecipientKey(agentContext, senderKey) if (receivedDidRecord) { - throw new AriesFrameworkError(`A received did record for sender key ${senderKey.fingerprint} already exists.`) + throw new CredoError(`A received did record for sender key ${senderKey.fingerprint} already exists.`) } const connectionRecord = await this.connectionService.processRequest(messageContext, outOfBandRecord) diff --git a/packages/core/src/modules/connections/handlers/ConnectionResponseHandler.ts b/packages/core/src/modules/connections/handlers/ConnectionResponseHandler.ts index cdecad6c95..fd3ec2ac29 100644 --- a/packages/core/src/modules/connections/handlers/ConnectionResponseHandler.ts +++ b/packages/core/src/modules/connections/handlers/ConnectionResponseHandler.ts @@ -6,7 +6,7 @@ import type { ConnectionService } from '../services/ConnectionService' import { OutboundMessageContext } from '../../../agent/models' import { ReturnRouteTypes } from '../../../decorators/transport/TransportDecorator' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { ConnectionResponseMessage } from '../messages' import { DidExchangeRole } from '../models' @@ -34,7 +34,7 @@ export class ConnectionResponseHandler implements MessageHandler { const { recipientKey, senderKey, message } = messageContext if (!recipientKey || !senderKey) { - throw new AriesFrameworkError('Unable to process connection response without senderKey or recipientKey') + throw new CredoError('Unable to process connection response without senderKey or recipientKey') } // Query by both role and thread id to allow connecting to self @@ -44,11 +44,11 @@ export class ConnectionResponseHandler implements MessageHandler { message.threadId ) if (!connectionRecord) { - throw new AriesFrameworkError(`Connection for thread ID ${message.threadId} not found!`) + throw new CredoError(`Connection for thread ID ${message.threadId} not found!`) } if (!connectionRecord.did) { - throw new AriesFrameworkError(`Connection record ${connectionRecord.id} has no 'did'`) + throw new CredoError(`Connection record ${connectionRecord.id} has no 'did'`) } const ourDidDocument = await this.didResolverService.resolveDidDocument( @@ -56,15 +56,13 @@ export class ConnectionResponseHandler implements MessageHandler { connectionRecord.did ) if (!ourDidDocument) { - throw new AriesFrameworkError(`Did document for did ${connectionRecord.did} was not resolved!`) + throw new CredoError(`Did document for did ${connectionRecord.did} was not resolved!`) } // Validate if recipient key is included in recipient keys of the did document resolved by // connection record did if (!ourDidDocument.recipientKeys.find((key) => key.fingerprint === recipientKey.fingerprint)) { - throw new AriesFrameworkError( - `Recipient key ${recipientKey.fingerprint} not found in did document recipient keys.` - ) + throw new CredoError(`Recipient key ${recipientKey.fingerprint} not found in did document recipient keys.`) } const outOfBandRecord = @@ -72,7 +70,7 @@ export class ConnectionResponseHandler implements MessageHandler { (await this.outOfBandService.findById(messageContext.agentContext, connectionRecord.outOfBandId)) if (!outOfBandRecord) { - throw new AriesFrameworkError(`Out-of-band record ${connectionRecord.outOfBandId} was not found.`) + throw new CredoError(`Out-of-band record ${connectionRecord.outOfBandId} was not found.`) } messageContext.connection = connectionRecord diff --git a/packages/core/src/modules/connections/handlers/DidExchangeCompleteHandler.ts b/packages/core/src/modules/connections/handlers/DidExchangeCompleteHandler.ts index 5d4ad8eb6a..3b83f51112 100644 --- a/packages/core/src/modules/connections/handlers/DidExchangeCompleteHandler.ts +++ b/packages/core/src/modules/connections/handlers/DidExchangeCompleteHandler.ts @@ -2,7 +2,7 @@ import type { MessageHandler, MessageHandlerInboundMessage } from '../../../agen import type { OutOfBandService } from '../../oob/OutOfBandService' import type { DidExchangeProtocol } from '../DidExchangeProtocol' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { tryParseDid } from '../../dids/domain/parse' import { OutOfBandState } from '../../oob/domain/OutOfBandState' import { DidExchangeCompleteMessage } from '../messages' @@ -22,12 +22,12 @@ export class DidExchangeCompleteHandler implements MessageHandler { const { connection: connectionRecord } = messageContext if (!connectionRecord) { - throw new AriesFrameworkError(`Connection is missing in message context`) + throw new CredoError(`Connection is missing in message context`) } const { protocol } = connectionRecord if (protocol !== HandshakeProtocol.DidExchange) { - throw new AriesFrameworkError( + throw new CredoError( `Connection record protocol is ${protocol} but handler supports only ${HandshakeProtocol.DidExchange}.` ) } @@ -35,7 +35,7 @@ export class DidExchangeCompleteHandler implements MessageHandler { const { message } = messageContext const parentThreadId = message.thread?.parentThreadId if (!parentThreadId) { - throw new AriesFrameworkError(`Message does not contain pthid attribute`) + throw new CredoError(`Message does not contain pthid attribute`) } const outOfBandRecord = await this.outOfBandService.findByCreatedInvitationId( messageContext.agentContext, @@ -44,7 +44,7 @@ export class DidExchangeCompleteHandler implements MessageHandler { ) if (!outOfBandRecord) { - throw new AriesFrameworkError(`OutOfBand record for message ID ${message.thread?.parentThreadId} not found!`) + throw new CredoError(`OutOfBand record for message ID ${message.thread?.parentThreadId} not found!`) } if (!outOfBandRecord.reusable) { diff --git a/packages/core/src/modules/connections/handlers/DidExchangeRequestHandler.ts b/packages/core/src/modules/connections/handlers/DidExchangeRequestHandler.ts index 9f2f9f01f3..eab93bc9be 100644 --- a/packages/core/src/modules/connections/handlers/DidExchangeRequestHandler.ts +++ b/packages/core/src/modules/connections/handlers/DidExchangeRequestHandler.ts @@ -7,7 +7,7 @@ import type { DidExchangeProtocol } from '../DidExchangeProtocol' import { TransportService } from '../../../agent/TransportService' import { OutboundMessageContext } from '../../../agent/models' -import { AriesFrameworkError } from '../../../error/AriesFrameworkError' +import { CredoError } from '../../../error/CredoError' import { tryParseDid } from '../../dids/domain/parse' import { OutOfBandState } from '../../oob/domain/OutOfBandState' import { DidExchangeRequestMessage } from '../messages' @@ -39,13 +39,13 @@ export class DidExchangeRequestHandler implements MessageHandler { const { agentContext, recipientKey, senderKey, message, connection, sessionId } = messageContext if (!recipientKey || !senderKey) { - throw new AriesFrameworkError('Unable to process connection request without senderKey or recipientKey') + throw new CredoError('Unable to process connection request without senderKey or recipientKey') } const parentThreadId = message.thread?.parentThreadId if (!parentThreadId) { - throw new AriesFrameworkError(`Message does not contain 'pthid' attribute`) + throw new CredoError(`Message does not contain 'pthid' attribute`) } const outOfBandRecord = tryParseDid(parentThreadId) @@ -57,26 +57,22 @@ export class DidExchangeRequestHandler implements MessageHandler { }) : await this.outOfBandService.findByCreatedInvitationId(agentContext, parentThreadId) if (!outOfBandRecord) { - throw new AriesFrameworkError(`OutOfBand record for message ID ${parentThreadId} not found!`) + throw new CredoError(`OutOfBand record for message ID ${parentThreadId} not found!`) } if (connection && !outOfBandRecord.reusable) { - throw new AriesFrameworkError( - `Connection record for non-reusable out-of-band ${outOfBandRecord.id} already exists.` - ) + throw new CredoError(`Connection record for non-reusable out-of-band ${outOfBandRecord.id} already exists.`) } const receivedDidRecord = await this.didRepository.findReceivedDidByRecipientKey(agentContext, senderKey) if (receivedDidRecord) { - throw new AriesFrameworkError(`A received did record for sender key ${senderKey.fingerprint} already exists.`) + throw new CredoError(`A received did record for sender key ${senderKey.fingerprint} already exists.`) } // TODO Shouldn't we check also if the keys match the keys from oob invitation services? if (outOfBandRecord.state === OutOfBandState.Done) { - throw new AriesFrameworkError( - 'Out-of-band record has been already processed and it does not accept any new requests' - ) + throw new CredoError('Out-of-band record has been already processed and it does not accept any new requests') } const connectionRecord = await this.didExchangeProtocol.processRequest(messageContext, outOfBandRecord) diff --git a/packages/core/src/modules/connections/handlers/DidExchangeResponseHandler.ts b/packages/core/src/modules/connections/handlers/DidExchangeResponseHandler.ts index 743a0f1720..24b0ba892e 100644 --- a/packages/core/src/modules/connections/handlers/DidExchangeResponseHandler.ts +++ b/packages/core/src/modules/connections/handlers/DidExchangeResponseHandler.ts @@ -7,7 +7,7 @@ import type { ConnectionService } from '../services' import { OutboundMessageContext } from '../../../agent/models' import { ReturnRouteTypes } from '../../../decorators/transport/TransportDecorator' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { OutOfBandState } from '../../oob/domain/OutOfBandState' import { DidExchangeResponseMessage } from '../messages' import { DidExchangeRole, HandshakeProtocol } from '../models' @@ -38,7 +38,7 @@ export class DidExchangeResponseHandler implements MessageHandler { const { agentContext, recipientKey, senderKey, message } = messageContext if (!recipientKey || !senderKey) { - throw new AriesFrameworkError('Unable to process connection response without sender key or recipient key') + throw new CredoError('Unable to process connection response without sender key or recipient key') } const connectionRecord = await this.connectionService.getByRoleAndThreadId( @@ -47,41 +47,39 @@ export class DidExchangeResponseHandler implements MessageHandler { message.threadId ) if (!connectionRecord) { - throw new AriesFrameworkError(`Connection for thread ID ${message.threadId} not found!`) + throw new CredoError(`Connection for thread ID ${message.threadId} not found!`) } if (!connectionRecord.did) { - throw new AriesFrameworkError(`Connection record ${connectionRecord.id} has no 'did'`) + throw new CredoError(`Connection record ${connectionRecord.id} has no 'did'`) } const ourDidDocument = await this.didResolverService.resolveDidDocument(agentContext, connectionRecord.did) if (!ourDidDocument) { - throw new AriesFrameworkError(`Did document for did ${connectionRecord.did} was not resolved`) + throw new CredoError(`Did document for did ${connectionRecord.did} was not resolved`) } // Validate if recipient key is included in recipient keys of the did document resolved by // connection record did if (!ourDidDocument.recipientKeys.find((key) => key.fingerprint === recipientKey.fingerprint)) { - throw new AriesFrameworkError( - `Recipient key ${recipientKey.fingerprint} not found in did document recipient keys.` - ) + throw new CredoError(`Recipient key ${recipientKey.fingerprint} not found in did document recipient keys.`) } const { protocol } = connectionRecord if (protocol !== HandshakeProtocol.DidExchange) { - throw new AriesFrameworkError( + throw new CredoError( `Connection record protocol is ${protocol} but handler supports only ${HandshakeProtocol.DidExchange}.` ) } if (!connectionRecord.outOfBandId) { - throw new AriesFrameworkError(`Connection ${connectionRecord.id} does not have outOfBandId!`) + throw new CredoError(`Connection ${connectionRecord.id} does not have outOfBandId!`) } const outOfBandRecord = await this.outOfBandService.findById(agentContext, connectionRecord.outOfBandId) if (!outOfBandRecord) { - throw new AriesFrameworkError( + throw new CredoError( `OutOfBand record for connection ${connectionRecord.id} with outOfBandId ${connectionRecord.outOfBandId} not found!` ) } diff --git a/packages/core/src/modules/connections/handlers/DidRotateHandler.ts b/packages/core/src/modules/connections/handlers/DidRotateHandler.ts index 9533253572..458f5bdb86 100644 --- a/packages/core/src/modules/connections/handlers/DidRotateHandler.ts +++ b/packages/core/src/modules/connections/handlers/DidRotateHandler.ts @@ -2,7 +2,7 @@ import type { MessageHandler, MessageHandlerInboundMessage } from '../../../agen import type { DidRotateService } from '../services' import type { ConnectionService } from '../services/ConnectionService' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { DidRotateMessage } from '../messages' export class DidRotateHandler implements MessageHandler { @@ -18,7 +18,7 @@ export class DidRotateHandler implements MessageHandler { public async handle(messageContext: MessageHandlerInboundMessage) { const { connection, recipientKey } = messageContext if (!connection) { - throw new AriesFrameworkError(`Connection for verkey ${recipientKey?.fingerprint} not found!`) + throw new CredoError(`Connection for verkey ${recipientKey?.fingerprint} not found!`) } return this.didRotateService.processRotate(messageContext) diff --git a/packages/core/src/modules/connections/handlers/TrustPingMessageHandler.ts b/packages/core/src/modules/connections/handlers/TrustPingMessageHandler.ts index 52da1423df..37b36d1929 100644 --- a/packages/core/src/modules/connections/handlers/TrustPingMessageHandler.ts +++ b/packages/core/src/modules/connections/handlers/TrustPingMessageHandler.ts @@ -2,7 +2,7 @@ import type { MessageHandler, MessageHandlerInboundMessage } from '../../../agen import type { ConnectionService } from '../services/ConnectionService' import type { TrustPingService } from '../services/TrustPingService' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { TrustPingMessage } from '../messages' import { DidExchangeState } from '../models' @@ -19,7 +19,7 @@ export class TrustPingMessageHandler implements MessageHandler { public async handle(messageContext: MessageHandlerInboundMessage) { const { connection, recipientKey } = messageContext if (!connection) { - throw new AriesFrameworkError(`Connection for verkey ${recipientKey?.fingerprint} not found!`) + throw new CredoError(`Connection for verkey ${recipientKey?.fingerprint} not found!`) } // TODO: This is better addressed in a middleware of some kind because diff --git a/packages/core/src/modules/connections/messages/ConnectionInvitationMessage.ts b/packages/core/src/modules/connections/messages/ConnectionInvitationMessage.ts index 30cf5f1499..420a1ea8f3 100644 --- a/packages/core/src/modules/connections/messages/ConnectionInvitationMessage.ts +++ b/packages/core/src/modules/connections/messages/ConnectionInvitationMessage.ts @@ -5,7 +5,7 @@ import { ArrayNotEmpty, IsArray, IsOptional, IsString, IsUrl, ValidateIf } from import { parseUrl } from 'query-string' import { AgentMessage } from '../../../agent/AgentMessage' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonEncoder } from '../../../utils/JsonEncoder' import { JsonTransformer } from '../../../utils/JsonTransformer' import { IsValidMessageType, parseMessageType, replaceLegacyDidSovPrefix } from '../../../utils/messageType' @@ -59,7 +59,7 @@ export class ConnectionInvitationMessage extends AgentMessage { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (options.did && (options.recipientKeys || options.routingKeys || options.serviceEndpoint)) { - throw new AriesFrameworkError( + throw new CredoError( 'either the did or the recipientKeys/serviceEndpoint/routingKeys must be set, but not both' ) } @@ -140,7 +140,7 @@ export class ConnectionInvitationMessage extends AgentMessage { return invitation } else { - throw new AriesFrameworkError('InvitationUrl is invalid. Needs to be encoded with either c_i, d_m, or oob') + throw new CredoError('InvitationUrl is invalid. Needs to be encoded with either c_i, d_m, or oob') } } } diff --git a/packages/core/src/modules/connections/models/did/authentication/index.ts b/packages/core/src/modules/connections/models/did/authentication/index.ts index 4524bfff0b..989e4d12ef 100644 --- a/packages/core/src/modules/connections/models/did/authentication/index.ts +++ b/packages/core/src/modules/connections/models/did/authentication/index.ts @@ -2,7 +2,7 @@ import type { ClassConstructor } from 'class-transformer' import { Transform, TransformationType, plainToInstance, instanceToPlain } from 'class-transformer' -import { AriesFrameworkError } from '../../../../../error' +import { CredoError } from '../../../../../error' import { PublicKey, publicKeyTypes } from '../publicKey' import { Authentication } from './Authentication' @@ -45,7 +45,7 @@ export function AuthenticationTransformer() { const publicKeyJson = obj.publicKey.find((publicKey) => publicKey.id === auth.publicKey) if (!publicKeyJson) { - throw new AriesFrameworkError(`Invalid public key referenced ${auth.publicKey}`) + throw new CredoError(`Invalid public key referenced ${auth.publicKey}`) } // Referenced keys use other types than embedded keys. diff --git a/packages/core/src/modules/connections/repository/ConnectionRecord.ts b/packages/core/src/modules/connections/repository/ConnectionRecord.ts index f25fa5ee1c..beb7154be4 100644 --- a/packages/core/src/modules/connections/repository/ConnectionRecord.ts +++ b/packages/core/src/modules/connections/repository/ConnectionRecord.ts @@ -4,7 +4,7 @@ import type { ConnectionType } from '../models/ConnectionType' import { Transform } from 'class-transformer' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { BaseRecord } from '../../../storage/BaseRecord' import { uuid } from '../../../utils/uuid' import { rfc0160StateFromDidExchangeState, DidExchangeRole, DidExchangeState, HandshakeProtocol } from '../models' @@ -144,7 +144,7 @@ export class ConnectionRecord extends BaseRecord key.publicKeyBase58 === recipientKey) if (!recipientKeyFound) { - throw new AriesFrameworkError(`Recipient key ${recipientKey} not found in our service`) + throw new CredoError(`Recipient key ${recipientKey} not found in our service`) } } @@ -534,7 +534,7 @@ export class ConnectionService { if (senderKey && theirService) { const senderKeyFound = theirService.recipientKeys.some((key) => key.publicKeyBase58 === senderKey) if (!senderKeyFound) { - throw new AriesFrameworkError(`Sender key ${senderKey} not found in their service.`) + throw new CredoError(`Sender key ${senderKey} not found in their service.`) } } } @@ -552,7 +552,7 @@ export class ConnectionService { { expectedConnectionId }: { expectedConnectionId?: string } ) { if (expectedConnectionId && messageContext.connection?.id === expectedConnectionId) { - throw new AriesFrameworkError( + throw new CredoError( `Expecting incoming message to have connection ${expectedConnectionId}, but incoming connection is ${ messageContext.connection?.id ?? 'undefined' }` @@ -571,7 +571,7 @@ export class ConnectionService { // There is no out of band record if (!outOfBandRecord) { - throw new AriesFrameworkError( + throw new CredoError( `No out of band record found for credential request message with thread ${messageContext.message.threadId}, out of band invitation id ${outOfBandInvitationId} and role ${OutOfBandRole.Sender}` ) } @@ -583,7 +583,7 @@ export class ConnectionService { legacyInvitationMetadata?.legacyInvitationType !== InvitationType.Connectionless && outOfBandRecord.outOfBandInvitation.id !== outOfBandInvitationId ) { - throw new AriesFrameworkError( + throw new CredoError( 'Response messages to out of band invitation requests MUST have a parent thread id that matches the out of band invitation id.' ) } @@ -591,19 +591,17 @@ export class ConnectionService { // This should not happen, as it is not allowed to create reusable out of band invitations with attached messages // But should that implementation change, we at least cover it here. if (outOfBandRecord.reusable) { - throw new AriesFrameworkError( - 'Receiving messages in response to reusable out of band invitations is not supported.' - ) + throw new CredoError('Receiving messages in response to reusable out of band invitations is not supported.') } if (outOfBandRecord.state === OutOfBandState.Done) { if (!messageContext.connection) { - throw new AriesFrameworkError( + throw new CredoError( "Can't find connection associated with incoming message, while out of band state is done. State must be await response if no connection has been created" ) } if (messageContext.connection.outOfBandId !== outOfBandRecord.id) { - throw new AriesFrameworkError( + throw new CredoError( 'Connection associated with incoming message is not associated with the out of band invitation containing the attached message.' ) } @@ -616,7 +614,7 @@ export class ConnectionService { outOfBandRecord.state = OutOfBandState.Done await outOfBandRepository.update(messageContext.agentContext, outOfBandRecord) } else { - throw new AriesFrameworkError(`Out of band record is in incorrect state ${outOfBandRecord.state}`) + throw new CredoError(`Out of band record is in incorrect state ${outOfBandRecord.state}`) } } diff --git a/packages/core/src/modules/connections/services/DidRotateService.ts b/packages/core/src/modules/connections/services/DidRotateService.ts index 23b9a5b7d5..d02812a61c 100644 --- a/packages/core/src/modules/connections/services/DidRotateService.ts +++ b/packages/core/src/modules/connections/services/DidRotateService.ts @@ -5,7 +5,7 @@ import type { ConnectionRecord } from '../repository/ConnectionRecord' import { OutboundMessageContext } from '../../../agent/models' import { InjectionSymbols } from '../../../constants' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { Logger } from '../../../logger' import { inject, injectable } from '../../../plugins' import { AckStatus } from '../../common' @@ -47,9 +47,7 @@ export class DidRotateService { const didRotateMetadata = connection.metadata.get(ConnectionMetadataKeys.DidRotate) if (didRotateMetadata) { - throw new AriesFrameworkError( - `There is already an existing opened did rotation flow for connection id ${connection.id}` - ) + throw new CredoError(`There is already an existing opened did rotation flow for connection id ${connection.id}`) } let didDocument, mediatorId @@ -61,7 +59,7 @@ export class DidRotateService { // Otherwise, create a did:peer based on the provided routing } else { if (!routing) { - throw new AriesFrameworkError('Routing configuration must be defined when rotating to a new peer did') + throw new CredoError('Routing configuration must be defined when rotating to a new peer did') } didDocument = await createPeerDidFromServices( @@ -215,11 +213,11 @@ export class DidRotateService { const didRotateMetadata = connection.metadata.get(ConnectionMetadataKeys.DidRotate) if (!didRotateMetadata) { - throw new AriesFrameworkError(`No did rotation data found for connection with id '${connection.id}'`) + throw new CredoError(`No did rotation data found for connection with id '${connection.id}'`) } if (didRotateMetadata.threadId !== message.threadId) { - throw new AriesFrameworkError( + throw new CredoError( `Existing did rotation flow thread id '${didRotateMetadata.threadId} does not match incoming message'` ) } @@ -254,7 +252,7 @@ export class DidRotateService { const didRotateMetadata = connection.metadata.get(ConnectionMetadataKeys.DidRotate) if (!didRotateMetadata) { - throw new AriesFrameworkError(`No did rotation data found for connection with id '${connection.id}'`) + throw new CredoError(`No did rotation data found for connection with id '${connection.id}'`) } connection.metadata.delete(ConnectionMetadataKeys.DidRotate) @@ -266,7 +264,7 @@ export class DidRotateService { const didRotateMetadata = connection.metadata.get(ConnectionMetadataKeys.DidRotate) if (!didRotateMetadata) { - throw new AriesFrameworkError(`No did rotation data found for connection with id '${connection.id}'`) + throw new CredoError(`No did rotation data found for connection with id '${connection.id}'`) } connection.metadata.delete(ConnectionMetadataKeys.DidRotate) diff --git a/packages/core/src/modules/connections/services/helpers.ts b/packages/core/src/modules/connections/services/helpers.ts index e0dc91a93a..4a3b6ebba8 100644 --- a/packages/core/src/modules/connections/services/helpers.ts +++ b/packages/core/src/modules/connections/services/helpers.ts @@ -5,7 +5,7 @@ import type { DidDocument, PeerDidNumAlgo } from '../../dids' import type { DidDoc, PublicKey } from '../models' import { Key, KeyType } from '../../../crypto' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { IndyAgentService, DidCommV1Service, @@ -110,7 +110,7 @@ function normalizeId(fullId: string): `#${string}` { function convertPublicKeyToVerificationMethod(publicKey: PublicKey) { if (!publicKey.value) { - throw new AriesFrameworkError(`Public key ${publicKey.id} does not have value property`) + throw new CredoError(`Public key ${publicKey.id} does not have value property`) } const publicKeyBase58 = publicKey.value const ed25519Key = Key.fromPublicKeyBase58(publicKeyBase58, KeyType.Ed25519) @@ -134,7 +134,7 @@ export async function getDidDocumentForCreatedDid(agentContext: AgentContext, di const didRecord = await agentContext.dependencyManager.resolve(DidRepository).findCreatedDid(agentContext, did) if (!didRecord?.didDocument) { - throw new AriesFrameworkError(`Could not get DidDocument for created did ${did}`) + throw new CredoError(`Could not get DidDocument for created did ${did}`) } return didRecord.didDocument } @@ -159,7 +159,7 @@ export async function createPeerDidFromServices( }) if (result.didState?.state !== 'finished') { - throw new AriesFrameworkError(`Did document creation failed: ${JSON.stringify(result.didState)}`) + throw new CredoError(`Did document creation failed: ${JSON.stringify(result.didState)}`) } return result.didState.didDocument diff --git a/packages/core/src/modules/credentials/CredentialsApi.ts b/packages/core/src/modules/credentials/CredentialsApi.ts index 8cdcc0f1f5..c2dc9ab29e 100644 --- a/packages/core/src/modules/credentials/CredentialsApi.ts +++ b/packages/core/src/modules/credentials/CredentialsApi.ts @@ -27,7 +27,7 @@ import { AgentContext } from '../../agent' import { MessageSender } from '../../agent/MessageSender' import { getOutboundMessageContext } from '../../agent/getOutboundMessageContext' import { InjectionSymbols } from '../../constants' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { Logger } from '../../logger' import { inject, injectable } from '../../plugins' import { DidCommMessageRepository } from '../../storage/didcomm/DidCommMessageRepository' @@ -130,7 +130,7 @@ export class CredentialsApi implements Credent const credentialProtocol = this.config.credentialProtocols.find((protocol) => protocol.version === protocolVersion) if (!credentialProtocol) { - throw new AriesFrameworkError(`No credential protocol registered for protocol version ${protocolVersion}`) + throw new CredoError(`No credential protocol registered for protocol version ${protocolVersion}`) } return credentialProtocol @@ -182,7 +182,7 @@ export class CredentialsApi implements Credent const credentialRecord = await this.getById(options.credentialRecordId) if (!credentialRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connectionId found for credential record '${credentialRecord.id}'. Connection-less issuance does not support credential proposal or negotiation.` ) } @@ -225,7 +225,7 @@ export class CredentialsApi implements Credent const credentialRecord = await this.getById(options.credentialRecordId) if (!credentialRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connection id for credential record ${credentialRecord.id} not found. Connection-less issuance does not support negotiation` ) } @@ -297,7 +297,7 @@ export class CredentialsApi implements Credent this.logger.debug(`Got a credentialProtocol object for this version; version = ${protocol.version}`) const offerMessage = await protocol.findOfferMessage(this.agentContext, credentialRecord.id) if (!offerMessage) { - throw new AriesFrameworkError(`No offer message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No offer message found for credential record with id '${credentialRecord.id}'`) } // Use connection if present @@ -339,7 +339,7 @@ export class CredentialsApi implements Credent const credentialRecord = await this.getById(options.credentialRecordId) if (!credentialRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connection id for credential record ${credentialRecord.id} not found. Connection-less issuance does not support negotiation` ) } @@ -414,11 +414,11 @@ export class CredentialsApi implements Credent const requestMessage = await protocol.findRequestMessage(this.agentContext, credentialRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No request message found for credential record with id '${credentialRecord.id}'`) } const offerMessage = await protocol.findOfferMessage(this.agentContext, credentialRecord.id) if (!offerMessage) { - throw new AriesFrameworkError(`No offer message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No offer message found for credential record with id '${credentialRecord.id}'`) } const { message } = await protocol.acceptRequest(this.agentContext, { @@ -465,13 +465,11 @@ export class CredentialsApi implements Credent const requestMessage = await protocol.findRequestMessage(this.agentContext, credentialRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No request message found for credential record with id '${credentialRecord.id}'`) } const credentialMessage = await protocol.findCredentialMessage(this.agentContext, credentialRecord.id) if (!credentialMessage) { - throw new AriesFrameworkError( - `No credential message found for credential record with id '${credentialRecord.id}'` - ) + throw new CredoError(`No credential message found for credential record with id '${credentialRecord.id}'`) } const { message } = await protocol.acceptCredential(this.agentContext, { @@ -509,12 +507,12 @@ export class CredentialsApi implements Credent const requestMessage = await protocol.findRequestMessage(this.agentContext, credentialRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No request message found for credential record with id '${credentialRecord.id}'`) } const offerMessage = await protocol.findOfferMessage(this.agentContext, credentialRecord.id) if (!offerMessage) { - throw new AriesFrameworkError(`No offer message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No offer message found for credential record with id '${credentialRecord.id}'`) } // Use connection if present @@ -540,7 +538,7 @@ export class CredentialsApi implements Credent public async sendProblemReport(options: SendCredentialProblemReportOptions) { const credentialRecord = await this.getById(options.credentialRecordId) if (!credentialRecord.connectionId) { - throw new AriesFrameworkError(`No connectionId found for credential record '${credentialRecord.id}'.`) + throw new CredoError(`No connectionId found for credential record '${credentialRecord.id}'.`) } const connectionRecord = await this.connectionService.getById(this.agentContext, credentialRecord.connectionId) diff --git a/packages/core/src/modules/credentials/formats/jsonld/JsonLdCredentialFormatService.ts b/packages/core/src/modules/credentials/formats/jsonld/JsonLdCredentialFormatService.ts index 1e38975f97..3829d4b7cb 100644 --- a/packages/core/src/modules/credentials/formats/jsonld/JsonLdCredentialFormatService.ts +++ b/packages/core/src/modules/credentials/formats/jsonld/JsonLdCredentialFormatService.ts @@ -25,7 +25,7 @@ import type { } from '../CredentialFormatServiceOptions' import { Attachment, AttachmentData } from '../../../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { JsonEncoder, areObjectsEqual } from '../../../../utils' import { JsonTransformer } from '../../../../utils/JsonTransformer' import { findVerificationMethodByKeyType } from '../../../dids/domain/DidDocument' @@ -60,7 +60,7 @@ export class JsonLdCredentialFormatService implements CredentialFormatService() if (!credProposalJson) { - throw new AriesFrameworkError('Missing jsonld credential proposal data payload') + throw new CredoError('Missing jsonld credential proposal data payload') } // validation is done in here @@ -128,7 +128,7 @@ export class JsonLdCredentialFormatService implements CredentialFormatService() if (!credentialOfferJson) { - throw new AriesFrameworkError('Missing jsonld credential offer data payload') + throw new CredoError('Missing jsonld credential offer data payload') } JsonTransformer.fromJSON(credentialOfferJson, JsonLdCredentialDetail) @@ -185,7 +185,7 @@ export class JsonLdCredentialFormatService implements CredentialFormatService() if (!requestJson) { - throw new AriesFrameworkError('Missing jsonld credential request data payload') + throw new CredoError('Missing jsonld credential request data payload') } // validate @@ -225,7 +225,7 @@ export class JsonLdCredentialFormatService implements CredentialFormatService options[field] !== undefined) if (foundFields.length > 0) { - throw new AriesFrameworkError( - `Some fields are not currently supported in credential options: ${foundFields.join(', ')}` - ) + throw new CredoError(`Some fields are not currently supported in credential options: ${foundFields.join(', ')}`) } const credential = JsonTransformer.fromJSON(credentialRequest.credential, W3cCredential) @@ -288,12 +286,12 @@ export class JsonLdCredentialFormatService implements CredentialFormatService::"` ) } @@ -141,7 +141,7 @@ export class RevocationNotificationService { const credentialId = messageContext.message.credentialId if (![v2IndyRevocationFormat, v2AnonCredsRevocationFormat].includes(messageContext.message.revocationFormat)) { - throw new AriesFrameworkError( + throw new CredoError( `Unknown revocation format: ${messageContext.message.revocationFormat}. Supported formats are indy-anoncreds and anoncreds` ) } @@ -150,7 +150,7 @@ export class RevocationNotificationService { const credentialIdGroups = credentialId.match(v2IndyRevocationIdentifierRegex) ?? credentialId.match(v2AnonCredsRevocationIdentifierRegex) if (!credentialIdGroups) { - throw new AriesFrameworkError( + throw new CredoError( `Incorrect revocation notification credentialId format: \n${credentialId}\ndoes not match\n"::"` ) } diff --git a/packages/core/src/modules/credentials/protocol/v2/CredentialFormatCoordinator.ts b/packages/core/src/modules/credentials/protocol/v2/CredentialFormatCoordinator.ts index c8fe64e86d..83c74dcc39 100644 --- a/packages/core/src/modules/credentials/protocol/v2/CredentialFormatCoordinator.ts +++ b/packages/core/src/modules/credentials/protocol/v2/CredentialFormatCoordinator.ts @@ -4,7 +4,7 @@ import type { CredentialFormatPayload, CredentialFormatService, ExtractCredentia import type { CredentialFormatSpec } from '../../models' import type { CredentialExchangeRecord } from '../../repository/CredentialExchangeRecord' -import { AriesFrameworkError } from '../../../../error/AriesFrameworkError' +import { CredoError } from '../../../../error/CredoError' import { DidCommMessageRepository, DidCommMessageRole } from '../../../../storage' import { @@ -557,7 +557,7 @@ export class CredentialFormatCoordinator const attachment = attachments.find((attachment) => attachment.id === attachmentId) if (!attachment) { - throw new AriesFrameworkError(`Attachment with id ${attachmentId} not found in attachments.`) + throw new CredoError(`Attachment with id ${attachmentId} not found in attachments.`) } return attachment @@ -566,7 +566,7 @@ export class CredentialFormatCoordinator private getAttachmentIdForService(credentialFormatService: CredentialFormatService, formats: CredentialFormatSpec[]) { const format = formats.find((format) => credentialFormatService.supportsFormat(format.format)) - if (!format) throw new AriesFrameworkError(`No attachment found for service ${credentialFormatService.formatKey}`) + if (!format) throw new CredoError(`No attachment found for service ${credentialFormatService.formatKey}`) return format.attachmentId } diff --git a/packages/core/src/modules/credentials/protocol/v2/V2CredentialProtocol.ts b/packages/core/src/modules/credentials/protocol/v2/V2CredentialProtocol.ts index 5d764fb5aa..ab9e89602a 100644 --- a/packages/core/src/modules/credentials/protocol/v2/V2CredentialProtocol.ts +++ b/packages/core/src/modules/credentials/protocol/v2/V2CredentialProtocol.ts @@ -30,7 +30,7 @@ import type { } from '../CredentialProtocolOptions' import { Protocol } from '../../../../agent/models/features/Protocol' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { DidCommMessageRepository } from '../../../../storage' import { uuid } from '../../../../utils/uuid' import { AckStatus } from '../../../common' @@ -122,7 +122,7 @@ export class V2CredentialProtocol { }) expect(aliceCredentialRecord.type).toBe(CredentialExchangeRecord.type) if (!aliceCredentialRecord.connectionId) { - throw new AriesFrameworkError('missing alice connection id') + throw new CredoError('missing alice connection id') } // we do not need to specify connection id in this object diff --git a/packages/core/src/modules/credentials/protocol/v2/handlers/V2IssueCredentialHandler.ts b/packages/core/src/modules/credentials/protocol/v2/handlers/V2IssueCredentialHandler.ts index 9f1ee870f2..f4217183bb 100644 --- a/packages/core/src/modules/credentials/protocol/v2/handlers/V2IssueCredentialHandler.ts +++ b/packages/core/src/modules/credentials/protocol/v2/handlers/V2IssueCredentialHandler.ts @@ -4,7 +4,7 @@ import type { CredentialExchangeRecord } from '../../../repository/CredentialExc import type { V2CredentialProtocol } from '../V2CredentialProtocol' import { getOutboundMessageContext } from '../../../../../agent/getOutboundMessageContext' -import { AriesFrameworkError } from '../../../../../error' +import { CredoError } from '../../../../../error' import { V2IssueCredentialMessage } from '../messages/V2IssueCredentialMessage' export class V2IssueCredentialHandler implements MessageHandler { @@ -42,7 +42,7 @@ export class V2IssueCredentialHandler implements MessageHandler { credentialRecord.id ) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for credential record with id '${credentialRecord.id}'`) + throw new CredoError(`No request message found for credential record with id '${credentialRecord.id}'`) } return getOutboundMessageContext(messageContext.agentContext, { diff --git a/packages/core/src/modules/credentials/protocol/v2/handlers/V2RequestCredentialHandler.ts b/packages/core/src/modules/credentials/protocol/v2/handlers/V2RequestCredentialHandler.ts index 98f04deb1a..757598f4cf 100644 --- a/packages/core/src/modules/credentials/protocol/v2/handlers/V2RequestCredentialHandler.ts +++ b/packages/core/src/modules/credentials/protocol/v2/handlers/V2RequestCredentialHandler.ts @@ -4,7 +4,7 @@ import type { CredentialExchangeRecord } from '../../../repository' import type { V2CredentialProtocol } from '../V2CredentialProtocol' import { getOutboundMessageContext } from '../../../../../agent/getOutboundMessageContext' -import { AriesFrameworkError } from '../../../../../error' +import { CredoError } from '../../../../../error' import { V2RequestCredentialMessage } from '../messages/V2RequestCredentialMessage' export class V2RequestCredentialHandler implements MessageHandler { @@ -40,7 +40,7 @@ export class V2RequestCredentialHandler implements MessageHandler { credentialRecord.id ) if (!offerMessage) { - throw new AriesFrameworkError(`Could not find offer message for credential record with id ${credentialRecord.id}`) + throw new CredoError(`Could not find offer message for credential record with id ${credentialRecord.id}`) } const { message } = await this.credentialProtocol.acceptRequest(messageContext.agentContext, { diff --git a/packages/core/src/modules/credentials/repository/CredentialExchangeRecord.ts b/packages/core/src/modules/credentials/repository/CredentialExchangeRecord.ts index bb1a41c079..600ee6c06b 100644 --- a/packages/core/src/modules/credentials/repository/CredentialExchangeRecord.ts +++ b/packages/core/src/modules/credentials/repository/CredentialExchangeRecord.ts @@ -6,7 +6,7 @@ import type { RevocationNotification } from '../models/RevocationNotification' import { Type } from 'class-transformer' import { Attachment } from '../../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { BaseRecord } from '../../../storage/BaseRecord' import { uuid } from '../../../utils/uuid' import { CredentialPreviewAttribute } from '../models/CredentialPreviewAttribute' @@ -100,7 +100,7 @@ export class CredentialExchangeRecord extends BaseRecord key.id.endsWith(keyId)) if (!verificationMethod) { - throw new AriesFrameworkError(`Unable to locate verification method with id '${keyId}'`) + throw new CredoError(`Unable to locate verification method with id '${keyId}'`) } return verificationMethod @@ -144,7 +144,7 @@ export class DidDocument { } } - throw new AriesFrameworkError(`Unable to locate verification method with id '${keyId}' in purposes ${purposes}`) + throw new CredoError(`Unable to locate verification method with id '${keyId}' in purposes ${purposes}`) } /** diff --git a/packages/core/src/modules/dids/domain/key-type/bls12381g1.ts b/packages/core/src/modules/dids/domain/key-type/bls12381g1.ts index 523b205faf..edcbd2d97c 100644 --- a/packages/core/src/modules/dids/domain/key-type/bls12381g1.ts +++ b/packages/core/src/modules/dids/domain/key-type/bls12381g1.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import type { VerificationMethod } from '../verificationMethod' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getKeyFromBls12381G1Key2020, isBls12381G1Key2020, @@ -21,7 +21,7 @@ export const keyDidBls12381g1: KeyDidMapping = { return getKeyFromBls12381G1Key2020(verificationMethod) } - throw new AriesFrameworkError( + throw new CredoError( `Verification method with type '${verificationMethod.type}' not supported for key type '${KeyType.Bls12381g1}'` ) }, diff --git a/packages/core/src/modules/dids/domain/key-type/bls12381g1g2.ts b/packages/core/src/modules/dids/domain/key-type/bls12381g1g2.ts index d906497cca..e5d402de4c 100644 --- a/packages/core/src/modules/dids/domain/key-type/bls12381g1g2.ts +++ b/packages/core/src/modules/dids/domain/key-type/bls12381g1g2.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import { Key } from '../../../../crypto/Key' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getBls12381G1Key2020, getBls12381G2Key2020 } from '../verificationMethod' export function getBls12381g1g2VerificationMethod(did: string, key: Key) { @@ -31,6 +31,6 @@ export const keyDidBls12381g1g2: KeyDidMapping = { // For a G1G2 key, we return two verification methods getVerificationMethods: getBls12381g1g2VerificationMethod, getKeyFromVerificationMethod: () => { - throw new AriesFrameworkError('Not supported for bls12381g1g2 key') + throw new CredoError('Not supported for bls12381g1g2 key') }, } diff --git a/packages/core/src/modules/dids/domain/key-type/bls12381g2.ts b/packages/core/src/modules/dids/domain/key-type/bls12381g2.ts index e99a3b43d6..395bb083fa 100644 --- a/packages/core/src/modules/dids/domain/key-type/bls12381g2.ts +++ b/packages/core/src/modules/dids/domain/key-type/bls12381g2.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import type { VerificationMethod } from '../verificationMethod' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getBls12381G2Key2020, getKeyFromBls12381G2Key2020, @@ -22,7 +22,7 @@ export const keyDidBls12381g2: KeyDidMapping = { return getKeyFromBls12381G2Key2020(verificationMethod) } - throw new AriesFrameworkError( + throw new CredoError( `Verification method with type '${verificationMethod.type}' not supported for key type '${KeyType.Bls12381g2}'` ) }, diff --git a/packages/core/src/modules/dids/domain/key-type/ed25519.ts b/packages/core/src/modules/dids/domain/key-type/ed25519.ts index b1184242eb..35754ca407 100644 --- a/packages/core/src/modules/dids/domain/key-type/ed25519.ts +++ b/packages/core/src/modules/dids/domain/key-type/ed25519.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import type { VerificationMethod } from '../verificationMethod' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getKeyFromEd25519VerificationKey2018, isEd25519VerificationKey2018, @@ -48,7 +48,7 @@ export const keyDidEd25519: KeyDidMapping = { return getKeyFromMultikey(verificationMethod) } - throw new AriesFrameworkError( + throw new CredoError( `Verification method with type '${verificationMethod.type}' not supported for key type '${KeyType.Ed25519}'` ) }, diff --git a/packages/core/src/modules/dids/domain/key-type/keyDidJsonWebKey.ts b/packages/core/src/modules/dids/domain/key-type/keyDidJsonWebKey.ts index 065a19f29b..3bf5d2f43e 100644 --- a/packages/core/src/modules/dids/domain/key-type/keyDidJsonWebKey.ts +++ b/packages/core/src/modules/dids/domain/key-type/keyDidJsonWebKey.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import type { VerificationMethod } from '../verificationMethod' import { getJwkFromJson } from '../../../../crypto/jose/jwk' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getJsonWebKey2020 } from '../verificationMethod' import { VERIFICATION_METHOD_TYPE_JSON_WEB_KEY_2020, isJsonWebKey2020 } from '../verificationMethod/JsonWebKey2020' @@ -12,7 +12,7 @@ export const keyDidJsonWebKey: KeyDidMapping = { getKeyFromVerificationMethod: (verificationMethod: VerificationMethod) => { if (!isJsonWebKey2020(verificationMethod) || !verificationMethod.publicKeyJwk) { - throw new AriesFrameworkError('Invalid verification method passed') + throw new CredoError('Invalid verification method passed') } return getJwkFromJson(verificationMethod.publicKeyJwk).key diff --git a/packages/core/src/modules/dids/domain/key-type/keyDidMapping.ts b/packages/core/src/modules/dids/domain/key-type/keyDidMapping.ts index e8dced5ea7..180b340ceb 100644 --- a/packages/core/src/modules/dids/domain/key-type/keyDidMapping.ts +++ b/packages/core/src/modules/dids/domain/key-type/keyDidMapping.ts @@ -2,7 +2,7 @@ import type { Key } from '../../../../crypto/Key' import { KeyType } from '../../../../crypto/KeyType' import { getJwkFromJson } from '../../../../crypto/jose/jwk' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VERIFICATION_METHOD_TYPE_MULTIKEY, isMultikey, @@ -67,7 +67,7 @@ export function getKeyDidMappingByKeyType(keyType: KeyType) { const keyDid = keyDidMapping[keyType] if (!keyDid) { - throw new AriesFrameworkError(`Unsupported key did from key type '${keyType}'`) + throw new CredoError(`Unsupported key did from key type '${keyType}'`) } return keyDid @@ -78,7 +78,7 @@ export function getKeyFromVerificationMethod(verificationMethod: VerificationMet if (isJsonWebKey2020(verificationMethod)) { // TODO: move this validation to another place if (!verificationMethod.publicKeyJwk) { - throw new AriesFrameworkError( + throw new CredoError( `Missing publicKeyJwk on verification method with type ${VERIFICATION_METHOD_TYPE_JSON_WEB_KEY_2020}` ) } @@ -88,7 +88,7 @@ export function getKeyFromVerificationMethod(verificationMethod: VerificationMet if (isMultikey(verificationMethod)) { if (!verificationMethod.publicKeyMultibase) { - throw new AriesFrameworkError( + throw new CredoError( `Missing publicKeyMultibase on verification method with type ${VERIFICATION_METHOD_TYPE_MULTIKEY}` ) } @@ -98,7 +98,7 @@ export function getKeyFromVerificationMethod(verificationMethod: VerificationMet const keyDid = verificationMethodKeyDidMapping[verificationMethod.type] if (!keyDid) { - throw new AriesFrameworkError(`Unsupported key did from verification method type '${verificationMethod.type}'`) + throw new CredoError(`Unsupported key did from verification method type '${verificationMethod.type}'`) } return keyDid.getKeyFromVerificationMethod(verificationMethod) @@ -108,7 +108,7 @@ export function getSupportedVerificationMethodTypesFromKeyType(keyType: KeyType) const keyDid = keyDidMapping[keyType] if (!keyDid) { - throw new AriesFrameworkError(`Unsupported key did from key type '${keyType}'`) + throw new CredoError(`Unsupported key did from key type '${keyType}'`) } return keyDid.supportedVerificationMethodTypes diff --git a/packages/core/src/modules/dids/domain/key-type/x25519.ts b/packages/core/src/modules/dids/domain/key-type/x25519.ts index d9683811bf..69e56b0e9c 100644 --- a/packages/core/src/modules/dids/domain/key-type/x25519.ts +++ b/packages/core/src/modules/dids/domain/key-type/x25519.ts @@ -2,7 +2,7 @@ import type { KeyDidMapping } from './keyDidMapping' import type { VerificationMethod } from '../verificationMethod' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getKeyFromX25519KeyAgreementKey2019, VERIFICATION_METHOD_TYPE_X25519_KEY_AGREEMENT_KEY_2019, @@ -38,7 +38,7 @@ export const keyDidX25519: KeyDidMapping = { return getKeyFromMultikey(verificationMethod) } - throw new AriesFrameworkError( + throw new CredoError( `Verification method with type '${verificationMethod.type}' not supported for key type '${KeyType.X25519}'` ) }, diff --git a/packages/core/src/modules/dids/domain/keyDidDocument.ts b/packages/core/src/modules/dids/domain/keyDidDocument.ts index 609b786071..1078b7548e 100644 --- a/packages/core/src/modules/dids/domain/keyDidDocument.ts +++ b/packages/core/src/modules/dids/domain/keyDidDocument.ts @@ -3,7 +3,7 @@ import type { VerificationMethod } from './verificationMethod/VerificationMethod import { Key } from '../../../crypto/Key' import { KeyType } from '../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { SECURITY_CONTEXT_BBS_URL, SECURITY_JWS_CONTEXT_URL, SECURITY_X25519_CONTEXT_URL } from '../../vc/constants' import { ED25519_SUITE_CONTEXT_URL_2018 } from '../../vc/data-integrity/signature-suites/ed25519/constants' @@ -72,7 +72,7 @@ export function getJsonWebKey2020DidDocument(did: string, key: Key) { didDocumentBuilder.addContext(SECURITY_JWS_CONTEXT_URL).addVerificationMethod(verificationMethod) if (!key.supportsEncrypting && !key.supportsSigning) { - throw new AriesFrameworkError('Key must support at least signing or encrypting') + throw new CredoError('Key must support at least signing or encrypting') } if (key.supportsSigning) { diff --git a/packages/core/src/modules/dids/domain/parse.ts b/packages/core/src/modules/dids/domain/parse.ts index 1cecefef6b..9690749e6b 100644 --- a/packages/core/src/modules/dids/domain/parse.ts +++ b/packages/core/src/modules/dids/domain/parse.ts @@ -2,13 +2,13 @@ import type { ParsedDid } from '../types' import { parse } from 'did-resolver' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' export function parseDid(did: string): ParsedDid { const parsed = tryParseDid(did) if (!parsed) { - throw new AriesFrameworkError(`Error parsing did '${did}'`) + throw new CredoError(`Error parsing did '${did}'`) } return parsed diff --git a/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G1Key2020.ts b/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G1Key2020.ts index a21a0f125e..224a407856 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G1Key2020.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G1Key2020.ts @@ -1,6 +1,6 @@ import { KeyType } from '../../../../crypto' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VerificationMethod } from './VerificationMethod' @@ -33,7 +33,7 @@ export function isBls12381G1Key2020(verificationMethod: VerificationMethod): ver */ export function getKeyFromBls12381G1Key2020(verificationMethod: Bls12381G1Key2020) { if (!verificationMethod.publicKeyBase58) { - throw new AriesFrameworkError('verification method is missing publicKeyBase58') + throw new CredoError('verification method is missing publicKeyBase58') } return Key.fromPublicKeyBase58(verificationMethod.publicKeyBase58, KeyType.Bls12381g1) diff --git a/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G2Key2020.ts b/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G2Key2020.ts index 4ebd8da275..dc2c7bd6d7 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G2Key2020.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/Bls12381G2Key2020.ts @@ -1,6 +1,6 @@ import { KeyType } from '../../../../crypto' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VerificationMethod } from './VerificationMethod' @@ -33,7 +33,7 @@ export function isBls12381G2Key2020(verificationMethod: VerificationMethod): ver */ export function getKeyFromBls12381G2Key2020(verificationMethod: Bls12381G2Key2020) { if (!verificationMethod.publicKeyBase58) { - throw new AriesFrameworkError('verification method is missing publicKeyBase58') + throw new CredoError('verification method is missing publicKeyBase58') } return Key.fromPublicKeyBase58(verificationMethod.publicKeyBase58, KeyType.Bls12381g2) diff --git a/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2018.ts b/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2018.ts index ed99fd9f03..3851d70b16 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2018.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2018.ts @@ -1,6 +1,6 @@ import { KeyType } from '../../../../crypto' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VerificationMethod } from './VerificationMethod' @@ -35,7 +35,7 @@ export function isEd25519VerificationKey2018( */ export function getKeyFromEd25519VerificationKey2018(verificationMethod: Ed25519VerificationKey2018) { if (!verificationMethod.publicKeyBase58) { - throw new AriesFrameworkError('verification method is missing publicKeyBase58') + throw new CredoError('verification method is missing publicKeyBase58') } return Key.fromPublicKeyBase58(verificationMethod.publicKeyBase58, KeyType.Ed25519) diff --git a/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2020.ts b/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2020.ts index 3c536064ad..607b47b717 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2020.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/Ed25519VerificationKey2020.ts @@ -1,6 +1,6 @@ import { KeyType } from '../../../../crypto' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VerificationMethod } from './VerificationMethod' @@ -35,12 +35,12 @@ export function isEd25519VerificationKey2020( */ export function getKeyFromEd25519VerificationKey2020(verificationMethod: Ed25519VerificationKey2020) { if (!verificationMethod.publicKeyMultibase) { - throw new AriesFrameworkError('verification method is missing publicKeyMultibase') + throw new CredoError('verification method is missing publicKeyMultibase') } const key = Key.fromFingerprint(verificationMethod.publicKeyMultibase) if (key.keyType !== KeyType.Ed25519) { - throw new AriesFrameworkError(`Verification method publicKeyMultibase is for unexpected key type ${key.keyType}`) + throw new CredoError(`Verification method publicKeyMultibase is for unexpected key type ${key.keyType}`) } return key diff --git a/packages/core/src/modules/dids/domain/verificationMethod/JsonWebKey2020.ts b/packages/core/src/modules/dids/domain/verificationMethod/JsonWebKey2020.ts index 757490f455..52882c4a8a 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/JsonWebKey2020.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/JsonWebKey2020.ts @@ -3,7 +3,7 @@ import type { Key } from '../../../../crypto/Key' import type { JwkJson } from '../../../../crypto/jose/jwk/Jwk' import { getJwkFromJson, getJwkFromKey } from '../../../../crypto/jose/jwk' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' export const VERIFICATION_METHOD_TYPE_JSON_WEB_KEY_2020 = 'JsonWebKey2020' @@ -45,7 +45,7 @@ export function isJsonWebKey2020( */ export function getKeyFromJsonWebKey2020(verificationMethod: VerificationMethod & { type: 'JsonWebKey2020' }) { if (!verificationMethod.publicKeyJwk) { - throw new AriesFrameworkError( + throw new CredoError( `Missing publicKeyJwk on verification method with type ${VERIFICATION_METHOD_TYPE_JSON_WEB_KEY_2020}` ) } diff --git a/packages/core/src/modules/dids/domain/verificationMethod/Multikey.ts b/packages/core/src/modules/dids/domain/verificationMethod/Multikey.ts index 4eb35ef715..e201f969ae 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/Multikey.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/Multikey.ts @@ -1,7 +1,7 @@ import type { VerificationMethod } from './VerificationMethod' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' export const VERIFICATION_METHOD_TYPE_MULTIKEY = 'Multikey' @@ -41,7 +41,7 @@ export function isMultikey( */ export function getKeyFromMultikey(verificationMethod: VerificationMethod & { type: 'Multikey' }) { if (!verificationMethod.publicKeyMultibase) { - throw new AriesFrameworkError( + throw new CredoError( `Missing publicKeyMultibase on verification method with type ${VERIFICATION_METHOD_TYPE_MULTIKEY}` ) } diff --git a/packages/core/src/modules/dids/domain/verificationMethod/X25519KeyAgreementKey2019.ts b/packages/core/src/modules/dids/domain/verificationMethod/X25519KeyAgreementKey2019.ts index 0731f84460..7df0c332f5 100644 --- a/packages/core/src/modules/dids/domain/verificationMethod/X25519KeyAgreementKey2019.ts +++ b/packages/core/src/modules/dids/domain/verificationMethod/X25519KeyAgreementKey2019.ts @@ -1,6 +1,6 @@ import { KeyType } from '../../../../crypto' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { VerificationMethod } from './VerificationMethod' @@ -35,7 +35,7 @@ export function isX25519KeyAgreementKey2019( */ export function getKeyFromX25519KeyAgreementKey2019(verificationMethod: X25519KeyAgreementKey2019) { if (!verificationMethod.publicKeyBase58) { - throw new AriesFrameworkError('verification method is missing publicKeyBase58') + throw new CredoError('verification method is missing publicKeyBase58') } return Key.fromPublicKeyBase58(verificationMethod.publicKeyBase58, KeyType.X25519) diff --git a/packages/core/src/modules/dids/methods/jwk/didJwkDidDocument.ts b/packages/core/src/modules/dids/methods/jwk/didJwkDidDocument.ts index 4a3e957603..b5b5087ba1 100644 --- a/packages/core/src/modules/dids/methods/jwk/didJwkDidDocument.ts +++ b/packages/core/src/modules/dids/methods/jwk/didJwkDidDocument.ts @@ -1,6 +1,6 @@ import type { DidJwk } from './DidJwk' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { JsonEncoder } from '../../../../utils' import { SECURITY_JWS_CONTEXT_URL } from '../../../vc/constants' import { getJsonWebKey2020, DidDocumentBuilder } from '../../domain' @@ -8,7 +8,7 @@ import { parseDid } from '../../domain/parse' export function getDidJwkDocument(didJwk: DidJwk) { if (!didJwk.allowsEncrypting && !didJwk.allowsSigning) { - throw new AriesFrameworkError('At least one of allowsSigning or allowsEncrypting must be enabled') + throw new CredoError('At least one of allowsSigning or allowsEncrypting must be enabled') } const parsed = parseDid(didJwk.did) diff --git a/packages/core/src/modules/dids/methods/peer/PeerDidResolver.ts b/packages/core/src/modules/dids/methods/peer/PeerDidResolver.ts index 4e15bee8fd..a55b706733 100644 --- a/packages/core/src/modules/dids/methods/peer/PeerDidResolver.ts +++ b/packages/core/src/modules/dids/methods/peer/PeerDidResolver.ts @@ -3,7 +3,7 @@ import type { DidDocument } from '../../domain' import type { DidResolver } from '../../domain/DidResolver' import type { DidResolutionResult } from '../../types' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { DidRepository } from '../../repository' import { getNumAlgoFromPeerDid, isValidPeerDid, PeerDidNumAlgo } from './didPeer' @@ -28,7 +28,7 @@ export class PeerDidResolver implements DidResolver { let didDocument: DidDocument if (!isValidPeerDid(did)) { - throw new AriesFrameworkError(`did ${did} is not a valid peer did`) + throw new CredoError(`did ${did} is not a valid peer did`) } const numAlgo = getNumAlgoFromPeerDid(did) @@ -44,11 +44,11 @@ export class PeerDidResolver implements DidResolver { const [didDocumentRecord] = await didRepository.findAllByDid(agentContext, did) if (!didDocumentRecord) { - throw new AriesFrameworkError(`No did record found for peer did ${did}.`) + throw new CredoError(`No did record found for peer did ${did}.`) } if (!didDocumentRecord.didDocument) { - throw new AriesFrameworkError(`Found did record for method 1 peer did (${did}), but no did document.`) + throw new CredoError(`Found did record for method 1 peer did (${did}), but no did document.`) } didDocument = didDocumentRecord.didDocument @@ -63,7 +63,7 @@ export class PeerDidResolver implements DidResolver { const [didRecord] = await didRepository.findAllByDid(agentContext, did) if (!didRecord) { - throw new AriesFrameworkError(`No did record found for peer did ${did}.`) + throw new CredoError(`No did record found for peer did ${did}.`) } didDocument = didToNumAlgo4DidDocument(didRecord.did) } else { diff --git a/packages/core/src/modules/dids/methods/peer/createPeerDidDocumentFromServices.ts b/packages/core/src/modules/dids/methods/peer/createPeerDidDocumentFromServices.ts index 7a194d4c4c..89fa2b67fc 100644 --- a/packages/core/src/modules/dids/methods/peer/createPeerDidDocumentFromServices.ts +++ b/packages/core/src/modules/dids/methods/peer/createPeerDidDocumentFromServices.ts @@ -4,7 +4,7 @@ import { convertPublicKeyToX25519 } from '@stablelib/ed25519' import { Key } from '../../../../crypto/Key' import { KeyType } from '../../../../crypto/KeyType' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getEd25519VerificationKey2018, getX25519KeyAgreementKey2019 } from '../../domain' import { DidDocumentBuilder } from '../../domain/DidDocumentBuilder' import { DidCommV1Service } from '../../domain/service/DidCommV1Service' @@ -23,7 +23,7 @@ export function createPeerDidDocumentFromServices(services: ResolvedDidCommServi if (recipientKeyIdMapping[recipientKey.fingerprint]) return recipientKeyIdMapping[recipientKey.fingerprint] if (recipientKey.keyType !== KeyType.Ed25519) { - throw new AriesFrameworkError( + throw new CredoError( `Unable to create did document from services. recipient key type ${recipientKey.keyType} is not supported. Supported key types are ${KeyType.Ed25519}` ) } diff --git a/packages/core/src/modules/dids/methods/peer/didPeer.ts b/packages/core/src/modules/dids/methods/peer/didPeer.ts index 622b5b6a9c..fb8aee487e 100644 --- a/packages/core/src/modules/dids/methods/peer/didPeer.ts +++ b/packages/core/src/modules/dids/methods/peer/didPeer.ts @@ -1,4 +1,4 @@ -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getAlternativeDidsForNumAlgo4Did } from './peerDidNumAlgo4' @@ -28,7 +28,7 @@ export function getNumAlgoFromPeerDid(did: string) { numAlgo !== PeerDidNumAlgo.MultipleInceptionKeyWithoutDoc && numAlgo !== PeerDidNumAlgo.ShortFormAndLongForm ) { - throw new AriesFrameworkError(`Invalid peer did numAlgo: ${numAlgo}`) + throw new CredoError(`Invalid peer did numAlgo: ${numAlgo}`) } return numAlgo as PeerDidNumAlgo diff --git a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo0.ts b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo0.ts index 84c0def303..9ac0495aa0 100644 --- a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo0.ts +++ b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo0.ts @@ -1,5 +1,5 @@ import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { getDidDocumentForKey } from '../../domain/keyDidDocument' import { parseDid } from '../../domain/parse' @@ -16,11 +16,11 @@ export function didToNumAlgo0DidDocument(did: string) { const numAlgo = getNumAlgoFromPeerDid(did) if (!isValidPeerDid(did)) { - throw new AriesFrameworkError(`Invalid peer did '${did}'`) + throw new CredoError(`Invalid peer did '${did}'`) } if (numAlgo !== PeerDidNumAlgo.InceptionKeyWithoutDoc) { - throw new AriesFrameworkError(`Invalid numAlgo ${numAlgo}, expected ${PeerDidNumAlgo.InceptionKeyWithoutDoc}`) + throw new CredoError(`Invalid numAlgo ${numAlgo}, expected ${PeerDidNumAlgo.InceptionKeyWithoutDoc}`) } const key = Key.fromFingerprint(parsed.id.substring(1)) diff --git a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo2.ts b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo2.ts index 769cefa21f..4b204a827a 100644 --- a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo2.ts +++ b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo2.ts @@ -3,7 +3,7 @@ import type { OutOfBandDidCommService } from '../../../oob/domain/OutOfBandDidCo import type { DidDocument, VerificationMethod } from '../../domain' import { Key } from '../../../../crypto/Key' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { JsonEncoder, JsonTransformer } from '../../../../utils' import { DidCommV1Service, DidDocumentService } from '../../domain' import { DidDocumentBuilder } from '../../domain/DidDocumentBuilder' @@ -228,6 +228,6 @@ function addVerificationMethodToDidDocument( // Add the verification method based on the method from the mapping addVerificationMethod(verificationMethod) } else { - throw new AriesFrameworkError(`Unsupported peer did purpose '${purpose}'`) + throw new CredoError(`Unsupported peer did purpose '${purpose}'`) } } diff --git a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo4.ts b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo4.ts index cb8d61598d..d19098b275 100644 --- a/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo4.ts +++ b/packages/core/src/modules/dids/methods/peer/peerDidNumAlgo4.ts @@ -1,6 +1,6 @@ import type { OutOfBandDidCommService } from '../../../oob/domain/OutOfBandDidCommService' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { JsonEncoder, JsonTransformer, @@ -40,17 +40,17 @@ export function didToNumAlgo4DidDocument(did: string) { const match = parsed.did.match(LONG_RE) if (!match) { - throw new AriesFrameworkError(`Invalid long form algo 4 did:peer: ${parsed.did}`) + throw new CredoError(`Invalid long form algo 4 did:peer: ${parsed.did}`) } const [, hash, encodedDocument] = match if (hash !== hashEncodedDocument(encodedDocument)) { - throw new AriesFrameworkError(`Hash is invalid for did: ${did}`) + throw new CredoError(`Hash is invalid for did: ${did}`) } const { data } = MultiBaseEncoder.decode(encodedDocument) const [multiCodecValue] = VarintEncoder.decode(data.subarray(0, 2)) if (multiCodecValue !== JSON_MULTICODEC_VARINT) { - throw new AriesFrameworkError(`Not a JSON multicodec data`) + throw new CredoError(`Not a JSON multicodec data`) } const didDocumentJson = JsonEncoder.fromBuffer(data.subarray(2)) diff --git a/packages/core/src/modules/dids/services/DidResolverService.ts b/packages/core/src/modules/dids/services/DidResolverService.ts index a24c8908ba..f73fc0aecb 100644 --- a/packages/core/src/modules/dids/services/DidResolverService.ts +++ b/packages/core/src/modules/dids/services/DidResolverService.ts @@ -3,7 +3,7 @@ import type { DidResolver } from '../domain/DidResolver' import type { DidResolutionOptions, DidResolutionResult, ParsedDid } from '../types' import { InjectionSymbols } from '../../../constants' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { Logger } from '../../../logger' import { injectable, inject } from '../../../plugins' import { JsonTransformer } from '../../../utils' @@ -126,7 +126,7 @@ export class DidResolverService { } = await this.resolve(agentContext, did) if (!didDocument) { - throw new AriesFrameworkError(`Unable to resolve did document for did '${did}': ${error} ${message}`) + throw new CredoError(`Unable to resolve did document for did '${did}': ${error} ${message}`) } return didDocument } diff --git a/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeError.ts b/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeError.ts index 5c06ec420a..9ba7bd72f4 100644 --- a/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeError.ts +++ b/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' -export class DifPresentationExchangeError extends AriesFrameworkError { +export class DifPresentationExchangeError extends CredoError { public additionalMessages?: Array public constructor( diff --git a/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeService.ts b/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeService.ts index eab8642230..301acc597b 100644 --- a/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeService.ts +++ b/packages/core/src/modules/dif-presentation-exchange/DifPresentationExchangeService.ts @@ -18,7 +18,7 @@ import { Status, PEVersion, PEX } from '@sphereon/pex' import { injectable } from 'tsyringe' import { getJwkFromKey } from '../../crypto' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { JsonTransformer } from '../../utils' import { DidsApi, getKeyFromVerificationMethod } from '../dids' import { @@ -68,7 +68,7 @@ export class DifPresentationExchangeService { credentialsForRequest: DifPexCredentialsForRequest ): DifPexInputDescriptorToCredentials { if (!credentialsForRequest.areRequirementsSatisfied) { - throw new AriesFrameworkError('Could not find the required credentials for the presentation submission') + throw new CredoError('Could not find the required credentials for the presentation submission') } const credentials: DifPexInputDescriptorToCredentials = {} diff --git a/packages/core/src/modules/discover-features/DiscoverFeaturesApi.ts b/packages/core/src/modules/discover-features/DiscoverFeaturesApi.ts index 2ab4550b52..e473dd97b5 100644 --- a/packages/core/src/modules/discover-features/DiscoverFeaturesApi.ts +++ b/packages/core/src/modules/discover-features/DiscoverFeaturesApi.ts @@ -15,7 +15,7 @@ import { EventEmitter } from '../../agent/EventEmitter' import { MessageSender } from '../../agent/MessageSender' import { OutboundMessageContext } from '../../agent/models' import { InjectionSymbols } from '../../constants' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { inject, injectable } from '../../plugins' import { ConnectionService } from '../connections/services' @@ -77,7 +77,7 @@ export class DiscoverFeaturesApi< public getService(protocolVersion: PVT): DiscoverFeaturesService { if (!this.serviceMap[protocolVersion]) { - throw new AriesFrameworkError(`No discover features service registered for protocol version ${protocolVersion}`) + throw new CredoError(`No discover features service registered for protocol version ${protocolVersion}`) } return this.serviceMap[protocolVersion] as DiscoverFeaturesService diff --git a/packages/core/src/modules/discover-features/protocol/v1/V1DiscoverFeaturesService.ts b/packages/core/src/modules/discover-features/protocol/v1/V1DiscoverFeaturesService.ts index 172381d316..8a7c830d1b 100644 --- a/packages/core/src/modules/discover-features/protocol/v1/V1DiscoverFeaturesService.ts +++ b/packages/core/src/modules/discover-features/protocol/v1/V1DiscoverFeaturesService.ts @@ -15,7 +15,7 @@ import { FeatureRegistry } from '../../../../agent/FeatureRegistry' import { MessageHandlerRegistry } from '../../../../agent/MessageHandlerRegistry' import { Protocol } from '../../../../agent/models' import { InjectionSymbols } from '../../../../constants' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { Logger } from '../../../../logger' import { inject, injectable } from '../../../../plugins' import { DiscoverFeaturesEventTypes } from '../../DiscoverFeaturesEvents' @@ -53,11 +53,11 @@ export class V1DiscoverFeaturesService extends DiscoverFeaturesService { options: CreateQueryOptions ): Promise> { if (options.queries.length > 1) { - throw new AriesFrameworkError('Discover Features V1 only supports a single query') + throw new CredoError('Discover Features V1 only supports a single query') } if (options.queries[0].featureType !== 'protocol') { - throw new AriesFrameworkError('Discover Features V1 only supports querying for protocol support') + throw new CredoError('Discover Features V1 only supports querying for protocol support') } const queryMessage = new V1QueryMessage({ @@ -100,11 +100,11 @@ export class V1DiscoverFeaturesService extends DiscoverFeaturesService { options: CreateDisclosureOptions ): Promise> { if (options.disclosureQueries.some((item) => item.featureType !== 'protocol')) { - throw new AriesFrameworkError('Discover Features V1 only supports protocols') + throw new CredoError('Discover Features V1 only supports protocols') } if (!options.threadId) { - throw new AriesFrameworkError('Thread Id is required for Discover Features V1 disclosure') + throw new CredoError('Thread Id is required for Discover Features V1 disclosure') } const matches = this.featureRegistry.query(...options.disclosureQueries) diff --git a/packages/core/src/modules/generic-records/services/GenericRecordService.ts b/packages/core/src/modules/generic-records/services/GenericRecordService.ts index ccdf9d59d3..25480091ce 100644 --- a/packages/core/src/modules/generic-records/services/GenericRecordService.ts +++ b/packages/core/src/modules/generic-records/services/GenericRecordService.ts @@ -2,7 +2,7 @@ import type { AgentContext } from '../../../agent' import type { Query } from '../../../storage/StorageService' import type { SaveGenericRecordOption } from '../repository/GenericRecord' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { injectable } from '../../../plugins' import { GenericRecord } from '../repository/GenericRecord' import { GenericRecordsRepository } from '../repository/GenericRecordsRepository' @@ -26,9 +26,7 @@ export class GenericRecordService { await this.genericRecordsRepository.save(agentContext, genericRecord) return genericRecord } catch (error) { - throw new AriesFrameworkError( - `Unable to store the genericRecord record with id ${genericRecord.id}. Message: ${error}` - ) + throw new CredoError(`Unable to store the genericRecord record with id ${genericRecord.id}. Message: ${error}`) } } @@ -36,7 +34,7 @@ export class GenericRecordService { try { await this.genericRecordsRepository.delete(agentContext, record) } catch (error) { - throw new AriesFrameworkError(`Unable to delete the genericRecord record with id ${record.id}. Message: ${error}`) + throw new CredoError(`Unable to delete the genericRecord record with id ${record.id}. Message: ${error}`) } } @@ -48,7 +46,7 @@ export class GenericRecordService { try { await this.genericRecordsRepository.update(agentContext, record) } catch (error) { - throw new AriesFrameworkError(`Unable to update the genericRecord record with id ${record.id}. Message: ${error}`) + throw new CredoError(`Unable to update the genericRecord record with id ${record.id}. Message: ${error}`) } } diff --git a/packages/core/src/modules/message-pickup/MessagePickupApi.ts b/packages/core/src/modules/message-pickup/MessagePickupApi.ts index 9878cc2684..e9025d9d29 100644 --- a/packages/core/src/modules/message-pickup/MessagePickupApi.ts +++ b/packages/core/src/modules/message-pickup/MessagePickupApi.ts @@ -19,7 +19,7 @@ import { AgentContext } from '../../agent' import { MessageSender } from '../../agent/MessageSender' import { OutboundMessageContext } from '../../agent/models' import { InjectionSymbols } from '../../constants' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { Logger } from '../../logger/Logger' import { inject, injectable } from '../../plugins' import { ConnectionService } from '../connections/services' @@ -75,7 +75,7 @@ export class MessagePickupApi protocol.version === protocolVersion) if (!protocol) { - throw new AriesFrameworkError(`No message pickup protocol registered for protocol version ${protocolVersion}`) + throw new CredoError(`No message pickup protocol registered for protocol version ${protocolVersion}`) } return protocol @@ -161,7 +161,7 @@ export class MessagePickupApi> { - throw new AriesFrameworkError('Live Delivery mode not supported in Message Pickup V1 protocol') + throw new CredoError('Live Delivery mode not supported in Message Pickup V1 protocol') } public async processBatchPickup(messageContext: InboundMessageContext) { diff --git a/packages/core/src/modules/message-pickup/protocol/v2/__tests__/V2MessagePickupProtocol.test.ts b/packages/core/src/modules/message-pickup/protocol/v2/__tests__/V2MessagePickupProtocol.test.ts index bf0d6b2f0a..7a4bc3dc22 100644 --- a/packages/core/src/modules/message-pickup/protocol/v2/__tests__/V2MessagePickupProtocol.test.ts +++ b/packages/core/src/modules/message-pickup/protocol/v2/__tests__/V2MessagePickupProtocol.test.ts @@ -7,7 +7,7 @@ import { MessageSender } from '../../../../../agent/MessageSender' import { InboundMessageContext } from '../../../../../agent/models/InboundMessageContext' import { InjectionSymbols } from '../../../../../constants' import { Attachment } from '../../../../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../../../../error' +import { CredoError } from '../../../../../error' import { uuid } from '../../../../../utils/uuid' import { DidExchangeState, TrustPingMessage } from '../../../../connections' import { ConnectionService } from '../../../../connections/services/ConnectionService' @@ -347,7 +347,7 @@ describe('V2MessagePickupProtocol', () => { }) await expect(pickupProtocol.processDelivery(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Error processing attachments') + new CredoError('Error processing attachments') ) }) diff --git a/packages/core/src/modules/oob/OutOfBandApi.ts b/packages/core/src/modules/oob/OutOfBandApi.ts index 38bfeade4c..ca935e2cd9 100644 --- a/packages/core/src/modules/oob/OutOfBandApi.ts +++ b/packages/core/src/modules/oob/OutOfBandApi.ts @@ -17,7 +17,7 @@ import { OutboundMessageContext } from '../../agent/models' import { InjectionSymbols } from '../../constants' import { Key } from '../../crypto' import { ServiceDecorator } from '../../decorators/service/ServiceDecorator' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { Logger } from '../../logger' import { inject, injectable } from '../../plugins' import { JsonEncoder, JsonTransformer } from '../../utils' @@ -156,19 +156,17 @@ export class OutOfBandApi { config.appendedAttachments && config.appendedAttachments.length > 0 ? config.appendedAttachments : undefined if (!handshake && !messages) { - throw new AriesFrameworkError( - 'One or both of handshake_protocols and requests~attach MUST be included in the message.' - ) + throw new CredoError('One or both of handshake_protocols and requests~attach MUST be included in the message.') } if (!handshake && customHandshakeProtocols) { - throw new AriesFrameworkError(`Attribute 'handshake' can not be 'false' when 'handshakeProtocols' is defined.`) + throw new CredoError(`Attribute 'handshake' can not be 'false' when 'handshakeProtocols' is defined.`) } // For now we disallow creating multi-use invitation with attachments. This would mean we need multi-use // credential and presentation exchanges. if (messages && multiUseInvitation) { - throw new AriesFrameworkError("Attribute 'multiUseInvitation' can not be 'true' when 'messages' is defined.") + throw new CredoError("Attribute 'multiUseInvitation' can not be 'true' when 'messages' is defined.") } let handshakeProtocols: string[] | undefined @@ -411,9 +409,7 @@ export class OutOfBandApi { const isConnectionless = handshakeProtocols === undefined || handshakeProtocols.length === 0 if ((!handshakeProtocols || handshakeProtocols.length === 0) && (!messages || messages?.length === 0)) { - throw new AriesFrameworkError( - 'One or both of handshake_protocols and requests~attach MUST be included in the message.' - ) + throw new CredoError('One or both of handshake_protocols and requests~attach MUST be included in the message.') } // Make sure we haven't received this invitation before @@ -425,7 +421,7 @@ export class OutOfBandApi { role: OutOfBandRole.Receiver, }) if (existingOobRecordsFromThisId.length > 0) { - throw new AriesFrameworkError( + throw new CredoError( `An out of band record with invitation ${outOfBandInvitation.id} has already been received. Invitations should have a unique id.` ) } @@ -711,8 +707,8 @@ export class OutOfBandApi { private assertHandshakeProtocolsSupported(handshakeProtocols: HandshakeProtocol[]) { if (!this.areHandshakeProtocolsSupported(handshakeProtocols)) { - const supportedProtocols = this.getSupportedHandshakeProtocols().map((p) => p.handshakeProtocol) - throw new AriesFrameworkError( + const supportedProtocols = this.getSupportedHandshakeProtocols() + throw new CredoError( `Handshake protocols [${handshakeProtocols}] are not supported. Supported protocols are [${supportedProtocols}]` ) } @@ -738,7 +734,7 @@ export class OutOfBandApi { ) if (supportedHandshakeProtocols.length === 0) { - throw new AriesFrameworkError('There is no handshake protocol supported. Agent can not create a connection.') + throw new CredoError('There is no handshake protocol supported. Agent can not create a connection.') } // Order protocols according to `parsedHandshakeProtocolUris` array (order of preference) @@ -776,7 +772,7 @@ export class OutOfBandApi { ) if (!firstSupportedProtocol) { - throw new AriesFrameworkError( + throw new CredoError( `Handshake protocols [${protocolUris}] are not supported. Supported protocols are [${supportedProtocols.map( (p) => p.handshakeProtocol )}]` @@ -819,7 +815,7 @@ export class OutOfBandApi { }) if (!plaintextMessage) { - throw new AriesFrameworkError('There is no message in requests~attach supported by agent.') + throw new CredoError('There is no message in requests~attach supported by agent.') } // Make sure message has correct parent thread id @@ -843,7 +839,7 @@ export class OutOfBandApi { messages: PlaintextMessage[] ) { if (!services || services.length === 0) { - throw new AriesFrameworkError(`There are no services. We can not emit messages`) + throw new CredoError(`There are no services. We can not emit messages`) } const supportedMessageTypes = this.messageHandlerRegistry.supportedMessageTypes @@ -853,7 +849,7 @@ export class OutOfBandApi { }) if (!plaintextMessage) { - throw new AriesFrameworkError('There is no message in requests~attach supported by agent.') + throw new CredoError('There is no message in requests~attach supported by agent.') } // Make sure message has correct parent thread id @@ -879,7 +875,7 @@ export class OutOfBandApi { plaintextMessage['~thread']?.pthid && plaintextMessage['~thread'].pthid !== outOfBandRecord.outOfBandInvitation.id ) { - throw new AriesFrameworkError( + throw new CredoError( `Out of band invitation requests~attach message contains parent thread id ${plaintextMessage['~thread'].pthid} that does not match the invitation id ${outOfBandRecord.outOfBandInvitation.id}` ) } diff --git a/packages/core/src/modules/oob/OutOfBandService.ts b/packages/core/src/modules/oob/OutOfBandService.ts index 93fbb26c9e..7c7da8552b 100644 --- a/packages/core/src/modules/oob/OutOfBandService.ts +++ b/packages/core/src/modules/oob/OutOfBandService.ts @@ -8,7 +8,7 @@ import type { ConnectionRecord } from '../connections' import type { HandshakeProtocol } from '../connections/models' import { EventEmitter } from '../../agent/EventEmitter' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { injectable } from '../../plugins' import { DidCommDocumentService } from '../didcomm/services/DidCommDocumentService' import { DidsApi } from '../dids' @@ -60,7 +60,7 @@ export class OutOfBandService { const didsApi = agentContext.dependencyManager.resolve(DidsApi) const [createdDid] = await didsApi.getCreatedDids({ did: publicDid.did }) if (!createdDid) { - throw new AriesFrameworkError(`Referenced public did ${did} not found.`) + throw new CredoError(`Referenced public did ${did} not found.`) } // Recreate an 'implicit invitation' matching the parameters used by the invitee when @@ -94,12 +94,12 @@ export class OutOfBandService { const parentThreadId = reuseMessage.thread?.parentThreadId if (!parentThreadId) { - throw new AriesFrameworkError('handshake-reuse message must have a parent thread id') + throw new CredoError('handshake-reuse message must have a parent thread id') } const outOfBandRecord = await this.findByCreatedInvitationId(messageContext.agentContext, parentThreadId) if (!outOfBandRecord) { - throw new AriesFrameworkError('No out of band record found for handshake-reuse message') + throw new CredoError('No out of band record found for handshake-reuse message') } // Assert @@ -108,7 +108,7 @@ export class OutOfBandService { const requestLength = outOfBandRecord.outOfBandInvitation.getRequests()?.length ?? 0 if (requestLength > 0) { - throw new AriesFrameworkError('Handshake reuse should only be used when no requests are present') + throw new CredoError('Handshake reuse should only be used when no requests are present') } const reusedConnection = messageContext.assertReadyConnection() @@ -139,12 +139,12 @@ export class OutOfBandService { const parentThreadId = reuseAcceptedMessage.thread?.parentThreadId if (!parentThreadId) { - throw new AriesFrameworkError('handshake-reuse-accepted message must have a parent thread id') + throw new CredoError('handshake-reuse-accepted message must have a parent thread id') } const outOfBandRecord = await this.findByReceivedInvitationId(messageContext.agentContext, parentThreadId) if (!outOfBandRecord) { - throw new AriesFrameworkError('No out of band record found for handshake-reuse-accepted message') + throw new CredoError('No out of band record found for handshake-reuse-accepted message') } // Assert @@ -160,7 +160,7 @@ export class OutOfBandService { // But this is an issue in general that has also come up for ACA-Py. How do I find the connection associated with an oob record? // Because it doesn't work really well with connection reuse. if (outOfBandRecord.reuseConnectionId !== reusedConnection.id) { - throw new AriesFrameworkError('handshake-reuse-accepted is not in response to a handshake-reuse message.') + throw new CredoError('handshake-reuse-accepted is not in response to a handshake-reuse message.') } this.eventEmitter.emit(messageContext.agentContext, { @@ -278,6 +278,6 @@ export class OutOfBandService { } } - throw new AriesFrameworkError('Could not extract a service from the out of band invitation.') + throw new CredoError('Could not extract a service from the out of band invitation.') } } diff --git a/packages/core/src/modules/oob/__tests__/OutOfBandService.test.ts b/packages/core/src/modules/oob/__tests__/OutOfBandService.test.ts index dafa6c5055..800d650207 100644 --- a/packages/core/src/modules/oob/__tests__/OutOfBandService.test.ts +++ b/packages/core/src/modules/oob/__tests__/OutOfBandService.test.ts @@ -12,7 +12,7 @@ import { import { EventEmitter } from '../../../agent/EventEmitter' import { InboundMessageContext } from '../../../agent/models/InboundMessageContext' import { KeyType, Key } from '../../../crypto' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { DidExchangeState } from '../../connections/models' import { OutOfBandService } from '../OutOfBandService' import { OutOfBandEventTypes } from '../domain/OutOfBandEvents' @@ -59,7 +59,7 @@ describe('OutOfBandService', () => { }) await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError('handshake-reuse message must have a parent thread id') + new CredoError('handshake-reuse message must have a parent thread id') ) }) @@ -75,7 +75,7 @@ describe('OutOfBandService', () => { }) await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError('No out of band record found for handshake-reuse message') + new CredoError('No out of band record found for handshake-reuse message') ) }) @@ -98,13 +98,13 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Invalid out-of-band record role receiver, expected is sender.') + new CredoError('Invalid out-of-band record role receiver, expected is sender.') ) mockOob.state = OutOfBandState.PrepareResponse mockOob.role = OutOfBandRole.Sender await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Invalid out-of-band record state prepare-response, valid states are: await-response.') + new CredoError('Invalid out-of-band record state prepare-response, valid states are: await-response.') ) }) @@ -127,7 +127,7 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Handshake reuse should only be used when no requests are present') + new CredoError('Handshake reuse should only be used when no requests are present') ) }) @@ -149,7 +149,7 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuse(messageContext)).rejects.toThrowError( - new AriesFrameworkError(`No connection associated with incoming message ${reuseMessage.type}`) + new CredoError(`No connection associated with incoming message ${reuseMessage.type}`) ) }) @@ -268,7 +268,7 @@ describe('OutOfBandService', () => { }) await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError('handshake-reuse-accepted message must have a parent thread id') + new CredoError('handshake-reuse-accepted message must have a parent thread id') ) }) @@ -285,7 +285,7 @@ describe('OutOfBandService', () => { }) await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError('No out of band record found for handshake-reuse-accepted message') + new CredoError('No out of band record found for handshake-reuse-accepted message') ) }) @@ -309,13 +309,13 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Invalid out-of-band record role sender, expected is receiver.') + new CredoError('Invalid out-of-band record role sender, expected is receiver.') ) mockOob.state = OutOfBandState.AwaitResponse mockOob.role = OutOfBandRole.Receiver await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError('Invalid out-of-band record state await-response, valid states are: prepare-response.') + new CredoError('Invalid out-of-band record state await-response, valid states are: prepare-response.') ) }) @@ -338,7 +338,7 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError(`No connection associated with incoming message ${reuseAcceptedMessage.type}`) + new CredoError(`No connection associated with incoming message ${reuseAcceptedMessage.type}`) ) }) @@ -363,7 +363,7 @@ describe('OutOfBandService', () => { mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(mockOob) await expect(outOfBandService.processHandshakeReuseAccepted(messageContext)).rejects.toThrowError( - new AriesFrameworkError(`handshake-reuse-accepted is not in response to a handshake-reuse message.`) + new CredoError(`handshake-reuse-accepted is not in response to a handshake-reuse message.`) ) }) diff --git a/packages/core/src/modules/oob/messages/OutOfBandInvitation.ts b/packages/core/src/modules/oob/messages/OutOfBandInvitation.ts index 83d3bdf03f..6bfc021fe0 100644 --- a/packages/core/src/modules/oob/messages/OutOfBandInvitation.ts +++ b/packages/core/src/modules/oob/messages/OutOfBandInvitation.ts @@ -6,7 +6,7 @@ import { parseUrl } from 'query-string' import { AgentMessage } from '../../../agent/AgentMessage' import { Attachment, AttachmentData } from '../../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonEncoder } from '../../../utils/JsonEncoder' import { JsonTransformer } from '../../../utils/JsonTransformer' import { IsValidMessageType, parseMessageType, replaceLegacyDidSovPrefix } from '../../../utils/messageType' @@ -82,7 +82,7 @@ export class OutOfBandInvitation extends AgentMessage { return invitation } else { - throw new AriesFrameworkError( + throw new CredoError( 'InvitationUrl is invalid. It needs to contain one, and only one, of the following parameters; `oob`' ) } diff --git a/packages/core/src/modules/oob/repository/OutOfBandRecord.ts b/packages/core/src/modules/oob/repository/OutOfBandRecord.ts index a4dd0c670f..1832996478 100644 --- a/packages/core/src/modules/oob/repository/OutOfBandRecord.ts +++ b/packages/core/src/modules/oob/repository/OutOfBandRecord.ts @@ -5,7 +5,7 @@ import type { OutOfBandState } from '../domain/OutOfBandState' import { Type } from 'class-transformer' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { BaseRecord } from '../../../storage/BaseRecord' import { getThreadIdFromPlainTextMessage } from '../../../utils/thread' import { uuid } from '../../../utils/uuid' @@ -94,7 +94,7 @@ export class OutOfBandRecord extends BaseRecord< public assertRole(expectedRole: OutOfBandRole) { if (this.role !== expectedRole) { - throw new AriesFrameworkError(`Invalid out-of-band record role ${this.role}, expected is ${expectedRole}.`) + throw new CredoError(`Invalid out-of-band record role ${this.role}, expected is ${expectedRole}.`) } } @@ -104,7 +104,7 @@ export class OutOfBandRecord extends BaseRecord< } if (!expectedStates.includes(this.state)) { - throw new AriesFrameworkError( + throw new CredoError( `Invalid out-of-band record state ${this.state}, valid states are: ${expectedStates.join(', ')}.` ) } diff --git a/packages/core/src/modules/problem-reports/errors/ProblemReportError.ts b/packages/core/src/modules/problem-reports/errors/ProblemReportError.ts index 708e694d59..8fe3dd8db5 100644 --- a/packages/core/src/modules/problem-reports/errors/ProblemReportError.ts +++ b/packages/core/src/modules/problem-reports/errors/ProblemReportError.ts @@ -1,11 +1,11 @@ -import { AriesFrameworkError } from '../../../error/AriesFrameworkError' +import { CredoError } from '../../../error/CredoError' import { ProblemReportMessage } from '../messages/ProblemReportMessage' export interface ProblemReportErrorOptions { problemCode: string } -export class ProblemReportError extends AriesFrameworkError { +export class ProblemReportError extends CredoError { public problemReport: ProblemReportMessage public constructor(message: string, { problemCode }: ProblemReportErrorOptions) { diff --git a/packages/core/src/modules/proofs/ProofsApi.ts b/packages/core/src/modules/proofs/ProofsApi.ts index 483ad5e2c1..20224a9ec7 100644 --- a/packages/core/src/modules/proofs/ProofsApi.ts +++ b/packages/core/src/modules/proofs/ProofsApi.ts @@ -30,7 +30,7 @@ import { injectable } from 'tsyringe' import { MessageSender } from '../../agent/MessageSender' import { AgentContext } from '../../agent/context/AgentContext' import { getOutboundMessageContext } from '../../agent/getOutboundMessageContext' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { ConnectionService } from '../connections/services/ConnectionService' import { ProofsModuleConfig } from './ProofsModuleConfig' @@ -115,7 +115,7 @@ export class ProofsApi implements ProofsApi { const proofProtocol = this.config.proofProtocols.find((protocol) => protocol.version === protocolVersion) if (!proofProtocol) { - throw new AriesFrameworkError(`No proof protocol registered for protocol version ${protocolVersion}`) + throw new CredoError(`No proof protocol registered for protocol version ${protocolVersion}`) } return proofProtocol @@ -166,7 +166,7 @@ export class ProofsApi implements ProofsApi { const proofRecord = await this.getById(options.proofRecordId) if (!proofRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connectionId found for proof record '${proofRecord.id}'. Connection-less verification does not support presentation proposal or negotiation.` ) } @@ -210,7 +210,7 @@ export class ProofsApi implements ProofsApi { const proofRecord = await this.getById(options.proofRecordId) if (!proofRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connectionId found for proof record '${proofRecord.id}'. Connection-less verification does not support negotiation.` ) } @@ -289,7 +289,7 @@ export class ProofsApi implements ProofsApi { const requestMessage = await protocol.findRequestMessage(this.agentContext, proofRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for proof record with id '${proofRecord.id}'`) + throw new CredoError(`No request message found for proof record with id '${proofRecord.id}'`) } // Use connection if present @@ -343,7 +343,7 @@ export class ProofsApi implements ProofsApi { const proofRecord = await this.getById(options.proofRecordId) if (!proofRecord.connectionId) { - throw new AriesFrameworkError( + throw new CredoError( `No connectionId found for proof record '${proofRecord.id}'. Connection-less verification does not support presentation proposal or negotiation.` ) } @@ -409,12 +409,12 @@ export class ProofsApi implements ProofsApi { const requestMessage = await protocol.findRequestMessage(this.agentContext, proofRecord.id) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for proof record with id '${proofRecord.id}'`) + throw new CredoError(`No request message found for proof record with id '${proofRecord.id}'`) } const presentationMessage = await protocol.findPresentationMessage(this.agentContext, proofRecord.id) if (!presentationMessage) { - throw new AriesFrameworkError(`No presentation message found for proof record with id '${proofRecord.id}'`) + throw new CredoError(`No presentation message found for proof record with id '${proofRecord.id}'`) } // Use connection if present @@ -509,7 +509,7 @@ export class ProofsApi implements ProofsApi { proofRecord.assertState(ProofState.RequestReceived) if (!requestMessage) { - throw new AriesFrameworkError(`No request message found for proof record with id '${proofRecord.id}'`) + throw new CredoError(`No request message found for proof record with id '${proofRecord.id}'`) } } diff --git a/packages/core/src/modules/proofs/formats/dif-presentation-exchange/DifPresentationExchangeProofFormatService.ts b/packages/core/src/modules/proofs/formats/dif-presentation-exchange/DifPresentationExchangeProofFormatService.ts index 80e772cdaf..ee86351c68 100644 --- a/packages/core/src/modules/proofs/formats/dif-presentation-exchange/DifPresentationExchangeProofFormatService.ts +++ b/packages/core/src/modules/proofs/formats/dif-presentation-exchange/DifPresentationExchangeProofFormatService.ts @@ -26,7 +26,7 @@ import type { } from '../ProofFormatServiceOptions' import { Attachment, AttachmentData } from '../../../../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { deepEquality, JsonTransformer } from '../../../../utils' import { DifPresentationExchangeService } from '../../../dif-presentation-exchange' import { @@ -64,7 +64,7 @@ export class PresentationExchangeProofFormatService implements ProofFormatServic const pexFormat = proofFormats.presentationExchange if (!pexFormat) { - throw new AriesFrameworkError('Missing Presentation Exchange format in create proposal attachment format') + throw new CredoError('Missing Presentation Exchange format in create proposal attachment format') } const { presentationDefinition } = pexFormat @@ -187,7 +187,7 @@ export class PresentationExchangeProofFormatService implements ProofFormatServic ) if (!areRequirementsSatisfied) { - throw new AriesFrameworkError('Requirements of the presentation definition could not be satisfied') + throw new CredoError('Requirements of the presentation definition could not be satisfied') } requirements.forEach((r) => { @@ -205,7 +205,7 @@ export class PresentationExchangeProofFormatService implements ProofFormatServic }) if (presentation.verifiablePresentations.length > 1) { - throw new AriesFrameworkError('Invalid amount of verifiable presentations. Only one is allowed.') + throw new CredoError('Invalid amount of verifiable presentations. Only one is allowed.') } const firstPresentation = presentation.verifiablePresentations[0] diff --git a/packages/core/src/modules/proofs/protocol/v2/ProofFormatCoordinator.ts b/packages/core/src/modules/proofs/protocol/v2/ProofFormatCoordinator.ts index d83b621e02..6bbb3783e9 100644 --- a/packages/core/src/modules/proofs/protocol/v2/ProofFormatCoordinator.ts +++ b/packages/core/src/modules/proofs/protocol/v2/ProofFormatCoordinator.ts @@ -9,7 +9,7 @@ import type { import type { ProofFormatSpec } from '../../models/ProofFormatSpec' import type { ProofExchangeRecord } from '../../repository' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { DidCommMessageRepository, DidCommMessageRole } from '../../../../storage' import { V2PresentationMessage, V2ProposePresentationMessage, V2RequestPresentationMessage } from './messages' @@ -523,7 +523,7 @@ export class ProofFormatCoordinator { const attachment = attachments.find((attachment) => attachment.id === attachmentId) if (!attachment) { - throw new AriesFrameworkError(`Attachment with id ${attachmentId} not found in attachments.`) + throw new CredoError(`Attachment with id ${attachmentId} not found in attachments.`) } return attachment @@ -532,7 +532,7 @@ export class ProofFormatCoordinator { private getAttachmentIdForService(credentialFormatService: ProofFormatService, formats: ProofFormatSpec[]) { const format = formats.find((format) => credentialFormatService.supportsFormat(format.format)) - if (!format) throw new AriesFrameworkError(`No attachment found for service ${credentialFormatService.formatKey}`) + if (!format) throw new CredoError(`No attachment found for service ${credentialFormatService.formatKey}`) return format.attachmentId } diff --git a/packages/core/src/modules/proofs/protocol/v2/V2ProofProtocol.ts b/packages/core/src/modules/proofs/protocol/v2/V2ProofProtocol.ts index 3ce7e2c9d8..4224e8aea6 100644 --- a/packages/core/src/modules/proofs/protocol/v2/V2ProofProtocol.ts +++ b/packages/core/src/modules/proofs/protocol/v2/V2ProofProtocol.ts @@ -32,7 +32,7 @@ import type { } from '../ProofProtocolOptions' import { Protocol } from '../../../../agent/models' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { DidCommMessageRepository } from '../../../../storage' import { uuid } from '../../../../utils/uuid' import { AckStatus } from '../../../common' @@ -113,7 +113,7 @@ export class V2ProofProtocol websocketSchemes.includes(s.protocolScheme)) if (!hasWebSocketTransport) { - throw new AriesFrameworkError('Cannot open websocket to connection without websocket service endpoint') + throw new CredoError('Cannot open websocket to connection without websocket service endpoint') } await this.messageSender.sendMessage( @@ -235,7 +235,7 @@ export class MediationRecipientApi { const { mediatorPollingInterval } = this.config const mediatorRecord = mediator ?? (await this.findDefaultMediator()) if (!mediatorRecord) { - throw new AriesFrameworkError('There is no mediator to pickup messages from') + throw new CredoError('There is no mediator to pickup messages from') } const mediatorPickupStrategy = pickupStrategy ?? (await this.getPickupStrategyForMediator(mediatorRecord)) diff --git a/packages/core/src/modules/routing/repository/MediationRecord.ts b/packages/core/src/modules/routing/repository/MediationRecord.ts index 24115007b8..a672e25087 100644 --- a/packages/core/src/modules/routing/repository/MediationRecord.ts +++ b/packages/core/src/modules/routing/repository/MediationRecord.ts @@ -2,7 +2,7 @@ import type { MediationRole } from '../models/MediationRole' import { Transform } from 'class-transformer' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { BaseRecord } from '../../../storage/BaseRecord' import { uuid } from '../../../utils/uuid' import { MediatorPickupStrategy } from '../MediatorPickupStrategy' @@ -106,7 +106,7 @@ export class MediationRecord public assertReady() { if (!this.isReady) { - throw new AriesFrameworkError( + throw new CredoError( `Mediation record is not ready to be used. Expected ${MediationState.Granted}, found invalid state ${this.state}` ) } @@ -118,7 +118,7 @@ export class MediationRecord } if (!expectedStates.includes(this.state)) { - throw new AriesFrameworkError( + throw new CredoError( `Mediation record is in invalid state ${this.state}. Valid states are: ${expectedStates.join(', ')}.` ) } @@ -126,7 +126,7 @@ export class MediationRecord public assertRole(expectedRole: MediationRole) { if (this.role !== expectedRole) { - throw new AriesFrameworkError(`Mediation record has invalid role ${this.role}. Expected role ${expectedRole}.`) + throw new CredoError(`Mediation record has invalid role ${this.role}. Expected role ${expectedRole}.`) } } } diff --git a/packages/core/src/modules/routing/services/MediationRecipientService.ts b/packages/core/src/modules/routing/services/MediationRecipientService.ts index dc464289b8..2d9a66be92 100644 --- a/packages/core/src/modules/routing/services/MediationRecipientService.ts +++ b/packages/core/src/modules/routing/services/MediationRecipientService.ts @@ -16,7 +16,7 @@ import { filterContextCorrelationId } from '../../../agent/Events' import { MessageSender } from '../../../agent/MessageSender' import { OutboundMessageContext } from '../../../agent/models' import { Key, KeyType } from '../../../crypto' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { injectable } from '../../../plugins' import { ConnectionType } from '../../connections/models/ConnectionType' import { ConnectionMetadataKeys } from '../../connections/repository/ConnectionMetadataTypes' @@ -248,7 +248,7 @@ export class MediationRecipientService { const mediationRecord = await this.getById(agentContext, mediatorId) if (!mediationRecord) { - throw new AriesFrameworkError('No mediation record to remove routing from has been found') + throw new CredoError('No mediation record to remove routing from has been found') } await this.keylistUpdateAndAwait( @@ -349,7 +349,7 @@ export class MediationRecipientService { const defaultMediator = await this.findDefaultMediator(agentContext) if (defaultMediator) { if (defaultMediator.state !== MediationState.Granted) { - throw new AriesFrameworkError( + throw new CredoError( `Mediation State for ${defaultMediator.id} is not granted, but is set as default mediator!` ) } diff --git a/packages/core/src/modules/routing/services/MediatorService.ts b/packages/core/src/modules/routing/services/MediatorService.ts index d7cdf433f1..4c6facea31 100644 --- a/packages/core/src/modules/routing/services/MediatorService.ts +++ b/packages/core/src/modules/routing/services/MediatorService.ts @@ -9,7 +9,7 @@ import { EventEmitter } from '../../../agent/EventEmitter' import { MessageSender } from '../../../agent/MessageSender' import { InjectionSymbols } from '../../../constants' import { KeyType } from '../../../crypto' -import { AriesFrameworkError, RecordDuplicateError } from '../../../error' +import { CredoError, RecordDuplicateError } from '../../../error' import { Logger } from '../../../logger' import { injectable, inject } from '../../../plugins' import { ConnectionService } from '../../connections' @@ -68,7 +68,7 @@ export class MediatorService { this.logger.debug(`Returning mediator routing keys ${mediatorRoutingRecord.routingKeys}`) return mediatorRoutingRecord.routingKeys } - throw new AriesFrameworkError(`Mediator has not been initialized yet.`) + throw new CredoError(`Mediator has not been initialized yet.`) } public async processForwardMessage(messageContext: InboundMessageContext): Promise { @@ -76,7 +76,7 @@ export class MediatorService { // TODO: update to class-validator validation if (!message.to) { - throw new AriesFrameworkError('Invalid Message: Missing required attribute "to"') + throw new CredoError('Invalid Message: Missing required attribute "to"') } const mediationRecord = await this.mediationRepository.getSingleByRecipientKey(agentContext, message.to) diff --git a/packages/core/src/modules/vc/W3cCredentialService.ts b/packages/core/src/modules/vc/W3cCredentialService.ts index 1cca4272de..511d2cc348 100644 --- a/packages/core/src/modules/vc/W3cCredentialService.ts +++ b/packages/core/src/modules/vc/W3cCredentialService.ts @@ -19,7 +19,7 @@ import type { import type { AgentContext } from '../../agent/context' import type { Query } from '../../storage/StorageService' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { injectable } from '../../plugins' import { CREDENTIALS_CONTEXT_V1_URL } from './constants' @@ -63,7 +63,7 @@ export class W3cCredentialService { } else if (options.format === ClaimFormat.LdpVc) { return this.w3cJsonLdCredentialService.signCredential(agentContext, options) } else { - throw new AriesFrameworkError(`Unsupported format in options. Format must be either 'jwt_vc' or 'ldp_vc'`) + throw new CredoError(`Unsupported format in options. Format must be either 'jwt_vc' or 'ldp_vc'`) } } @@ -79,7 +79,7 @@ export class W3cCredentialService { } else if (options.credential instanceof W3cJwtVerifiableCredential || typeof options.credential === 'string') { return this.w3cJwtCredentialService.verifyCredential(agentContext, options as W3cJwtVerifyCredentialOptions) } else { - throw new AriesFrameworkError( + throw new CredoError( `Unsupported credential type in options. Credential must be either a W3cJsonLdVerifiableCredential or a W3cJwtVerifiableCredential` ) } @@ -119,7 +119,7 @@ export class W3cCredentialService { } else if (options.format === ClaimFormat.LdpVp) { return this.w3cJsonLdCredentialService.signPresentation(agentContext, options) } else { - throw new AriesFrameworkError(`Unsupported format in options. Format must be either 'jwt_vp' or 'ldp_vp'`) + throw new CredoError(`Unsupported format in options. Format must be either 'jwt_vp' or 'ldp_vp'`) } } @@ -144,7 +144,7 @@ export class W3cCredentialService { ) { return this.w3cJwtCredentialService.verifyPresentation(agentContext, options as W3cJwtVerifyPresentationOptions) } else { - throw new AriesFrameworkError( + throw new CredoError( 'Unsupported credential type in options. Presentation must be either a W3cJsonLdVerifiablePresentation or a W3cJwtVerifiablePresentation' ) } diff --git a/packages/core/src/modules/vc/data-integrity/SignatureSuiteRegistry.ts b/packages/core/src/modules/vc/data-integrity/SignatureSuiteRegistry.ts index d7cd6e37b4..61675ced7a 100644 --- a/packages/core/src/modules/vc/data-integrity/SignatureSuiteRegistry.ts +++ b/packages/core/src/modules/vc/data-integrity/SignatureSuiteRegistry.ts @@ -1,6 +1,6 @@ import type { KeyType } from '../../../crypto' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { injectable, injectAll } from '../../../plugins' import { suites } from './libraries/jsonld-signatures' @@ -39,7 +39,7 @@ export class SignatureSuiteRegistry { const suiteInfo = this.suiteMapping.find((x) => x.proofType === proofType) if (!suiteInfo) { - throw new AriesFrameworkError(`No signature suite for proof type: ${proofType}`) + throw new CredoError(`No signature suite for proof type: ${proofType}`) } return suiteInfo @@ -49,7 +49,7 @@ export class SignatureSuiteRegistry { const suiteInfo = this.suiteMapping.find((suiteInfo) => suiteInfo.proofType === proofType) if (!suiteInfo) { - throw new AriesFrameworkError(`No verification method type found for proof type: ${proofType}`) + throw new CredoError(`No verification method type found for proof type: ${proofType}`) } return suiteInfo.verificationMethodTypes diff --git a/packages/core/src/modules/vc/data-integrity/W3cJsonLdCredentialService.ts b/packages/core/src/modules/vc/data-integrity/W3cJsonLdCredentialService.ts index f2777463dc..98151c0432 100644 --- a/packages/core/src/modules/vc/data-integrity/W3cJsonLdCredentialService.ts +++ b/packages/core/src/modules/vc/data-integrity/W3cJsonLdCredentialService.ts @@ -12,7 +12,7 @@ import type { W3cVerifyCredentialResult, W3cVerifyPresentationResult } from '../ import type { W3cJsonCredential } from '../models/credential/W3cJsonCredential' import { createWalletKeyPairClass } from '../../../crypto/WalletKeyPair' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { injectable } from '../../../plugins' import { asArray, JsonTransformer } from '../../../utils' import { VerificationMethod } from '../../dids' @@ -58,7 +58,7 @@ export class W3cJsonLdCredentialService { const suiteInfo = this.signatureSuiteRegistry.getByProofType(options.proofType) if (!suiteInfo.keyTypes.includes(signingKey.keyType)) { - throw new AriesFrameworkError('The key type of the verification method does not match the suite') + throw new CredoError('The key type of the verification method does not match the suite') } const keyPair = new WalletKeyPair({ @@ -112,9 +112,7 @@ export class W3cJsonLdCredentialService { checkStatus: ({ credential }: { credential: W3cJsonCredential }) => { // Only throw error if credentialStatus is present if (verifyCredentialStatus && 'credentialStatus' in credential) { - throw new AriesFrameworkError( - 'Verifying credential status for JSON-LD credentials is currently not supported' - ) + throw new CredoError('Verifying credential status for JSON-LD credentials is currently not supported') } return { verified: true, @@ -175,13 +173,13 @@ export class W3cJsonLdCredentialService { const suiteInfo = this.signatureSuiteRegistry.getByProofType(options.proofType) if (!suiteInfo) { - throw new AriesFrameworkError(`The requested proofType ${options.proofType} is not supported`) + throw new CredoError(`The requested proofType ${options.proofType} is not supported`) } const signingKey = await this.getPublicKeyFromVerificationMethod(agentContext, options.verificationMethod) if (!suiteInfo.keyTypes.includes(signingKey.keyType)) { - throw new AriesFrameworkError('The key type of the verification method does not match the suite') + throw new CredoError('The key type of the verification method does not match the suite') } const documentLoader = this.w3cCredentialsModuleConfig.documentLoader(agentContext) @@ -330,7 +328,7 @@ export class W3cJsonLdCredentialService { const suite = this.signatureSuiteRegistry.getByVerificationMethodType(verificationMethodType) if (!suite) { - throw new AriesFrameworkError(`No suite found for verification method type ${verificationMethodType}}`) + throw new CredoError(`No suite found for verification method type ${verificationMethodType}}`) } return suite.proofType diff --git a/packages/core/src/modules/vc/data-integrity/jsonldUtil.ts b/packages/core/src/modules/vc/data-integrity/jsonldUtil.ts index 6975e92c99..960edc5549 100644 --- a/packages/core/src/modules/vc/data-integrity/jsonldUtil.ts +++ b/packages/core/src/modules/vc/data-integrity/jsonldUtil.ts @@ -3,7 +3,7 @@ import type { GetProofsResult } from './models/GetProofsResult' import type { GetTypeOptions } from './models/GetTypeOptions' import type { JsonObject, JsonValue } from '../../../types' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { SECURITY_CONTEXT_URL } from '../constants' import jsonld from './libraries/jsonld' @@ -38,7 +38,7 @@ export function assertOnlyW3cJsonLdVerifiableCredentials( credentials: unknown[] ): asserts credentials is W3cJsonLdVerifiableCredential[] { if (credentials.some((c) => !(c instanceof W3cJsonLdVerifiableCredential))) { - throw new AriesFrameworkError('JSON-LD VPs can only contain JSON-LD VCs') + throw new CredoError('JSON-LD VPs can only contain JSON-LD VCs') } } diff --git a/packages/core/src/modules/vc/data-integrity/libraries/documentLoader.ts b/packages/core/src/modules/vc/data-integrity/libraries/documentLoader.ts index 99520137ff..d4619f96d5 100644 --- a/packages/core/src/modules/vc/data-integrity/libraries/documentLoader.ts +++ b/packages/core/src/modules/vc/data-integrity/libraries/documentLoader.ts @@ -1,7 +1,7 @@ import type { DocumentLoader } from './jsonld' import type { AgentContext } from '../../../../agent/context/AgentContext' -import { AriesFrameworkError } from '../../../../error/AriesFrameworkError' +import { CredoError } from '../../../../error/CredoError' import { isDid } from '../../../../utils' import { DidResolverService } from '../../../dids' @@ -18,7 +18,7 @@ export function defaultDocumentLoader(agentContext: AgentContext): DocumentLoade const result = await didResolver.resolve(agentContext, url) if (result.didResolutionMetadata.error || !result.didDocument) { - throw new AriesFrameworkError(`Unable to resolve DID: ${url}`) + throw new CredoError(`Unable to resolve DID: ${url}`) } const framed = await jsonld.frame( diff --git a/packages/core/src/modules/vc/data-integrity/signature-suites/JwsLinkedDataSignature.ts b/packages/core/src/modules/vc/data-integrity/signature-suites/JwsLinkedDataSignature.ts index db012f8555..a47c238cc2 100644 --- a/packages/core/src/modules/vc/data-integrity/signature-suites/JwsLinkedDataSignature.ts +++ b/packages/core/src/modules/vc/data-integrity/signature-suites/JwsLinkedDataSignature.ts @@ -4,7 +4,7 @@ import type { DocumentLoader, Proof, VerificationMethod } from '../jsonldUtil' import type { LdKeyPair } from '../models/LdKeyPair' -import { AriesFrameworkError } from '../../../../error' +import { CredoError } from '../../../../error' import { TypedArrayEncoder, JsonEncoder } from '../../../../utils' import { suites } from '../libraries/jsonld-signatures' @@ -183,9 +183,7 @@ export class JwsLinkedDataSignature extends LinkedDataSignature { } if (!options.documentLoader) { - throw new AriesFrameworkError( - 'Missing custom document loader. This is required for resolving verification methods.' - ) + throw new CredoError('Missing custom document loader. This is required for resolving verification methods.') } const { document } = await options.documentLoader(verificationMethod) diff --git a/packages/core/src/modules/vc/jwt-vc/W3cJwtCredentialService.ts b/packages/core/src/modules/vc/jwt-vc/W3cJwtCredentialService.ts index 0abeb864cf..6047cbf0f4 100644 --- a/packages/core/src/modules/vc/jwt-vc/W3cJwtCredentialService.ts +++ b/packages/core/src/modules/vc/jwt-vc/W3cJwtCredentialService.ts @@ -11,7 +11,7 @@ import type { SingleValidationResult, W3cVerifyCredentialResult, W3cVerifyPresen import { JwsService } from '../../../crypto' import { getJwkFromKey, getJwkClassFromJwaSignatureAlgorithm } from '../../../crypto/jose/jwk' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { injectable } from '../../../plugins' import { asArray, isDid, MessageValidator } from '../../../utils' import { getKeyDidMappingByKeyType, DidResolverService, getKeyFromVerificationMethod } from '../../dids' @@ -63,7 +63,7 @@ export class W3cJwtCredentialService { const jwtPayload = getJwtPayloadFromCredential(options.credential) if (!isDid(options.verificationMethod)) { - throw new AriesFrameworkError(`Only did identifiers are supported as verification method`) + throw new CredoError(`Only did identifiers are supported as verification method`) } const verificationMethod = await this.resolveVerificationMethod(agentContext, options.verificationMethod, [ @@ -157,7 +157,7 @@ export class W3cJwtCredentialService { if (!signatureResult.isValid) { validationResults.validations.signature = { isValid: false, - error: new AriesFrameworkError('Invalid JWS signature'), + error: new CredoError('Invalid JWS signature'), } } else { validationResults.validations.signature = { @@ -176,7 +176,7 @@ export class W3cJwtCredentialService { if (credential.issuerId !== issuerVerificationMethod.controller) { validationResults.validations.issuerIsSigner = { isValid: false, - error: new AriesFrameworkError( + error: new CredoError( `Credential is signed using verification method ${issuerVerificationMethod.id}, while the issuer of the credential is '${credential.issuerId}'` ), } @@ -193,7 +193,7 @@ export class W3cJwtCredentialService { if (!issuerIsSigner) { validationResults.validations.issuerIsSigner = { isValid: false, - error: new AriesFrameworkError('Credential is not signed by the issuer of the credential'), + error: new CredoError('Credential is not signed by the issuer of the credential'), } } else { validationResults.validations.issuerIsSigner = { @@ -209,7 +209,7 @@ export class W3cJwtCredentialService { } else if (verifyCredentialStatus && credential.credentialStatus) { validationResults.validations.credentialStatus = { isValid: false, - error: new AriesFrameworkError('Verifying credential status is not supported for JWT VCs'), + error: new CredoError('Verifying credential status is not supported for JWT VCs'), } } @@ -301,12 +301,12 @@ export class W3cJwtCredentialService { // Make sure challenge matches nonce if (options.challenge !== presentation.jwt.payload.additionalClaims.nonce) { - throw new AriesFrameworkError(`JWT payload 'nonce' does not match challenge '${options.challenge}'`) + throw new CredoError(`JWT payload 'nonce' does not match challenge '${options.challenge}'`) } const audArray = asArray(presentation.jwt.payload.aud) if (options.domain && !audArray.includes(options.domain)) { - throw new AriesFrameworkError(`JWT payload 'aud' does not include domain '${options.domain}'`) + throw new CredoError(`JWT payload 'aud' does not include domain '${options.domain}'`) } validationResults.validations.dataModel = { @@ -340,7 +340,7 @@ export class W3cJwtCredentialService { if (!signatureResult.isValid) { validationResults.validations.presentationSignature = { isValid: false, - error: new AriesFrameworkError('Invalid JWS signature on presentation'), + error: new CredoError('Invalid JWS signature on presentation'), } } else { validationResults.validations.presentationSignature = { @@ -359,7 +359,7 @@ export class W3cJwtCredentialService { if (presentation.holderId && proverVerificationMethod.controller !== presentation.holderId) { validationResults.validations.holderIsSigner = { isValid: false, - error: new AriesFrameworkError( + error: new CredoError( `Presentation is signed using verification method ${proverVerificationMethod.id}, while the holder of the presentation is '${presentation.holderId}'` ), } @@ -380,7 +380,7 @@ export class W3cJwtCredentialService { if (credential instanceof W3cJsonLdVerifiableCredential) { return { isValid: false, - error: new AriesFrameworkError( + error: new CredoError( 'Credential is of format ldp_vc. presentations in jwp_vp format can only contain credentials in jwt_vc format' ), validations: {}, @@ -409,7 +409,7 @@ export class W3cJwtCredentialService { if (credentialSubjectIds.length > 0 && !presentationAuthenticatesCredentialSubject) { credentialSubjectAuthentication = { isValid: false, - error: new AriesFrameworkError( + error: new CredoError( 'Credential has one or more credentialSubject ids, but presentation does not authenticate credential subject' ), } @@ -496,7 +496,7 @@ export class W3cJwtCredentialService { // If the kid starts with # we assume it is a relative did url, and we resolve it based on the `iss` and the `kid` if (kid?.startsWith('#')) { if (!signerId) { - throw new AriesFrameworkError(`JWT 'kid' MUST be absolute when when no 'iss' is present in JWT payload`) + throw new CredoError(`JWT 'kid' MUST be absolute when when no 'iss' is present in JWT payload`) } const didDocument = await didResolver.resolveDidDocument(agentContext, signerId) @@ -509,16 +509,16 @@ export class W3cJwtCredentialService { verificationMethod = didDocument.dereferenceKey(kid, purpose) if (signerId && didDocument.id !== signerId) { - throw new AriesFrameworkError(`kid '${kid}' does not match id of signer (holder/issuer) '${signerId}'`) + throw new CredoError(`kid '${kid}' does not match id of signer (holder/issuer) '${signerId}'`) } } else { if (!signerId) { - throw new AriesFrameworkError(`JWT 'iss' MUST be present in payload when no 'kid' is specified`) + throw new CredoError(`JWT 'iss' MUST be present in payload when no 'kid' is specified`) } // Find the verificationMethod in the did document based on the alg and proofPurpose const jwkClass = getJwkClassFromJwaSignatureAlgorithm(credential.jwt.header.alg) - if (!jwkClass) throw new AriesFrameworkError(`Unsupported JWT alg '${credential.jwt.header.alg}'`) + if (!jwkClass) throw new CredoError(`Unsupported JWT alg '${credential.jwt.header.alg}'`) const { supportedVerificationMethodTypes } = getKeyDidMappingByKeyType(jwkClass.keyType) @@ -529,11 +529,11 @@ export class W3cJwtCredentialService { .filter((v) => supportedVerificationMethodTypes.includes(v.type)) ?? [] if (verificationMethods.length === 0) { - throw new AriesFrameworkError( + throw new CredoError( `No verification methods found for signer '${signerId}' and key type '${jwkClass.keyType}' for alg '${credential.jwt.header.alg}'. Unable to determine which public key is associated with the credential.` ) } else if (verificationMethods.length > 1) { - throw new AriesFrameworkError( + throw new CredoError( `Multiple verification methods found for signer '${signerId}' and key type '${jwkClass.keyType}' for alg '${credential.jwt.header.alg}'. Unable to determine which public key is associated with the credential.` ) } @@ -543,7 +543,7 @@ export class W3cJwtCredentialService { // Verify the controller of the verificationMethod matches the signer of the credential if (signerId && verificationMethod.controller !== signerId) { - throw new AriesFrameworkError( + throw new CredoError( `Verification method controller '${verificationMethod.controller}' does not match the signer '${signerId}'` ) } diff --git a/packages/core/src/modules/vc/jwt-vc/W3cJwtVerifiablePresentation.ts b/packages/core/src/modules/vc/jwt-vc/W3cJwtVerifiablePresentation.ts index e2869c5333..68a1923e5d 100644 --- a/packages/core/src/modules/vc/jwt-vc/W3cJwtVerifiablePresentation.ts +++ b/packages/core/src/modules/vc/jwt-vc/W3cJwtVerifiablePresentation.ts @@ -1,7 +1,7 @@ import type { W3cPresentation } from '../models' import { Jwt } from '../../../crypto/jose/jwt/Jwt' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { ClaimFormat } from '../models' import { getPresentationFromJwtPayload } from './presentationTransformer' @@ -24,7 +24,7 @@ export class W3cJwtVerifiablePresentation { const jwt = Jwt.fromSerializedJwt(serializedJwt) if (!jwt.payload.additionalClaims.nonce) { - throw new AriesFrameworkError(`JWT payload does not contain required claim 'nonce'`) + throw new CredoError(`JWT payload does not contain required claim 'nonce'`) } return new W3cJwtVerifiablePresentation({ diff --git a/packages/core/src/modules/vc/jwt-vc/__tests__/W3cJwtCredentialService.test.ts b/packages/core/src/modules/vc/jwt-vc/__tests__/W3cJwtCredentialService.test.ts index 51aa0706b0..ccb585c17b 100644 --- a/packages/core/src/modules/vc/jwt-vc/__tests__/W3cJwtCredentialService.test.ts +++ b/packages/core/src/modules/vc/jwt-vc/__tests__/W3cJwtCredentialService.test.ts @@ -4,7 +4,7 @@ import { InjectionSymbols } from '../../../../constants' import { JwsService, KeyType } from '../../../../crypto' import { JwaSignatureAlgorithm } from '../../../../crypto/jose/jwa' import { getJwkFromKey } from '../../../../crypto/jose/jwk' -import { AriesFrameworkError, ClassValidationError } from '../../../../error' +import { CredoError, ClassValidationError } from '../../../../error' import { JsonTransformer } from '../../../../utils' import { DidJwk, DidKey, DidsModuleConfig } from '../../../dids' import { CREDENTIALS_CONTEXT_V1_URL } from '../../constants' @@ -232,7 +232,7 @@ describe('W3cJwtCredentialService', () => { validations: { dataModel: { isValid: false, - error: expect.any(AriesFrameworkError), + error: expect.any(CredoError), }, }, }) @@ -255,11 +255,11 @@ describe('W3cJwtCredentialService', () => { }, signature: { isValid: false, - error: expect.any(AriesFrameworkError), + error: expect.any(CredoError), }, issuerIsSigner: { isValid: false, - error: expect.any(AriesFrameworkError), + error: expect.any(CredoError), }, credentialStatus: { isValid: true, @@ -384,7 +384,7 @@ describe('W3cJwtCredentialService', () => { }, credentialSubjectAuthentication: { isValid: false, - error: new AriesFrameworkError( + error: new CredoError( 'Credential has one or more credentialSubject ids, but presentation does not authenticate credential subject' ), }, diff --git a/packages/core/src/modules/vc/jwt-vc/credentialTransformer.ts b/packages/core/src/modules/vc/jwt-vc/credentialTransformer.ts index 243bbfff11..5a13b15619 100644 --- a/packages/core/src/modules/vc/jwt-vc/credentialTransformer.ts +++ b/packages/core/src/modules/vc/jwt-vc/credentialTransformer.ts @@ -4,7 +4,7 @@ import type { W3cJsonCredential } from '../models/credential/W3cJsonCredential' import { isObject } from 'class-validator' import { JwtPayload } from '../../../crypto/jose/jwt' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonTransformer, isJsonObject } from '../../../utils' import { W3cCredential } from '../models/credential/W3cCredential' import { w3cDate } from '../util' @@ -21,7 +21,7 @@ export function getJwtPayloadFromCredential(credential: W3cCredential) { // Extract `nbf` and remove issuance date from vc const issuanceDate = Date.parse(credential.issuanceDate) if (isNaN(issuanceDate)) { - throw new AriesFrameworkError('JWT VCs must have a valid issuance date') + throw new CredoError('JWT VCs must have a valid issuance date') } payloadOptions.nbf = Math.floor(issuanceDate / 1000) delete vc.issuanceDate @@ -53,7 +53,7 @@ export function getJwtPayloadFromCredential(credential: W3cCredential) { } if (Array.isArray(credential.credentialSubject) && credential.credentialSubject.length !== 1) { - throw new AriesFrameworkError('JWT VCs must have exactly one credential subject') + throw new CredoError('JWT VCs must have exactly one credential subject') } // Extract `sub` and remove credential subject id from vc @@ -73,34 +73,34 @@ export function getJwtPayloadFromCredential(credential: W3cCredential) { export function getCredentialFromJwtPayload(jwtPayload: JwtPayload) { if (!('vc' in jwtPayload.additionalClaims) || !isJsonObject(jwtPayload.additionalClaims.vc)) { - throw new AriesFrameworkError("JWT does not contain a valid 'vc' claim") + throw new CredoError("JWT does not contain a valid 'vc' claim") } const jwtVc = jwtPayload.additionalClaims.vc if (!jwtPayload.nbf || !jwtPayload.iss) { - throw new AriesFrameworkError("JWT does not contain valid 'nbf' and 'iss' claims") + throw new CredoError("JWT does not contain valid 'nbf' and 'iss' claims") } if (Array.isArray(jwtVc.credentialSubject) && jwtVc.credentialSubject.length !== 1) { - throw new AriesFrameworkError('JWT VCs must have exactly one credential subject') + throw new CredoError('JWT VCs must have exactly one credential subject') } if (Array.isArray(jwtVc.credentialSubject) && !isObject(jwtVc.credentialSubject[0])) { - throw new AriesFrameworkError('JWT VCs must have a credential subject of type object') + throw new CredoError('JWT VCs must have a credential subject of type object') } const credentialSubject = Array.isArray(jwtVc.credentialSubject) ? jwtVc.credentialSubject[0] : jwtVc.credentialSubject if (!isJsonObject(credentialSubject)) { - throw new AriesFrameworkError('JWT VC does not have a valid credential subject') + throw new CredoError('JWT VC does not have a valid credential subject') } const subjectWithId = jwtPayload.sub ? { ...credentialSubject, id: jwtPayload.sub } : credentialSubject // Validate vc.id and jti if (jwtVc.id && jwtPayload.jti !== jwtVc.id) { - throw new AriesFrameworkError('JWT jti and vc.id do not match') + throw new CredoError('JWT jti and vc.id do not match') } // Validate vc.issuer and iss @@ -108,30 +108,30 @@ export function getCredentialFromJwtPayload(jwtPayload: JwtPayload) { (typeof jwtVc.issuer === 'string' && jwtPayload.iss !== jwtVc.issuer) || (isJsonObject(jwtVc.issuer) && jwtVc.issuer.id && jwtPayload.iss !== jwtVc.issuer.id) ) { - throw new AriesFrameworkError('JWT iss and vc.issuer(.id) do not match') + throw new CredoError('JWT iss and vc.issuer(.id) do not match') } // Validate vc.issuanceDate and nbf if (jwtVc.issuanceDate) { if (typeof jwtVc.issuanceDate !== 'string') { - throw new AriesFrameworkError('JWT vc.issuanceDate must be a string') + throw new CredoError('JWT vc.issuanceDate must be a string') } const issuanceDate = Date.parse(jwtVc.issuanceDate) / 1000 if (jwtPayload.nbf !== issuanceDate) { - throw new AriesFrameworkError('JWT nbf and vc.issuanceDate do not match') + throw new CredoError('JWT nbf and vc.issuanceDate do not match') } } // Validate vc.expirationDate and exp if (jwtVc.expirationDate) { if (typeof jwtVc.expirationDate !== 'string') { - throw new AriesFrameworkError('JWT vc.expirationDate must be a string') + throw new CredoError('JWT vc.expirationDate must be a string') } const expirationDate = Date.parse(jwtVc.expirationDate) / 1000 if (expirationDate !== jwtPayload.exp) { - throw new AriesFrameworkError('JWT exp and vc.expirationDate do not match') + throw new CredoError('JWT exp and vc.expirationDate do not match') } } @@ -145,7 +145,7 @@ export function getCredentialFromJwtPayload(jwtPayload: JwtPayload) { jwtVc.credentialSubject[0].id && jwtPayload.sub !== jwtVc.credentialSubject[0].id) ) { - throw new AriesFrameworkError('JWT sub and vc.credentialSubject.id do not match') + throw new CredoError('JWT sub and vc.credentialSubject.id do not match') } // Create a verifiable credential structure that is compatible with the VC data model diff --git a/packages/core/src/modules/vc/jwt-vc/presentationTransformer.ts b/packages/core/src/modules/vc/jwt-vc/presentationTransformer.ts index 71f9a9868e..9b70b3ecf4 100644 --- a/packages/core/src/modules/vc/jwt-vc/presentationTransformer.ts +++ b/packages/core/src/modules/vc/jwt-vc/presentationTransformer.ts @@ -2,7 +2,7 @@ import type { JwtPayloadOptions } from '../../../crypto/jose/jwt' import type { W3cJsonPresentation } from '../models/presentation/W3cJsonPresentation' import { JwtPayload } from '../../../crypto/jose/jwt' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { JsonTransformer, isJsonObject } from '../../../utils' import { W3cPresentation } from '../models/presentation/W3cPresentation' @@ -40,14 +40,14 @@ export function getJwtPayloadFromPresentation(presentation: W3cPresentation) { export function getPresentationFromJwtPayload(jwtPayload: JwtPayload) { if (!('vp' in jwtPayload.additionalClaims) || !isJsonObject(jwtPayload.additionalClaims.vp)) { - throw new AriesFrameworkError("JWT does not contain a valid 'vp' claim") + throw new CredoError("JWT does not contain a valid 'vp' claim") } const jwtVp = jwtPayload.additionalClaims.vp // Validate vp.id and jti if (jwtVp.id && jwtPayload.jti !== jwtVp.id) { - throw new AriesFrameworkError('JWT jti and vp.id do not match') + throw new CredoError('JWT jti and vp.id do not match') } // Validate vp.holder and iss @@ -55,7 +55,7 @@ export function getPresentationFromJwtPayload(jwtPayload: JwtPayload) { (typeof jwtVp.holder === 'string' && jwtPayload.iss !== jwtVp.holder) || (isJsonObject(jwtVp.holder) && jwtVp.holder.id && jwtPayload.iss !== jwtVp.holder.id) ) { - throw new AriesFrameworkError('JWT iss and vp.holder(.id) do not match') + throw new CredoError('JWT iss and vp.holder(.id) do not match') } const dataModelVp = { diff --git a/packages/core/src/modules/vc/models/credential/W3cVerifiableCredential.ts b/packages/core/src/modules/vc/models/credential/W3cVerifiableCredential.ts index ae16558744..93dc4e7e3c 100644 --- a/packages/core/src/modules/vc/models/credential/W3cVerifiableCredential.ts +++ b/packages/core/src/modules/vc/models/credential/W3cVerifiableCredential.ts @@ -4,7 +4,7 @@ import type { ClaimFormat } from '../ClaimFormat' import { Transform, TransformationType } from 'class-transformer' import { ValidationError } from 'class-validator' -import { AriesFrameworkError, ClassValidationError } from '../../../../error' +import { CredoError, ClassValidationError } from '../../../../error' import { JsonTransformer } from '../../../../utils' import { W3cJsonLdVerifiableCredential } from '../../data-integrity/models/W3cJsonLdVerifiableCredential' import { W3cJwtVerifiableCredential } from '../../jwt-vc/W3cJwtVerifiableCredential' @@ -17,7 +17,7 @@ const getCredential = (v: unknown) => { JsonTransformer.fromJSON(v, W3cJsonLdVerifiableCredential, { validate: false }) } catch (error) { if (error instanceof ValidationError || error instanceof ClassValidationError) throw error - throw new AriesFrameworkError(`value '${v}' is not a valid W3cJwtVerifiableCredential. ${error.message}`) + throw new CredoError(`value '${v}' is not a valid W3cJwtVerifiableCredential. ${error.message}`) } } diff --git a/packages/core/src/plugins/DependencyManager.ts b/packages/core/src/plugins/DependencyManager.ts index e836ec895b..fd3e5f6669 100644 --- a/packages/core/src/plugins/DependencyManager.ts +++ b/packages/core/src/plugins/DependencyManager.ts @@ -7,7 +7,7 @@ import { container as rootContainer, InjectionToken, Lifecycle } from 'tsyringe' import { FeatureRegistry } from '../agent/FeatureRegistry' import { MessageHandlerRegistry } from '../agent/MessageHandlerRegistry' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' export { InjectionToken } @@ -28,7 +28,7 @@ export class DependencyManager { for (const [moduleKey, module] of Object.entries(modules)) { if (this.registeredModules[moduleKey]) { - throw new AriesFrameworkError( + throw new CredoError( `Module with key ${moduleKey} has already been registered. Only a single module can be registered with the same key.` ) } diff --git a/packages/core/src/storage/__tests__/Repository.test.ts b/packages/core/src/storage/__tests__/Repository.test.ts index ae56c636af..e6e93f5718 100644 --- a/packages/core/src/storage/__tests__/Repository.test.ts +++ b/packages/core/src/storage/__tests__/Repository.test.ts @@ -8,7 +8,7 @@ import { Subject } from 'rxjs' import { InMemoryStorageService } from '../../../../../tests/InMemoryStorageService' import { getAgentConfig, getAgentContext, mockFunction } from '../../../tests/helpers' import { EventEmitter } from '../../agent/EventEmitter' -import { AriesFrameworkError, RecordDuplicateError, RecordNotFoundError } from '../../error' +import { CredoError, RecordDuplicateError, RecordNotFoundError } from '../../error' import { Repository } from '../Repository' import { RepositoryEventTypes } from '../RepositoryEvents' @@ -205,9 +205,9 @@ describe('Repository', () => { }) it('should return null if the storage service throws an error that is not RecordNotFoundError', async () => { - mockFunction(storageMock.getById).mockReturnValue(Promise.reject(new AriesFrameworkError('Not found'))) + mockFunction(storageMock.getById).mockReturnValue(Promise.reject(new CredoError('Not found'))) - expect(repository.findById(agentContext, 'test-id')).rejects.toThrowError(AriesFrameworkError) + expect(repository.findById(agentContext, 'test-id')).rejects.toThrowError(CredoError) expect(storageMock.getById).toBeCalledWith(agentContext, TestRecord, 'test-id') }) }) diff --git a/packages/core/src/storage/didcomm/DidCommMessageRecord.ts b/packages/core/src/storage/didcomm/DidCommMessageRecord.ts index 4de5321396..28d5d05949 100644 --- a/packages/core/src/storage/didcomm/DidCommMessageRecord.ts +++ b/packages/core/src/storage/didcomm/DidCommMessageRecord.ts @@ -2,7 +2,7 @@ import type { DidCommMessageRole } from './DidCommMessageRole' import type { ConstructableAgentMessage } from '../../agent/AgentMessage' import type { PlaintextMessage } from '../../types' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { JsonTransformer } from '../../utils/JsonTransformer' import { canHandleMessageType, parseMessageType } from '../../utils/messageType' import { isJsonObject } from '../../utils/type' @@ -93,7 +93,7 @@ export class DidCommMessageRecord extends BaseRecord const messageType = parseMessageType(this.message['@type'] as string) if (!canHandleMessageType(messageClass, messageType)) { - throw new AriesFrameworkError('Provided message class type does not match type of stored message') + throw new CredoError('Provided message class type does not match type of stored message') } return JsonTransformer.fromJSON(this.message, messageClass) as InstanceType diff --git a/packages/core/src/storage/migration/UpdateAssistant.ts b/packages/core/src/storage/migration/UpdateAssistant.ts index 7a99b8d408..d441e77c75 100644 --- a/packages/core/src/storage/migration/UpdateAssistant.ts +++ b/packages/core/src/storage/migration/UpdateAssistant.ts @@ -4,7 +4,7 @@ import type { Module } from '../../plugins' import type { FileSystem } from '../FileSystem' import { InjectionSymbols } from '../../constants' -import { AriesFrameworkError } from '../../error' +import { CredoError } from '../../error' import { isFirstVersionEqualToSecond, isFirstVersionHigherThanSecond, parseVersionString } from '../../utils/version' import { WalletExportPathExistsError } from '../../wallet/error' import { WalletError } from '../../wallet/error/WalletError' @@ -30,7 +30,7 @@ export class UpdateAssistant = BaseAgent> { public async initialize() { if (this.agent.isInitialized) { - throw new AriesFrameworkError("Can't initialize UpdateAssistant after agent is initialized") + throw new CredoError("Can't initialize UpdateAssistant after agent is initialized") } // Initialize the wallet if not already done @@ -92,14 +92,14 @@ export class UpdateAssistant = BaseAgent> { neededUpdates.length > 0 && isFirstVersionHigherThanSecond(parseVersionString(neededUpdates[0].fromVersion), currentStorageVersion) ) { - throw new AriesFrameworkError( + throw new CredoError( `First fromVersion is higher than current storage version. You need to use an older version of the framework to update to at least version ${neededUpdates[0].fromVersion}` ) } const lastUpdateToVersion = neededUpdates.length > 0 ? neededUpdates[neededUpdates.length - 1].toVersion : undefined if (toVersion && lastUpdateToVersion && lastUpdateToVersion !== toVersion) { - throw new AriesFrameworkError( + throw new CredoError( `No update found for toVersion ${toVersion}. Make sure the toVersion is a valid version you can update to` ) } @@ -237,7 +237,7 @@ export class UpdateAssistant = BaseAgent> { const walletKey = this.agent.wallet.walletConfig?.key if (!walletKey) { - throw new AriesFrameworkError("Could not extract wallet key from wallet module. Can't create backup") + throw new CredoError("Could not extract wallet key from wallet module. Can't create backup") } await this.agent.wallet.export({ key: walletKey, path: backupPath }) @@ -251,7 +251,7 @@ export class UpdateAssistant = BaseAgent> { const walletConfig = this.agent.wallet.walletConfig if (!walletConfig) { - throw new AriesFrameworkError('Could not extract wallet config from wallet module. Cannot restore backup') + throw new CredoError('Could not extract wallet config from wallet module. Cannot restore backup') } // Export and delete current wallet diff --git a/packages/core/src/storage/migration/__tests__/backup-askar.test.ts b/packages/core/src/storage/migration/__tests__/backup-askar.test.ts index 3db486adc1..a8fdc3a618 100644 --- a/packages/core/src/storage/migration/__tests__/backup-askar.test.ts +++ b/packages/core/src/storage/migration/__tests__/backup-askar.test.ts @@ -8,7 +8,7 @@ import { askarModule } from '../../../../../askar/tests/helpers' import { getAgentOptions, getAskarWalletConfig } from '../../../../tests/helpers' import { Agent } from '../../../agent/Agent' import { InjectionSymbols } from '../../../constants' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { CredentialExchangeRecord, CredentialRepository } from '../../../modules/credentials' import { JsonTransformer } from '../../../utils' import { StorageUpdateService } from '../StorageUpdateService' @@ -137,7 +137,7 @@ describe('UpdateAssistant | Backup | Aries Askar', () => { fromVersion: '0.1', toVersion: '0.2', doUpdate: async () => { - throw new AriesFrameworkError("Uh oh I'm broken") + throw new CredoError("Uh oh I'm broken") }, }, ]) diff --git a/packages/core/src/storage/migration/__tests__/backup.test.ts b/packages/core/src/storage/migration/__tests__/backup.test.ts index 6001ac2a99..5e3b09e78d 100644 --- a/packages/core/src/storage/migration/__tests__/backup.test.ts +++ b/packages/core/src/storage/migration/__tests__/backup.test.ts @@ -8,7 +8,7 @@ import { askarModule } from '../../../../../askar/tests/helpers' import { getAgentOptions, getAskarWalletConfig } from '../../../../tests/helpers' import { Agent } from '../../../agent/Agent' import { InjectionSymbols } from '../../../constants' -import { AriesFrameworkError } from '../../../error' +import { CredoError } from '../../../error' import { CredentialExchangeRecord, CredentialRepository } from '../../../modules/credentials' import { JsonTransformer } from '../../../utils' import { StorageUpdateService } from '../StorageUpdateService' @@ -139,7 +139,7 @@ describe('UpdateAssistant | Backup', () => { fromVersion: '0.1', toVersion: '0.2', doUpdate: async () => { - throw new AriesFrameworkError("Uh oh I'm broken") + throw new CredoError("Uh oh I'm broken") }, }, ]) diff --git a/packages/core/src/storage/migration/error/StorageUpdateError.ts b/packages/core/src/storage/migration/error/StorageUpdateError.ts index 5ecef032c3..c597a2a36a 100644 --- a/packages/core/src/storage/migration/error/StorageUpdateError.ts +++ b/packages/core/src/storage/migration/error/StorageUpdateError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '../../../error/AriesFrameworkError' +import { CredoError } from '../../../error/CredoError' -export class StorageUpdateError extends AriesFrameworkError { +export class StorageUpdateError extends CredoError { public constructor(message: string, { cause }: { cause?: Error } = {}) { super(message, { cause }) } diff --git a/packages/core/src/transport/HttpOutboundTransport.ts b/packages/core/src/transport/HttpOutboundTransport.ts index 35ebdec5ca..8b2c73d32d 100644 --- a/packages/core/src/transport/HttpOutboundTransport.ts +++ b/packages/core/src/transport/HttpOutboundTransport.ts @@ -7,7 +7,7 @@ import type { OutboundPackage } from '../types' import { AbortController } from 'abort-controller' import { AgentEventTypes } from '../agent/Events' -import { AriesFrameworkError } from '../error/AriesFrameworkError' +import { CredoError } from '../error/CredoError' import { isValidJweStructure, JsonEncoder } from '../utils' export class HttpOutboundTransport implements OutboundTransport { @@ -34,7 +34,7 @@ export class HttpOutboundTransport implements OutboundTransport { const { payload, endpoint } = outboundPackage if (!endpoint) { - throw new AriesFrameworkError(`Missing endpoint. I don't know how and where to send the message.`) + throw new CredoError(`Missing endpoint. I don't know how and where to send the message.`) } this.logger.debug(`Sending outbound message to endpoint '${outboundPackage.endpoint}'`, { @@ -102,7 +102,7 @@ export class HttpOutboundTransport implements OutboundTransport { body: payload, didCommMimeType: this.agent.config.didCommMimeType, }) - throw new AriesFrameworkError(`Error sending message to ${endpoint}: ${error.message}`, { cause: error }) + throw new CredoError(`Error sending message to ${endpoint}: ${error.message}`, { cause: error }) } } } diff --git a/packages/core/src/transport/WsOutboundTransport.ts b/packages/core/src/transport/WsOutboundTransport.ts index 18a4eda3a9..c4c34e0219 100644 --- a/packages/core/src/transport/WsOutboundTransport.ts +++ b/packages/core/src/transport/WsOutboundTransport.ts @@ -7,7 +7,7 @@ import type { OutboundPackage } from '../types' import type WebSocket from 'ws' import { AgentEventTypes } from '../agent/Events' -import { AriesFrameworkError } from '../error/AriesFrameworkError' +import { CredoError } from '../error/CredoError' import { isValidJweStructure, JsonEncoder } from '../utils' import { Buffer } from '../utils/buffer' @@ -44,7 +44,7 @@ export class WsOutboundTransport implements OutboundTransport { }) if (!endpoint) { - throw new AriesFrameworkError("Missing connection or endpoint. I don't know how and where to send the message.") + throw new CredoError("Missing connection or endpoint. I don't know how and where to send the message.") } const socketId = `${endpoint}-${connectionId}` @@ -78,7 +78,7 @@ export class WsOutboundTransport implements OutboundTransport { if (!socket || socket.readyState === this.WebSocketClass.CLOSING) { if (!endpoint) { - throw new AriesFrameworkError(`Missing endpoint. I don't know how and where to send the message.`) + throw new CredoError(`Missing endpoint. I don't know how and where to send the message.`) } socket = await this.createSocketConnection({ endpoint, @@ -90,7 +90,7 @@ export class WsOutboundTransport implements OutboundTransport { } if (socket.readyState !== this.WebSocketClass.OPEN) { - throw new AriesFrameworkError('Socket is not open.') + throw new CredoError('Socket is not open.') } return socket diff --git a/packages/core/src/utils/attachment.ts b/packages/core/src/utils/attachment.ts index a50441abb5..f179ff6d1d 100644 --- a/packages/core/src/utils/attachment.ts +++ b/packages/core/src/utils/attachment.ts @@ -1,7 +1,7 @@ import type { BaseName } from './MultiBaseEncoder' import type { Attachment } from '../decorators/attachment/Attachment' -import { AriesFrameworkError } from '../error/AriesFrameworkError' +import { CredoError } from '../error/CredoError' import { HashlinkEncoder } from './HashlinkEncoder' import { TypedArrayEncoder } from './TypedArrayEncoder' @@ -24,11 +24,9 @@ export function encodeAttachment( } else if (attachment.data.base64) { return HashlinkEncoder.encode(TypedArrayEncoder.fromBase64(attachment.data.base64), hashAlgorithm, baseName) } else if (attachment.data.json) { - throw new AriesFrameworkError( - `Attachment: (${attachment.id}) has json encoded data. This is currently not supported` - ) + throw new CredoError(`Attachment: (${attachment.id}) has json encoded data. This is currently not supported`) } else { - throw new AriesFrameworkError(`Attachment: (${attachment.id}) has no data to create a link with`) + throw new CredoError(`Attachment: (${attachment.id}) has no data to create a link with`) } } diff --git a/packages/core/src/utils/parseInvitation.ts b/packages/core/src/utils/parseInvitation.ts index 4b5b5232a8..cbe8574983 100644 --- a/packages/core/src/utils/parseInvitation.ts +++ b/packages/core/src/utils/parseInvitation.ts @@ -4,7 +4,7 @@ import { AbortController } from 'abort-controller' import { parseUrl } from 'query-string' import { AgentMessage } from '../agent/AgentMessage' -import { AriesFrameworkError } from '../error' +import { CredoError } from '../error' import { ConnectionInvitationMessage } from '../modules/connections' import { OutOfBandDidCommService } from '../modules/oob/domain/OutOfBandDidCommService' import { convertToNewInvitation } from '../modules/oob/helpers' @@ -28,7 +28,7 @@ const fetchShortUrl = async (invitationUrl: string, dependencies: AgentDependenc }, }) } catch (error) { - throw new AriesFrameworkError(`Get request failed on provided url: ${error.message}`, { cause: error }) + throw new CredoError(`Get request failed on provided url: ${error.message}`, { cause: error }) } clearTimeout(id) return response @@ -44,7 +44,7 @@ export const parseInvitationJson = (invitationJson: Record): Ou const messageType = invitationJson['@type'] as string if (!messageType) { - throw new AriesFrameworkError('Invitation is not a valid DIDComm message') + throw new CredoError('Invitation is not a valid DIDComm message') } const parsedMessageType = parseMessageType(messageType) @@ -63,7 +63,7 @@ export const parseInvitationJson = (invitationJson: Record): Ou // This is probably a legacy connectionless invitation return transformLegacyConnectionlessInvitationToOutOfBandInvitation(invitationJson) } else { - throw new AriesFrameworkError(`Invitation with '@type' ${parsedMessageType.messageTypeUri} not supported.`) + throw new CredoError(`Invitation with '@type' ${parsedMessageType.messageTypeUri} not supported.`) } } @@ -83,7 +83,7 @@ export const parseInvitationUrl = (invitationUrl: string): OutOfBandInvitation = const invitationJson = JsonEncoder.fromBase64(encodedInvitation) as Record return parseInvitationJson(invitationJson) } - throw new AriesFrameworkError( + throw new CredoError( 'InvitationUrl is invalid. It needs to contain one, and only one, of the following parameters: `oob`, `c_i` or `d_m`.' ) } @@ -105,7 +105,7 @@ export const oobInvitationFromShortUrl = async (response: Response): Promise) { @@ -113,7 +113,7 @@ export function transformLegacyConnectionlessInvitationToOutOfBandInvitation(mes // ~service is required for legacy connectionless invitations if (!agentMessage.service) { - throw new AriesFrameworkError('Invalid legacy connectionless invitation url. Missing ~service decorator.') + throw new CredoError('Invalid legacy connectionless invitation url. Missing ~service decorator.') } // This destructuring removes the ~service property from the message, and @@ -160,7 +160,7 @@ export const parseInvitationShortUrl = async ( outOfBandInvitation.invitationType = InvitationType.OutOfBand return outOfBandInvitation } catch (error) { - throw new AriesFrameworkError( + throw new CredoError( 'InvitationUrl is invalid. It needs to contain one, and only one, of the following parameters: `oob`, `c_i` or `d_m`, or be valid shortened URL' ) } diff --git a/packages/core/src/wallet/error/WalletError.ts b/packages/core/src/wallet/error/WalletError.ts index 8fa4a4ceb0..414f2014aa 100644 --- a/packages/core/src/wallet/error/WalletError.ts +++ b/packages/core/src/wallet/error/WalletError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '../../error/AriesFrameworkError' +import { CredoError } from '../../error/CredoError' -export class WalletError extends AriesFrameworkError { +export class WalletError extends CredoError { public constructor(message: string, { cause }: { cause?: Error } = {}) { super(message, { cause }) } diff --git a/packages/core/tests/oob.test.ts b/packages/core/tests/oob.test.ts index 278b7850f4..6176fce000 100644 --- a/packages/core/tests/oob.test.ts +++ b/packages/core/tests/oob.test.ts @@ -22,7 +22,7 @@ import { JsonEncoder, JsonTransformer } from '../src/utils' import { TestMessage } from './TestMessage' import { getInMemoryAgentOptions, waitForCredentialRecord } from './helpers' -import { AgentEventTypes, AriesFrameworkError, AutoAcceptCredential, CredentialState } from '@credo-ts/core' +import { AgentEventTypes, CredoError, AutoAcceptCredential, CredentialState } from '@credo-ts/core' // FIXME: oob.test doesn't need heavy AnonCreds / indy dependencies const faberAgentOptions = getInMemoryAgentOptions( @@ -146,9 +146,7 @@ describe('out of band', () => { describe('createInvitation', () => { test('throw error when there is no handshake or message', async () => { await expect(faberAgent.oob.createInvitation({ label: 'test-connection', handshake: false })).rejects.toEqual( - new AriesFrameworkError( - 'One or both of handshake_protocols and requests~attach MUST be included in the message.' - ) + new CredoError('One or both of handshake_protocols and requests~attach MUST be included in the message.') ) }) @@ -159,9 +157,7 @@ describe('out of band', () => { messages: [{} as AgentMessage], multiUseInvitation: true, }) - ).rejects.toEqual( - new AriesFrameworkError("Attribute 'multiUseInvitation' can not be 'true' when 'messages' is defined.") - ) + ).rejects.toEqual(new CredoError("Attribute 'multiUseInvitation' can not be 'true' when 'messages' is defined.")) }) test('handles empty messages array as no messages being passed', async () => { @@ -171,9 +167,7 @@ describe('out of band', () => { handshake: false, }) ).rejects.toEqual( - new AriesFrameworkError( - 'One or both of handshake_protocols and requests~attach MUST be included in the message.' - ) + new CredoError('One or both of handshake_protocols and requests~attach MUST be included in the message.') ) }) @@ -614,7 +608,7 @@ describe('out of band', () => { // Try to receive the invitation again await expect(aliceAgent.oob.receiveInvitation(outOfBandInvitation)).rejects.toThrow( - new AriesFrameworkError( + new CredoError( `An out of band record with invitation ${outOfBandInvitation.id} has already been received. Invitations should have a unique id.` ) ) @@ -692,7 +686,7 @@ describe('out of band', () => { outOfBandInvitation.handshakeProtocols = [unsupportedProtocol as HandshakeProtocol] await expect(aliceAgent.oob.receiveInvitation(outOfBandInvitation, receiveInvitationConfig)).rejects.toEqual( - new AriesFrameworkError( + new CredoError( `Handshake protocols [${unsupportedProtocol}] are not supported. Supported protocols are [https://didcomm.org/didexchange/1.x,https://didcomm.org/connections/1.x]` ) ) @@ -702,9 +696,7 @@ describe('out of band', () => { const outOfBandInvitation = new OutOfBandInvitation({ label: 'test-connection', services: [] }) await expect(aliceAgent.oob.receiveInvitation(outOfBandInvitation, receiveInvitationConfig)).rejects.toEqual( - new AriesFrameworkError( - 'One or both of handshake_protocols and requests~attach MUST be included in the message.' - ) + new CredoError('One or both of handshake_protocols and requests~attach MUST be included in the message.') ) }) @@ -717,7 +709,7 @@ describe('out of band', () => { }) await expect(aliceAgent.oob.receiveInvitation(outOfBandInvitation, receiveInvitationConfig)).rejects.toEqual( - new AriesFrameworkError('There is no message in requests~attach supported by agent.') + new CredoError('There is no message in requests~attach supported by agent.') ) }) }) diff --git a/packages/indy-sdk-to-askar-migration/src/errors/IndySdkToAskarMigrationError.ts b/packages/indy-sdk-to-askar-migration/src/errors/IndySdkToAskarMigrationError.ts index e91f8f6f7f..287fdb507c 100644 --- a/packages/indy-sdk-to-askar-migration/src/errors/IndySdkToAskarMigrationError.ts +++ b/packages/indy-sdk-to-askar-migration/src/errors/IndySdkToAskarMigrationError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' /** * @internal */ -export class IndySdkToAskarMigrationError extends AriesFrameworkError {} +export class IndySdkToAskarMigrationError extends CredoError {} diff --git a/packages/indy-vdr/src/anoncreds/IndyVdrAnonCredsRegistry.ts b/packages/indy-vdr/src/anoncreds/IndyVdrAnonCredsRegistry.ts index 3d93942bd4..e2e725dd71 100644 --- a/packages/indy-vdr/src/anoncreds/IndyVdrAnonCredsRegistry.ts +++ b/packages/indy-vdr/src/anoncreds/IndyVdrAnonCredsRegistry.ts @@ -43,7 +43,7 @@ import { parseIndySchemaId, dateToTimestamp, } from '@credo-ts/anoncreds' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' import { RevocationRegistryEntryRequest, RevocationRegistryDefinitionRequest, @@ -848,13 +848,13 @@ export class IndyVdrAnonCredsRegistry implements AnonCredsRegistry { ) if (revocationRegistryNamespace && revocationRegistryNamespace !== namespace) { - throw new AriesFrameworkError( + throw new CredoError( `Issued id '${revocationStatusList.issuerId}' does not have the same namespace (${namespace}) as the revocation registry definition '${revocationRegistryNamespace}'` ) } if (revocationRegistryNamespaceIdentifier !== namespaceIdentifier) { - throw new AriesFrameworkError( + throw new CredoError( `Cannot register revocation registry definition using a different DID. Revocation registry definition contains '${revocationRegistryNamespaceIdentifier}', but DID used was '${namespaceIdentifier}'` ) } diff --git a/packages/indy-vdr/src/anoncreds/utils/transform.ts b/packages/indy-vdr/src/anoncreds/utils/transform.ts index 629223218f..8b65468586 100644 --- a/packages/indy-vdr/src/anoncreds/utils/transform.ts +++ b/packages/indy-vdr/src/anoncreds/utils/transform.ts @@ -1,6 +1,6 @@ import type { AnonCredsRevocationStatusList, AnonCredsRevocationRegistryDefinition } from '@credo-ts/anoncreds' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' export type RevocationRegistryDelta = { accum: string @@ -24,7 +24,7 @@ export function anonCredsRevocationStatusListFromIndyVdr( // revocation registry definition. This will likely also be checked on other levels as well // by the ledger or the indy-vdr library itself if (Math.max(...delta.issued, ...delta.revoked) >= revocationRegistryDefinition.value.maxCredNum) { - throw new AriesFrameworkError( + throw new CredoError( `Highest delta index '${Math.max( ...delta.issued, ...delta.revoked @@ -81,7 +81,7 @@ export function indyVdrCreateLatestRevocationDelta( previousDelta?: RevocationRegistryDelta ) { if (previousDelta && Math.max(...previousDelta.issued, ...previousDelta.revoked) > revocationStatusList.length - 1) { - throw new AriesFrameworkError( + throw new CredoError( `Indy Vdr delta contains an index '${Math.max( ...previousDelta.revoked, ...previousDelta.issued diff --git a/packages/indy-vdr/src/dids/didIndyUtil.ts b/packages/indy-vdr/src/dids/didIndyUtil.ts index 87d179ceb9..38bcf88978 100644 --- a/packages/indy-vdr/src/dids/didIndyUtil.ts +++ b/packages/indy-vdr/src/dids/didIndyUtil.ts @@ -4,7 +4,7 @@ import type { AgentContext } from '@credo-ts/core' import { parseIndyDid } from '@credo-ts/anoncreds' import { - AriesFrameworkError, + CredoError, DidDocument, DidDocumentBuilder, DidsApi, @@ -168,7 +168,7 @@ export function indyDidFromNamespaceAndInitialKey(namespace: string, initialKey: /** * Fetches the verification key for a given did:indy did and returns the key as a {@link Key} object. * - * @throws {@link AriesFrameworkError} if the did could not be resolved or the key could not be extracted + * @throws {@link CredoError} if the did could not be resolved or the key could not be extracted */ export async function verificationKeyForIndyDid(agentContext: AgentContext, did: string) { // FIXME: we should store the didDocument in the DidRecord so we don't have to fetch our own did @@ -177,7 +177,7 @@ export async function verificationKeyForIndyDid(agentContext: AgentContext, did: const didResult = await didsApi.resolve(did) if (!didResult.didDocument) { - throw new AriesFrameworkError( + throw new CredoError( `Could not resolve did ${did}. ${didResult.didResolutionMetadata.error} ${didResult.didResolutionMetadata.message}` ) } diff --git a/packages/indy-vdr/src/dids/didSovUtil.ts b/packages/indy-vdr/src/dids/didSovUtil.ts index 1e40451da7..c2bd6cdc6a 100644 --- a/packages/indy-vdr/src/dids/didSovUtil.ts +++ b/packages/indy-vdr/src/dids/didSovUtil.ts @@ -5,7 +5,7 @@ import { DidCommV1Service, DidCommV2Service, convertPublicKeyToX25519, - AriesFrameworkError, + CredoError, } from '@credo-ts/core' export type CommEndpointType = 'endpoint' | 'did-communication' | 'DIDComm' @@ -113,7 +113,7 @@ export function endpointsAttribFromServices(services: DidDocumentService[]): Ind // Check that all services use the same endpoint, as only one is accepted if (!commServices.every((item) => item.serviceEndpoint === services[0].serviceEndpoint)) { - throw new AriesFrameworkError('serviceEndpoint for all services must match') + throw new CredoError('serviceEndpoint for all services must match') } const types: CommEndpointType[] = [] @@ -122,7 +122,7 @@ export function endpointsAttribFromServices(services: DidDocumentService[]): Ind for (const commService of commServices) { const commServiceType = commService.type as CommEndpointType if (types.includes(commServiceType)) { - throw new AriesFrameworkError('Only a single communication service per type is supported') + throw new CredoError('Only a single communication service per type is supported') } types.push(commServiceType) diff --git a/packages/indy-vdr/src/error/IndyVdrError.ts b/packages/indy-vdr/src/error/IndyVdrError.ts index cdd77a08dd..a54d960105 100644 --- a/packages/indy-vdr/src/error/IndyVdrError.ts +++ b/packages/indy-vdr/src/error/IndyVdrError.ts @@ -1,6 +1,6 @@ -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' -export class IndyVdrError extends AriesFrameworkError { +export class IndyVdrError extends CredoError { public constructor(message: string, { cause }: { cause?: Error } = {}) { super(message, { cause }) } diff --git a/packages/node/src/NodeFileSystem.ts b/packages/node/src/NodeFileSystem.ts index 342d843a01..eb8611d7c4 100644 --- a/packages/node/src/NodeFileSystem.ts +++ b/packages/node/src/NodeFileSystem.ts @@ -1,6 +1,6 @@ import type { DownloadToFileOptions, FileSystem } from '@credo-ts/core' -import { AriesFrameworkError, TypedArrayEncoder } from '@credo-ts/core' +import { CredoError, TypedArrayEncoder } from '@credo-ts/core' import { createHash } from 'crypto' import fs, { promises } from 'fs' import http from 'http' @@ -92,7 +92,7 @@ export class NodeFileSystem implements FileSystem { await fs.promises.unlink(path) reject( - new AriesFrameworkError( + new CredoError( `Hash of downloaded file does not match expected hash. Expected: ${ options.verifyHash.hash }, Actual: ${TypedArrayEncoder.toUtf8String(digest)})}` diff --git a/packages/node/src/transport/HttpInboundTransport.ts b/packages/node/src/transport/HttpInboundTransport.ts index 6c28c12f3b..2296f4c483 100644 --- a/packages/node/src/transport/HttpInboundTransport.ts +++ b/packages/node/src/transport/HttpInboundTransport.ts @@ -2,7 +2,7 @@ import type { InboundTransport, Agent, TransportSession, EncryptedMessage, Agent import type { Express, Request, Response } from 'express' import type { Server } from 'http' -import { DidCommMimeType, AriesFrameworkError, TransportService, utils, MessageReceiver } from '@credo-ts/core' +import { DidCommMimeType, CredoError, TransportService, utils, MessageReceiver } from '@credo-ts/core' import express, { text } from 'express' const supportedContentTypes: string[] = [DidCommMimeType.V0, DidCommMimeType.V1] @@ -95,7 +95,7 @@ export class HttpTransportSession implements TransportSession { public async send(agentContext: AgentContext, encryptedMessage: EncryptedMessage): Promise { if (this.res.headersSent) { - throw new AriesFrameworkError(`${this.type} transport session has been closed.`) + throw new CredoError(`${this.type} transport session has been closed.`) } // By default we take the agent config's default DIDComm content-type diff --git a/packages/node/src/transport/WsInboundTransport.ts b/packages/node/src/transport/WsInboundTransport.ts index 00ffd17243..ae2d7d881c 100644 --- a/packages/node/src/transport/WsInboundTransport.ts +++ b/packages/node/src/transport/WsInboundTransport.ts @@ -1,6 +1,6 @@ import type { Agent, InboundTransport, Logger, TransportSession, EncryptedMessage, AgentContext } from '@credo-ts/core' -import { AriesFrameworkError, TransportService, utils, MessageReceiver } from '@credo-ts/core' +import { CredoError, TransportService, utils, MessageReceiver } from '@credo-ts/core' import WebSocket, { Server } from 'ws' export class WsInboundTransport implements InboundTransport { @@ -85,12 +85,12 @@ export class WebSocketTransportSession implements TransportSession { public async send(agentContext: AgentContext, encryptedMessage: EncryptedMessage): Promise { if (this.socket.readyState !== WebSocket.OPEN) { - throw new AriesFrameworkError(`${this.type} transport session has been closed.`) + throw new CredoError(`${this.type} transport session has been closed.`) } this.socket.send(JSON.stringify(encryptedMessage), (error?) => { if (error != undefined) { this.logger.debug(`Error sending message: ${error}`) - throw new AriesFrameworkError(`${this.type} send message failed.`, { cause: error }) + throw new CredoError(`${this.type} send message failed.`, { cause: error }) } else { this.logger.debug(`${this.type} sent message successfully.`) } diff --git a/packages/openid4vc-client/src/OpenId4VcClientService.ts b/packages/openid4vc-client/src/OpenId4VcClientService.ts index 0d64cec1c5..3c7d2ff9e2 100644 --- a/packages/openid4vc-client/src/OpenId4VcClientService.ts +++ b/packages/openid4vc-client/src/OpenId4VcClientService.ts @@ -19,7 +19,7 @@ import { ClaimFormat, getJwkClassFromJwaSignatureAlgorithm, W3cJwtVerifiableCredential, - AriesFrameworkError, + CredoError, getKeyFromVerificationMethod, Hasher, inject, @@ -81,7 +81,7 @@ export class OpenId4VcClientService { this.logger.debug('Generating authorization url') if (!options.scope || options.scope.length === 0) { - throw new AriesFrameworkError( + throw new CredoError( 'Only scoped based authorization requests are supported at this time. Please provide at least one scope' ) } @@ -129,9 +129,7 @@ export class OpenId4VcClientService { const flowType = flowTypeMapping[options.flowType] if (!flowType) { - throw new AriesFrameworkError( - `Unsupported flowType ${options.flowType}. Valid values are ${Object.values(AuthFlowType)}` - ) + throw new CredoError(`Unsupported flowType ${options.flowType}. Valid values are ${Object.values(AuthFlowType)}`) } const client = await OpenID4VCIClient.initiateFromURI({ @@ -247,9 +245,7 @@ export class OpenId4VcClientService { const JwkClass = getJwkClassFromJwaSignatureAlgorithm(signatureAlgorithm) if (!JwkClass) { - throw new AriesFrameworkError( - `Could not determine JWK key type based on JWA signature algorithm '${signatureAlgorithm}'` - ) + throw new CredoError(`Could not determine JWK key type based on JWA signature algorithm '${signatureAlgorithm}'`) } const supportedVerificationMethods = getSupportedVerificationMethodTypesFromKeyType(JwkClass.keyType) @@ -272,7 +268,7 @@ export class OpenId4VcClientService { ) { const { method } = parseDid(verificationMethod.id) const supportedDidMethodsString = supportedDidMethods.join(', ') - throw new AriesFrameworkError( + throw new CredoError( `Verification method uses did method '${method}', but issuer only supports '${supportedDidMethodsString}'` ) } @@ -280,7 +276,7 @@ export class OpenId4VcClientService { // Make sure the verification method uses a supported verification method type if (!supportedVerificationMethods.includes(verificationMethod.type)) { const supportedVerificationMethodsString = supportedVerificationMethods.join(', ') - throw new AriesFrameworkError( + throw new CredoError( `Verification method uses verification method type '${verificationMethod.type}', but only '${supportedVerificationMethodsString}' verification methods are supported for key type '${JwkClass.keyType}'` ) } @@ -312,7 +308,7 @@ export class OpenId4VcClientService { // DOES support one of the issuer formats, but it is not in the allowedFormats if (potentialCredentialFormats.length === 0) { const formatsString = Object.keys(options.credentialMetadata.formats).join(', ') - throw new AriesFrameworkError( + throw new CredoError( `Issuer only supports formats '${formatsString}' for credential type '${ options.credentialType }', but the wallet only allows formats '${options.allowedCredentialFormats.join(', ')}'` @@ -373,7 +369,7 @@ export class OpenId4VcClientService { } } - throw new AriesFrameworkError( + throw new CredoError( 'Could not determine the correct credential format and signature algorithm to use for the proof of possession.' ) } @@ -411,7 +407,7 @@ export class OpenId4VcClientService { this.logger.debug('Credential request response', credentialResponse) if (!credentialResponse.successBody) { - throw new AriesFrameworkError('Did not receive a successful credential response') + throw new CredoError('Did not receive a successful credential response') } let credential: W3cVerifiableCredential @@ -429,11 +425,11 @@ export class OpenId4VcClientService { verifyCredentialStatus: options.verifyCredentialStatus, }) } else { - throw new AriesFrameworkError(`Unsupported credential format ${credentialResponse.successBody.format}`) + throw new CredoError(`Unsupported credential format ${credentialResponse.successBody.format}`) } if (!result || !result.isValid) { - throw new AriesFrameworkError(`Failed to validate credential, error = ${result.error}`) + throw new CredoError(`Failed to validate credential, error = ${result.error}`) } const storedCredential = await this.w3cCredentialService.storeCredential(agentContext, { @@ -448,17 +444,17 @@ export class OpenId4VcClientService { private signCallback(agentContext: AgentContext, verificationMethod: VerificationMethod) { return async (jwt: Jwt, kid: string) => { if (!jwt.header) { - throw new AriesFrameworkError('No header present on JWT') + throw new CredoError('No header present on JWT') } if (!jwt.payload) { - throw new AriesFrameworkError('No payload present on JWT') + throw new CredoError('No payload present on JWT') } // We have determined the verification method before and already passed that when creating the callback, // however we just want to make sure that the kid matches the verification method id if (verificationMethod.id !== kid) { - throw new AriesFrameworkError(`kid ${kid} does not match verification method id ${verificationMethod.id}`) + throw new CredoError(`kid ${kid} does not match verification method id ${verificationMethod.id}`) } const key = getKeyFromVerificationMethod(verificationMethod) @@ -466,13 +462,13 @@ export class OpenId4VcClientService { const payload = JsonEncoder.toBuffer(jwt.payload) if (!jwk.supportsSignatureAlgorithm(jwt.header.alg)) { - throw new AriesFrameworkError( + throw new CredoError( `kid ${kid} refers to a key of type '${jwk.keyType}', which does not support the JWS signature alg '${jwt.header.alg}'` ) } // We don't support these properties, remove them, so we can pass all other header properties to the JWS service - if (jwt.header.x5c || jwt.header.jwk) throw new AriesFrameworkError('x5c and jwk are not supported') + if (jwt.header.x5c || jwt.header.jwk) throw new CredoError('x5c and jwk are not supported') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { x5c: _x5c, jwk: _jwk, ...supportedHeaderOptions } = jwt.header diff --git a/packages/question-answer/src/repository/QuestionAnswerRecord.ts b/packages/question-answer/src/repository/QuestionAnswerRecord.ts index 12ad9aece1..868eed97d0 100644 --- a/packages/question-answer/src/repository/QuestionAnswerRecord.ts +++ b/packages/question-answer/src/repository/QuestionAnswerRecord.ts @@ -2,7 +2,7 @@ import type { QuestionAnswerRole } from '../QuestionAnswerRole' import type { QuestionAnswerState, ValidResponse } from '../models' import type { RecordTags, TagsBase } from '@credo-ts/core' -import { AriesFrameworkError, utils, BaseRecord } from '@credo-ts/core' +import { CredoError, utils, BaseRecord } from '@credo-ts/core' export type CustomQuestionAnswerTags = TagsBase export type DefaultQuestionAnswerTags = { @@ -76,7 +76,7 @@ export class QuestionAnswerRecord extends BaseRecord e.text === response)) { await this.updateState(agentContext, questionAnswerRecord, QuestionAnswerState.AnswerSent) } else { - throw new AriesFrameworkError(`Response does not match valid responses`) + throw new CredoError(`Response does not match valid responses`) } return { answerMessage, questionAnswerRecord } } @@ -154,7 +154,7 @@ export class QuestionAnswerService { answerMessage.threadId ) if (!questionAnswerRecord) { - throw new AriesFrameworkError(`Question Answer record with thread Id ${answerMessage.threadId} not found.`) + throw new CredoError(`Question Answer record with thread Id ${answerMessage.threadId} not found.`) } questionAnswerRecord.assertState(QuestionAnswerState.QuestionSent) questionAnswerRecord.assertRole(QuestionAnswerRole.Questioner) diff --git a/packages/react-native/src/ReactNativeFileSystem.ts b/packages/react-native/src/ReactNativeFileSystem.ts index 4360ed75a6..6711400698 100644 --- a/packages/react-native/src/ReactNativeFileSystem.ts +++ b/packages/react-native/src/ReactNativeFileSystem.ts @@ -1,6 +1,6 @@ import type { FileSystem, DownloadToFileOptions } from '@credo-ts/core' -import { TypedArrayEncoder, AriesFrameworkError, getDirFromFilePath, Buffer } from '@credo-ts/core' +import { TypedArrayEncoder, CredoError, getDirFromFilePath, Buffer } from '@credo-ts/core' import { Platform } from 'react-native' import * as RNFS from 'react-native-fs' @@ -83,7 +83,7 @@ export class ReactNativeFileSystem implements FileSystem { // If hash doesn't match, remove file and throw error if (fileHashBuffer.compare(options.verifyHash.hash) !== 0) { await RNFS.unlink(path) - throw new AriesFrameworkError( + throw new CredoError( `Hash of downloaded file does not match expected hash. Expected: ${TypedArrayEncoder.toBase58( options.verifyHash.hash )}, Actual: ${TypedArrayEncoder.toBase58(fileHashBuffer)}` diff --git a/packages/sd-jwt-vc/src/SdJwtVcError.ts b/packages/sd-jwt-vc/src/SdJwtVcError.ts index 7f51b3d5de..805dfaf741 100644 --- a/packages/sd-jwt-vc/src/SdJwtVcError.ts +++ b/packages/sd-jwt-vc/src/SdJwtVcError.ts @@ -1,3 +1,3 @@ -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' -export class SdJwtVcError extends AriesFrameworkError {} +export class SdJwtVcError extends CredoError {} diff --git a/packages/tenants/src/TenantAgent.ts b/packages/tenants/src/TenantAgent.ts index 23ce34c7c9..f1ffeab4d0 100644 --- a/packages/tenants/src/TenantAgent.ts +++ b/packages/tenants/src/TenantAgent.ts @@ -1,6 +1,6 @@ import type { AgentContext, DefaultAgentModules, ModulesMap } from '@credo-ts/core' -import { AriesFrameworkError, BaseAgent } from '@credo-ts/core' +import { CredoError, BaseAgent } from '@credo-ts/core' export class TenantAgent extends BaseAgent { private sessionHasEnded = false @@ -11,7 +11,7 @@ export class TenantAgent public async initialize() { if (this.sessionHasEnded) { - throw new AriesFrameworkError("Can't initialize agent after tenant sessions has been ended.") + throw new CredoError("Can't initialize agent after tenant sessions has been ended.") } await super.initialize() diff --git a/packages/tenants/src/context/TenantAgentContextProvider.ts b/packages/tenants/src/context/TenantAgentContextProvider.ts index 27e8665373..c3cbe9a3e9 100644 --- a/packages/tenants/src/context/TenantAgentContextProvider.ts +++ b/packages/tenants/src/context/TenantAgentContextProvider.ts @@ -1,7 +1,7 @@ import type { AgentContextProvider, RoutingCreatedEvent, EncryptedMessage } from '@credo-ts/core' import { - AriesFrameworkError, + CredoError, injectable, AgentContext, EventEmitter, @@ -93,7 +93,7 @@ export class TenantAgentContextProvider implements AgentContextProvider { inboundMessage, recipientKeys: recipientKeys.map((key) => key.fingerprint), }) - throw new AriesFrameworkError("Couldn't determine tenant id for inbound message. Unable to create context") + throw new CredoError("Couldn't determine tenant id for inbound message. Unable to create context") } const agentContext = await this.getAgentContextForContextCorrelationId(tenantId) diff --git a/packages/tenants/src/context/TenantSessionCoordinator.ts b/packages/tenants/src/context/TenantSessionCoordinator.ts index b262dc9ddc..7445eb5946 100644 --- a/packages/tenants/src/context/TenantSessionCoordinator.ts +++ b/packages/tenants/src/context/TenantSessionCoordinator.ts @@ -4,7 +4,7 @@ import type { MutexInterface } from 'async-mutex' import { AgentConfig, AgentContext, - AriesFrameworkError, + CredoError, inject, injectable, InjectionSymbols, @@ -122,7 +122,7 @@ export class TenantSessionCoordinator { this.logger.error( `Unknown agent context with contextCorrelationId '${agentContext.contextCorrelationId}'. Cannot end session` ) - throw new AriesFrameworkError( + throw new CredoError( `Unknown agent context with contextCorrelationId '${agentContext.contextCorrelationId}'. Cannot end session` ) } @@ -163,9 +163,7 @@ export class TenantSessionCoordinator { // be fast enough to not cause a problem. This wil also only be problem when the wallet is being created // for the first time or being acquired while wallet initialization is in progress. this.tenantsModuleConfig.sessionAcquireTimeout, - new AriesFrameworkError( - `Error acquiring lock for tenant ${tenantId}. Wallet initialization or shutdown took too long.` - ) + new CredoError(`Error acquiring lock for tenant ${tenantId}. Wallet initialization or shutdown took too long.`) ), } this.tenantAgentContextMapping[tenantId] = tenantSessionMapping diff --git a/packages/tenants/src/context/TenantSessionMutex.ts b/packages/tenants/src/context/TenantSessionMutex.ts index 6e7a6aa6a4..8779990572 100644 --- a/packages/tenants/src/context/TenantSessionMutex.ts +++ b/packages/tenants/src/context/TenantSessionMutex.ts @@ -1,7 +1,7 @@ import type { Logger } from '@credo-ts/core' import type { MutexInterface } from 'async-mutex' -import { AriesFrameworkError } from '@credo-ts/core' +import { CredoError } from '@credo-ts/core' import { withTimeout, Mutex } from 'async-mutex' /** @@ -23,7 +23,7 @@ export class TenantSessionMutex { this.sessionMutex = withTimeout( new Mutex(), sessionAcquireTimeout, - new AriesFrameworkError(`Failed to acquire an agent context session within ${sessionAcquireTimeout}ms`) + new CredoError(`Failed to acquire an agent context session within ${sessionAcquireTimeout}ms`) ) } diff --git a/samples/extension-module/requester.ts b/samples/extension-module/requester.ts index 94293e3cd3..a2e4d29b9f 100644 --- a/samples/extension-module/requester.ts +++ b/samples/extension-module/requester.ts @@ -3,7 +3,7 @@ import type { DummyRecord, DummyStateChangedEvent } from './dummy' import { HttpOutboundTransport, Agent, - AriesFrameworkError, + CredoError, ConsoleLogger, LogLevel, WsOutboundTransport, @@ -52,7 +52,7 @@ const run = async () => { const invitationUrl = await (await agentDependencies.fetch(`http://localhost:${port}/invitation`)).text() const { connectionRecord } = await agent.oob.receiveInvitationFromUrl(invitationUrl) if (!connectionRecord) { - throw new AriesFrameworkError('Connection record for out-of-band invitation was not created.') + throw new CredoError('Connection record for out-of-band invitation was not created.') } await agent.connections.returnWhenIsConnected(connectionRecord.id) diff --git a/tests/InMemoryWallet.ts b/tests/InMemoryWallet.ts index fd46f2359e..1b087ce524 100644 --- a/tests/InMemoryWallet.ts +++ b/tests/InMemoryWallet.ts @@ -21,7 +21,7 @@ import { isValidPrivateKey, KeyType, Buffer, - AriesFrameworkError, + CredoError, WalletError, Key, TypedArrayEncoder, @@ -185,7 +185,7 @@ export class InMemoryWallet implements Wallet { if (error instanceof WalletError) throw error if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError(`Error creating key with key type '${keyType}': ${error.message}`, { cause: error }) } @@ -327,7 +327,7 @@ export class InMemoryWallet implements Wallet { return new BigNumber(nonce).toString() } catch (error) { if (!isError(error)) { - throw new AriesFrameworkError('Attempted to throw error, but it was not of type Error', { cause: error }) + throw new CredoError('Attempted to throw error, but it was not of type Error', { cause: error }) } throw new WalletError('Error generating nonce', { cause: error }) } diff --git a/tests/InMemoryWalletModule.ts b/tests/InMemoryWalletModule.ts index c33326b79f..a43a903dcd 100644 --- a/tests/InMemoryWalletModule.ts +++ b/tests/InMemoryWalletModule.ts @@ -3,18 +3,18 @@ import type { DependencyManager, Module } from '@credo-ts/core' import { InMemoryStorageService } from './InMemoryStorageService' import { InMemoryWallet } from './InMemoryWallet' -import { AriesFrameworkError, InjectionSymbols } from '@credo-ts/core' +import { CredoError, InjectionSymbols } from '@credo-ts/core' export class InMemoryWalletModule implements Module { public register(dependencyManager: DependencyManager) { if (dependencyManager.isRegistered(InjectionSymbols.Wallet)) { - throw new AriesFrameworkError('There is an instance of Wallet already registered') + throw new CredoError('There is an instance of Wallet already registered') } else { dependencyManager.registerContextScoped(InjectionSymbols.Wallet, InMemoryWallet) } if (dependencyManager.isRegistered(InjectionSymbols.StorageService)) { - throw new AriesFrameworkError('There is an instance of StorageService already registered') + throw new CredoError('There is an instance of StorageService already registered') } else { dependencyManager.registerSingleton(InjectionSymbols.StorageService, InMemoryStorageService) } diff --git a/tests/transport/SubjectOutboundTransport.ts b/tests/transport/SubjectOutboundTransport.ts index 2ca5fc7e1d..0291f84948 100644 --- a/tests/transport/SubjectOutboundTransport.ts +++ b/tests/transport/SubjectOutboundTransport.ts @@ -3,7 +3,7 @@ import type { OutboundPackage, OutboundTransport, Agent, Logger } from '@credo-t import { takeUntil, Subject, take } from 'rxjs' -import { MessageReceiver, InjectionSymbols, AriesFrameworkError } from '@credo-ts/core' +import { MessageReceiver, InjectionSymbols, CredoError } from '@credo-ts/core' export class SubjectOutboundTransport implements OutboundTransport { private logger!: Logger @@ -36,13 +36,13 @@ export class SubjectOutboundTransport implements OutboundTransport { const { payload, endpoint } = outboundPackage if (!endpoint) { - throw new AriesFrameworkError('Cannot send message to subject without endpoint') + throw new CredoError('Cannot send message to subject without endpoint') } const subject = this.subjectMap[endpoint] if (!subject) { - throw new AriesFrameworkError(`No subject found for endpoint ${endpoint}`) + throw new CredoError(`No subject found for endpoint ${endpoint}`) } // Create a replySubject just for this session. Both ends will be able to close it,