const require_rolldown_runtime = require('../../../../../_virtual/rolldown_runtime.js');
const require_decorateMetadata = require('../../../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorateMetadata.js');
const require_decorate = require('../../../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorate.js');
const require_DidCommAttachment = require('../../decorators/attachment/DidCommAttachment.js');
require('../../models/index.js');
const require_DidCommDidExchangeState = require('./models/DidCommDidExchangeState.js');
const require_DidCommDidExchangeRole = require('./models/DidCommDidExchangeRole.js');
const require_DidCommHandshakeProtocol = require('./models/DidCommHandshakeProtocol.js');
require('./models/index.js');
const require_DidCommDidExchangeRequestMessage = require('./messages/DidCommDidExchangeRequestMessage.js');
const require_DidCommDidExchangeResponseMessage = require('./messages/DidCommDidExchangeResponseMessage.js');
const require_DidCommDidExchangeCompleteMessage = require('./messages/DidCommDidExchangeCompleteMessage.js');
require('./messages/index.js');
const require_DidExchangeProblemReportError = require('./errors/DidExchangeProblemReportError.js');
const require_DidExchangeProblemReportReason = require('./errors/DidExchangeProblemReportReason.js');
require('./errors/index.js');
const require_DidCommOutOfBandState = require('../oob/domain/DidCommOutOfBandState.js');
const require_decorateParam = require('../../../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorateParam.js');
const require_DidCommDocumentService = require('../../services/DidCommDocumentService.js');
require('../../services/index.js');
const require_helpers = require('./services/helpers.js');
const require_DidCommOutOfBandRole = require('../oob/domain/DidCommOutOfBandRole.js');
const require_DidCommConnectionService = require('./services/DidCommConnectionService.js');
const require_helpers$1 = require('../routing/services/helpers.js');
const require_DidCommConnectionsModuleConfig = require('./DidCommConnectionsModuleConfig.js');
require('./services/index.js');
const require_DidExchangeStateMachine = require('./DidExchangeStateMachine.js');
let __credo_ts_core = require("@credo-ts/core");
__credo_ts_core = require_rolldown_runtime.__toESM(__credo_ts_core);

