

const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.js');
const require_CredoError = require('../../../error/CredoError.js');
require('../../../error/index.js');
require('../../../plugins/index.js');
const require_decorateMetadata = require('../../../_virtual/_@oxc-project_runtime@0.95.0/helpers/decorateMetadata.js');
const require_decorate = require('../../../_virtual/_@oxc-project_runtime@0.95.0/helpers/decorate.js');
const require_array = require('../../../utils/array.js');
const require_MessageValidator = require('../../../utils/MessageValidator.js');
const require_JsonTransformer = require('../../../utils/JsonTransformer.js');
const require_timestamp = require('../../../utils/timestamp.js');
require('../../../utils/index.js');
const require_JwtPayload = require('../../../crypto/jose/jwt/JwtPayload.js');
const require_JwsService = require('../../../crypto/JwsService.js');
const require_keyDidMapping = require('../../dids/domain/key-type/keyDidMapping.js');
const require_W3cV2JwtVerifiableCredential = require('./W3cV2JwtVerifiableCredential.js');
require('../../../crypto/index.js');
const require_utils = require('../../sd-jwt-vc/utils.js');
const require_v2_jwt_utils = require('../v2-jwt-utils.js');
const require_W3cV2JwtVerifiablePresentation = require('./W3cV2JwtVerifiablePresentation.js');
let tsyringe = require("tsyringe");
tsyringe = require_rolldown_runtime.__toESM(tsyringe);

