UNPKG

@gaonengwww/jose

Version:

JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes

1,408 lines (1,377 loc) 43.1 kB
// src/lib/buffer_utils.ts var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; for (const buffer of buffers) { buf.set(buffer, i); i += buffer.length; } return buf; } function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); } function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } // src/lib/base64.ts function decodeBase64(encoded) { if (Uint8Array.fromBase64) { return Uint8Array.fromBase64(encoded); } const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; } // src/util/base64url.ts function decode(input) { if (Uint8Array.fromBase64) { return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" }); } let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch { throw new TypeError("The input to be decoded is not correctly encoded."); } } // src/util/errors.ts var JOSEError = class extends Error { /** * A unique error code for the particular error subclass. * * @ignore */ static code = "ERR_JOSE_GENERIC"; /** A unique error code for {@link JOSEError}. */ code = "ERR_JOSE_GENERIC"; /** @ignore */ constructor(message2, options) { super(message2, options); this.name = this.constructor.name; Error.captureStackTrace?.(this, this.constructor); } }; var JOSEAlgNotAllowed = class extends JOSEError { /** @ignore */ static code = "ERR_JOSE_ALG_NOT_ALLOWED"; /** A unique error code for {@link JOSEAlgNotAllowed}. */ code = "ERR_JOSE_ALG_NOT_ALLOWED"; }; var JOSENotSupported = class extends JOSEError { /** @ignore */ static code = "ERR_JOSE_NOT_SUPPORTED"; /** A unique error code for {@link JOSENotSupported}. */ code = "ERR_JOSE_NOT_SUPPORTED"; }; var JWEDecryptionFailed = class extends JOSEError { /** @ignore */ static code = "ERR_JWE_DECRYPTION_FAILED"; /** A unique error code for {@link JWEDecryptionFailed}. */ code = "ERR_JWE_DECRYPTION_FAILED"; /** @ignore */ constructor(message2 = "decryption operation failed", options) { super(message2, options); } }; var JWEInvalid = class extends JOSEError { /** @ignore */ static code = "ERR_JWE_INVALID"; /** A unique error code for {@link JWEInvalid}. */ code = "ERR_JWE_INVALID"; }; // src/lib/iv.ts function bitLength(alg) { switch (alg) { case "A128GCM": case "A128GCMKW": case "A192GCM": case "A192GCMKW": case "A256GCM": case "A256GCMKW": return 96; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": return 128; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } // src/lib/check_iv_length.ts var check_iv_length_default = (enc, iv) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid("Invalid Initialization Vector length"); } }; // src/lib/check_cek_length.ts var check_cek_length_default = (cek, expected) => { const actual = cek.byteLength << 3; if (actual !== expected) { throw new JWEInvalid( `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits` ); } }; // src/lib/crypto_key.ts function unusable(name, prop = "algorithm.name") { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function checkUsage(key, usage) { if (usage && !key.usages.includes(usage)) { throw new TypeError( `CryptoKey does not support this operation, its usages must include ${usage}.` ); } } function checkEncCryptoKey(key, alg, usage) { switch (alg) { case "A128GCM": case "A192GCM": case "A256GCM": { if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "A128KW": case "A192KW": case "A256KW": { if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "ECDH": { switch (key.algorithm.name) { case "ECDH": case "X25519": break; default: throw unusable("ECDH or X25519"); } break; } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usage); } // src/lib/invalid_key_input.ts function message(msg, actual, ...types) { types = types.filter(Boolean); if (types.length > 2) { const last = types.pop(); msg += `one of type ${types.join(", ")}, or ${last}.`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.`; } else { msg += `of type ${types[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === "function" && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === "object" && actual != null) { if (actual.constructor?.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } var invalid_key_input_default = (actual, ...types) => { return message("Key must be ", actual, ...types); }; function withAlg(alg, actual, ...types) { return message(`Key for the ${alg} algorithm must be `, actual, ...types); } // src/lib/is_key_like.ts function assertCryptoKey(key) { if (!isCryptoKey(key)) { throw new Error("CryptoKey instance expected"); } } function isCryptoKey(key) { return key?.[Symbol.toStringTag] === "CryptoKey"; } function isKeyObject(key) { return key?.[Symbol.toStringTag] === "KeyObject"; } var is_key_like_default = (key) => { return isCryptoKey(key) || isKeyObject(key); }; // src/lib/decrypt.ts async function timingSafeEqual(a, b) { if (!(a instanceof Uint8Array)) { throw new TypeError("First argument must be a buffer"); } if (!(b instanceof Uint8Array)) { throw new TypeError("Second argument must be a buffer"); } const algorithm = { name: "HMAC", hash: "SHA-256" }; const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]); const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a)); const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b)); let out = 0; let i = -1; while (++i < 32) { out |= aHmac[i] ^ bHmac[i]; } return out === 0; } async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, "Uint8Array")); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await crypto.subtle.importKey( "raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"] ); const macKey = await crypto.subtle.importKey( "raw", cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: "HMAC" }, false, ["sign"] ); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const expectedTag = new Uint8Array( (await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3) ); let macCheckPassed; try { macCheckPassed = await timingSafeEqual(tag2, expectedTag); } catch { } if (!macCheckPassed) { throw new JWEDecryptionFailed(); } let plaintext; try { plaintext = new Uint8Array( await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext) ); } catch { } if (!plaintext) { throw new JWEDecryptionFailed(); } return plaintext; } async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); } else { checkEncCryptoKey(cek, enc, "decrypt"); encKey = cek; } try { return new Uint8Array( await crypto.subtle.decrypt( { additionalData: aad, iv, name: "AES-GCM", tagLength: 128 }, encKey, concat(ciphertext, tag2) ) ); } catch { throw new JWEDecryptionFailed(); } } var decrypt_default = async (enc, cek, ciphertext, iv, tag2, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError( invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key") ); } if (!iv) { throw new JWEInvalid("JWE Initialization Vector missing"); } if (!tag2) { throw new JWEInvalid("JWE Authentication Tag missing"); } check_iv_length_default(enc, iv); switch (enc) { case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(-3), 10)); return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad); case "A128GCM": case "A192GCM": case "A256GCM": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad); default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); } }; // src/lib/is_disjoint.ts var is_disjoint_default = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; // src/lib/is_object.ts function isObjectLike(value) { return typeof value === "object" && value !== null; } var is_object_default = (input) => { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; }; // src/lib/aeskw.ts function checkKeySize(key, alg) { if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function getCryptoKey(key, alg, usage) { if (key instanceof Uint8Array) { return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); } checkEncCryptoKey(key, alg, usage); return key; } async function unwrap(alg, key, encryptedKey) { const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await crypto.subtle.unwrapKey( "raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"] ); return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); } // src/lib/digest.ts var digest_default = async (algorithm, data) => { const subtleDigest = `SHA-${algorithm.slice(-3)}`; return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); }; // src/lib/ecdhes.ts function lengthAndInput(input) { return concat(uint32be(input.length), input); } async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await digest_default("sha256", buf), iter * 32); } return res.slice(0, bits >> 3); } async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { checkEncCryptoKey(publicKey, "ECDH"); checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); const value = concat( lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength) ); let length; if (publicKey.algorithm.name === "X25519") { length = 256; } else { length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; } const sharedSecret = new Uint8Array( await crypto.subtle.deriveBits( { name: publicKey.algorithm.name, public: publicKey }, privateKey, length ) ); return concatKdf(sharedSecret, keyLength, value); } function allowed(key) { switch (key.algorithm.namedCurve) { case "P-256": case "P-384": case "P-521": return true; default: return key.algorithm.name === "X25519"; } } // src/lib/pbes2kw.ts function getCryptoKey2(key, alg) { if (key instanceof Uint8Array) { return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]); } checkEncCryptoKey(key, alg, "deriveBits"); return key; } var concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); async function deriveKey2(p2s, alg, p2c, key) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); } const salt = concatSalt(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10); const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: "PBKDF2", salt }; const cryptoKey = await getCryptoKey2(key, alg); return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); } async function unwrap2(alg, key, encryptedKey, p2c, p2s) { const derived = await deriveKey2(p2s, alg, p2c, key); return unwrap(alg.slice(-6), derived, encryptedKey); } // src/lib/check_key_length.ts var check_key_length_default = (alg, key) => { if (alg.startsWith("RS") || alg.startsWith("PS")) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; // src/lib/rsaes.ts var subtleAlgorithm = (alg) => { switch (alg) { case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": return "RSA-OAEP"; default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime` ); } }; async function decrypt(alg, key, encryptedKey) { checkEncCryptoKey(key, alg, "decrypt"); check_key_length_default(alg, key); return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)); } // src/lib/cek.ts function bitLength2(alg) { switch (alg) { case "A128GCM": return 128; case "A192GCM": return 192; case "A256GCM": case "A128CBC-HS256": return 256; case "A192CBC-HS384": return 384; case "A256CBC-HS512": return 512; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } var cek_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength2(alg) >> 3)); // src/lib/jwk_to_key.ts function subtleMapping(jwk) { let algorithm; let keyUsages; switch (jwk.kty) { case "RSA": { switch (jwk.alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` }; keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "EC": { switch (jwk.alg) { case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: "ECDH", namedCurve: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "OKP": { switch (jwk.alg) { case "Ed25519": // Fall through case "EdDSA": algorithm = { name: "Ed25519" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } return { algorithm, keyUsages }; } var jwk_to_key_default = async (jwk) => { if (!jwk.alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } const { algorithm, keyUsages } = subtleMapping(jwk); const keyData = { ...jwk }; delete keyData.alg; delete keyData.use; return crypto.subtle.importKey( "jwk", keyData, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages ); }; // src/key/import.ts async function importJWK(jwk, alg, options) { if (!is_object_default(jwk)) { throw new TypeError("JWK must be an object"); } let ext; alg ??= jwk.alg; ext ??= options?.extractable ?? jwk.ext; switch (jwk.kty) { case "oct": if (typeof jwk.k !== "string" || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } return decode(jwk.k); case "RSA": if ("oth" in jwk && jwk.oth !== void 0) { throw new JOSENotSupported( 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported' ); } case "EC": case "OKP": return jwk_to_key_default({ ...jwk, alg, ext }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } // src/lib/aesgcmkw.ts async function unwrap3(alg, key, encryptedKey, iv, tag2) { const jweAlgorithm = alg.slice(0, 7); return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0)); } // src/lib/decrypt_key_management.ts var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader, options) => { switch (alg) { case "dir": { if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); return key; } case "ECDH-ES": if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { if (!is_object_default(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); assertCryptoKey(key); if (!allowed(key)) throw new JOSENotSupported( "ECDH with the provided key is not allowed or not supported by your javascript runtime" ); const epk = await importJWK(joseHeader.epk, alg); assertCryptoKey(epk); let partyUInfo; let partyVInfo; if (joseHeader.apu !== void 0) { if (typeof joseHeader.apu !== "string") throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); try { partyUInfo = decode(joseHeader.apu); } catch { throw new JWEInvalid("Failed to base64url decode the apu"); } } if (joseHeader.apv !== void 0) { if (typeof joseHeader.apv !== "string") throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); try { partyVInfo = decode(joseHeader.apv); } catch { throw new JWEInvalid("Failed to base64url decode the apv"); } } const sharedSecret = await deriveKey( epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo ); if (alg === "ECDH-ES") return sharedSecret; if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg.slice(-6), sharedSecret, encryptedKey); } case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); assertCryptoKey(key); return decrypt(alg, key, encryptedKey); } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.p2c !== "number") throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = options?.maxPBES2Count || 1e4; if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== "string") throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); let p2s; try { p2s = decode(joseHeader.p2s); } catch { throw new JWEInvalid("Failed to base64url decode the p2s"); } return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s); } case "A128KW": case "A192KW": case "A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg, key, encryptedKey); } case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.iv !== "string") throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== "string") throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); let iv; try { iv = decode(joseHeader.iv); } catch { throw new JWEInvalid("Failed to base64url decode the iv"); } let tag2; try { tag2 = decode(joseHeader.tag); } catch { throw new JWEInvalid("Failed to base64url decode the tag"); } return unwrap3(alg, key, encryptedKey, iv, tag2); } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } }; // src/lib/validate_crit.ts var validate_crit_default = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => { if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === void 0) { return /* @__PURE__ */ new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { throw new Err( '"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present' ); } let recognized; if (recognizedOption !== void 0) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); }; // src/lib/validate_algorithms.ts var validate_algorithms_default = (option, algorithms) => { if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return void 0; } return new Set(algorithms); }; // src/lib/is_jwk.ts function isJWK(key) { return is_object_default(key) && typeof key.kty === "string"; } function isPrivateJWK(key) { return key.kty !== "oct" && typeof key.d === "string"; } function isPublicJWK(key) { return key.kty !== "oct" && typeof key.d === "undefined"; } function isSecretJWK(key) { return key.kty === "oct" && typeof key.k === "string"; } // src/lib/normalize_key.ts var cache; var handleJWK = async (key, jwk, alg, freeze = false) => { cache ||= /* @__PURE__ */ new WeakMap(); let cached = cache.get(key); if (cached?.[alg]) { return cached[alg]; } const cryptoKey = await jwk_to_key_default({ ...jwk, alg }); if (freeze) Object.freeze(key); if (!cached) { cache.set(key, { [alg]: cryptoKey }); } else { cached[alg] = cryptoKey; } return cryptoKey; }; var handleKeyObject = (keyObject, alg) => { cache ||= /* @__PURE__ */ new WeakMap(); let cached = cache.get(keyObject); if (cached?.[alg]) { return cached[alg]; } const isPublic = keyObject.type === "public"; const extractable = isPublic ? true : false; let cryptoKey; if (keyObject.asymmetricKeyType === "x25519") { switch (alg) { case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": break; default: throw new TypeError("given KeyObject instance cannot be used for this algorithm"); } cryptoKey = keyObject.toCryptoKey( keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"] ); } if (keyObject.asymmetricKeyType === "ed25519") { if (alg !== "EdDSA" && alg !== "Ed25519") { throw new TypeError("given KeyObject instance cannot be used for this algorithm"); } cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ isPublic ? "verify" : "sign" ]); } if (keyObject.asymmetricKeyType === "rsa") { let hash; switch (alg) { case "RSA-OAEP": hash = "SHA-1"; break; case "RS256": case "PS256": case "RSA-OAEP-256": hash = "SHA-256"; break; case "RS384": case "PS384": case "RSA-OAEP-384": hash = "SHA-384"; break; case "RS512": case "PS512": case "RSA-OAEP-512": hash = "SHA-512"; break; default: throw new TypeError("given KeyObject instance cannot be used for this algorithm"); } if (alg.startsWith("RSA-OAEP")) { return keyObject.toCryptoKey( { name: "RSA-OAEP", hash }, extractable, isPublic ? ["encrypt"] : ["decrypt"] ); } cryptoKey = keyObject.toCryptoKey( { name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash }, extractable, [isPublic ? "verify" : "sign"] ); } if (keyObject.asymmetricKeyType === "ec") { const nist = /* @__PURE__ */ new Map([ ["prime256v1", "P-256"], ["secp384r1", "P-384"], ["secp521r1", "P-521"] ]); const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); if (!namedCurve) { throw new TypeError("given KeyObject instance cannot be used for this algorithm"); } if (alg === "ES256" && namedCurve === "P-256") { cryptoKey = keyObject.toCryptoKey( { name: "ECDSA", namedCurve }, extractable, [isPublic ? "verify" : "sign"] ); } if (alg === "ES384" && namedCurve === "P-384") { cryptoKey = keyObject.toCryptoKey( { name: "ECDSA", namedCurve }, extractable, [isPublic ? "verify" : "sign"] ); } if (alg === "ES512" && namedCurve === "P-521") { cryptoKey = keyObject.toCryptoKey( { name: "ECDSA", namedCurve }, extractable, [isPublic ? "verify" : "sign"] ); } if (alg.startsWith("ECDH-ES")) { cryptoKey = keyObject.toCryptoKey( { name: "ECDH", namedCurve }, extractable, isPublic ? [] : ["deriveBits"] ); } } if (!cryptoKey) { throw new TypeError("given KeyObject instance cannot be used for this algorithm"); } if (!cached) { cache.set(keyObject, { [alg]: cryptoKey }); } else { cached[alg] = cryptoKey; } return cryptoKey; }; var normalize_key_default = async (key, alg) => { if (key instanceof Uint8Array) { return key; } if (isCryptoKey(key)) { return key; } if (isKeyObject(key)) { if (key.type === "secret") { return key.export(); } if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { try { return handleKeyObject(key, alg); } catch (err) { if (err instanceof TypeError) { throw err; } } } let jwk = key.export({ format: "jwk" }); return handleJWK(key, jwk, alg); } if (isJWK(key)) { if (key.k) { return decode(key.k); } return handleJWK(key, key, alg, true); } throw new Error("unreachable"); }; // src/lib/check_key_type.ts var tag = (key) => key?.[Symbol.toStringTag]; var jwkMatchesOp = (alg, key, usage) => { if (key.use !== void 0) { let expected; switch (usage) { case "sign": case "verify": expected = "sig"; break; case "encrypt": case "decrypt": expected = "enc"; break; } if (key.use !== expected) { throw new TypeError( `Invalid key for this operation, its "use" must be "${expected}" when present` ); } } if (key.alg !== void 0 && key.alg !== alg) { throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); } if (Array.isArray(key.key_ops)) { let expectedKeyOp; switch (true) { case (usage === "sign" || usage === "verify"): // Fall through case alg === "dir": // Fall through case alg.includes("CBC-HS"): expectedKeyOp = usage; break; case alg.startsWith("PBES2"): expectedKeyOp = "deriveBits"; break; case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): if (!alg.includes("GCM") && alg.endsWith("KW")) { expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; } else { expectedKeyOp = usage; } break; case (usage === "encrypt" && alg.startsWith("RSA")): expectedKeyOp = "wrapKey"; break; case usage === "decrypt": expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; break; } if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { throw new TypeError( `Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present` ); } } return true; }; var symmetricTypeCheck = (alg, key, usage) => { if (key instanceof Uint8Array) return; if (isJWK(key)) { if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError( `JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present` ); } if (!is_key_like_default(key)) { throw new TypeError( withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") ); } if (key.type !== "secret") { throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); } }; var asymmetricTypeCheck = (alg, key, usage) => { if (isJWK(key)) { switch (usage) { case "decrypt": case "sign": if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError(`JSON Web Key for this operation be a private JWK`); case "encrypt": case "verify": if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError(`JSON Web Key for this operation be a public JWK`); } } if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); } if (key.type === "secret") { throw new TypeError( `${tag(key)} instances for asymmetric algorithms must not be of type "secret"` ); } if (key.type === "public") { switch (usage) { case "sign": throw new TypeError( `${tag(key)} instances for asymmetric algorithm signing must be of type "private"` ); case "decrypt": throw new TypeError( `${tag(key)} instances for asymmetric algorithm decryption must be of type "private"` ); default: break; } } if (key.type === "private") { switch (usage) { case "verify": throw new TypeError( `${tag(key)} instances for asymmetric algorithm verifying must be of type "public"` ); case "encrypt": throw new TypeError( `${tag(key)} instances for asymmetric algorithm encryption must be of type "public"` ); default: break; } } }; var check_key_type_default = (alg, key, usage) => { const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key, usage); } else { asymmetricTypeCheck(alg, key, usage); } }; // src/jwe/flattened/decrypt.ts async function flattenedDecrypt(jwe, key, options) { if (!is_object_default(jwe)) { throw new JWEInvalid("Flattened JWE must be an object"); } if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { throw new JWEInvalid("JOSE Header missing"); } if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { throw new JWEInvalid("JWE Initialization Vector incorrect type"); } if (typeof jwe.ciphertext !== "string") { throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); } if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { throw new JWEInvalid("JWE Authentication Tag incorrect type"); } if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { throw new JWEInvalid("JWE Protected Header incorrect type"); } if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { throw new JWEInvalid("JWE Encrypted Key incorrect type"); } if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { throw new JWEInvalid("JWE AAD incorrect type"); } if (jwe.header !== void 0 && !is_object_default(jwe.header)) { throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); } if (jwe.unprotected !== void 0 && !is_object_default(jwe.unprotected)) { throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); } let parsedProt; if (jwe.protected) { try { const protectedHeader2 = decode(jwe.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader2)); } catch { throw new JWEInvalid("JWE Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid( "JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint" ); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected }; validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); if (joseHeader.zip !== void 0) { throw new JOSENotSupported( 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.' ); } const { alg, enc } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); } if (typeof enc !== "string" || !enc) { throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); } const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); } let encryptedKey; if (jwe.encrypted_key !== void 0) { try { encryptedKey = decode(jwe.encrypted_key); } catch { throw new JWEInvalid("Failed to base64url decode the encrypted_key"); } } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jwe); resolvedKey = true; } check_key_type_default(alg === "dir" ? enc : alg, key, "decrypt"); const k = await normalize_key_default(key, alg); let cek; try { cek = await decrypt_key_management_default(alg, k, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err; } cek = cek_default(enc); } let iv; let tag2; if (jwe.iv !== void 0) { try { iv = decode(jwe.iv); } catch { throw new JWEInvalid("Failed to base64url decode the iv"); } } if (jwe.tag !== void 0) { try { tag2 = decode(jwe.tag); } catch { throw new JWEInvalid("Failed to base64url decode the tag"); } } const protectedHeader = encoder.encode(jwe.protected ?? ""); let additionalData; if (jwe.aad !== void 0) { additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let ciphertext; try { ciphertext = decode(jwe.ciphertext); } catch { throw new JWEInvalid("Failed to base64url decode the ciphertext"); } const plaintext = await decrypt_default(enc, cek, ciphertext, iv, tag2, additionalData); const result = { plaintext }; if (jwe.protected !== void 0) { result.protectedHeader = parsedProt; } if (jwe.aad !== void 0) { try { result.additionalAuthenticatedData = decode(jwe.aad); } catch { throw new JWEInvalid("Failed to base64url decode the aad"); } } if (jwe.unprotected !== void 0) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== void 0) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key: k }; } return result; } // src/jwe/compact/decrypt.ts async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe); } if (typeof jwe !== "string") { throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split("."); if (length !== 5) { throw new JWEInvalid("Invalid Compact JWE"); } const decrypted = await flattenedDecrypt( { ciphertext, iv: iv || void 0, protected: protectedHeader, tag: tag2 || void 0, encrypted_key: encryptedKey || void 0 }, key, options ); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === "function") { return { ...result, key: decrypted.key }; } return result; } export { compactDecrypt };