//#region ../didcomm/src/modules/connections/DidExchangeProtocol.ts
var _ref, _ref2, _ref3, _ref4;
let DidExchangeProtocol = class DidExchangeProtocol$1 {
	constructor(connectionService, didRepository, jwsService, didcommDocumentService, logger) {
		this.connectionService = connectionService;
		this.didRepository = didRepository;
		this.jwsService = jwsService;
		this.didcommDocumentService = didcommDocumentService;
		this.logger = logger;
	}
	async createRequest(agentContext, outOfBandRecord, params) {
		this.logger.debug(`Create message ${require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type.messageTypeUri} start`, {
			outOfBandRecord,
			params
		});
		const config = agentContext.dependencyManager.resolve(require_DidCommConnectionsModuleConfig.DidCommConnectionsModuleConfig);
		const { outOfBandInvitation } = outOfBandRecord;
		const { alias, goal, goalCode, routing, autoAcceptConnection, ourDid: did } = params;
		const [invitationDid] = outOfBandInvitation.invitationDids;
		const label = params.label;
		let didDocument;
		let keys;
		let mediatorId;
		if (did) {
			const resolved = await agentContext.resolve(__credo_ts_core.DidsApi).resolveCreatedDidDocumentWithKeys(did);
			didDocument = resolved.didDocument;
			keys = resolved.keys;
			mediatorId = (await require_helpers$1.getMediationRecordForDidDocument(agentContext, didDocument))?.id;
		} else {
			if (!routing) throw new __credo_ts_core.CredoError(`'routing' must be defined if 'ourDid' is not specified`);
			const resolved = await require_helpers.createPeerDidFromServices(agentContext, require_helpers.routingToServices(routing), config.peerNumAlgoForDidExchangeRequests);
			didDocument = resolved.didDocument;
			keys = resolved.keys;
			mediatorId = routing.mediatorId;
		}
		const parentThreadId = outOfBandRecord.outOfBandInvitation.id;
		const message = new require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage({
			label,
			parentThreadId,
			did: didDocument.id,
			goal,
			goalCode
		});
		const signingKeys = didDocument.getRecipientKeysWithVerificationMethod({ mapX25519ToEd25519: true }).map(({ publicJwk, verificationMethod }) => {
			publicJwk.keyId = keys?.find(({ didDocumentRelativeKeyId }) => verificationMethod.id.endsWith(didDocumentRelativeKeyId))?.kmsKeyId ?? publicJwk.legacyKeyId;
			return publicJwk;
		});
		if ((0, __credo_ts_core.isValidPeerDid)(didDocument.id) && (0, __credo_ts_core.getNumAlgoFromPeerDid)(didDocument.id) === __credo_ts_core.PeerDidNumAlgo.GenesisDoc) message.didDoc = await this.createSignedAttachment(agentContext, didDocument.toJSON(), signingKeys);
		const connectionRecord = await this.connectionService.createConnection(agentContext, {
			protocol: require_DidCommHandshakeProtocol.DidCommHandshakeProtocol.DidExchange,
			role: require_DidCommDidExchangeRole.DidCommDidExchangeRole.Requester,
			alias,
			state: require_DidCommDidExchangeState.DidCommDidExchangeState.InvitationReceived,
			theirLabel: outOfBandInvitation.label,
			mediatorId,
			autoAcceptConnection: outOfBandRecord.autoAcceptConnection,
			outOfBandId: outOfBandRecord.id,
			invitationDid,
			imageUrl: outOfBandInvitation.imageUrl
		});
		require_DidExchangeStateMachine.DidExchangeStateMachine.assertCreateMessageState(require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type, connectionRecord);
		connectionRecord.did = didDocument.id;
		connectionRecord.threadId = message.id;
		if (autoAcceptConnection !== void 0 || autoAcceptConnection !== null) connectionRecord.autoAcceptConnection = autoAcceptConnection;
		await this.updateState(agentContext, require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type, connectionRecord);
		this.logger.debug(`Create message ${require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type.messageTypeUri} end`, {
			connectionRecord,
			message
		});
		return {
			message,
			connectionRecord
		};
	}
	async processRequest(messageContext, outOfBandRecord) {
		this.logger.debug(`Process message ${messageContext.message.type} start`, { message: messageContext.message });
		outOfBandRecord.assertRole(require_DidCommOutOfBandRole.DidCommOutOfBandRole.Sender);
		outOfBandRecord.assertState(require_DidCommOutOfBandState.DidCommOutOfBandState.AwaitResponse);
		const { message, agentContext } = messageContext;
		const parentThreadId = message.thread?.parentThreadId;
		if (!parentThreadId || !(0, __credo_ts_core.tryParseDid)(parentThreadId) && parentThreadId !== outOfBandRecord.getTags().invitationId) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("Missing reference to invitation.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.RequestNotAccepted });
		const didDocument = await this.resolveDidDocument(agentContext, message);
		const didRecord = await this.didRepository.storeReceivedDid(messageContext.agentContext, {
			did: didDocument.id,
			didDocument: !(0, __credo_ts_core.isValidPeerDid)(didDocument.id) || (0, __credo_ts_core.getNumAlgoFromPeerDid)(message.did) === __credo_ts_core.PeerDidNumAlgo.GenesisDoc ? didDocument : void 0,
			tags: {
				recipientKeyFingerprints: didDocument.recipientKeys.map((key) => key.fingerprint),
				alternativeDids: (0, __credo_ts_core.isValidPeerDid)(didDocument.id) ? (0, __credo_ts_core.getAlternativeDidsForPeerDid)(didDocument.id) : void 0
			}
		});
		this.logger.debug("Saved DID record", {
			id: didRecord.id,
			did: didRecord.did,
			role: didRecord.role,
			tags: didRecord.getTags(),
			didDocument: "omitted..."
		});
		const connectionRecord = await this.connectionService.createConnection(messageContext.agentContext, {
			protocol: require_DidCommHandshakeProtocol.DidCommHandshakeProtocol.DidExchange,
			role: require_DidCommDidExchangeRole.DidCommDidExchangeRole.Responder,
			state: require_DidCommDidExchangeState.DidCommDidExchangeState.RequestReceived,
			alias: outOfBandRecord.alias,
			theirDid: message.did,
			theirLabel: message.label,
			threadId: message.threadId,
			mediatorId: outOfBandRecord.mediatorId,
			autoAcceptConnection: outOfBandRecord.autoAcceptConnection,
			outOfBandId: outOfBandRecord.id
		});
		await this.updateState(messageContext.agentContext, require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type, connectionRecord);
		this.logger.debug(`Process message ${require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage.type.messageTypeUri} end`, connectionRecord);
		return connectionRecord;
	}
	async createResponse(agentContext, connectionRecord, outOfBandRecord, routing) {
		this.logger.debug(`Create message ${require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type.messageTypeUri} start`, connectionRecord);
		require_DidExchangeStateMachine.DidExchangeStateMachine.assertCreateMessageState(require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type, connectionRecord);
		const { threadId, theirDid } = connectionRecord;
		const config = agentContext.dependencyManager.resolve(require_DidCommConnectionsModuleConfig.DidCommConnectionsModuleConfig);
		if (!threadId) throw new __credo_ts_core.CredoError("Missing threadId on connection record.");
		if (!theirDid) throw new __credo_ts_core.CredoError("Missing theirDid on connection record.");
		const inlineResolvedServices = outOfBandRecord.outOfBandInvitation.getInlineServices().map((service) => require_helpers.getResolvedDidcommServiceWithSigningKeyId(service, outOfBandRecord.invitationInlineServiceKeys));
		let services = [];
		if (routing) services = require_helpers.routingToServices(routing);
		else if (inlineResolvedServices.length > 0) services = inlineResolvedServices;
		else throw new __credo_ts_core.CredoError("No routing provided, and no inline services found in out of band invitation. When using did services in out of band invitation, make sure to provide routing information for rotation.");
		const numAlgo = (0, __credo_ts_core.isValidPeerDid)(theirDid) ? (0, __credo_ts_core.getNumAlgoFromPeerDid)(theirDid) : config.peerNumAlgoForDidExchangeRequests;
		const { didDocument } = await require_helpers.createPeerDidFromServices(agentContext, services, numAlgo);
		const message = new require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage({
			did: didDocument.id,
			threadId
		});
		const invitationRecipientKeys = inlineResolvedServices.flatMap((s) => s.recipientKeys);
		for (const did of outOfBandRecord.outOfBandInvitation.getDidServices()) {
			const resolved = await agentContext.resolve(__credo_ts_core.DidsApi).resolveCreatedDidDocumentWithKeys((0, __credo_ts_core.parseDid)(did).did);
			invitationRecipientKeys.push(...resolved.didDocument.getRecipientKeysWithVerificationMethod({ mapX25519ToEd25519: true }).map(({ publicJwk, verificationMethod }) => {
				publicJwk.keyId = resolved.keys?.find(({ didDocumentRelativeKeyId }) => verificationMethod.id.endsWith(didDocumentRelativeKeyId))?.kmsKeyId ?? publicJwk.legacyKeyId;
				return publicJwk;
			}));
		}
		if (numAlgo === __credo_ts_core.PeerDidNumAlgo.GenesisDoc) message.didDoc = await this.createSignedAttachment(agentContext, didDocument.toJSON(), invitationRecipientKeys);
		else message.didRotate = await this.createSignedAttachment(agentContext, didDocument.id, invitationRecipientKeys);
		connectionRecord.did = didDocument.id;
		await this.updateState(agentContext, require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type, connectionRecord);
		this.logger.debug(`Create message ${require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type.messageTypeUri} end`, {
			connectionRecord,
			message
		});
		return message;
	}
	async processResponse(messageContext, outOfBandRecord) {
		this.logger.debug(`Process message ${require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type.messageTypeUri} start`, { message: messageContext.message });
		const { connection: connectionRecord, message, agentContext } = messageContext;
		if (!connectionRecord) throw new __credo_ts_core.CredoError("No connection record in message context.");
		require_DidExchangeStateMachine.DidExchangeStateMachine.assertProcessMessageState(require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type, connectionRecord);
		if (!message.thread?.threadId || message.thread?.threadId !== connectionRecord.threadId) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("Invalid or missing thread ID.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		const didDocument = await this.resolveDidDocument(agentContext, message, outOfBandRecord.getTags().recipientKeyFingerprints.map((fingerprint) => {
			const publicJwk = __credo_ts_core.Kms.PublicJwk.fromFingerprint(fingerprint);
			if (!publicJwk.is(__credo_ts_core.Kms.Ed25519PublicJwk)) throw new __credo_ts_core.CredoError("Expected fingerprint to be of type Ed25519");
			return publicJwk;
		}));
		if ((0, __credo_ts_core.isValidPeerDid)(didDocument.id)) {
			const didRecord = await this.didRepository.storeReceivedDid(messageContext.agentContext, {
				did: didDocument.id,
				didDocument: (0, __credo_ts_core.getNumAlgoFromPeerDid)(message.did) === __credo_ts_core.PeerDidNumAlgo.GenesisDoc ? didDocument : void 0,
				tags: {
					recipientKeyFingerprints: didDocument.recipientKeys.map((key) => key.fingerprint),
					alternativeDids: (0, __credo_ts_core.getAlternativeDidsForPeerDid)(didDocument.id)
				}
			});
			this.logger.debug("Saved DID record", {
				id: didRecord.id,
				did: didRecord.did,
				role: didRecord.role,
				tags: didRecord.getTags(),
				didDocument: "omitted..."
			});
		}
		connectionRecord.theirDid = message.did;
		await this.updateState(messageContext.agentContext, require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type, connectionRecord);
		this.logger.debug(`Process message ${require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage.type.messageTypeUri} end`, connectionRecord);
		return connectionRecord;
	}
	async createComplete(agentContext, connectionRecord, outOfBandRecord) {
		this.logger.debug(`Create message ${require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type.messageTypeUri} start`, connectionRecord);
		require_DidExchangeStateMachine.DidExchangeStateMachine.assertCreateMessageState(require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type, connectionRecord);
		const threadId = connectionRecord.threadId;
		const parentThreadId = outOfBandRecord.outOfBandInvitation.id;
		if (!threadId) throw new __credo_ts_core.CredoError(`Connection record ${connectionRecord.id} does not have 'threadId' attribute.`);
		if (!parentThreadId) throw new __credo_ts_core.CredoError(`Connection record ${connectionRecord.id} does not have 'parentThreadId' attribute.`);
		const message = new require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage({
			threadId,
			parentThreadId
		});
		await this.updateState(agentContext, require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type, connectionRecord);
		this.logger.debug(`Create message ${require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type.messageTypeUri} end`, {
			connectionRecord,
			message
		});
		return message;
	}
	async processComplete(messageContext, outOfBandRecord) {
		this.logger.debug(`Process message ${require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type.messageTypeUri} start`, { message: messageContext.message });
		const { connection: connectionRecord, message } = messageContext;
		if (!connectionRecord) throw new __credo_ts_core.CredoError("No connection record in message context.");
		require_DidExchangeStateMachine.DidExchangeStateMachine.assertProcessMessageState(require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type, connectionRecord);
		if (message.threadId !== connectionRecord.threadId) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("Invalid or missing thread ID.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.CompleteRejected });
		const pthid = message.thread?.parentThreadId;
		if (!pthid || pthid !== outOfBandRecord.outOfBandInvitation.id) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("Invalid or missing parent thread ID referencing to the invitation.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.CompleteRejected });
		await this.updateState(messageContext.agentContext, require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type, connectionRecord);
		this.logger.debug(`Process message ${require_DidCommDidExchangeCompleteMessage.DidCommDidExchangeCompleteMessage.type.messageTypeUri} end`, { connectionRecord });
		return connectionRecord;
	}
	async updateState(agentContext, messageType, connectionRecord) {
		this.logger.debug("Updating state", { connectionRecord });
		const nextState = require_DidExchangeStateMachine.DidExchangeStateMachine.nextState(messageType, connectionRecord);
		return this.connectionService.updateState(agentContext, connectionRecord, nextState);
	}
	async createSignedAttachment(agentContext, data, signingKeys) {
		this.logger.debug("Creating signed attachment");
		const signedAttach = new require_DidCommAttachment.DidCommAttachment({
			mimeType: typeof data === "string" ? void 0 : "application/json",
			data: new require_DidCommAttachment.DidCommAttachmentData({ base64: typeof data === "string" ? __credo_ts_core.TypedArrayEncoder.toBase64URL(__credo_ts_core.Buffer.from(data)) : __credo_ts_core.JsonEncoder.toBase64(data) })
		});
		await Promise.all(signingKeys.map(async (signingKey) => {
			const kid = new __credo_ts_core.DidKey(signingKey).did;
			const payload = typeof data === "string" ? __credo_ts_core.TypedArrayEncoder.fromString(data) : __credo_ts_core.JsonEncoder.toBuffer(data);
			const jws = await this.jwsService.createJws(agentContext, {
				payload,
				keyId: signingKey.keyId,
				header: { kid },
				protectedHeaderOptions: {
					alg: __credo_ts_core.Kms.KnownJwaSignatureAlgorithms.EdDSA,
					jwk: signingKey
				}
			});
			signedAttach.addJws(jws);
		}));
		return signedAttach;
	}
	/**
	* Resolves a did document from a given `request` or `response` message, verifying its signature or did rotate
	* signature in case it is taken from message attachment.
	*
	* @param message DID request or DID response message
	* @param invitationKeys array containing keys from connection invitation that could be used for signing of DID document
	* @returns verified DID document content from message attachment
	*/
	async resolveDidDocument(agentContext, message, invitationKeys = []) {
		return (0, __credo_ts_core.isDid)(message.did, "peer") && (0, __credo_ts_core.getNumAlgoFromPeerDid)(message.did) === __credo_ts_core.PeerDidNumAlgo.GenesisDoc ? this.extractAttachedDidDocument(agentContext, message, invitationKeys) : this.extractResolvableDidDocument(agentContext, message, invitationKeys);
	}
	/**
	* Extracts DID document from message (resolving it externally if required) and verifies did-rotate attachment signature
	* if applicable
	*/
	async extractResolvableDidDocument(agentContext, message, invitationKeys) {
		if (message instanceof require_DidCommDidExchangeResponseMessage.DidCommDidExchangeResponseMessage) {
			const didRotateAttachment = message.didRotate;
			if (!didRotateAttachment) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("DID Rotate attachment is missing.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
			const jws = didRotateAttachment.data.jws;
			if (!jws) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("DID Rotate signature is missing.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
			if (!didRotateAttachment.data.base64) throw new __credo_ts_core.CredoError("DID Rotate attachment is missing base64 property for signed did.");
			const base64UrlPayload = (0, __credo_ts_core.base64ToBase64URL)(didRotateAttachment.data.base64);
			if (__credo_ts_core.TypedArrayEncoder.fromBase64(base64UrlPayload).toString() !== message.did) throw new __credo_ts_core.CredoError(`DID Rotate attachment's did ${message.did} does not correspond to message did ${message.did}`);
			const { isValid, jwsSigners } = await this.jwsService.verifyJws(agentContext, {
				jws: {
					...jws,
					payload: base64UrlPayload
				},
				allowedJwsSignerMethods: ["did"],
				resolveJwsSigner: ({ jws: { header } }) => {
					if (typeof header.kid !== "string" || !(0, __credo_ts_core.isDid)(header.kid, "key")) throw new __credo_ts_core.CredoError("JWS header kid must be a did:key DID.");
					const didKey = __credo_ts_core.DidKey.fromDid(header.kid);
					return {
						method: "did",
						didUrl: `${didKey.did}#${didKey.publicJwk.fingerprint}`,
						jwk: didKey.publicJwk
					};
				}
			});
			const jwsSignerKeys = jwsSigners.map((signer) => signer.jwk);
			if (!jwsSignerKeys.every((key) => key.is(__credo_ts_core.Kms.Ed25519PublicJwk))) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("Expected DID Rotate signature to be signed with Ed25519 key.", { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
			if (!isValid || !jwsSignerKeys.every((key) => invitationKeys?.some((invitationKey) => invitationKey.equals(key)))) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError(`DID Rotate signature is invalid. isValid: ${isValid} signerKeys: ${JSON.stringify(jwsSignerKeys.map((key) => key.fingerprint))} invitationKeys:${JSON.stringify(invitationKeys?.map((key) => key.fingerprint))}`, { problemCode: require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		}
		try {
			return await agentContext.dependencyManager.resolve(__credo_ts_core.DidsApi).resolveDidDocument(message.did);
		} catch (error) {
			throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError(error, { problemCode: message instanceof require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage ? require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.RequestNotAccepted : require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		}
	}
	/**
	* Extracts DID document as is from request or response message attachment and verifies its signature.
	*
	* @param message DID request or DID response message
	* @param invitationKeys array containing keys from connection invitation that could be used for signing of DID document
	* @returns verified DID document content from message attachment
	*/
	async extractAttachedDidDocument(agentContext, message, invitationKeys = []) {
		if (!message.didDoc) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("DID Document attachment is missing.", { problemCode: message instanceof require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage ? require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.RequestNotAccepted : require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		const didDocumentAttachment = message.didDoc;
		const jws = didDocumentAttachment.data.jws;
		if (!jws) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("DID Document signature is missing.", { problemCode: message instanceof require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage ? require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.RequestNotAccepted : require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		if (!didDocumentAttachment.data.base64) throw new __credo_ts_core.CredoError("DID Document attachment is missing base64 property for signed did document.");
		const base64UrlPayload = (0, __credo_ts_core.base64ToBase64URL)(didDocumentAttachment.data.base64);
		const { isValid, jwsSigners } = await this.jwsService.verifyJws(agentContext, {
			jws: {
				...jws,
				payload: base64UrlPayload
			},
			allowedJwsSignerMethods: ["did"],
			resolveJwsSigner: ({ jws: { header } }) => {
				if (typeof header.kid !== "string" || !(0, __credo_ts_core.isDid)(header.kid, "key")) throw new __credo_ts_core.CredoError("JWS header kid must be a did:key DID.");
				const didKey = __credo_ts_core.DidKey.fromDid(header.kid);
				return {
					method: "did",
					didUrl: `${didKey.did}#${didKey.publicJwk.fingerprint}`,
					jwk: didKey.publicJwk
				};
			}
		});
		const json = __credo_ts_core.JsonEncoder.fromBase64(didDocumentAttachment.data.base64);
		const didDocument = __credo_ts_core.JsonTransformer.fromJSON(json, __credo_ts_core.DidDocument);
		const didDocumentKeys = didDocument.authentication?.map((authentication) => {
			return (0, __credo_ts_core.getPublicJwkFromVerificationMethod)(typeof authentication === "string" ? didDocument.dereferenceVerificationMethod(authentication) : authentication);
		}).concat(invitationKeys);
		this.logger.trace("JWS verification result", {
			isValid,
			jwsSigners
		});
		if (!isValid || !jwsSigners.every((jwsSigner) => didDocumentKeys?.some((key) => key.equals(jwsSigner.jwk)))) throw new require_DidExchangeProblemReportError.DidExchangeProblemReportError("DID Document signature is invalid.", { problemCode: message instanceof require_DidCommDidExchangeRequestMessage.DidCommDidExchangeRequestMessage ? require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.RequestNotAccepted : require_DidExchangeProblemReportReason.DidExchangeProblemReportReason.ResponseNotAccepted });
		return didDocument;
	}
};
DidExchangeProtocol = require_decorate.__decorate([
	(0, __credo_ts_core.injectable)(),
	require_decorateParam.__decorateParam(4, (0, __credo_ts_core.inject)(__credo_ts_core.InjectionSymbols.Logger)),
	require_decorateMetadata.__decorateMetadata("design:paramtypes", [
		typeof (_ref = typeof require_DidCommConnectionService.DidCommConnectionService !== "undefined" && require_DidCommConnectionService.DidCommConnectionService) === "function" ? _ref : Object,
		typeof (_ref2 = typeof __credo_ts_core.DidRepository !== "undefined" && __credo_ts_core.DidRepository) === "function" ? _ref2 : Object,
		typeof (_ref3 = typeof __credo_ts_core.JwsService !== "undefined" && __credo_ts_core.JwsService) === "function" ? _ref3 : Object,
		typeof (_ref4 = typeof require_DidCommDocumentService.DidCommDocumentService !== "undefined" && require_DidCommDocumentService.DidCommDocumentService) === "function" ? _ref4 : Object,
		Object
	])
], DidExchangeProtocol);

//#endregion
Object.defineProperty(exports, 'DidExchangeProtocol', {
  enumerable: true,
  get: function () {
    return DidExchangeProtocol;
  }
});