//#region src/modules/vc/jwt-vc/W3cV2JwtCredentialService.ts
var _ref;
let W3cV2JwtCredentialService = class W3cV2JwtCredentialService$1 {
	constructor(jwsService) {
		this.jwsService = jwsService;
	}
	/**
	* Signs a credential
	*/
	async signCredential(agentContext, options) {
		require_MessageValidator.MessageValidator.validateSync(options.credential);
		const jwtPayload = new require_JwtPayload.JwtPayload({ additionalClaims: require_JsonTransformer.JsonTransformer.toJSON(options.credential) });
		jwtPayload.iat = require_timestamp.nowInSeconds();
		jwtPayload.additionalClaims.cnf = options.holder ? (await require_utils.extractKeyFromHolderBinding(agentContext, options.holder)).cnf : void 0;
		const publicJwk = await require_v2_jwt_utils.validateAndResolveVerificationMethod(agentContext, options.verificationMethod, ["assertionMethod"]);
		const jwt = await this.jwsService.createJwsCompact(agentContext, {
			payload: jwtPayload,
			keyId: publicJwk.keyId,
			protectedHeaderOptions: {
				typ: "vc+jwt",
				alg: options.alg,
				kid: options.verificationMethod
			}
		});
		return require_W3cV2JwtVerifiableCredential.W3cV2JwtVerifiableCredential.fromCompact(jwt);
	}
	/**
	* Verifies the signature(s) of a credential
	*
	* @param credential the credential to be verified
	* @returns the verification result
	*/
	async verifyCredential(agentContext, options) {
		const validationResults = {
			isValid: false,
			validations: {}
		};
		try {
			let credential;
			try {
				if (options.credential instanceof require_W3cV2JwtVerifiableCredential.W3cV2JwtVerifiableCredential) options.credential.validate();
				credential = options.credential instanceof require_W3cV2JwtVerifiableCredential.W3cV2JwtVerifiableCredential ? options.credential : require_W3cV2JwtVerifiableCredential.W3cV2JwtVerifiableCredential.fromCompact(options.credential);
				credential.jwt.payload.validate();
				validationResults.validations.dataModel = { isValid: true };
			} catch (error) {
				validationResults.validations.dataModel = {
					isValid: false,
					error
				};
				return validationResults;
			}
			const issuerVerificationMethod = await require_v2_jwt_utils.getVerificationMethodForJwt(agentContext, credential, ["assertionMethod"]);
			const issuerPublicKey = require_keyDidMapping.getPublicJwkFromVerificationMethod(issuerVerificationMethod);
			let signatureResult;
			try {
				signatureResult = await this.jwsService.verifyJws(agentContext, {
					jws: credential.jwt.serializedJwt,
					jwsSigner: {
						method: "did",
						jwk: issuerPublicKey,
						didUrl: issuerVerificationMethod.id
					}
				});
				if (!signatureResult.isValid) validationResults.validations.signature = {
					isValid: false,
					error: new require_CredoError.CredoError("Invalid JWS signature")
				};
				else validationResults.validations.signature = { isValid: true };
			} catch (error) {
				validationResults.validations.signature = {
					isValid: false,
					error
				};
			}
			if (credential.resolvedCredential.issuerId !== issuerVerificationMethod.controller) validationResults.validations.issuerIsSigner = {
				isValid: false,
				error: new require_CredoError.CredoError(`Credential is signed using verification method ${issuerVerificationMethod.id}, while the issuer of the credential is '${credential.resolvedCredential.issuerId}'`)
			};
			else validationResults.validations.issuerIsSigner = { isValid: true };
			if (!signatureResult?.jwsSigners.some((jwsSigner) => jwsSigner.jwk.fingerprint === issuerPublicKey.fingerprint)) validationResults.validations.issuerIsSigner = {
				isValid: false,
				error: new require_CredoError.CredoError("Credential is not signed by the issuer of the credential")
			};
			else validationResults.validations.issuerIsSigner = { isValid: true };
			validationResults.isValid = Object.values(validationResults.validations).every((v) => v.isValid);
			return validationResults;
		} catch (error) {
			validationResults.error = error;
			return validationResults;
		}
	}
	/**
	* Signs a presentation including the credentials it includes
	*
	* @param presentation the presentation to be signed
	* @returns the signed presentation
	*/
	async signPresentation(agentContext, options) {
		require_MessageValidator.MessageValidator.validateSync(options.presentation);
		const jwtPayload = new require_JwtPayload.JwtPayload({ additionalClaims: require_JsonTransformer.JsonTransformer.toJSON(options.presentation) });
		jwtPayload.additionalClaims.nonce = options.challenge;
		jwtPayload.aud = options.domain;
		const holder = await require_v2_jwt_utils.extractHolderFromPresentationCredentials(agentContext, options.presentation);
		const jwt = await this.jwsService.createJwsCompact(agentContext, {
			payload: jwtPayload,
			keyId: holder.publicJwk.keyId,
			protectedHeaderOptions: {
				typ: "vp+jwt",
				alg: holder.alg,
				kid: holder?.cnf?.kid
			}
		});
		return require_W3cV2JwtVerifiablePresentation.W3cV2JwtVerifiablePresentation.fromCompact(jwt);
	}
	/**
	* Verifies a presentation including the credentials it includes
	*
	* @param presentation the presentation to be verified
	* @returns the verification result
	*/
	async verifyPresentation(agentContext, options) {
		const validationResults = {
			isValid: false,
			validations: {}
		};
		try {
			let presentation;
			try {
				if (options.presentation instanceof require_W3cV2JwtVerifiablePresentation.W3cV2JwtVerifiablePresentation) options.presentation.validate();
				presentation = options.presentation instanceof require_W3cV2JwtVerifiablePresentation.W3cV2JwtVerifiablePresentation ? options.presentation : require_W3cV2JwtVerifiablePresentation.W3cV2JwtVerifiablePresentation.fromCompact(options.presentation);
				presentation.jwt.payload.validate();
				if (options.challenge !== presentation.jwt.payload.additionalClaims.nonce) throw new require_CredoError.CredoError(`JWT payload 'nonce' does not match challenge '${options.challenge}'`);
				const audArray = require_array.asArray(presentation.jwt.payload.aud);
				if (options.domain && !audArray.includes(options.domain)) throw new require_CredoError.CredoError(`JWT payload 'aud' does not include domain '${options.domain}'`);
				validationResults.validations.dataModel = { isValid: true };
			} catch (error) {
				validationResults.validations.dataModel = {
					isValid: false,
					error
				};
				return validationResults;
			}
			const proverVerificationMethod = await require_v2_jwt_utils.getVerificationMethodForJwt(agentContext, presentation, ["authentication"]);
			const proverPublicKey = require_keyDidMapping.getPublicJwkFromVerificationMethod(proverVerificationMethod);
			let signatureResult;
			try {
				signatureResult = await this.jwsService.verifyJws(agentContext, {
					jws: presentation.jwt.serializedJwt,
					allowedJwsSignerMethods: ["did"],
					jwsSigner: {
						method: "did",
						didUrl: proverVerificationMethod.id,
						jwk: proverPublicKey
					},
					trustedCertificates: []
				});
				if (!signatureResult.isValid) validationResults.validations.presentationSignature = {
					isValid: false,
					error: new require_CredoError.CredoError("Invalid JWS signature on presentation")
				};
				else validationResults.validations.presentationSignature = { isValid: true };
			} catch (error) {
				validationResults.validations.presentationSignature = {
					isValid: false,
					error
				};
			}
			if (presentation.resolvedPresentation.holderId && proverVerificationMethod.controller !== presentation.resolvedPresentation.holderId) validationResults.validations.holderIsSigner = {
				isValid: false,
				error: new require_CredoError.CredoError(`Presentation is signed using verification method ${proverVerificationMethod.id}, while the holder of the presentation is '${presentation.resolvedPresentation.holderId}'`)
			};
			else validationResults.validations.holderIsSigner = { isValid: true };
			const credentials = require_array.asArray(presentation.resolvedPresentation.verifiableCredential);
			validationResults.validations.credentials = await Promise.all(credentials.map(async (credential) => {
				if (!(credential.envelopedCredential instanceof require_W3cV2JwtVerifiableCredential.W3cV2JwtVerifiableCredential)) return {
					isValid: false,
					error: new require_CredoError.CredoError("Credential is not of format JWT. Presentations in JWT format can only contain credentials in JWT format."),
					validations: {}
				};
				const credentialResult = await this.verifyCredential(agentContext, { credential: credential.envelopedCredential });
				let credentialSubjectAuthentication;
				const credentialSubjectIds = credential.resolvedCredential.credentialSubjectIds;
				const presentationAuthenticatesCredentialSubject = credentialSubjectIds.some((subjectId) => proverVerificationMethod.controller === subjectId);
				if (credentialSubjectIds.length > 0 && !presentationAuthenticatesCredentialSubject) credentialSubjectAuthentication = {
					isValid: false,
					error: new require_CredoError.CredoError("Credential has one or more credentialSubject ids, but presentation does not authenticate credential subject")
				};
				else credentialSubjectAuthentication = { isValid: true };
				return {
					...credentialResult,
					isValid: credentialResult.isValid && credentialSubjectAuthentication.isValid,
					validations: {
						...credentialResult.validations,
						credentialSubjectAuthentication
					}
				};
			}));
			validationResults.isValid = Object.values(validationResults.validations).every((v) => Array.isArray(v) ? v.every((vv) => vv.isValid) : v.isValid);
			return validationResults;
		} catch (error) {
			validationResults.error = error;
			return validationResults;
		}
	}
};
W3cV2JwtCredentialService = require_decorate.__decorate([(0, tsyringe.injectable)(), require_decorateMetadata.__decorateMetadata("design:paramtypes", [typeof (_ref = typeof require_JwsService.JwsService !== "undefined" && require_JwsService.JwsService) === "function" ? _ref : Object])], W3cV2JwtCredentialService);

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