

const require_KeyManagementError = require('../../error/KeyManagementError.js');
const require_humanDescription = require('../humanDescription.js');

//#region src/modules/kms/jwk/alg/keyDerivation.ts
function isCrvJwk(jwk) {
	return jwk.kty === "EC" || jwk.kty === "OKP";
}
function supportedKeyDerivationAlgsForKey(jwk) {
	const algs = [];
	if (isCrvJwk(jwk) && [
		"P-256",
		"P-384",
		"P-521",
		"X25519",
		"secp256k1"
	].includes(jwk.crv)) algs.push("ECDH-ES", "ECDH-ES+A128KW", "ECDH-ES+A192KW", "ECDH-ES+A256KW");
	if (jwk.kty === "OKP" && (jwk.crv === "X25519" || jwk.crv === "Ed25519")) algs.push("ECDH-HSALSA20");
	return algs;
}
/**
* Get the allowed key derivation algs for a key. If takes all the known supported
* algs and will filter these based on the optional `alg` key in the JWK.
*
* This does not handle the intended key `use` and `key_ops`.
*/
function allowedKeyDerivationAlgsForKey(jwk) {
	const supportedAlgs = supportedKeyDerivationAlgsForKey(jwk);
	const allowedAlg = jwk.alg;
	return !allowedAlg ? supportedAlgs : allowedAlg && supportedAlgs.includes(allowedAlg) ? [allowedAlg] : [];
}
function assertAllowedKeyDerivationAlgForKey(jwk, algorithm) {
	const allowedAlgs = allowedKeyDerivationAlgsForKey(jwk);
	if (!allowedAlgs.includes(algorithm)) {
		const allowedAlgsText = allowedAlgs.length > 0 ? ` Allowed algs are ${allowedAlgs.map((alg) => `'${alg}'`).join(", ")}` : "";
		throw new require_KeyManagementError.KeyManagementError(`${require_humanDescription.getJwkHumanDescription(jwk)} cannot be used with algorithm '${algorithm}' for key derivation.${allowedAlgsText}`);
	}
}

//#endregion
exports.allowedKeyDerivationAlgsForKey = allowedKeyDerivationAlgsForKey;
exports.assertAllowedKeyDerivationAlgForKey = assertAllowedKeyDerivationAlgForKey;
exports.supportedKeyDerivationAlgsForKey = supportedKeyDerivationAlgsForKey;