diff --git a/dist/browser/index.bundle.js b/dist/browser/index.bundle.js deleted file mode 100644 index 5b03746c33..0000000000 --- a/dist/browser/index.bundle.js +++ /dev/null @@ -1,3559 +0,0 @@ -var __defProp = Object.defineProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; - -// dist/browser/runtime/webcrypto.js -var webcrypto_default = crypto; -var isCryptoKey = (key) => key instanceof CryptoKey; - -// dist/browser/runtime/digest.js -var digest = async (algorithm, data) => { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await webcrypto_default.subtle.digest(subtleDigest, data)); -}; -var digest_default = digest; - -// dist/browser/lib/buffer_utils.js -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 p2s(alg, p2sInput) { - return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); -} -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; -} -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); -} - -// dist/browser/runtime/base64url.js -var encodeBase64 = (input) => { - let unencoded = input; - if (typeof unencoded === "string") { - unencoded = encoder.encode(unencoded); - } - const CHUNK_SIZE = 32768; - const arr = []; - for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { - arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); - } - return btoa(arr.join("")); -}; -var encode = (input) => { - return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -}; -var decodeBase64 = (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; -}; -var decode = (input) => { - 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."); - } -}; - -// dist/browser/util/errors.js -var errors_exports = {}; -__export(errors_exports, { - JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, - JOSEError: () => JOSEError, - JOSENotSupported: () => JOSENotSupported, - JWEDecryptionFailed: () => JWEDecryptionFailed, - JWEInvalid: () => JWEInvalid, - JWKInvalid: () => JWKInvalid, - JWKSInvalid: () => JWKSInvalid, - JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, - JWKSNoMatchingKey: () => JWKSNoMatchingKey, - JWKSTimeout: () => JWKSTimeout, - JWSInvalid: () => JWSInvalid, - JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, - JWTClaimValidationFailed: () => JWTClaimValidationFailed, - JWTExpired: () => JWTExpired, - JWTInvalid: () => JWTInvalid -}); -var JOSEError = class extends Error { - static get code() { - return "ERR_JOSE_GENERIC"; - } - constructor(message2) { - super(message2); - this.code = "ERR_JOSE_GENERIC"; - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -}; -var JWTClaimValidationFailed = class extends JOSEError { - static get code() { - return "ERR_JWT_CLAIM_VALIDATION_FAILED"; - } - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2); - this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JWTExpired = class extends JOSEError { - static get code() { - return "ERR_JWT_EXPIRED"; - } - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2); - this.code = "ERR_JWT_EXPIRED"; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JOSEAlgNotAllowed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; - } - static get code() { - return "ERR_JOSE_ALG_NOT_ALLOWED"; - } -}; -var JOSENotSupported = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JOSE_NOT_SUPPORTED"; - } - static get code() { - return "ERR_JOSE_NOT_SUPPORTED"; - } -}; -var JWEDecryptionFailed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWE_DECRYPTION_FAILED"; - this.message = "decryption operation failed"; - } - static get code() { - return "ERR_JWE_DECRYPTION_FAILED"; - } -}; -var JWEInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWE_INVALID"; - } - static get code() { - return "ERR_JWE_INVALID"; - } -}; -var JWSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWS_INVALID"; - } - static get code() { - return "ERR_JWS_INVALID"; - } -}; -var JWTInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWT_INVALID"; - } - static get code() { - return "ERR_JWT_INVALID"; - } -}; -var JWKInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWK_INVALID"; - } - static get code() { - return "ERR_JWK_INVALID"; - } -}; -var JWKSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_INVALID"; - } - static get code() { - return "ERR_JWKS_INVALID"; - } -}; -var JWKSNoMatchingKey = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_NO_MATCHING_KEY"; - this.message = "no applicable key found in the JSON Web Key Set"; - } - static get code() { - return "ERR_JWKS_NO_MATCHING_KEY"; - } -}; -var JWKSMultipleMatchingKeys = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - this.message = "multiple matching keys found in the JSON Web Key Set"; - } - static get code() { - return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - } -}; -var JWKSTimeout = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_TIMEOUT"; - this.message = "request timed out"; - } - static get code() { - return "ERR_JWKS_TIMEOUT"; - } -}; -var JWSSignatureVerificationFailed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - this.message = "signature verification failed"; - } - static get code() { - return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - } -}; - -// dist/browser/runtime/random.js -var random_default = webcrypto_default.getRandomValues.bind(webcrypto_default); - -// dist/browser/lib/iv.js -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}`); - } -} -var iv_default = (alg) => random_default(new Uint8Array(bitLength(alg) >> 3)); - -// dist/browser/lib/check_iv_length.js -var checkIvLength = (enc, iv) => { - if (iv.length << 3 !== bitLength(enc)) { - throw new JWEInvalid("Invalid Initialization Vector length"); - } -}; -var check_iv_length_default = checkIvLength; - -// dist/browser/runtime/check_cek_length.js -var checkCekLength = (cek, expected) => { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } -}; -var check_cek_length_default = checkCekLength; - -// dist/browser/runtime/timing_safe_equal.js -var 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"); - } - if (a.length !== b.length) { - throw new TypeError("Input buffers must have the same length"); - } - const len = a.length; - let out = 0; - let i = -1; - while (++i < len) { - out |= a[i] ^ b[i]; - } - return out === 0; -}; -var timing_safe_equal_default = timingSafeEqual; - -// dist/browser/lib/crypto_key.js -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 getNamedCurve(alg) { - switch (alg) { - case "ES256": - return "P-256"; - case "ES384": - return "P-384"; - case "ES512": - return "P-521"; - default: - throw new Error("unreachable"); - } -} -function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = "CryptoKey does not support this operation, its usages must include "; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(", ")}, or ${last}.`; - } else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } -} -function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case "HS256": - case "HS384": - case "HS512": { - if (!isAlgorithm(key.algorithm, "HMAC")) - throw unusable("HMAC"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "RS256": - case "RS384": - case "RS512": { - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) - throw unusable("RSASSA-PKCS1-v1_5"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "PS256": - case "PS384": - case "PS512": { - if (!isAlgorithm(key.algorithm, "RSA-PSS")) - throw unusable("RSA-PSS"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "EdDSA": { - if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { - throw unusable("Ed25519 or Ed448"); - } - break; - } - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) - throw unusable("ECDSA"); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usages); -} -function checkEncCryptoKey(key, alg, ...usages) { - 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": - case "X448": - break; - default: - throw unusable("ECDH, X25519, or X448"); - } - 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, usages); -} - -// dist/browser/lib/invalid_key_input.js -function message(msg, actual, ...types2) { - types2 = types2.filter(Boolean); - if (types2.length > 2) { - const last = types2.pop(); - msg += `one of type ${types2.join(", ")}, or ${last}.`; - } else if (types2.length === 2) { - msg += `one of type ${types2[0]} or ${types2[1]}.`; - } else { - msg += `of type ${types2[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, ...types2) => { - return message("Key must be ", actual, ...types2); -}; -function withAlg(alg, actual, ...types2) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types2); -} - -// dist/browser/runtime/is_key_like.js -var is_key_like_default = (key) => { - if (isCryptoKey(key)) { - return true; - } - return key?.[Symbol.toStringTag] === "KeyObject"; -}; -var types = ["CryptoKey"]; - -// dist/browser/runtime/decrypt.js -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 webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]); - const macKey = await webcrypto_default.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 webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); - let macCheckPassed; - try { - macCheckPassed = timing_safe_equal_default(tag2, expectedTag); - } catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - plaintext = new Uint8Array(await webcrypto_default.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 webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); - } else { - checkEncCryptoKey(cek, enc, "decrypt"); - encKey = cek; - } - try { - return new Uint8Array(await webcrypto_default.subtle.decrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, concat(ciphertext, tag2))); - } catch { - throw new JWEDecryptionFailed(); - } -} -var decrypt = async (enc, cek, ciphertext, iv, tag2, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); - } - 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"); - } -}; -var decrypt_default = decrypt; - -// dist/browser/lib/is_disjoint.js -var isDisjoint = (...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; -}; -var is_disjoint_default = isDisjoint; - -// dist/browser/lib/is_object.js -function isObjectLike(value) { - return typeof value === "object" && value !== null; -} -function isObject(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; -} - -// dist/browser/runtime/bogus.js -var bogusWebCrypto = [ - { hash: "SHA-256", name: "HMAC" }, - true, - ["sign"] -]; -var bogus_default = bogusWebCrypto; - -// dist/browser/runtime/aeskw.js -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 (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - return webcrypto_default.subtle.importKey("raw", key, "AES-KW", true, [usage]); - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); -} -var wrap = async (alg, key, cek) => { - const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); -}; -var unwrap = async (alg, key, encryptedKey) => { - const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); -}; - -// dist/browser/runtime/ecdhes.js -async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - if (!isCryptoKey(publicKey)) { - throw new TypeError(invalid_key_input_default(publicKey, ...types)); - } - checkEncCryptoKey(publicKey, "ECDH"); - if (!isCryptoKey(privateKey)) { - throw new TypeError(invalid_key_input_default(privateKey, ...types)); - } - 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 if (publicKey.algorithm.name === "X448") { - length = 448; - } else { - length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; - } - const sharedSecret = new Uint8Array(await webcrypto_default.subtle.deriveBits({ - name: publicKey.algorithm.name, - public: publicKey - }, privateKey, length)); - return concatKdf(sharedSecret, keyLength, value); -} -async function generateEpk(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return webcrypto_default.subtle.generateKey(key.algorithm, true, ["deriveBits"]); -} -function ecdhAllowed(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return ["P-256", "P-384", "P-521"].includes(key.algorithm.namedCurve) || key.algorithm.name === "X25519" || key.algorithm.name === "X448"; -} - -// dist/browser/lib/check_p2s.js -function checkP2s(p2s2) { - if (!(p2s2 instanceof Uint8Array) || p2s2.length < 8) { - throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); - } -} - -// dist/browser/runtime/pbes2kw.js -function getCryptoKey2(key, alg) { - if (key instanceof Uint8Array) { - return webcrypto_default.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]); - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, "deriveBits", "deriveKey"); - return key; - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); -} -async function deriveKey2(p2s2, alg, p2c, key) { - checkP2s(p2s2); - const salt = p2s(alg, p2s2); - const keylen = parseInt(alg.slice(13, 16), 10); - const subtleAlg = { - hash: `SHA-${alg.slice(8, 11)}`, - iterations: p2c, - name: "PBKDF2", - salt - }; - const wrapAlg = { - length: keylen, - name: "AES-KW" - }; - const cryptoKey = await getCryptoKey2(key, alg); - if (cryptoKey.usages.includes("deriveBits")) { - return new Uint8Array(await webcrypto_default.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); - } - if (cryptoKey.usages.includes("deriveKey")) { - return webcrypto_default.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ["wrapKey", "unwrapKey"]); - } - throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); -} -var encrypt = async (alg, key, cek, p2c = 2048, p2s2 = random_default(new Uint8Array(16))) => { - const derived = await deriveKey2(p2s2, alg, p2c, key); - const encryptedKey = await wrap(alg.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: encode(p2s2) }; -}; -var decrypt2 = async (alg, key, encryptedKey, p2c, p2s2) => { - const derived = await deriveKey2(p2s2, alg, p2c, key); - return unwrap(alg.slice(-6), derived, encryptedKey); -}; - -// dist/browser/runtime/subtle_rsaes.js -function subtleRsaEs(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`); - } -} - -// dist/browser/runtime/check_key_length.js -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`); - } - } -}; - -// dist/browser/runtime/rsaes.js -var encrypt2 = async (alg, key, cek) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - checkEncCryptoKey(key, alg, "encrypt", "wrapKey"); - check_key_length_default(alg, key); - if (key.usages.includes("encrypt")) { - return new Uint8Array(await webcrypto_default.subtle.encrypt(subtleRsaEs(alg), key, cek)); - } - if (key.usages.includes("wrapKey")) { - const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, key, subtleRsaEs(alg))); - } - throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); -}; -var decrypt3 = async (alg, key, encryptedKey) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - checkEncCryptoKey(key, alg, "decrypt", "unwrapKey"); - check_key_length_default(alg, key); - if (key.usages.includes("decrypt")) { - return new Uint8Array(await webcrypto_default.subtle.decrypt(subtleRsaEs(alg), key, encryptedKey)); - } - if (key.usages.includes("unwrapKey")) { - const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, key, subtleRsaEs(alg), ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); - } - throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); -}; - -// dist/browser/lib/is_jwk.js -function isJWK(key) { - return isObject(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 isJWK(key) && key.kty === "oct" && typeof key.k === "string"; -} - -// dist/browser/runtime/jwk_to_key.js -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 "EdDSA": - algorithm = { name: jwk.crv }; - 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 parse = async (jwk) => { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm, keyUsages } = subtleMapping(jwk); - const rest = [ - algorithm, - jwk.ext ?? false, - jwk.key_ops ?? keyUsages - ]; - const keyData = { ...jwk }; - delete keyData.alg; - delete keyData.use; - return webcrypto_default.subtle.importKey("jwk", keyData, ...rest); -}; -var jwk_to_key_default = parse; - -// dist/browser/runtime/normalize_key.js -var exportKeyValue = (k) => decode(k); -var privCache; -var pubCache; -var isKeyObject = (key) => { - return key?.[Symbol.toStringTag] === "KeyObject"; -}; -var importAndCache = async (cache, key, jwk, alg, freeze = false) => { - 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 normalizePublicKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: "jwk" }); - delete jwk.d; - delete jwk.dp; - delete jwk.dq; - delete jwk.p; - delete jwk.q; - delete jwk.qi; - if (jwk.k) { - return exportKeyValue(jwk.k); - } - pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); - return importAndCache(pubCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); - const cryptoKey = importAndCache(pubCache, key, key, alg, true); - return cryptoKey; - } - return key; -}; -var normalizePrivateKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: "jwk" }); - if (jwk.k) { - return exportKeyValue(jwk.k); - } - privCache || (privCache = /* @__PURE__ */ new WeakMap()); - return importAndCache(privCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - privCache || (privCache = /* @__PURE__ */ new WeakMap()); - const cryptoKey = importAndCache(privCache, key, key, alg, true); - return cryptoKey; - } - return key; -}; -var normalize_key_default = { normalizePublicKey, normalizePrivateKey }; - -// dist/browser/lib/cek.js -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) => random_default(new Uint8Array(bitLength2(alg) >> 3)); - -// dist/browser/lib/format_pem.js -var format_pem_default = (b64, descriptor) => { - const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); - return `-----BEGIN ${descriptor}----- -${newlined} ------END ${descriptor}-----`; -}; - -// dist/browser/runtime/asn1.js -var genericExport = async (keyType, keyFormat, key) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - if (!key.extractable) { - throw new TypeError("CryptoKey is not extractable"); - } - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return format_pem_default(encodeBase64(new Uint8Array(await webcrypto_default.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); -}; -var toSPKI = (key) => { - return genericExport("public", "spki", key); -}; -var toPKCS8 = (key) => { - return genericExport("private", "pkcs8", key); -}; -var findOid = (keyData, oid, from = 0) => { - if (from === 0) { - oid.unshift(oid.length); - oid.unshift(6); - } - const i = keyData.indexOf(oid[0], from); - if (i === -1) - return false; - const sub = keyData.subarray(i, i + oid.length); - if (sub.length !== oid.length) - return false; - return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); -}; -var getNamedCurve2 = (keyData) => { - switch (true) { - case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]): - return "P-256"; - case findOid(keyData, [43, 129, 4, 0, 34]): - return "P-384"; - case findOid(keyData, [43, 129, 4, 0, 35]): - return "P-521"; - case findOid(keyData, [43, 101, 110]): - return "X25519"; - case findOid(keyData, [43, 101, 111]): - return "X448"; - case findOid(keyData, [43, 101, 112]): - return "Ed25519"; - case findOid(keyData, [43, 101, 113]): - return "Ed448"; - default: - throw new JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type"); - } -}; -var genericImport = async (replace, keyFormat, pem, alg, options) => { - let algorithm; - let keyUsages; - const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0))); - const isPublic = keyFormat === "spki"; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` - }; - keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; - break; - case "ES256": - algorithm = { name: "ECDSA", namedCurve: "P-256" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ES384": - algorithm = { name: "ECDSA", namedCurve: "P-384" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ES512": - algorithm = { name: "ECDSA", namedCurve: "P-521" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - const namedCurve = getNamedCurve2(keyData); - algorithm = namedCurve.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: namedCurve }; - keyUsages = isPublic ? [] : ["deriveBits"]; - break; - } - case "EdDSA": - algorithm = { name: getNamedCurve2(keyData) }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - default: - throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); - } - return webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages); -}; -var fromPKCS8 = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options); -}; -var fromSPKI = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options); -}; -function getElement(seq) { - const result = []; - let next = 0; - while (next < seq.length) { - const nextPart = parseElement(seq.subarray(next)); - result.push(nextPart); - next += nextPart.byteLength; - } - return result; -} -function parseElement(bytes) { - let position = 0; - let tag2 = bytes[0] & 31; - position++; - if (tag2 === 31) { - tag2 = 0; - while (bytes[position] >= 128) { - tag2 = tag2 * 128 + bytes[position] - 128; - position++; - } - tag2 = tag2 * 128 + bytes[position] - 128; - position++; - } - let length = 0; - if (bytes[position] < 128) { - length = bytes[position]; - position++; - } else if (length === 128) { - length = 0; - while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { - if (length > bytes.byteLength) { - throw new TypeError("invalid indefinite form length"); - } - length++; - } - const byteLength2 = position + length + 2; - return { - byteLength: byteLength2, - contents: bytes.subarray(position, position + length), - raw: bytes.subarray(0, byteLength2) - }; - } else { - const numberOfDigits = bytes[position] & 127; - position++; - length = 0; - for (let i = 0; i < numberOfDigits; i++) { - length = length * 256 + bytes[position]; - position++; - } - } - const byteLength = position + length; - return { - byteLength, - contents: bytes.subarray(position, byteLength), - raw: bytes.subarray(0, byteLength) - }; -} -function spkiFromX509(buf) { - const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); - return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw); -} -function getSPKI(x509) { - const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ""); - const raw = decodeBase64(pem); - return format_pem_default(spkiFromX509(raw), "PUBLIC KEY"); -} -var fromX509 = (pem, alg, options) => { - let spki; - try { - spki = getSPKI(pem); - } catch (cause) { - throw new TypeError("Failed to parse the X.509 certificate", { cause }); - } - return fromSPKI(spki, alg, options); -}; - -// dist/browser/key/import.js -async function importSPKI(spki, alg, options) { - if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return fromSPKI(spki, alg, options); -} -async function importX509(x509, alg, options) { - if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return fromX509(x509, alg, options); -} -async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return fromPKCS8(pkcs8, alg, options); -} -async function importJWK(jwk, alg) { - if (!isObject(jwk)) { - throw new TypeError("JWK must be an object"); - } - alg || (alg = jwk.alg); - 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 (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 }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} - -// dist/browser/lib/check_key_type.js -var tag = (key) => key?.[Symbol.toStringTag]; -var jwkMatchesOp = (alg, key, usage) => { - if (key.use !== void 0 && key.use !== "sig") { - throw new TypeError("Invalid key for this operation, when present its use must be sig"); - } - if (key.key_ops !== void 0 && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== void 0 && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; -}; -var symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && 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, ...types, "Uint8Array", allowJwk ? "JSON Web Key" : null)); - } - if (key.type !== "secret") { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -var asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && isJWK(key)) { - switch (usage) { - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - 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, ...types, allowJwk ? "JSON Web Key" : null)); - } - if (key.type === "secret") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === "sign" && key.type === "public") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === "decrypt" && key.type === "public") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === "verify" && key.type === "private") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === "encrypt" && key.type === "private") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } else { - asymmetricTypeCheck(alg, key, usage, allowJwk); - } -} -var check_key_type_default = checkKeyType.bind(void 0, false); -var checkKeyTypeWithJwk = checkKeyType.bind(void 0, true); - -// dist/browser/runtime/encrypt.js -async function cbcEncrypt(enc, plaintext, cek, iv, 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 webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]); - const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: "HMAC" - }, false, ["sign"]); - const ciphertext = new Uint8Array(await webcrypto_default.subtle.encrypt({ - iv, - name: "AES-CBC" - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag2 = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); - return { ciphertext, tag: tag2, iv }; -} -async function gcmEncrypt(enc, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); - } else { - checkEncCryptoKey(cek, enc, "encrypt"); - encKey = cek; - } - const encrypted = new Uint8Array(await webcrypto_default.subtle.encrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, plaintext)); - const tag2 = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag: tag2, iv }; -} -var encrypt3 = async (enc, plaintext, cek, iv, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); - } - if (iv) { - check_iv_length_default(enc, iv); - } else { - iv = iv_default(enc); - } - 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 cbcEncrypt(enc, plaintext, cek, iv, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) { - check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); - } - return gcmEncrypt(enc, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); - } -}; -var encrypt_default = encrypt3; - -// dist/browser/lib/aesgcmkw.js -async function wrap2(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: encode(wrapped.iv), - tag: encode(wrapped.tag) - }; -} -async function unwrap2(alg, key, encryptedKey, iv, tag2) { - const jweAlgorithm = alg.slice(0, 7); - return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0)); -} - -// dist/browser/lib/decrypt_key_management.js -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - check_key_type_default(alg, key, "decrypt"); - key = await normalize_key_default.normalizePrivateKey?.(key, alg) || key; - 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 (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ecdhAllowed(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); - 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 "RSA1_5": - 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"); - return decrypt3(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 p2s2; - try { - p2s2 = decode(joseHeader.p2s); - } catch { - throw new JWEInvalid("Failed to base64url decode the p2s"); - } - return decrypt2(alg, key, encryptedKey, joseHeader.p2c, p2s2); - } - 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 unwrap2(alg, key, encryptedKey, iv, tag2); - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } -} -var decrypt_key_management_default = decryptKeyManagement; - -// dist/browser/lib/validate_crit.js -function validateCrit(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); -} -var validate_crit_default = validateCrit; - -// dist/browser/lib/validate_algorithms.js -var validateAlgorithms = (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); -}; -var validate_algorithms_default = validateAlgorithms; - -// dist/browser/jwe/flattened/decrypt.js -async function flattenedDecrypt(jwe, key, options) { - if (!isObject(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 && !isObject(jwe.header)) { - throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); - } - if (jwe.unprotected !== void 0 && !isObject(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; - } - let cek; - try { - cek = await decrypt_key_management_default(alg, key, 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 }; - } - return result; -} - -// dist/browser/jwe/compact/decrypt.js -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; -} - -// dist/browser/jwe/general/decrypt.js -async function generalDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid("General JWE must be an object"); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { - throw new JWEInvalid("JWE Recipients missing or incorrect type"); - } - if (!jwe.recipients.length) { - throw new JWEInvalid("JWE Recipients has no members"); - } - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected - }, key, options); - } catch { - } - } - throw new JWEDecryptionFailed(); -} - -// dist/browser/lib/private_symbols.js -var unprotected = Symbol(); - -// dist/browser/runtime/key_to_jwk.js -var keyToJWK = async (key) => { - if (key instanceof Uint8Array) { - return { - kty: "oct", - k: encode(key) - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); - } - if (!key.extractable) { - throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); - } - const { ext, key_ops, alg, use, ...jwk } = await webcrypto_default.subtle.exportKey("jwk", key); - return jwk; -}; -var key_to_jwk_default = keyToJWK; - -// dist/browser/key/export.js -async function exportSPKI(key) { - return toSPKI(key); -} -async function exportPKCS8(key) { - return toPKCS8(key); -} -async function exportJWK(key) { - return key_to_jwk_default(key); -} - -// dist/browser/lib/encrypt_key_management.js -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - check_key_type_default(alg, key, "encrypt"); - key = await normalize_key_default.normalizePublicKey?.(key, alg) || key; - switch (alg) { - case "dir": { - cek = key; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - if (!ecdhAllowed(key)) { - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey || (ephemeralKey = (await generateEpk(key)).privateKey); - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === "EC") - parameters.epk.y = y; - if (apu) - parameters.apu = encode(apu); - if (apv) - parameters.apv = encode(apv); - if (alg === "ECDH-ES") { - cek = sharedSecret; - break; - } - cek = providedCek || cek_default(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await wrap(kwAlg, sharedSecret, cek); - break; - } - case "RSA1_5": - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - cek = providedCek || cek_default(enc); - encryptedKey = await encrypt2(alg, key, cek); - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - cek = providedCek || cek_default(enc); - const { p2c, p2s: p2s2 } = providedParameters; - ({ encryptedKey, ...parameters } = await encrypt(alg, key, cek, p2c, p2s2)); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - cek = providedCek || cek_default(enc); - encryptedKey = await wrap(alg, key, cek); - break; - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - cek = providedCek || cek_default(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - return { cek, encryptedKey, parameters }; -} -var encrypt_key_management_default = encryptKeyManagement; - -// dist/browser/jwe/flattened/encrypt.js -var FlattenedEncrypt = class { - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError("plaintext must be an instance of Uint8Array"); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError("setKeyManagementParameters can only be called once"); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError("setSharedUnprotectedHeader can only be called once"); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError("setContentEncryptionKey can only be called once"); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError("setInitializationVector can only be called once"); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); - } - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader - }; - validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this._protectedHeader, 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('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== "string" || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === "dir" || alg === "ECDH-ES")) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); - } else { - protectedHeader = encoder.encode(""); - } - if (this._aad) { - aadMember = encode(this._aad); - additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember)); - } else { - additionalData = protectedHeader; - } - const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: encode(ciphertext) - }; - if (iv) { - jwe.iv = encode(iv); - } - if (tag2) { - jwe.tag = encode(tag2); - } - if (encryptedKey) { - jwe.encrypted_key = encode(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; - } -}; - -// dist/browser/jwe/general/encrypt.js -var IndividualRecipient = class { - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } -}; -var GeneralEncrypt = class { - constructor(plaintext) { - this._recipients = []; - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setSharedUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new JWEInvalid("at least one recipient must be added"); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options }); - const jwe2 = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag - }; - if (flattened.aad) - jwe2.aad = flattened.aad; - if (flattened.protected) - jwe2.protected = flattened.protected; - if (flattened.unprotected) - jwe2.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe2.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe2.recipients[0].header = flattened.header; - return jwe2; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader - }; - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === "dir" || alg === "ECDH-ES") { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } else if (enc !== joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== void 0) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - } - const cek = cek_default(enc); - const jwe = { - ciphertext: "", - iv: "", - recipients: [], - tag: "" - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader - }; - const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0; - if (i === 0) { - const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, { - ...recipient.options, - [unprotected]: true - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const { encryptedKey, parameters } = await encrypt_key_management_default(recipient.unprotectedHeader?.alg || this._protectedHeader?.alg || this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = encode(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } -}; - -// dist/browser/runtime/subtle_dsa.js -function subtleDsa(alg, algorithm) { - const hash = `SHA-${alg.slice(-3)}`; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - return { hash, name: "HMAC" }; - case "PS256": - case "PS384": - case "PS512": - return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; - case "RS256": - case "RS384": - case "RS512": - return { hash, name: "RSASSA-PKCS1-v1_5" }; - case "ES256": - case "ES384": - case "ES512": - return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; - case "EdDSA": - return { name: algorithm.name }; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} - -// dist/browser/runtime/get_sign_verify_key.js -async function getCryptoKey3(alg, key, usage) { - if (usage === "sign") { - key = await normalize_key_default.normalizePrivateKey(key, alg); - } - if (usage === "verify") { - key = await normalize_key_default.normalizePublicKey(key, alg); - } - if (isCryptoKey(key)) { - checkSigCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - if (!alg.startsWith("HS")) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array", "JSON Web Key")); -} - -// dist/browser/runtime/verify.js -var verify = async (alg, key, signature, data) => { - const cryptoKey = await getCryptoKey3(alg, key, "verify"); - check_key_length_default(alg, cryptoKey); - const algorithm = subtleDsa(alg, cryptoKey.algorithm); - try { - return await webcrypto_default.subtle.verify(algorithm, cryptoKey, signature, data); - } catch { - return false; - } -}; -var verify_default = verify; - -// dist/browser/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid("Flattened JWS must be an object"); - } - if (jws.protected === void 0 && jws.header === void 0) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== void 0 && typeof jws.protected !== "string") { - throw new JWSInvalid("JWS Protected Header incorrect type"); - } - if (jws.payload === void 0) { - throw new JWSInvalid("JWS Payload missing"); - } - if (typeof jws.signature !== "string") { - throw new JWSInvalid("JWS Signature missing or incorrect type"); - } - if (jws.header !== void 0 && !isObject(jws.header)) { - throw new JWSInvalid("JWS Unprotected Header incorrect type"); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = decode(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - } - if (!is_disjoint_default(parsedProt, jws.header)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validate_algorithms_default("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== "string") { - throw new JWSInvalid("JWS Payload must be a string"); - } - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - checkKeyTypeWithJwk(alg, key, "verify"); - if (isJWK(key)) { - key = await importJWK(key, alg); - } - } else { - checkKeyTypeWithJwk(alg, key, "verify"); - } - const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = decode(jws.signature); - } catch { - throw new JWSInvalid("Failed to base64url decode the signature"); - } - const verified = await verify_default(alg, key, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = decode(jws.payload); - } catch { - throw new JWSInvalid("Failed to base64url decode the payload"); - } - } else if (typeof jws.payload === "string") { - payload = encoder.encode(jws.payload); - } else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jws.header !== void 0) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} - -// dist/browser/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== "string") { - throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) { - throw new JWSInvalid("Invalid Compact JWS"); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} - -// dist/browser/jws/general/verify.js -async function generalVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid("General JWS must be an object"); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { - throw new JWSInvalid("JWS Signatures missing or incorrect type"); - } - for (const signature of jws.signatures) { - try { - return await flattenedVerify({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature - }, key, options); - } catch { - } - } - throw new JWSSignatureVerificationFailed(); -} - -// dist/browser/lib/epoch.js -var epoch_default = (date) => Math.floor(date.getTime() / 1e3); - -// dist/browser/lib/secs.js -var minute = 60; -var hour = minute * 60; -var day = hour * 24; -var week = day * 7; -var year = day * 365.25; -var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -var secs_default = (str) => { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) { - throw new TypeError("Invalid time period format"); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") { - return -numericDate; - } - return numericDate; -}; - -// dist/browser/lib/jwt_claims_set.js -var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ""); -var checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch { - } - if (!isObject(payload)) { - throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - } - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) - presenceCheck.push("iat"); - if (audience !== void 0) - presenceCheck.push("aud"); - if (subject !== void 0) - presenceCheck.push("sub"); - if (issuer !== void 0) - presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); - } - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); - } - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs_default(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: - throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now = epoch_default(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); - } - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); - } - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); - } - } - return payload; -}; - -// dist/browser/jwt/verify.js -async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} - -// dist/browser/jwt/decrypt.js -async function jwtDecrypt(jwt, key, options) { - const decrypted = await compactDecrypt(jwt, key, options); - const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); - } - if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); - } - if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); - } - const result = { payload, protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} - -// dist/browser/jwe/compact/encrypt.js -var CompactEncrypt = class { - constructor(plaintext) { - this._flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); - } -}; - -// dist/browser/runtime/sign.js -var sign = async (alg, key, data) => { - const cryptoKey = await getCryptoKey3(alg, key, "sign"); - check_key_length_default(alg, cryptoKey); - const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -}; -var sign_default = sign; - -// dist/browser/jws/flattened/sign.js -var FlattenedSign = class { - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError("payload must be an instance of Uint8Array"); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); - } - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader - }; - const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyTypeWithJwk(alg, key, "sign"); - let payload = this._payload; - if (b64) { - payload = encoder.encode(encode(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); - } else { - protectedHeader = encoder.encode(""); - } - const data = concat(protectedHeader, encoder.encode("."), payload); - const signature = await sign_default(alg, key, data); - const jws = { - signature: encode(signature), - payload: "" - }; - if (b64) { - jws.payload = decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = decoder.decode(protectedHeader); - } - return jws; - } -}; - -// dist/browser/jws/compact/sign.js -var CompactSign = class { - constructor(payload) { - this._flattened = new FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === void 0) { - throw new TypeError("use the flattened module for creating JWS with b64: false"); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -}; - -// dist/browser/jws/general/sign.js -var IndividualSignature = class { - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } -}; -var GeneralSign = class { - constructor(payload) { - this._signatures = []; - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new JWSInvalid("at least one signature must be added"); - } - const jws = { - signatures: [], - payload: "" - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } else if (jws.payload !== payload) { - throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)"); - } - jws.signatures.push(rest); - } - return jws; - } -}; - -// dist/browser/jwt/produce.js -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -var ProduceJWT = class { - constructor(payload = {}) { - if (!isObject(payload)) { - throw new TypeError("JWT Claims Set MUST be an object"); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === "number") { - this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) }; - } else { - this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === "number") { - this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) }; - } else { - this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === "undefined") { - this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) }; - } else if (typeof input === "string") { - this._payload = { - ...this._payload, - iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input)) - }; - } else { - this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) }; - } - return this; - } -}; - -// dist/browser/jwt/sign.js -var SignJWT = class extends ProduceJWT { - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - return sig.sign(key, options); - } -}; - -// dist/browser/jwt/encrypt.js -var EncryptJWT = class extends ProduceJWT { - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError("setKeyManagementParameters can only be called once"); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError("setContentEncryptionKey can only be called once"); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError("setInitializationVector can only be called once"); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } -}; - -// dist/browser/jwk/thumbprint.js -var check = (value, description) => { - if (typeof value !== "string" || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } -}; -async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!isObject(jwk)) { - throw new TypeError("JWK must be an object"); - } - digestAlgorithm ?? (digestAlgorithm = "sha256"); - if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case "EC": - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case "OKP": - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case "RSA": - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case "oct": - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encoder.encode(JSON.stringify(components)); - return encode(await digest_default(digestAlgorithm, data)); -} -async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ?? (digestAlgorithm = "sha256"); - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; -} - -// dist/browser/jwk/embedded.js -async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header - }; - if (!isObject(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; -} - -// dist/browser/jwks/local.js -function getKtyFromAlg(alg) { - switch (typeof alg === "string" && alg.slice(0, 2)) { - case "RS": - case "PS": - return "RSA"; - case "ES": - return "EC"; - case "Ed": - return "OKP"; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject(key); -} -function clone(obj) { - if (typeof structuredClone === "function") { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); -} -var LocalJWKSet = class { - constructor(jwks) { - this._cached = /* @__PURE__ */ new WeakMap(); - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid("JSON Web Key Set malformed"); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk2) => { - let candidate = kty === jwk2.kty; - if (candidate && typeof kid === "string") { - candidate = kid === jwk2.kid; - } - if (candidate && typeof jwk2.alg === "string") { - candidate = alg === jwk2.alg; - } - if (candidate && typeof jwk2.use === "string") { - candidate = jwk2.use === "sig"; - } - if (candidate && Array.isArray(jwk2.key_ops)) { - candidate = jwk2.key_ops.includes("verify"); - } - if (candidate && alg === "EdDSA") { - candidate = jwk2.crv === "Ed25519" || jwk2.crv === "Ed448"; - } - if (candidate) { - switch (alg) { - case "ES256": - candidate = jwk2.crv === "P-256"; - break; - case "ES256K": - candidate = jwk2.crv === "secp256k1"; - break; - case "ES384": - candidate = jwk2.crv === "P-384"; - break; - case "ES512": - candidate = jwk2.crv === "P-521"; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk2 of candidates) { - try { - yield await importWithAlgCache(_cached, jwk2, alg); - } catch { - } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } -}; -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === void 0) { - const key = await importJWK({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - } - cached[alg] = key; - } - return cached[alg]; -} -function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false - } - }); - return localJWKSet; -} - -// dist/browser/runtime/fetch_jwks.js -var fetchJwks = async (url, timeout, options) => { - let controller; - let id; - let timedOut = false; - if (typeof AbortController === "function") { - controller = new AbortController(); - id = setTimeout(() => { - timedOut = true; - controller.abort(); - }, timeout); - } - const response = await fetch(url.href, { - signal: controller ? controller.signal : void 0, - redirect: "manual", - headers: options.headers - }).catch((err) => { - if (timedOut) - throw new JWKSTimeout(); - throw err; - }); - if (id !== void 0) - clearTimeout(id); - if (response.status !== 200) { - throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - } - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -}; -var fetch_jwks_default = fetchJwks; - -// dist/browser/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -var USER_AGENT; -if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { - const NAME = "jose"; - const VERSION = "v5.9.1"; - USER_AGENT = `${NAME}/${VERSION}`; -} -var jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) { - return false; - } - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) { - return false; - } - return true; -} -var RemoteJWKSet = class { - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError("url must be an instance of URL"); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this._cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this._cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - if (options?.[jwksCache] !== void 0) { - this._cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = createLocalJWKSet(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; - } - fresh() { - return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = void 0; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has("User-Agent")) { - headers.set("User-Agent", USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch || (this._pendingFetch = fetch_jwks_default(this._url, this._timeoutDuration, this._options).then((json) => { - this._local = createLocalJWKSet(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = void 0; - }).catch((err) => { - this._pendingFetch = void 0; - throw err; - })); - await this._pendingFetch; - } -}; -function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} -var experimental_jwksCache = jwksCache; - -// dist/browser/jwt/unsecured.js -var UnsecuredJWT = class extends ProduceJWT { - encode() { - const header = encode(JSON.stringify({ alg: "none" })); - const payload = encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== "string") { - throw new JWTInvalid("Unsecured JWT must be a string"); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split("."); - if (length !== 3 || signature !== "") { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - let header; - try { - header = JSON.parse(decoder.decode(decode(encodedHeader))); - if (header.alg !== "none") - throw new Error(); - } catch { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - const payload = jwt_claims_set_default(header, decode(encodedPayload), options); - return { payload, header }; - } -}; - -// dist/browser/util/base64url.js -var base64url_exports2 = {}; -__export(base64url_exports2, { - decode: () => decode2, - encode: () => encode2 -}); -var encode2 = encode; -var decode2 = decode; - -// dist/browser/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } else if (typeof token === "object" && token) { - if ("protected" in token) { - protectedB64u = token.protected; - } else { - throw new TypeError("Token does not contain a Protected Header"); - } - } - try { - if (typeof protectedB64u !== "string" || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(decode2(protectedB64u))); - if (!isObject(result)) { - throw new Error(); - } - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} - -// dist/browser/util/decode_jwt.js -function decodeJwt(jwt) { - if (typeof jwt !== "string") - throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt.split("."); - if (length === 5) - throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) - throw new JWTInvalid("Invalid JWT"); - if (!payload) - throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode2(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject(result)) - throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} - -// dist/browser/runtime/generate.js -async function generateSecret(alg, options) { - let length; - let algorithm; - let keyUsages; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - length = parseInt(alg.slice(-3), 10); - algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; - keyUsages = ["sign", "verify"]; - break; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - length = parseInt(alg.slice(-3), 10); - return random_default(new Uint8Array(length >> 3)); - case "A128KW": - case "A192KW": - case "A256KW": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-KW", length }; - keyUsages = ["wrapKey", "unwrapKey"]; - break; - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": - case "A128GCM": - case "A192GCM": - case "A256GCM": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-GCM", length }; - keyUsages = ["encrypt", "decrypt"]; - break; - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return webcrypto_default.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); -} -function getModulusLengthOption(options) { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); - } - return modulusLength; -} -async function generateKeyPair(alg, options) { - let algorithm; - let keyUsages; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { - name: "RSA-PSS", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["sign", "verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { - name: "RSASSA-PKCS1-v1_5", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["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(alg.slice(-3), 10) || 1}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; - break; - case "ES256": - algorithm = { name: "ECDSA", namedCurve: "P-256" }; - keyUsages = ["sign", "verify"]; - break; - case "ES384": - algorithm = { name: "ECDSA", namedCurve: "P-384" }; - keyUsages = ["sign", "verify"]; - break; - case "ES512": - algorithm = { name: "ECDSA", namedCurve: "P-521" }; - keyUsages = ["sign", "verify"]; - break; - case "EdDSA": { - keyUsages = ["sign", "verify"]; - const crv = options?.crv ?? "Ed25519"; - switch (crv) { - case "Ed25519": - case "Ed448": - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported("Invalid or unsupported crv option provided"); - } - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - keyUsages = ["deriveKey", "deriveBits"]; - const crv = options?.crv ?? "P-256"; - switch (crv) { - case "P-256": - case "P-384": - case "P-521": { - algorithm = { name: "ECDH", namedCurve: crv }; - break; - } - case "X25519": - case "X448": - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448"); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return webcrypto_default.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); -} - -// dist/browser/key/generate_key_pair.js -async function generateKeyPair2(alg, options) { - return generateKeyPair(alg, options); -} - -// dist/browser/key/generate_secret.js -async function generateSecret2(alg, options) { - return generateSecret(alg, options); -} - -// dist/browser/runtime/runtime.js -var runtime_default = "WebCryptoAPI"; - -// dist/browser/util/runtime.js -var runtime_default2 = runtime_default; -export { - CompactEncrypt, - CompactSign, - EmbeddedJWK, - EncryptJWT, - FlattenedEncrypt, - FlattenedSign, - GeneralEncrypt, - GeneralSign, - SignJWT, - UnsecuredJWT, - base64url_exports2 as base64url, - calculateJwkThumbprint, - calculateJwkThumbprintUri, - compactDecrypt, - compactVerify, - createLocalJWKSet, - createRemoteJWKSet, - runtime_default2 as cryptoRuntime, - decodeJwt, - decodeProtectedHeader, - errors_exports as errors, - experimental_jwksCache, - exportJWK, - exportPKCS8, - exportSPKI, - flattenedDecrypt, - flattenedVerify, - generalDecrypt, - generalVerify, - generateKeyPair2 as generateKeyPair, - generateSecret2 as generateSecret, - importJWK, - importPKCS8, - importSPKI, - importX509, - jwksCache, - jwtDecrypt, - jwtVerify -}; diff --git a/dist/browser/index.bundle.min.js b/dist/browser/index.bundle.min.js deleted file mode 100644 index 167ec8e947..0000000000 --- a/dist/browser/index.bundle.min.js +++ /dev/null @@ -1,4 +0,0 @@ -var fr=Object.defineProperty;var yt=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0})};var f=crypto,K=e=>e instanceof CryptoKey;var ur=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},We=ur;var w=new TextEncoder,x=new TextDecoder,ve=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function wt(e,t){return W(w.encode(e),new Uint8Array([0]),t)}function ze(e,t,r){if(t<0||t>=ve)throw new RangeError(`value must be >= 0 and <= ${ve-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function Je(e){let t=Math.floor(e/ve),r=e%ve,n=new Uint8Array(8);return ze(n,t,0),ze(n,r,4),n}function Te(e){let t=new Uint8Array(4);return ze(t,e),t}function Ie(e){return W(Te(e.length),e)}async function Et(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var Oe=e=>{let t=e;typeof t=="string"&&(t=w.encode(t));let r=32768,n=[];for(let o=0;oOe(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Xe=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=x.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Xe(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var St={};yt(St,{JOSEAlgNotAllowed:()=>$,JOSEError:()=>H,JOSENotSupported:()=>h,JWEDecryptionFailed:()=>M,JWEInvalid:()=>c,JWKInvalid:()=>ue,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>he,JWKSNoMatchingKey:()=>X,JWKSTimeout:()=>me,JWSInvalid:()=>l,JWSSignatureVerificationFailed:()=>Y,JWTClaimValidationFailed:()=>C,JWTExpired:()=>ne,JWTInvalid:()=>_});var H=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},C=class extends H{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r,n="unspecified",o="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=o,this.payload=r}},ne=class extends H{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r,n="unspecified",o="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=o,this.payload=r}},$=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},h=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},M=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},c=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},l=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},_=class extends H{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ue=class extends H{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},oe=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},X=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},he=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},me=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Y=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var k=f.getRandomValues.bind(f);function Ye(e){switch(e){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 h(`Unsupported JWE Algorithm: ${e}`)}}var bt=e=>k(new Uint8Array(Ye(e)>>3));var hr=(e,t)=>{if(t.length<<3!==Ye(e))throw new c("Invalid Initialization Vector length")},Re=hr;var mr=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ae=mr;var lr=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++oe.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function xt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!B(e.algorithm,"HMAC"))throw v("HMAC");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!B(e.algorithm,"RSASSA-PKCS1-v1_5"))throw v("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!B(e.algorithm,"RSA-PSS"))throw v("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw v("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!B(e.algorithm,"ECDSA"))throw v("ECDSA");let n=yr(t);if(e.algorithm.namedCurve!==n)throw v(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r)}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!B(e.algorithm,"AES-GCM"))throw v("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!B(e.algorithm,"AES-KW"))throw v("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw v("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!B(e.algorithm,"PBKDF2"))throw v("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!B(e.algorithm,"RSA-OAEP"))throw v("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r)}function _t(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>_t("Key must be ",e,...t);function qe(e,t,...r){return _t(`Key for the ${e} algorithm must be `,t,...r)}var Ze=e=>K(e)?!0:e?.[Symbol.toStringTag]==="KeyObject",b=["CryptoKey"];async function wr(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),d=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Je(a.length<<3)),u=new Uint8Array((await f.subtle.sign("HMAC",d,p)).slice(0,i>>3)),m;try{m=At(o,u)}catch{}if(!m)throw new M;let T;try{T=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}if(!T)throw new M;return T}async function Er(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await f.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(I(t,e,"decrypt"),i=t);try{return new Uint8Array(await f.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,W(r,o)))}catch{throw new M}}var gr=async(e,t,r,n,o,a)=>{if(!K(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...b,"Uint8Array"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(Re(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ae(t,parseInt(e.slice(-3),10)),wr(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ae(t,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o,a);default:throw new h("Unsupported JWE Content Encryption Algorithm")}},De=gr;var Sr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},O=Sr;function br(e){return typeof e=="object"&&e!==null}function y(e){if(!br(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Ar=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],ie=Ar;function Ht(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Ct(e,t,r){if(K(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...b,"Uint8Array"))}var le=async(e,t,r)=>{let n=await Ct(t,e,"wrapKey");Ht(n,e);let o=await f.subtle.importKey("raw",r,...ie);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},ye=async(e,t,r)=>{let n=await Ct(t,e,"unwrapKey");Ht(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...ie);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Me(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!K(e))throw new TypeError(A(e,...b));if(I(e,"ECDH"),!K(t))throw new TypeError(A(t,...b));I(t,"ECDH","deriveBits");let i=W(Ie(w.encode(r)),Ie(o),Ie(a),Te(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let d=new Uint8Array(await f.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return Et(d,n,i)}async function Pt(e){if(!K(e))throw new TypeError(A(e,...b));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Ne(e){if(!K(e))throw new TypeError(A(e,...b));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Qe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets")}function Kr(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(K(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...b,"Uint8Array"))}async function vt(e,t,r,n){Qe(e);let o=wt(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},d=await Kr(n,t);if(d.usages.includes("deriveBits"))return new Uint8Array(await f.subtle.deriveBits(i,d,a));if(d.usages.includes("deriveKey"))return f.subtle.deriveKey(i,d,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var Jt=async(e,t,r,n=2048,o=k(new Uint8Array(16)))=>{let a=await vt(o,e,n,t);return{encryptedKey:await le(e.slice(-6),a,r),p2c:n,p2s:E(o)}},Tt=async(e,t,r,n,o)=>{let a=await vt(o,e,n,t);return ye(e.slice(-6),a,r)};function se(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new h(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var It=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"encrypt","wrapKey"),q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(se(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...ie);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,se(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ot=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"decrypt","unwrapKey"),q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(se(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,se(e),...ie);return new Uint8Array(await f.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function N(e){return y(e)&&typeof e.kty=="string"}function Rt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ut(e){return e.kty!=="oct"&&typeof e.d>"u"}function Dt(e){return N(e)&&e.kty==="oct"&&typeof e.k=="string"}function _r(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new h('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var Hr=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=_r(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,f.subtle.importKey("jwk",o,...n)},Le=Hr;var Mt=e=>g(e),ce,de,Nt=e=>e?.[Symbol.toStringTag]==="KeyObject",$e=async(e,t,r,n,o=!1)=>{let a=e.get(t);if(a?.[n])return a[n];let i=await Le({...r,alg:n});return o&&Object.freeze(t),a?a[n]=i:e.set(t,{[n]:i}),i},Cr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mt(r.k):(de||(de=new WeakMap),$e(de,e,r,t))}return N(e)?e.k?g(e.k):(de||(de=new WeakMap),$e(de,e,e,t,!0)):e},Pr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return r.k?Mt(r.k):(ce||(ce=new WeakMap),$e(ce,e,r,t))}return N(e)?e.k?g(e.k):(ce||(ce=new WeakMap),$e(ce,e,e,t,!0)):e},Z={normalizePublicKey:Cr,normalizePrivateKey:Pr};function we(e){switch(e){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 h(`Unsupported JWE Algorithm: ${e}`)}}var R=e=>k(new Uint8Array(we(e)>>3));var je=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` -`);return`-----BEGIN ${t}----- -${r} ------END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),G=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||G(e,t,n+1)},Lt=e=>{switch(!0){case G(e,[42,134,72,206,61,3,1,7]):return"P-256";case G(e,[43,129,4,0,34]):return"P-384";case G(e,[43,129,4,0,35]):return"P-521";case G(e,[43,101,110]):return"X25519";case G(e,[43,101,111]):return"X448";case G(e,[43,101,112]):return"Ed25519";case G(e,[43,101,113]):return"Ed448";default:throw new h("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=async(e,t,r,n,o)=>{let a,i,s=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},i=d?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},i=d?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},i=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let p=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new h('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let a=t+n+2;return{byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else{let a=e[t]&127;t++,n=0;for(let i=0;i{let n;try{n=vr(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function L(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return g(e.k);case"RSA":if(e.oth!==void 0)throw new h('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Le({...e,alg:t});default:throw new h('Unsupported "kty" (Key Type) Parameter value')}}var pe=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&N(t)){if(Dt(t)&&tt(e,t,r))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(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${pe(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&N(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${pe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${pe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${pe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${pe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${pe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e)}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),u=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return{ciphertext:d,tag:u,iv:n}}async function Dr(e,t,r,n,o){let a;r instanceof Uint8Array?a=await f.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(I(r,e,"encrypt"),a=r);let i=new Uint8Array(await f.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ae(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ae(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new h("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return{encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await Z.normalizePrivateKey?.(t,e)||t,e){case"dir":{if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new h("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await L(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new c('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=g(n.apu)}catch{throw new c("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new c('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=g(n.apv)}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return d;if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(e.slice(-6),d,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new c("JWE Encrypted Key missing");return Ot(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new c('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=o?.maxPBES2Count||1e4;if(n.p2c>a)throw new c('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new c('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=g(n.p2s)}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new c('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new c('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=g(n.iv)}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag)}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new h('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new h(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var U=Lr;var $r=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},ge=$r;async function Se(e,t,r){if(!y(e))throw new c("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new c("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new c("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new c("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new c("JWE AAD incorrect type");if(e.header!==void 0&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let re=g(e.protected);n=JSON.parse(x.decode(re))}catch{throw new c("JWE Protected Header is invalid")}if(!O(n,e.header,e.unprotected))throw new c("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(U(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new h('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:a,enc:i}=o;if(typeof a!="string"||!a)throw new c("missing JWE Algorithm (alg) in JWE Header");if(typeof i!="string"||!i)throw new c("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(a)||!s&&a.startsWith("PBES2"))throw new $('"alg" (Algorithm) Header Parameter value not allowed');if(d&&!d.has(i))throw new $('"enc" (Encryption Algorithm) Header Parameter value not allowed');let p;if(e.encrypted_key!==void 0)try{p=g(e.encrypted_key)}catch{throw new c("Failed to base64url decode the encrypted_key")}let u=!1;typeof t=="function"&&(t=await t(n,e),u=!0);let m;try{m=await Qt(a,t,p,o,r)}catch(re){if(re instanceof TypeError||re instanceof c||re instanceof h)throw re;m=R(i)}let T,J;if(e.iv!==void 0)try{T=g(e.iv)}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag)}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext)}catch{throw new c("Failed to base64url decode the ciphertext")}let te={plaintext:await De(i,m,Pe,T,J,P)};if(e.protected!==void 0&&(te.protectedHeader=n),e.aad!==void 0)try{te.additionalAuthenticatedData=g(e.aad)}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(te.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(te.unprotectedHeader=e.header),u?{...te,key:t}:te}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.decode(e)),typeof e!="string")throw new c("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:d}=e.split(".");if(d!==5)throw new c("Invalid Compact JWE");let p=await Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),u={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...u,key:p.key}:u}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))throw new c("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new c("JWE Recipients has no members");for(let n of e.recipients)try{return await Se({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new M}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await f.subtle.exportKey("jwk",e);return a},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await Z.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new h("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:u}=o;u||(u=(await Pt(r)).privateKey);let{x:m,y:T,crv:J,kty:S}=await nt(u),P=await Me(r,u,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:m,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||R(t);let Pe=e.slice(-6);a=await le(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||R(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||R(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||R(t),a=await le(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||R(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new h('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var F=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new c("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!O(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new c("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(U(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new h('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new c('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new c('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters)),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P))}let d,p,u;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(u=E(this._aad),d=W(p,w.encode("."),w.encode(u))):d=p;let{ciphertext:m,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(m)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),u&&(S.aad=u),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},at=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new ot(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new c("at least one recipient must be added");if(this._recipients.length===1){let[o]=this._recipients,a=await new F(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),i={ciphertext:a.ciphertext,iv:a.iv,recipients:[{}],tag:a.tag};return a.aad&&(i.aad=a.aad),a.protected&&(i.protected=a.protected),a.unprotected&&(i.unprotected=a.unprotected),a.encrypted_key&&(i.recipients[0].encrypted_key=a.encrypted_key),a.header&&(i.recipients[0].header=a.header),i}let t;for(let o=0;o>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new h(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await Z.normalizePrivateKey(t,e)),r==="verify"&&(t=await Z.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return!1}},er=zr;async function Ke(e,t,r){if(!y(e))throw new l("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new l('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new l("JWS Protected Header incorrect type");if(e.payload===void 0)throw new l("JWS Payload missing");if(typeof e.signature!="string")throw new l("JWS Signature missing or incorrect type");if(e.header!==void 0&&!y(e.header))throw new l("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P))}catch{throw new l("JWS Protected Header is invalid")}if(!O(n,e.header))throw new l("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=U(l,new Map([["b64",!0]]),r?.crit,n,o),i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new l('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new l('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&ge("algorithms",r.algorithms);if(d&&!d.has(s))throw new $('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new l("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new l("JWS Payload must be a string or an Uint8Array instance");let p=!1;typeof t=="function"?(t=await t(n,e),p=!0,Ee(s,t,"verify"),N(t)&&(t=await L(t,s))):Ee(s,t,"verify");let u=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),m;try{m=g(e.signature)}catch{throw new l("Failed to base64url decode the signature")}if(!await er(s,t,m,u))throw new Y;let J;if(i)try{J=g(e.payload)}catch{throw new l("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.decode(e)),typeof e!="string")throw new l("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new l("Invalid Compact JWS");let s=await Ke({payload:o,protected:n,signature:a},t,r),d={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...d,key:s.key}:d}async function Xr(e,t,r){if(!y(e))throw new l("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new l("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Y}var D=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Q=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,fe=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t))}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,u=[...a];p!==void 0&&u.push("iat"),d!==void 0&&u.push("aud"),s!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(let S of new Set(u.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let m;switch(typeof r.clockTolerance){case"string":m=Q(r.clockTolerance);break;case"number":m=r.clockTolerance;break;case"undefined":m=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=D(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+m)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-m)throw new ne('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:Q(p);if(S-m>P)throw new ne('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-m)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:fe(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=fe(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new F(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var jr=async(e,t,r)=>{let n=await Ae(e,t,"sign");q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var j=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new l("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!O(this._protectedHeader,this._unprotectedHeader))throw new l("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=U(l,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new l('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new l('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),u=await rr(i,t,p),m={signature:E(u),payload:""};return a&&(m.payload=x.decode(s)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=x.decode(d)),m}};var _e=class{constructor(t){this._flattened=new j(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var st=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ct=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new st(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new l("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r"u"?this._payload={...this._payload,iat:D(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ee("setIssuedAt",D(t))}:typeof t=="string"?this._payload={...this._payload,iat:ee("setIssuedAt",D(new Date)+Q(t))}:this._payload={...this._payload,iat:ee("setIssuedAt",t)},this}};var dt=class extends V{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends V{setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var z=(e,t)=>{if(typeof e!="string"||!e)throw new ue(`${t} missing or invalid`)};async function nr(e,t){if(!y(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":z(e.crv,'"crv" (Curve) Parameter'),z(e.x,'"x" (X Coordinate) Parameter'),z(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":z(e.crv,'"crv" (Subtype of Key Pair) Parameter'),z(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":z(e.e,'"e" (Exponent) Parameter'),z(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":z(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new h('"kty" (Key Type) Parameter missing or unsupported')}let n=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new l('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await L({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new l('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function rn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new h('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new oe("JSON Web Key Set malformed");this._jwks=ar(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let u=a===p.kty;if(u&&typeof o=="string"&&(u=o===p.kid),u&&typeof p.alg=="string"&&(u=n===p.alg),u&&typeof p.use=="string"&&(u=p.use==="sig"),u&&Array.isArray(p.key_ops)&&(u=p.key_ops.includes("verify")),u&&n==="EdDSA"&&(u=p.crv==="Ed25519"||p.crv==="Ed448"),u)switch(n){case"ES256":u=p.crv==="P-256";break;case"ES256K":u=p.crv==="secp256k1";break;case"ES384":u=p.crv==="P-384";break;case"ES512":u=p.crv==="P-521";break}return u}),{0:s,length:d}=i;if(d===0)throw new X;if(d!==1){let p=new he,{_cached:u}=this;throw p[Symbol.asyncIterator]=async function*(){for(let m of i)try{yield await or(u,m,n)}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await L({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new oe("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort()},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new me:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new H("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new H("Failed to parse the JSON Web Key Set HTTP response as JSON")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.1");var He=Symbol();function cn(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var mt=class extends V{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return{payload:fe(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t)}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n))}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),k(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function lt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new h("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];let o=t?.crv??"Ed25519";switch(o){case"Ed25519":case"Ed448":r={name:o};break;default:throw new h("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new h("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function mn(e,t){return dr(e,t)}async function ln(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr;export{xe as CompactEncrypt,_e as CompactSign,tn as EmbeddedJWK,pt as EncryptJWT,F as FlattenedEncrypt,j as FlattenedSign,at as GeneralEncrypt,ct as GeneralSign,dt as SignJWT,mt as UnsecuredJWT,sr as base64url,nr as calculateJwkThumbprint,en as calculateJwkThumbprintUri,rt as compactDecrypt,it as compactVerify,Ve as createLocalJWKSet,dn as createRemoteJWKSet,yn as cryptoRuntime,hn as decodeJwt,un as decodeProtectedHeader,St as errors,pn as experimental_jwksCache,nt as exportJWK,Fr as exportPKCS8,Gr as exportSPKI,Se as flattenedDecrypt,Ke as flattenedVerify,kr as generalDecrypt,Xr as generalVerify,mn as generateKeyPair,ln as generateSecret,L as importJWK,Ir as importPKCS8,Jr as importSPKI,Tr as importX509,He as jwksCache,Qr as jwtDecrypt,Zr as jwtVerify}; diff --git a/dist/browser/index.js b/dist/browser/index.js deleted file mode 100644 index 386fbf5fef..0000000000 --- a/dist/browser/index.js +++ /dev/null @@ -1,30 +0,0 @@ -export { compactDecrypt } from './jwe/compact/decrypt.js'; -export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; -export { generalDecrypt } from './jwe/general/decrypt.js'; -export { GeneralEncrypt } from './jwe/general/encrypt.js'; -export { compactVerify } from './jws/compact/verify.js'; -export { flattenedVerify } from './jws/flattened/verify.js'; -export { generalVerify } from './jws/general/verify.js'; -export { jwtVerify } from './jwt/verify.js'; -export { jwtDecrypt } from './jwt/decrypt.js'; -export { CompactEncrypt } from './jwe/compact/encrypt.js'; -export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; -export { CompactSign } from './jws/compact/sign.js'; -export { FlattenedSign } from './jws/flattened/sign.js'; -export { GeneralSign } from './jws/general/sign.js'; -export { SignJWT } from './jwt/sign.js'; -export { EncryptJWT } from './jwt/encrypt.js'; -export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; -export { EmbeddedJWK } from './jwk/embedded.js'; -export { createLocalJWKSet } from './jwks/local.js'; -export { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote.js'; -export { UnsecuredJWT } from './jwt/unsecured.js'; -export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; -export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; -export { decodeProtectedHeader } from './util/decode_protected_header.js'; -export { decodeJwt } from './util/decode_jwt.js'; -export * as errors from './util/errors.js'; -export { generateKeyPair } from './key/generate_key_pair.js'; -export { generateSecret } from './key/generate_secret.js'; -export * as base64url from './util/base64url.js'; -export { default as cryptoRuntime } from './util/runtime.js'; diff --git a/dist/browser/index.umd.js b/dist/browser/index.umd.js deleted file mode 100644 index a48f3e2888..0000000000 --- a/dist/browser/index.umd.js +++ /dev/null @@ -1,3565 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jose = {})); -})(this, (function (exports) { 'use strict'; - - var __defProp = Object.defineProperty; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - - // dist/browser/runtime/webcrypto.js - var webcrypto_default = crypto; - var isCryptoKey = (key) => key instanceof CryptoKey; - - // dist/browser/runtime/digest.js - var digest = async (algorithm, data) => { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await webcrypto_default.subtle.digest(subtleDigest, data)); - }; - var digest_default = digest; - - // dist/browser/lib/buffer_utils.js - 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 p2s(alg, p2sInput) { - return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); - } - 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; - } - 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); - } - - // dist/browser/runtime/base64url.js - var encodeBase64 = (input) => { - let unencoded = input; - if (typeof unencoded === "string") { - unencoded = encoder.encode(unencoded); - } - const CHUNK_SIZE = 32768; - const arr = []; - for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { - arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); - } - return btoa(arr.join("")); - }; - var encode = (input) => { - return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); - }; - var decodeBase64 = (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; - }; - var decode = (input) => { - 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."); - } - }; - - // dist/browser/util/errors.js - var errors_exports = {}; - __export(errors_exports, { - JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, - JOSEError: () => JOSEError, - JOSENotSupported: () => JOSENotSupported, - JWEDecryptionFailed: () => JWEDecryptionFailed, - JWEInvalid: () => JWEInvalid, - JWKInvalid: () => JWKInvalid, - JWKSInvalid: () => JWKSInvalid, - JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, - JWKSNoMatchingKey: () => JWKSNoMatchingKey, - JWKSTimeout: () => JWKSTimeout, - JWSInvalid: () => JWSInvalid, - JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, - JWTClaimValidationFailed: () => JWTClaimValidationFailed, - JWTExpired: () => JWTExpired, - JWTInvalid: () => JWTInvalid - }); - var JOSEError = class extends Error { - static get code() { - return "ERR_JOSE_GENERIC"; - } - constructor(message2) { - super(message2); - this.code = "ERR_JOSE_GENERIC"; - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } - }; - var JWTClaimValidationFailed = class extends JOSEError { - static get code() { - return "ERR_JWT_CLAIM_VALIDATION_FAILED"; - } - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2); - this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } - }; - var JWTExpired = class extends JOSEError { - static get code() { - return "ERR_JWT_EXPIRED"; - } - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2); - this.code = "ERR_JWT_EXPIRED"; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } - }; - var JOSEAlgNotAllowed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; - } - static get code() { - return "ERR_JOSE_ALG_NOT_ALLOWED"; - } - }; - var JOSENotSupported = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JOSE_NOT_SUPPORTED"; - } - static get code() { - return "ERR_JOSE_NOT_SUPPORTED"; - } - }; - var JWEDecryptionFailed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWE_DECRYPTION_FAILED"; - this.message = "decryption operation failed"; - } - static get code() { - return "ERR_JWE_DECRYPTION_FAILED"; - } - }; - var JWEInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWE_INVALID"; - } - static get code() { - return "ERR_JWE_INVALID"; - } - }; - var JWSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWS_INVALID"; - } - static get code() { - return "ERR_JWS_INVALID"; - } - }; - var JWTInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWT_INVALID"; - } - static get code() { - return "ERR_JWT_INVALID"; - } - }; - var JWKInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWK_INVALID"; - } - static get code() { - return "ERR_JWK_INVALID"; - } - }; - var JWKSInvalid = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_INVALID"; - } - static get code() { - return "ERR_JWKS_INVALID"; - } - }; - var JWKSNoMatchingKey = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_NO_MATCHING_KEY"; - this.message = "no applicable key found in the JSON Web Key Set"; - } - static get code() { - return "ERR_JWKS_NO_MATCHING_KEY"; - } - }; - var JWKSMultipleMatchingKeys = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - this.message = "multiple matching keys found in the JSON Web Key Set"; - } - static get code() { - return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - } - }; - var JWKSTimeout = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWKS_TIMEOUT"; - this.message = "request timed out"; - } - static get code() { - return "ERR_JWKS_TIMEOUT"; - } - }; - var JWSSignatureVerificationFailed = class extends JOSEError { - constructor() { - super(...arguments); - this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - this.message = "signature verification failed"; - } - static get code() { - return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - } - }; - - // dist/browser/runtime/random.js - var random_default = webcrypto_default.getRandomValues.bind(webcrypto_default); - - // dist/browser/lib/iv.js - 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}`); - } - } - var iv_default = (alg) => random_default(new Uint8Array(bitLength(alg) >> 3)); - - // dist/browser/lib/check_iv_length.js - var checkIvLength = (enc, iv) => { - if (iv.length << 3 !== bitLength(enc)) { - throw new JWEInvalid("Invalid Initialization Vector length"); - } - }; - var check_iv_length_default = checkIvLength; - - // dist/browser/runtime/check_cek_length.js - var checkCekLength = (cek, expected) => { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } - }; - var check_cek_length_default = checkCekLength; - - // dist/browser/runtime/timing_safe_equal.js - var 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"); - } - if (a.length !== b.length) { - throw new TypeError("Input buffers must have the same length"); - } - const len = a.length; - let out = 0; - let i = -1; - while (++i < len) { - out |= a[i] ^ b[i]; - } - return out === 0; - }; - var timing_safe_equal_default = timingSafeEqual; - - // dist/browser/lib/crypto_key.js - 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 getNamedCurve(alg) { - switch (alg) { - case "ES256": - return "P-256"; - case "ES384": - return "P-384"; - case "ES512": - return "P-521"; - default: - throw new Error("unreachable"); - } - } - function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = "CryptoKey does not support this operation, its usages must include "; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(", ")}, or ${last}.`; - } else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } - } - function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case "HS256": - case "HS384": - case "HS512": { - if (!isAlgorithm(key.algorithm, "HMAC")) - throw unusable("HMAC"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "RS256": - case "RS384": - case "RS512": { - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) - throw unusable("RSASSA-PKCS1-v1_5"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "PS256": - case "PS384": - case "PS512": { - if (!isAlgorithm(key.algorithm, "RSA-PSS")) - throw unusable("RSA-PSS"); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); - break; - } - case "EdDSA": { - if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { - throw unusable("Ed25519 or Ed448"); - } - break; - } - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) - throw unusable("ECDSA"); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usages); - } - function checkEncCryptoKey(key, alg, ...usages) { - 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": - case "X448": - break; - default: - throw unusable("ECDH, X25519, or X448"); - } - 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, usages); - } - - // dist/browser/lib/invalid_key_input.js - function message(msg, actual, ...types2) { - types2 = types2.filter(Boolean); - if (types2.length > 2) { - const last = types2.pop(); - msg += `one of type ${types2.join(", ")}, or ${last}.`; - } else if (types2.length === 2) { - msg += `one of type ${types2[0]} or ${types2[1]}.`; - } else { - msg += `of type ${types2[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, ...types2) => { - return message("Key must be ", actual, ...types2); - }; - function withAlg(alg, actual, ...types2) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types2); - } - - // dist/browser/runtime/is_key_like.js - var is_key_like_default = (key) => { - if (isCryptoKey(key)) { - return true; - } - return key?.[Symbol.toStringTag] === "KeyObject"; - }; - var types = ["CryptoKey"]; - - // dist/browser/runtime/decrypt.js - 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 webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]); - const macKey = await webcrypto_default.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 webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); - let macCheckPassed; - try { - macCheckPassed = timing_safe_equal_default(tag2, expectedTag); - } catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - plaintext = new Uint8Array(await webcrypto_default.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 webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); - } else { - checkEncCryptoKey(cek, enc, "decrypt"); - encKey = cek; - } - try { - return new Uint8Array(await webcrypto_default.subtle.decrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, concat(ciphertext, tag2))); - } catch { - throw new JWEDecryptionFailed(); - } - } - var decrypt = async (enc, cek, ciphertext, iv, tag2, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); - } - 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"); - } - }; - var decrypt_default = decrypt; - - // dist/browser/lib/is_disjoint.js - var isDisjoint = (...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; - }; - var is_disjoint_default = isDisjoint; - - // dist/browser/lib/is_object.js - function isObjectLike(value) { - return typeof value === "object" && value !== null; - } - function isObject(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; - } - - // dist/browser/runtime/bogus.js - var bogusWebCrypto = [ - { hash: "SHA-256", name: "HMAC" }, - true, - ["sign"] - ]; - var bogus_default = bogusWebCrypto; - - // dist/browser/runtime/aeskw.js - 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 (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - return webcrypto_default.subtle.importKey("raw", key, "AES-KW", true, [usage]); - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); - } - var wrap = async (alg, key, cek) => { - const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); - }; - var unwrap = async (alg, key, encryptedKey) => { - const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); - }; - - // dist/browser/runtime/ecdhes.js - async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - if (!isCryptoKey(publicKey)) { - throw new TypeError(invalid_key_input_default(publicKey, ...types)); - } - checkEncCryptoKey(publicKey, "ECDH"); - if (!isCryptoKey(privateKey)) { - throw new TypeError(invalid_key_input_default(privateKey, ...types)); - } - 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 if (publicKey.algorithm.name === "X448") { - length = 448; - } else { - length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; - } - const sharedSecret = new Uint8Array(await webcrypto_default.subtle.deriveBits({ - name: publicKey.algorithm.name, - public: publicKey - }, privateKey, length)); - return concatKdf(sharedSecret, keyLength, value); - } - async function generateEpk(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return webcrypto_default.subtle.generateKey(key.algorithm, true, ["deriveBits"]); - } - function ecdhAllowed(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return ["P-256", "P-384", "P-521"].includes(key.algorithm.namedCurve) || key.algorithm.name === "X25519" || key.algorithm.name === "X448"; - } - - // dist/browser/lib/check_p2s.js - function checkP2s(p2s2) { - if (!(p2s2 instanceof Uint8Array) || p2s2.length < 8) { - throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); - } - } - - // dist/browser/runtime/pbes2kw.js - function getCryptoKey2(key, alg) { - if (key instanceof Uint8Array) { - return webcrypto_default.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]); - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, "deriveBits", "deriveKey"); - return key; - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); - } - async function deriveKey2(p2s2, alg, p2c, key) { - checkP2s(p2s2); - const salt = p2s(alg, p2s2); - const keylen = parseInt(alg.slice(13, 16), 10); - const subtleAlg = { - hash: `SHA-${alg.slice(8, 11)}`, - iterations: p2c, - name: "PBKDF2", - salt - }; - const wrapAlg = { - length: keylen, - name: "AES-KW" - }; - const cryptoKey = await getCryptoKey2(key, alg); - if (cryptoKey.usages.includes("deriveBits")) { - return new Uint8Array(await webcrypto_default.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); - } - if (cryptoKey.usages.includes("deriveKey")) { - return webcrypto_default.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ["wrapKey", "unwrapKey"]); - } - throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); - } - var encrypt = async (alg, key, cek, p2c = 2048, p2s2 = random_default(new Uint8Array(16))) => { - const derived = await deriveKey2(p2s2, alg, p2c, key); - const encryptedKey = await wrap(alg.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: encode(p2s2) }; - }; - var decrypt2 = async (alg, key, encryptedKey, p2c, p2s2) => { - const derived = await deriveKey2(p2s2, alg, p2c, key); - return unwrap(alg.slice(-6), derived, encryptedKey); - }; - - // dist/browser/runtime/subtle_rsaes.js - function subtleRsaEs(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`); - } - } - - // dist/browser/runtime/check_key_length.js - 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`); - } - } - }; - - // dist/browser/runtime/rsaes.js - var encrypt2 = async (alg, key, cek) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - checkEncCryptoKey(key, alg, "encrypt", "wrapKey"); - check_key_length_default(alg, key); - if (key.usages.includes("encrypt")) { - return new Uint8Array(await webcrypto_default.subtle.encrypt(subtleRsaEs(alg), key, cek)); - } - if (key.usages.includes("wrapKey")) { - const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, key, subtleRsaEs(alg))); - } - throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); - }; - var decrypt3 = async (alg, key, encryptedKey) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - checkEncCryptoKey(key, alg, "decrypt", "unwrapKey"); - check_key_length_default(alg, key); - if (key.usages.includes("decrypt")) { - return new Uint8Array(await webcrypto_default.subtle.decrypt(subtleRsaEs(alg), key, encryptedKey)); - } - if (key.usages.includes("unwrapKey")) { - const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, key, subtleRsaEs(alg), ...bogus_default); - return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); - } - throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); - }; - - // dist/browser/lib/is_jwk.js - function isJWK(key) { - return isObject(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 isJWK(key) && key.kty === "oct" && typeof key.k === "string"; - } - - // dist/browser/runtime/jwk_to_key.js - 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 "EdDSA": - algorithm = { name: jwk.crv }; - 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 parse = async (jwk) => { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm, keyUsages } = subtleMapping(jwk); - const rest = [ - algorithm, - jwk.ext ?? false, - jwk.key_ops ?? keyUsages - ]; - const keyData = { ...jwk }; - delete keyData.alg; - delete keyData.use; - return webcrypto_default.subtle.importKey("jwk", keyData, ...rest); - }; - var jwk_to_key_default = parse; - - // dist/browser/runtime/normalize_key.js - var exportKeyValue = (k) => decode(k); - var privCache; - var pubCache; - var isKeyObject = (key) => { - return key?.[Symbol.toStringTag] === "KeyObject"; - }; - var importAndCache = async (cache, key, jwk, alg, freeze = false) => { - 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 normalizePublicKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: "jwk" }); - delete jwk.d; - delete jwk.dp; - delete jwk.dq; - delete jwk.p; - delete jwk.q; - delete jwk.qi; - if (jwk.k) { - return exportKeyValue(jwk.k); - } - pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); - return importAndCache(pubCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); - const cryptoKey = importAndCache(pubCache, key, key, alg, true); - return cryptoKey; - } - return key; - }; - var normalizePrivateKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: "jwk" }); - if (jwk.k) { - return exportKeyValue(jwk.k); - } - privCache || (privCache = /* @__PURE__ */ new WeakMap()); - return importAndCache(privCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - privCache || (privCache = /* @__PURE__ */ new WeakMap()); - const cryptoKey = importAndCache(privCache, key, key, alg, true); - return cryptoKey; - } - return key; - }; - var normalize_key_default = { normalizePublicKey, normalizePrivateKey }; - - // dist/browser/lib/cek.js - 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) => random_default(new Uint8Array(bitLength2(alg) >> 3)); - - // dist/browser/lib/format_pem.js - var format_pem_default = (b64, descriptor) => { - const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); - return `-----BEGIN ${descriptor}----- -${newlined} ------END ${descriptor}-----`; - }; - - // dist/browser/runtime/asn1.js - var genericExport = async (keyType, keyFormat, key) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - if (!key.extractable) { - throw new TypeError("CryptoKey is not extractable"); - } - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return format_pem_default(encodeBase64(new Uint8Array(await webcrypto_default.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); - }; - var toSPKI = (key) => { - return genericExport("public", "spki", key); - }; - var toPKCS8 = (key) => { - return genericExport("private", "pkcs8", key); - }; - var findOid = (keyData, oid, from = 0) => { - if (from === 0) { - oid.unshift(oid.length); - oid.unshift(6); - } - const i = keyData.indexOf(oid[0], from); - if (i === -1) - return false; - const sub = keyData.subarray(i, i + oid.length); - if (sub.length !== oid.length) - return false; - return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); - }; - var getNamedCurve2 = (keyData) => { - switch (true) { - case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]): - return "P-256"; - case findOid(keyData, [43, 129, 4, 0, 34]): - return "P-384"; - case findOid(keyData, [43, 129, 4, 0, 35]): - return "P-521"; - case findOid(keyData, [43, 101, 110]): - return "X25519"; - case findOid(keyData, [43, 101, 111]): - return "X448"; - case findOid(keyData, [43, 101, 112]): - return "Ed25519"; - case findOid(keyData, [43, 101, 113]): - return "Ed448"; - default: - throw new JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type"); - } - }; - var genericImport = async (replace, keyFormat, pem, alg, options) => { - let algorithm; - let keyUsages; - const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0))); - const isPublic = keyFormat === "spki"; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` - }; - keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; - break; - case "ES256": - algorithm = { name: "ECDSA", namedCurve: "P-256" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ES384": - algorithm = { name: "ECDSA", namedCurve: "P-384" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ES512": - algorithm = { name: "ECDSA", namedCurve: "P-521" }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - const namedCurve = getNamedCurve2(keyData); - algorithm = namedCurve.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: namedCurve }; - keyUsages = isPublic ? [] : ["deriveBits"]; - break; - } - case "EdDSA": - algorithm = { name: getNamedCurve2(keyData) }; - keyUsages = isPublic ? ["verify"] : ["sign"]; - break; - default: - throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); - } - return webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages); - }; - var fromPKCS8 = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options); - }; - var fromSPKI = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options); - }; - function getElement(seq) { - const result = []; - let next = 0; - while (next < seq.length) { - const nextPart = parseElement(seq.subarray(next)); - result.push(nextPart); - next += nextPart.byteLength; - } - return result; - } - function parseElement(bytes) { - let position = 0; - let tag2 = bytes[0] & 31; - position++; - if (tag2 === 31) { - tag2 = 0; - while (bytes[position] >= 128) { - tag2 = tag2 * 128 + bytes[position] - 128; - position++; - } - tag2 = tag2 * 128 + bytes[position] - 128; - position++; - } - let length = 0; - if (bytes[position] < 128) { - length = bytes[position]; - position++; - } else if (length === 128) { - length = 0; - while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { - if (length > bytes.byteLength) { - throw new TypeError("invalid indefinite form length"); - } - length++; - } - const byteLength2 = position + length + 2; - return { - byteLength: byteLength2, - contents: bytes.subarray(position, position + length), - raw: bytes.subarray(0, byteLength2) - }; - } else { - const numberOfDigits = bytes[position] & 127; - position++; - length = 0; - for (let i = 0; i < numberOfDigits; i++) { - length = length * 256 + bytes[position]; - position++; - } - } - const byteLength = position + length; - return { - byteLength, - contents: bytes.subarray(position, byteLength), - raw: bytes.subarray(0, byteLength) - }; - } - function spkiFromX509(buf) { - const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); - return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw); - } - function getSPKI(x509) { - const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ""); - const raw = decodeBase64(pem); - return format_pem_default(spkiFromX509(raw), "PUBLIC KEY"); - } - var fromX509 = (pem, alg, options) => { - let spki; - try { - spki = getSPKI(pem); - } catch (cause) { - throw new TypeError("Failed to parse the X.509 certificate", { cause }); - } - return fromSPKI(spki, alg, options); - }; - - // dist/browser/key/import.js - async function importSPKI(spki, alg, options) { - if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return fromSPKI(spki, alg, options); - } - async function importX509(x509, alg, options) { - if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return fromX509(x509, alg, options); - } - async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return fromPKCS8(pkcs8, alg, options); - } - async function importJWK(jwk, alg) { - if (!isObject(jwk)) { - throw new TypeError("JWK must be an object"); - } - alg || (alg = jwk.alg); - 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 (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 }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } - } - - // dist/browser/lib/check_key_type.js - var tag = (key) => key?.[Symbol.toStringTag]; - var jwkMatchesOp = (alg, key, usage) => { - if (key.use !== void 0 && key.use !== "sig") { - throw new TypeError("Invalid key for this operation, when present its use must be sig"); - } - if (key.key_ops !== void 0 && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== void 0 && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; - }; - var symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && 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, ...types, "Uint8Array", allowJwk ? "JSON Web Key" : null)); - } - if (key.type !== "secret") { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } - }; - var asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && isJWK(key)) { - switch (usage) { - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - 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, ...types, allowJwk ? "JSON Web Key" : null)); - } - if (key.type === "secret") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === "sign" && key.type === "public") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === "decrypt" && key.type === "public") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === "verify" && key.type === "private") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === "encrypt" && key.type === "private") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } - }; - function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } else { - asymmetricTypeCheck(alg, key, usage, allowJwk); - } - } - var check_key_type_default = checkKeyType.bind(void 0, false); - var checkKeyTypeWithJwk = checkKeyType.bind(void 0, true); - - // dist/browser/runtime/encrypt.js - async function cbcEncrypt(enc, plaintext, cek, iv, 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 webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]); - const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: "HMAC" - }, false, ["sign"]); - const ciphertext = new Uint8Array(await webcrypto_default.subtle.encrypt({ - iv, - name: "AES-CBC" - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag2 = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); - return { ciphertext, tag: tag2, iv }; - } - async function gcmEncrypt(enc, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); - } else { - checkEncCryptoKey(cek, enc, "encrypt"); - encKey = cek; - } - const encrypted = new Uint8Array(await webcrypto_default.subtle.encrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, plaintext)); - const tag2 = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag: tag2, iv }; - } - var encrypt3 = async (enc, plaintext, cek, iv, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); - } - if (iv) { - check_iv_length_default(enc, iv); - } else { - iv = iv_default(enc); - } - 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 cbcEncrypt(enc, plaintext, cek, iv, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) { - check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); - } - return gcmEncrypt(enc, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); - } - }; - var encrypt_default = encrypt3; - - // dist/browser/lib/aesgcmkw.js - async function wrap2(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: encode(wrapped.iv), - tag: encode(wrapped.tag) - }; - } - async function unwrap2(alg, key, encryptedKey, iv, tag2) { - const jweAlgorithm = alg.slice(0, 7); - return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0)); - } - - // dist/browser/lib/decrypt_key_management.js - async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - check_key_type_default(alg, key, "decrypt"); - key = await normalize_key_default.normalizePrivateKey?.(key, alg) || key; - 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 (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ecdhAllowed(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); - 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 "RSA1_5": - 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"); - return decrypt3(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 p2s2; - try { - p2s2 = decode(joseHeader.p2s); - } catch { - throw new JWEInvalid("Failed to base64url decode the p2s"); - } - return decrypt2(alg, key, encryptedKey, joseHeader.p2c, p2s2); - } - 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 unwrap2(alg, key, encryptedKey, iv, tag2); - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - } - var decrypt_key_management_default = decryptKeyManagement; - - // dist/browser/lib/validate_crit.js - function validateCrit(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); - } - var validate_crit_default = validateCrit; - - // dist/browser/lib/validate_algorithms.js - var validateAlgorithms = (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); - }; - var validate_algorithms_default = validateAlgorithms; - - // dist/browser/jwe/flattened/decrypt.js - async function flattenedDecrypt(jwe, key, options) { - if (!isObject(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 && !isObject(jwe.header)) { - throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); - } - if (jwe.unprotected !== void 0 && !isObject(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; - } - let cek; - try { - cek = await decrypt_key_management_default(alg, key, 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 }; - } - return result; - } - - // dist/browser/jwe/compact/decrypt.js - 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; - } - - // dist/browser/jwe/general/decrypt.js - async function generalDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid("General JWE must be an object"); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { - throw new JWEInvalid("JWE Recipients missing or incorrect type"); - } - if (!jwe.recipients.length) { - throw new JWEInvalid("JWE Recipients has no members"); - } - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected - }, key, options); - } catch { - } - } - throw new JWEDecryptionFailed(); - } - - // dist/browser/lib/private_symbols.js - var unprotected = Symbol(); - - // dist/browser/runtime/key_to_jwk.js - var keyToJWK = async (key) => { - if (key instanceof Uint8Array) { - return { - kty: "oct", - k: encode(key) - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); - } - if (!key.extractable) { - throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); - } - const { ext, key_ops, alg, use, ...jwk } = await webcrypto_default.subtle.exportKey("jwk", key); - return jwk; - }; - var key_to_jwk_default = keyToJWK; - - // dist/browser/key/export.js - async function exportSPKI(key) { - return toSPKI(key); - } - async function exportPKCS8(key) { - return toPKCS8(key); - } - async function exportJWK(key) { - return key_to_jwk_default(key); - } - - // dist/browser/lib/encrypt_key_management.js - async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - check_key_type_default(alg, key, "encrypt"); - key = await normalize_key_default.normalizePublicKey?.(key, alg) || key; - switch (alg) { - case "dir": { - cek = key; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - if (!ecdhAllowed(key)) { - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey || (ephemeralKey = (await generateEpk(key)).privateKey); - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === "EC") - parameters.epk.y = y; - if (apu) - parameters.apu = encode(apu); - if (apv) - parameters.apv = encode(apv); - if (alg === "ECDH-ES") { - cek = sharedSecret; - break; - } - cek = providedCek || cek_default(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await wrap(kwAlg, sharedSecret, cek); - break; - } - case "RSA1_5": - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - cek = providedCek || cek_default(enc); - encryptedKey = await encrypt2(alg, key, cek); - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - cek = providedCek || cek_default(enc); - const { p2c, p2s: p2s2 } = providedParameters; - ({ encryptedKey, ...parameters } = await encrypt(alg, key, cek, p2c, p2s2)); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - cek = providedCek || cek_default(enc); - encryptedKey = await wrap(alg, key, cek); - break; - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - cek = providedCek || cek_default(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - return { cek, encryptedKey, parameters }; - } - var encrypt_key_management_default = encryptKeyManagement; - - // dist/browser/jwe/flattened/encrypt.js - var FlattenedEncrypt = class { - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError("plaintext must be an instance of Uint8Array"); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError("setKeyManagementParameters can only be called once"); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError("setSharedUnprotectedHeader can only be called once"); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError("setContentEncryptionKey can only be called once"); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError("setInitializationVector can only be called once"); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); - } - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader - }; - validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this._protectedHeader, 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('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== "string" || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === "dir" || alg === "ECDH-ES")) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); - } else { - protectedHeader = encoder.encode(""); - } - if (this._aad) { - aadMember = encode(this._aad); - additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember)); - } else { - additionalData = protectedHeader; - } - const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: encode(ciphertext) - }; - if (iv) { - jwe.iv = encode(iv); - } - if (tag2) { - jwe.tag = encode(tag2); - } - if (encryptedKey) { - jwe.encrypted_key = encode(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; - } - }; - - // dist/browser/jwe/general/encrypt.js - var IndividualRecipient = class { - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } - }; - var GeneralEncrypt = class { - constructor(plaintext) { - this._recipients = []; - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setSharedUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new JWEInvalid("at least one recipient must be added"); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options }); - const jwe2 = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag - }; - if (flattened.aad) - jwe2.aad = flattened.aad; - if (flattened.protected) - jwe2.protected = flattened.protected; - if (flattened.unprotected) - jwe2.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe2.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe2.recipients[0].header = flattened.header; - return jwe2; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader - }; - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === "dir" || alg === "ECDH-ES") { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } else if (enc !== joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== void 0) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - } - const cek = cek_default(enc); - const jwe = { - ciphertext: "", - iv: "", - recipients: [], - tag: "" - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader - }; - const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0; - if (i === 0) { - const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, { - ...recipient.options, - [unprotected]: true - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const { encryptedKey, parameters } = await encrypt_key_management_default(recipient.unprotectedHeader?.alg || this._protectedHeader?.alg || this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = encode(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } - }; - - // dist/browser/runtime/subtle_dsa.js - function subtleDsa(alg, algorithm) { - const hash = `SHA-${alg.slice(-3)}`; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - return { hash, name: "HMAC" }; - case "PS256": - case "PS384": - case "PS512": - return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; - case "RS256": - case "RS384": - case "RS512": - return { hash, name: "RSASSA-PKCS1-v1_5" }; - case "ES256": - case "ES384": - case "ES512": - return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; - case "EdDSA": - return { name: algorithm.name }; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - } - - // dist/browser/runtime/get_sign_verify_key.js - async function getCryptoKey3(alg, key, usage) { - if (usage === "sign") { - key = await normalize_key_default.normalizePrivateKey(key, alg); - } - if (usage === "verify") { - key = await normalize_key_default.normalizePublicKey(key, alg); - } - if (isCryptoKey(key)) { - checkSigCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - if (!alg.startsWith("HS")) { - throw new TypeError(invalid_key_input_default(key, ...types)); - } - return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); - } - throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array", "JSON Web Key")); - } - - // dist/browser/runtime/verify.js - var verify = async (alg, key, signature, data) => { - const cryptoKey = await getCryptoKey3(alg, key, "verify"); - check_key_length_default(alg, cryptoKey); - const algorithm = subtleDsa(alg, cryptoKey.algorithm); - try { - return await webcrypto_default.subtle.verify(algorithm, cryptoKey, signature, data); - } catch { - return false; - } - }; - var verify_default = verify; - - // dist/browser/jws/flattened/verify.js - async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid("Flattened JWS must be an object"); - } - if (jws.protected === void 0 && jws.header === void 0) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== void 0 && typeof jws.protected !== "string") { - throw new JWSInvalid("JWS Protected Header incorrect type"); - } - if (jws.payload === void 0) { - throw new JWSInvalid("JWS Payload missing"); - } - if (typeof jws.signature !== "string") { - throw new JWSInvalid("JWS Signature missing or incorrect type"); - } - if (jws.header !== void 0 && !isObject(jws.header)) { - throw new JWSInvalid("JWS Unprotected Header incorrect type"); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = decode(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - } - if (!is_disjoint_default(parsedProt, jws.header)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validate_algorithms_default("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== "string") { - throw new JWSInvalid("JWS Payload must be a string"); - } - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - checkKeyTypeWithJwk(alg, key, "verify"); - if (isJWK(key)) { - key = await importJWK(key, alg); - } - } else { - checkKeyTypeWithJwk(alg, key, "verify"); - } - const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = decode(jws.signature); - } catch { - throw new JWSInvalid("Failed to base64url decode the signature"); - } - const verified = await verify_default(alg, key, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = decode(jws.payload); - } catch { - throw new JWSInvalid("Failed to base64url decode the payload"); - } - } else if (typeof jws.payload === "string") { - payload = encoder.encode(jws.payload); - } else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jws.header !== void 0) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; - } - - // dist/browser/jws/compact/verify.js - async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== "string") { - throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) { - throw new JWSInvalid("Invalid Compact JWS"); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; - } - - // dist/browser/jws/general/verify.js - async function generalVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid("General JWS must be an object"); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { - throw new JWSInvalid("JWS Signatures missing or incorrect type"); - } - for (const signature of jws.signatures) { - try { - return await flattenedVerify({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature - }, key, options); - } catch { - } - } - throw new JWSSignatureVerificationFailed(); - } - - // dist/browser/lib/epoch.js - var epoch_default = (date) => Math.floor(date.getTime() / 1e3); - - // dist/browser/lib/secs.js - var minute = 60; - var hour = minute * 60; - var day = hour * 24; - var week = day * 7; - var year = day * 365.25; - var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; - var secs_default = (str) => { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) { - throw new TypeError("Invalid time period format"); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") { - return -numericDate; - } - return numericDate; - }; - - // dist/browser/lib/jwt_claims_set.js - var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ""); - var checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; - }; - var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch { - } - if (!isObject(payload)) { - throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - } - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) - presenceCheck.push("iat"); - if (audience !== void 0) - presenceCheck.push("aud"); - if (subject !== void 0) - presenceCheck.push("sub"); - if (issuer !== void 0) - presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); - } - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); - } - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs_default(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: - throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now = epoch_default(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); - } - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); - } - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); - } - } - return payload; - }; - - // dist/browser/jwt/verify.js - async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; - } - - // dist/browser/jwt/decrypt.js - async function jwtDecrypt(jwt, key, options) { - const decrypted = await compactDecrypt(jwt, key, options); - const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); - } - if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); - } - if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); - } - const result = { payload, protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; - } - - // dist/browser/jwe/compact/encrypt.js - var CompactEncrypt = class { - constructor(plaintext) { - this._flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); - } - }; - - // dist/browser/runtime/sign.js - var sign = async (alg, key, data) => { - const cryptoKey = await getCryptoKey3(alg, key, "sign"); - check_key_length_default(alg, cryptoKey); - const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); - }; - var sign_default = sign; - - // dist/browser/jws/flattened/sign.js - var FlattenedSign = class { - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError("payload must be an instance of Uint8Array"); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); - } - if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader - }; - const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyTypeWithJwk(alg, key, "sign"); - let payload = this._payload; - if (b64) { - payload = encoder.encode(encode(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); - } else { - protectedHeader = encoder.encode(""); - } - const data = concat(protectedHeader, encoder.encode("."), payload); - const signature = await sign_default(alg, key, data); - const jws = { - signature: encode(signature), - payload: "" - }; - if (b64) { - jws.payload = decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = decoder.decode(protectedHeader); - } - return jws; - } - }; - - // dist/browser/jws/compact/sign.js - var CompactSign = class { - constructor(payload) { - this._flattened = new FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === void 0) { - throw new TypeError("use the flattened module for creating JWS with b64: false"); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } - }; - - // dist/browser/jws/general/sign.js - var IndividualSignature = class { - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError("setUnprotectedHeader can only be called once"); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } - }; - var GeneralSign = class { - constructor(payload) { - this._signatures = []; - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new JWSInvalid("at least one signature must be added"); - } - const jws = { - signatures: [], - payload: "" - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } else if (jws.payload !== payload) { - throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)"); - } - jws.signatures.push(rest); - } - return jws; - } - }; - - // dist/browser/jwt/produce.js - function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; - } - var ProduceJWT = class { - constructor(payload = {}) { - if (!isObject(payload)) { - throw new TypeError("JWT Claims Set MUST be an object"); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === "number") { - this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) }; - } else { - this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === "number") { - this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) }; - } else { - this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === "undefined") { - this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) }; - } else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) }; - } else if (typeof input === "string") { - this._payload = { - ...this._payload, - iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input)) - }; - } else { - this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) }; - } - return this; - } - }; - - // dist/browser/jwt/sign.js - var SignJWT = class extends ProduceJWT { - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - return sig.sign(key, options); - } - }; - - // dist/browser/jwt/encrypt.js - var EncryptJWT = class extends ProduceJWT { - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError("setProtectedHeader can only be called once"); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError("setKeyManagementParameters can only be called once"); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError("setContentEncryptionKey can only be called once"); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError("setInitializationVector can only be called once"); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } - }; - - // dist/browser/jwk/thumbprint.js - var check = (value, description) => { - if (typeof value !== "string" || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } - }; - async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!isObject(jwk)) { - throw new TypeError("JWK must be an object"); - } - digestAlgorithm ?? (digestAlgorithm = "sha256"); - if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case "EC": - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case "OKP": - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case "RSA": - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case "oct": - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encoder.encode(JSON.stringify(components)); - return encode(await digest_default(digestAlgorithm, data)); - } - async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ?? (digestAlgorithm = "sha256"); - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; - } - - // dist/browser/jwk/embedded.js - async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header - }; - if (!isObject(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; - } - - // dist/browser/jwks/local.js - function getKtyFromAlg(alg) { - switch (typeof alg === "string" && alg.slice(0, 2)) { - case "RS": - case "PS": - return "RSA"; - case "ES": - return "EC"; - case "Ed": - return "OKP"; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } - } - function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); - } - function isJWKLike(key) { - return isObject(key); - } - function clone(obj) { - if (typeof structuredClone === "function") { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); - } - var LocalJWKSet = class { - constructor(jwks) { - this._cached = /* @__PURE__ */ new WeakMap(); - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid("JSON Web Key Set malformed"); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk2) => { - let candidate = kty === jwk2.kty; - if (candidate && typeof kid === "string") { - candidate = kid === jwk2.kid; - } - if (candidate && typeof jwk2.alg === "string") { - candidate = alg === jwk2.alg; - } - if (candidate && typeof jwk2.use === "string") { - candidate = jwk2.use === "sig"; - } - if (candidate && Array.isArray(jwk2.key_ops)) { - candidate = jwk2.key_ops.includes("verify"); - } - if (candidate && alg === "EdDSA") { - candidate = jwk2.crv === "Ed25519" || jwk2.crv === "Ed448"; - } - if (candidate) { - switch (alg) { - case "ES256": - candidate = jwk2.crv === "P-256"; - break; - case "ES256K": - candidate = jwk2.crv === "secp256k1"; - break; - case "ES384": - candidate = jwk2.crv === "P-384"; - break; - case "ES512": - candidate = jwk2.crv === "P-521"; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk2 of candidates) { - try { - yield await importWithAlgCache(_cached, jwk2, alg); - } catch { - } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } - }; - async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === void 0) { - const key = await importJWK({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - } - cached[alg] = key; - } - return cached[alg]; - } - function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false - } - }); - return localJWKSet; - } - - // dist/browser/runtime/fetch_jwks.js - var fetchJwks = async (url, timeout, options) => { - let controller; - let id; - let timedOut = false; - if (typeof AbortController === "function") { - controller = new AbortController(); - id = setTimeout(() => { - timedOut = true; - controller.abort(); - }, timeout); - } - const response = await fetch(url.href, { - signal: controller ? controller.signal : void 0, - redirect: "manual", - headers: options.headers - }).catch((err) => { - if (timedOut) - throw new JWKSTimeout(); - throw err; - }); - if (id !== void 0) - clearTimeout(id); - if (response.status !== 200) { - throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - } - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } - }; - var fetch_jwks_default = fetchJwks; - - // dist/browser/jwks/remote.js - function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; - } - var USER_AGENT; - if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { - const NAME = "jose"; - const VERSION = "v5.9.1"; - USER_AGENT = `${NAME}/${VERSION}`; - } - var jwksCache = Symbol(); - function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) { - return false; - } - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) { - return false; - } - return true; - } - var RemoteJWKSet = class { - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError("url must be an instance of URL"); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this._cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this._cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - if (options?.[jwksCache] !== void 0) { - this._cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = createLocalJWKSet(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; - } - fresh() { - return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = void 0; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has("User-Agent")) { - headers.set("User-Agent", USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch || (this._pendingFetch = fetch_jwks_default(this._url, this._timeoutDuration, this._options).then((json) => { - this._local = createLocalJWKSet(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = void 0; - }).catch((err) => { - this._pendingFetch = void 0; - throw err; - })); - await this._pendingFetch; - } - }; - function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; - } - var experimental_jwksCache = jwksCache; - - // dist/browser/jwt/unsecured.js - var UnsecuredJWT = class extends ProduceJWT { - encode() { - const header = encode(JSON.stringify({ alg: "none" })); - const payload = encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== "string") { - throw new JWTInvalid("Unsecured JWT must be a string"); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split("."); - if (length !== 3 || signature !== "") { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - let header; - try { - header = JSON.parse(decoder.decode(decode(encodedHeader))); - if (header.alg !== "none") - throw new Error(); - } catch { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - const payload = jwt_claims_set_default(header, decode(encodedPayload), options); - return { payload, header }; - } - }; - - // dist/browser/util/base64url.js - var base64url_exports2 = {}; - __export(base64url_exports2, { - decode: () => decode2, - encode: () => encode2 - }); - var encode2 = encode; - var decode2 = decode; - - // dist/browser/util/decode_protected_header.js - function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) { - [protectedB64u] = parts; - } - } else if (typeof token === "object" && token) { - if ("protected" in token) { - protectedB64u = token.protected; - } else { - throw new TypeError("Token does not contain a Protected Header"); - } - } - try { - if (typeof protectedB64u !== "string" || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(decode2(protectedB64u))); - if (!isObject(result)) { - throw new Error(); - } - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } - } - - // dist/browser/util/decode_jwt.js - function decodeJwt(jwt) { - if (typeof jwt !== "string") - throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt.split("."); - if (length === 5) - throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) - throw new JWTInvalid("Invalid JWT"); - if (!payload) - throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode2(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject(result)) - throw new JWTInvalid("Invalid JWT Claims Set"); - return result; - } - - // dist/browser/runtime/generate.js - async function generateSecret(alg, options) { - let length; - let algorithm; - let keyUsages; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - length = parseInt(alg.slice(-3), 10); - algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; - keyUsages = ["sign", "verify"]; - break; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - length = parseInt(alg.slice(-3), 10); - return random_default(new Uint8Array(length >> 3)); - case "A128KW": - case "A192KW": - case "A256KW": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-KW", length }; - keyUsages = ["wrapKey", "unwrapKey"]; - break; - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": - case "A128GCM": - case "A192GCM": - case "A256GCM": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-GCM", length }; - keyUsages = ["encrypt", "decrypt"]; - break; - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return webcrypto_default.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); - } - function getModulusLengthOption(options) { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); - } - return modulusLength; - } - async function generateKeyPair(alg, options) { - let algorithm; - let keyUsages; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { - name: "RSA-PSS", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["sign", "verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { - name: "RSASSA-PKCS1-v1_5", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["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(alg.slice(-3), 10) || 1}`, - publicExponent: new Uint8Array([1, 0, 1]), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; - break; - case "ES256": - algorithm = { name: "ECDSA", namedCurve: "P-256" }; - keyUsages = ["sign", "verify"]; - break; - case "ES384": - algorithm = { name: "ECDSA", namedCurve: "P-384" }; - keyUsages = ["sign", "verify"]; - break; - case "ES512": - algorithm = { name: "ECDSA", namedCurve: "P-521" }; - keyUsages = ["sign", "verify"]; - break; - case "EdDSA": { - keyUsages = ["sign", "verify"]; - const crv = options?.crv ?? "Ed25519"; - switch (crv) { - case "Ed25519": - case "Ed448": - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported("Invalid or unsupported crv option provided"); - } - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - keyUsages = ["deriveKey", "deriveBits"]; - const crv = options?.crv ?? "P-256"; - switch (crv) { - case "P-256": - case "P-384": - case "P-521": { - algorithm = { name: "ECDH", namedCurve: crv }; - break; - } - case "X25519": - case "X448": - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448"); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return webcrypto_default.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); - } - - // dist/browser/key/generate_key_pair.js - async function generateKeyPair2(alg, options) { - return generateKeyPair(alg, options); - } - - // dist/browser/key/generate_secret.js - async function generateSecret2(alg, options) { - return generateSecret(alg, options); - } - - // dist/browser/runtime/runtime.js - var runtime_default = "WebCryptoAPI"; - - // dist/browser/util/runtime.js - var runtime_default2 = runtime_default; - - exports.CompactEncrypt = CompactEncrypt; - exports.CompactSign = CompactSign; - exports.EmbeddedJWK = EmbeddedJWK; - exports.EncryptJWT = EncryptJWT; - exports.FlattenedEncrypt = FlattenedEncrypt; - exports.FlattenedSign = FlattenedSign; - exports.GeneralEncrypt = GeneralEncrypt; - exports.GeneralSign = GeneralSign; - exports.SignJWT = SignJWT; - exports.UnsecuredJWT = UnsecuredJWT; - exports.base64url = base64url_exports2; - exports.calculateJwkThumbprint = calculateJwkThumbprint; - exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; - exports.compactDecrypt = compactDecrypt; - exports.compactVerify = compactVerify; - exports.createLocalJWKSet = createLocalJWKSet; - exports.createRemoteJWKSet = createRemoteJWKSet; - exports.cryptoRuntime = runtime_default2; - exports.decodeJwt = decodeJwt; - exports.decodeProtectedHeader = decodeProtectedHeader; - exports.errors = errors_exports; - exports.experimental_jwksCache = experimental_jwksCache; - exports.exportJWK = exportJWK; - exports.exportPKCS8 = exportPKCS8; - exports.exportSPKI = exportSPKI; - exports.flattenedDecrypt = flattenedDecrypt; - exports.flattenedVerify = flattenedVerify; - exports.generalDecrypt = generalDecrypt; - exports.generalVerify = generalVerify; - exports.generateKeyPair = generateKeyPair2; - exports.generateSecret = generateSecret2; - exports.importJWK = importJWK; - exports.importPKCS8 = importPKCS8; - exports.importSPKI = importSPKI; - exports.importX509 = importX509; - exports.jwksCache = jwksCache; - exports.jwtDecrypt = jwtDecrypt; - exports.jwtVerify = jwtVerify; - -})); diff --git a/dist/browser/index.umd.min.js b/dist/browser/index.umd.min.js deleted file mode 100644 index 0a3a073a65..0000000000 --- a/dist/browser/index.umd.min.js +++ /dev/null @@ -1,5 +0,0 @@ -(function(g,f){typeof exports==='object'&&typeof module!=='undefined'?f(exports):typeof define==='function'&&define.amd?define(['exports'],f):(g=typeof globalThis!=='undefined'?globalThis:g||self,f(g.jose={}));})(this,(function(exports){'use strict';var fr=Object.defineProperty;var yt=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0});};var f=crypto,K=e=>e instanceof CryptoKey;var ur=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},We=ur;var w=new TextEncoder,x=new TextDecoder,ve=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function wt(e,t){return W(w.encode(e),new Uint8Array([0]),t)}function ze(e,t,r){if(t<0||t>=ve)throw new RangeError(`value must be >= 0 and <= ${ve-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r);}function Je(e){let t=Math.floor(e/ve),r=e%ve,n=new Uint8Array(8);return ze(n,t,0),ze(n,r,4),n}function Te(e){let t=new Uint8Array(4);return ze(t,e),t}function Ie(e){return W(Te(e.length),e)}async function Et(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var Oe=e=>{let t=e;typeof t=="string"&&(t=w.encode(t));let r=32768,n=[];for(let o=0;oOe(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Xe=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=x.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Xe(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var St={};yt(St,{JOSEAlgNotAllowed:()=>$,JOSEError:()=>H,JOSENotSupported:()=>h,JWEDecryptionFailed:()=>M,JWEInvalid:()=>c,JWKInvalid:()=>ue,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>he,JWKSNoMatchingKey:()=>X,JWKSTimeout:()=>me,JWSInvalid:()=>l,JWSSignatureVerificationFailed:()=>Y,JWTClaimValidationFailed:()=>C,JWTExpired:()=>ne,JWTInvalid:()=>_});var H=class extends Error{static get code(){return "ERR_JOSE_GENERIC"}constructor(t){super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor);}},C=class extends H{static get code(){return "ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r,n="unspecified",o="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=o,this.payload=r;}},ne=class extends H{static get code(){return "ERR_JWT_EXPIRED"}constructor(t,r,n="unspecified",o="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=o,this.payload=r;}},$=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED";}static get code(){return "ERR_JOSE_ALG_NOT_ALLOWED"}},h=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED";}static get code(){return "ERR_JOSE_NOT_SUPPORTED"}},M=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed";}static get code(){return "ERR_JWE_DECRYPTION_FAILED"}},c=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_INVALID";}static get code(){return "ERR_JWE_INVALID"}},l=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_INVALID";}static get code(){return "ERR_JWS_INVALID"}},_=class extends H{constructor(){super(...arguments),this.code="ERR_JWT_INVALID";}static get code(){return "ERR_JWT_INVALID"}},ue=class extends H{constructor(){super(...arguments),this.code="ERR_JWK_INVALID";}static get code(){return "ERR_JWK_INVALID"}},oe=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID";}static get code(){return "ERR_JWKS_INVALID"}},X=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set";}static get code(){return "ERR_JWKS_NO_MATCHING_KEY"}},he=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set";}static get code(){return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},me=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out";}static get code(){return "ERR_JWKS_TIMEOUT"}},Y=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed";}static get code(){return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var k=f.getRandomValues.bind(f);function Ye(e){switch(e){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 h(`Unsupported JWE Algorithm: ${e}`)}}var bt=e=>k(new Uint8Array(Ye(e)>>3));var hr=(e,t)=>{if(t.length<<3!==Ye(e))throw new c("Invalid Initialization Vector length")},Re=hr;var mr=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ae=mr;var lr=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++oe.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`;}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function xt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!B(e.algorithm,"HMAC"))throw v("HMAC");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!B(e.algorithm,"RSASSA-PKCS1-v1_5"))throw v("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!B(e.algorithm,"RSA-PSS"))throw v("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw v("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!B(e.algorithm,"ECDSA"))throw v("ECDSA");let n=yr(t);if(e.algorithm.namedCurve!==n)throw v(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r);}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!B(e.algorithm,"AES-GCM"))throw v("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!B(e.algorithm,"AES-KW"))throw v("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw v("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!B(e.algorithm,"PBKDF2"))throw v("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!B(e.algorithm,"RSA-OAEP"))throw v("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r);}function _t(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`;}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>_t("Key must be ",e,...t);function qe(e,t,...r){return _t(`Key for the ${e} algorithm must be `,t,...r)}var Ze=e=>K(e)?!0:e?.[Symbol.toStringTag]==="KeyObject",b=["CryptoKey"];async function wr(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),d=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Je(a.length<<3)),u=new Uint8Array((await f.subtle.sign("HMAC",d,p)).slice(0,i>>3)),m;try{m=At(o,u);}catch{}if(!m)throw new M;let T;try{T=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r));}catch{}if(!T)throw new M;return T}async function Er(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await f.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(I(t,e,"decrypt"),i=t);try{return new Uint8Array(await f.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,W(r,o)))}catch{throw new M}}var gr=async(e,t,r,n,o,a)=>{if(!K(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...b,"Uint8Array"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(Re(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ae(t,parseInt(e.slice(-3),10)),wr(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ae(t,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o,a);default:throw new h("Unsupported JWE Content Encryption Algorithm")}},De=gr;var Sr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return !0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return !1;r.add(a);}}return !0},O=Sr;function br(e){return typeof e=="object"&&e!==null}function y(e){if(!br(e)||Object.prototype.toString.call(e)!=="[object Object]")return !1;if(Object.getPrototypeOf(e)===null)return !0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Ar=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],ie=Ar;function Ht(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Ct(e,t,r){if(K(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...b,"Uint8Array"))}var le=async(e,t,r)=>{let n=await Ct(t,e,"wrapKey");Ht(n,e);let o=await f.subtle.importKey("raw",r,...ie);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},ye=async(e,t,r)=>{let n=await Ct(t,e,"unwrapKey");Ht(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...ie);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Me(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!K(e))throw new TypeError(A(e,...b));if(I(e,"ECDH"),!K(t))throw new TypeError(A(t,...b));I(t,"ECDH","deriveBits");let i=W(Ie(w.encode(r)),Ie(o),Ie(a),Te(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let d=new Uint8Array(await f.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return Et(d,n,i)}async function Pt(e){if(!K(e))throw new TypeError(A(e,...b));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Ne(e){if(!K(e))throw new TypeError(A(e,...b));return ["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Qe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets")}function Kr(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(K(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...b,"Uint8Array"))}async function vt(e,t,r,n){Qe(e);let o=wt(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},d=await Kr(n,t);if(d.usages.includes("deriveBits"))return new Uint8Array(await f.subtle.deriveBits(i,d,a));if(d.usages.includes("deriveKey"))return f.subtle.deriveKey(i,d,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var Jt=async(e,t,r,n=2048,o=k(new Uint8Array(16)))=>{let a=await vt(o,e,n,t);return {encryptedKey:await le(e.slice(-6),a,r),p2c:n,p2s:E(o)}},Tt=async(e,t,r,n,o)=>{let a=await vt(o,e,n,t);return ye(e.slice(-6),a,r)};function se(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return "RSA-OAEP";default:throw new h(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var It=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"encrypt","wrapKey"),q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(se(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...ie);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,se(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ot=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"decrypt","unwrapKey"),q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(se(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,se(e),...ie);return new Uint8Array(await f.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function N(e){return y(e)&&typeof e.kty=="string"}function Rt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ut(e){return e.kty!=="oct"&&typeof e.d>"u"}function Dt(e){return N(e)&&e.kty==="oct"&&typeof e.k=="string"}function _r(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new h('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:r}}var Hr=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=_r(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,f.subtle.importKey("jwk",o,...n)},Le=Hr;var Mt=e=>g(e),ce,de,Nt=e=>e?.[Symbol.toStringTag]==="KeyObject",$e=async(e,t,r,n,o=!1)=>{let a=e.get(t);if(a?.[n])return a[n];let i=await Le({...r,alg:n});return o&&Object.freeze(t),a?a[n]=i:e.set(t,{[n]:i}),i},Cr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mt(r.k):(de||(de=new WeakMap),$e(de,e,r,t))}return N(e)?e.k?g(e.k):(de||(de=new WeakMap),$e(de,e,e,t,!0)):e},Pr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return r.k?Mt(r.k):(ce||(ce=new WeakMap),$e(ce,e,r,t))}return N(e)?e.k?g(e.k):(ce||(ce=new WeakMap),$e(ce,e,e,t,!0)):e},Z={normalizePublicKey:Cr,normalizePrivateKey:Pr};function we(e){switch(e){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 h(`Unsupported JWE Algorithm: ${e}`)}}var R=e=>k(new Uint8Array(we(e)>>3));var je=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` -`);return `-----BEGIN ${t}----- -${r} ------END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),G=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return !1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||G(e,t,n+1)},Lt=e=>{switch(!0){case G(e,[42,134,72,206,61,3,1,7]):return "P-256";case G(e,[43,129,4,0,34]):return "P-384";case G(e,[43,129,4,0,35]):return "P-521";case G(e,[43,101,110]):return "X25519";case G(e,[43,101,111]):return "X448";case G(e,[43,101,112]):return "Ed25519";case G(e,[43,101,113]):return "Ed448";default:throw new h("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=async(e,t,r,n,o)=>{let a,i,s=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},i=d?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},i=d?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},i=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let p=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new h('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++;}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++;}let a=t+n+2;return {byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else {let a=e[t]&127;t++,n=0;for(let i=0;i{let n;try{n=vr(e);}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function L(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return g(e.k);case"RSA":if(e.oth!==void 0)throw new h('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Le({...e,alg:t});default:throw new h('Unsupported "kty" (Key Type) Parameter value')}}var pe=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return !0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&N(t)){if(Dt(t)&&tt(e,t,r))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(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${pe(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&N(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${pe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${pe(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${pe(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${pe(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${pe(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e);}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),u=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return {ciphertext:d,tag:u,iv:n}}async function Dr(e,t,r,n,o){let a;r instanceof Uint8Array?a=await f.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(I(r,e,"encrypt"),a=r);let i=new Uint8Array(await f.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return {ciphertext:i.slice(0,-16),tag:s,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ae(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ae(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new h("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return {encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await Z.normalizePrivateKey?.(t,e)||t,e){case"dir":{if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new h("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await L(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new c('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=g(n.apu);}catch{throw new c("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new c('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=g(n.apv);}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return d;if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(e.slice(-6),d,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new c("JWE Encrypted Key missing");return Ot(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new c('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=o?.maxPBES2Count||1e4;if(n.p2c>a)throw new c('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new c('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=g(n.p2s);}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new c('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new c('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=g(n.iv);}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag);}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new h('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new h(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var U=Lr;var $r=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},ge=$r;async function Se(e,t,r){if(!y(e))throw new c("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new c("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new c("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new c("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new c("JWE AAD incorrect type");if(e.header!==void 0&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let re=g(e.protected);n=JSON.parse(x.decode(re));}catch{throw new c("JWE Protected Header is invalid")}if(!O(n,e.header,e.unprotected))throw new c("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(U(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new h('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:a,enc:i}=o;if(typeof a!="string"||!a)throw new c("missing JWE Algorithm (alg) in JWE Header");if(typeof i!="string"||!i)throw new c("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(a)||!s&&a.startsWith("PBES2"))throw new $('"alg" (Algorithm) Header Parameter value not allowed');if(d&&!d.has(i))throw new $('"enc" (Encryption Algorithm) Header Parameter value not allowed');let p;if(e.encrypted_key!==void 0)try{p=g(e.encrypted_key);}catch{throw new c("Failed to base64url decode the encrypted_key")}let u=!1;typeof t=="function"&&(t=await t(n,e),u=!0);let m;try{m=await Qt(a,t,p,o,r);}catch(re){if(re instanceof TypeError||re instanceof c||re instanceof h)throw re;m=R(i);}let T,J;if(e.iv!==void 0)try{T=g(e.iv);}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag);}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext);}catch{throw new c("Failed to base64url decode the ciphertext")}let te={plaintext:await De(i,m,Pe,T,J,P)};if(e.protected!==void 0&&(te.protectedHeader=n),e.aad!==void 0)try{te.additionalAuthenticatedData=g(e.aad);}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(te.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(te.unprotectedHeader=e.header),u?{...te,key:t}:te}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.decode(e)),typeof e!="string")throw new c("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:d}=e.split(".");if(d!==5)throw new c("Invalid Compact JWE");let p=await Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),u={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...u,key:p.key}:u}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))throw new c("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new c("JWE Recipients has no members");for(let n of e.recipients)try{return await Se({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new M}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return {kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await f.subtle.exportKey("jwk",e);return a},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await Z.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new h("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:u}=o;u||(u=(await Pt(r)).privateKey);let{x:m,y:T,crv:J,kty:S}=await nt(u),P=await Me(r,u,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:m,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||R(t);let Pe=e.slice(-6);a=await le(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||R(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||R(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||R(t),a=await le(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||R(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new h('Invalid or unsupported "alg" (JWE Algorithm) header value')}return {cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var F=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t;}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new c("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!O(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new c("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(U(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new h('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new c('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new c('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;(({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters))),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P));}let d,p,u;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(u=E(this._aad),d=W(p,w.encode("."),w.encode(u))):d=p;let{ciphertext:m,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(m)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),u&&(S.aad=u),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},at=class{constructor(t){this._recipients=[],this._plaintext=t;}addRecipient(t,r){let n=new ot(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new c("at least one recipient must be added");if(this._recipients.length===1){let[o]=this._recipients,a=await new F(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),i={ciphertext:a.ciphertext,iv:a.iv,recipients:[{}],tag:a.tag};return a.aad&&(i.aad=a.aad),a.protected&&(i.protected=a.protected),a.unprotected&&(i.unprotected=a.unprotected),a.encrypted_key&&(i.recipients[0].encrypted_key=a.encrypted_key),a.header&&(i.recipients[0].header=a.header),i}let t;for(let o=0;o>3};case"RS256":case"RS384":case"RS512":return {hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return {hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return {name:t.name};default:throw new h(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await Z.normalizePrivateKey(t,e)),r==="verify"&&(t=await Z.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return !1}},er=zr;async function Ke(e,t,r){if(!y(e))throw new l("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new l('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new l("JWS Protected Header incorrect type");if(e.payload===void 0)throw new l("JWS Payload missing");if(typeof e.signature!="string")throw new l("JWS Signature missing or incorrect type");if(e.header!==void 0&&!y(e.header))throw new l("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P));}catch{throw new l("JWS Protected Header is invalid")}if(!O(n,e.header))throw new l("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=U(l,new Map([["b64",!0]]),r?.crit,n,o),i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new l('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new l('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&ge("algorithms",r.algorithms);if(d&&!d.has(s))throw new $('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new l("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new l("JWS Payload must be a string or an Uint8Array instance");let p=!1;typeof t=="function"?(t=await t(n,e),p=!0,Ee(s,t,"verify"),N(t)&&(t=await L(t,s))):Ee(s,t,"verify");let u=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),m;try{m=g(e.signature);}catch{throw new l("Failed to base64url decode the signature")}if(!await er(s,t,m,u))throw new Y;let J;if(i)try{J=g(e.payload);}catch{throw new l("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.decode(e)),typeof e!="string")throw new l("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new l("Invalid Compact JWS");let s=await Ke({payload:o,protected:n,signature:a},t,r),d={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...d,key:s.key}:d}async function Xr(e,t,r){if(!y(e))throw new l("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new l("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Y}var D=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Q=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,fe=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t));}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,u=[...a];p!==void 0&&u.push("iat"),d!==void 0&&u.push("aud"),s!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(let S of new Set(u.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let m;switch(typeof r.clockTolerance){case"string":m=Q(r.clockTolerance);break;case"number":m=r.clockTolerance;break;case"undefined":m=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=D(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+m)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-m)throw new ne('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:Q(p);if(S-m>P)throw new ne('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-m)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:fe(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=fe(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new F(t);}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return [n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var jr=async(e,t,r)=>{let n=await Ae(e,t,"sign");q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var j=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t;}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new l("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!O(this._protectedHeader,this._unprotectedHeader))throw new l("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=U(l,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new l('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new l('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),u=await rr(i,t,p),m={signature:E(u),payload:""};return a&&(m.payload=x.decode(s)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=x.decode(d)),m}};var _e=class{constructor(t){this._flattened=new j(t);}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return `${n.protected}.${n.payload}.${n.signature}`}};var st=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ct=class{constructor(t){this._signatures=[],this._payload=t;}addSignature(t,r){let n=new st(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new l("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r"u"?this._payload={...this._payload,iat:D(new Date)}:t instanceof Date?this._payload={...this._payload,iat:ee("setIssuedAt",D(t))}:typeof t=="string"?this._payload={...this._payload,iat:ee("setIssuedAt",D(new Date)+Q(t))}:this._payload={...this._payload,iat:ee("setIssuedAt",t)},this}};var dt=class extends V{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends V{setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var z=(e,t)=>{if(typeof e!="string"||!e)throw new ue(`${t} missing or invalid`)};async function nr(e,t){if(!y(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":z(e.crv,'"crv" (Curve) Parameter'),z(e.x,'"x" (X Coordinate) Parameter'),z(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":z(e.crv,'"crv" (Subtype of Key Pair) Parameter'),z(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":z(e.e,'"e" (Exponent) Parameter'),z(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":z(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new h('"kty" (Key Type) Parameter missing or unsupported')}let n=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return `urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new l('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await L({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new l('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function rn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return "RSA";case"ES":return "EC";case"Ed":return "OKP";default:throw new h('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new oe("JSON Web Key Set malformed");this._jwks=ar(t);}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let u=a===p.kty;if(u&&typeof o=="string"&&(u=o===p.kid),u&&typeof p.alg=="string"&&(u=n===p.alg),u&&typeof p.use=="string"&&(u=p.use==="sig"),u&&Array.isArray(p.key_ops)&&(u=p.key_ops.includes("verify")),u&&n==="EdDSA"&&(u=p.crv==="Ed25519"||p.crv==="Ed448"),u)switch(n){case"ES256":u=p.crv==="P-256";break;case"ES256K":u=p.crv==="secp256k1";break;case"ES384":u=p.crv==="P-384";break;case"ES512":u=p.crv==="P-521";break}return u}),{0:s,length:d}=i;if(d===0)throw new X;if(d!==1){let p=new he,{_cached:u}=this;throw p[Symbol.asyncIterator]=async function*(){for(let m of i)try{yield await or(u,m,n);}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await L({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new oe("JSON Web Key Set members must be public keys");n[r]=o;}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort();},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new me:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new H("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new H("Failed to parse the JSON Web Key Set HTTP response as JSON")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.1");var He=Symbol();function cn(e,t){return !(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)));}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0;}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch;}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var mt=class extends V{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return `${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return {payload:fe(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r);}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t);}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n));}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),k(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function lt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new h("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:lt(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];let o=t?.crv??"Ed25519";switch(o){case"Ed25519":case"Ed448":r={name:o};break;default:throw new h("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new h("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function mn(e,t){return dr(e,t)}async function ln(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr; -exports.CompactEncrypt=xe;exports.CompactSign=_e;exports.EmbeddedJWK=tn;exports.EncryptJWT=pt;exports.FlattenedEncrypt=F;exports.FlattenedSign=j;exports.GeneralEncrypt=at;exports.GeneralSign=ct;exports.SignJWT=dt;exports.UnsecuredJWT=mt;exports.base64url=sr;exports.calculateJwkThumbprint=nr;exports.calculateJwkThumbprintUri=en;exports.compactDecrypt=rt;exports.compactVerify=it;exports.createLocalJWKSet=Ve;exports.createRemoteJWKSet=dn;exports.cryptoRuntime=yn;exports.decodeJwt=hn;exports.decodeProtectedHeader=un;exports.errors=St;exports.experimental_jwksCache=pn;exports.exportJWK=nt;exports.exportPKCS8=Fr;exports.exportSPKI=Gr;exports.flattenedDecrypt=Se;exports.flattenedVerify=Ke;exports.generalDecrypt=kr;exports.generalVerify=Xr;exports.generateKeyPair=mn;exports.generateSecret=ln;exports.importJWK=L;exports.importPKCS8=Ir;exports.importSPKI=Jr;exports.importX509=Tr;exports.jwksCache=He;exports.jwtDecrypt=Qr;exports.jwtVerify=Zr;})); \ No newline at end of file diff --git a/dist/browser/jwe/compact/decrypt.js b/dist/browser/jwe/compact/decrypt.js deleted file mode 100644 index d74a67b134..0000000000 --- a/dist/browser/jwe/compact/decrypt.js +++ /dev/null @@ -1,27 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.js'; -import { JWEInvalid } from '../../util/errors.js'; -import { decoder } from '../../lib/buffer_utils.js'; -export 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: tag, length, } = jwe.split('.'); - if (length !== 5) { - throw new JWEInvalid('Invalid Compact JWE'); - } - const decrypted = await flattenedDecrypt({ - ciphertext, - iv: iv || undefined, - protected: protectedHeader, - tag: tag || undefined, - encrypted_key: encryptedKey || undefined, - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} diff --git a/dist/browser/jwe/compact/encrypt.js b/dist/browser/jwe/compact/encrypt.js deleted file mode 100644 index e689139465..0000000000 --- a/dist/browser/jwe/compact/encrypt.js +++ /dev/null @@ -1,26 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.js'; -export class CompactEncrypt { - constructor(plaintext) { - this._flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); - } -} diff --git a/dist/browser/jwe/flattened/decrypt.js b/dist/browser/jwe/flattened/decrypt.js deleted file mode 100644 index 8b963a3873..0000000000 --- a/dist/browser/jwe/flattened/decrypt.js +++ /dev/null @@ -1,161 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.js'; -import decrypt from '../../runtime/decrypt.js'; -import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import isObject from '../../lib/is_object.js'; -import decryptKeyManagement from '../../lib/decrypt_key_management.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import generateCek from '../../lib/cek.js'; -import validateCrit from '../../lib/validate_crit.js'; -import validateAlgorithms from '../../lib/validate_algorithms.js'; -export async function flattenedDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid('Flattened JWE must be an object'); - } - if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { - throw new JWEInvalid('JOSE Header missing'); - } - if (jwe.iv !== undefined && 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 !== undefined && typeof jwe.tag !== 'string') { - throw new JWEInvalid('JWE Authentication Tag incorrect type'); - } - if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { - throw new JWEInvalid('JWE Protected Header incorrect type'); - } - if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { - throw new JWEInvalid('JWE Encrypted Key incorrect type'); - } - if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { - throw new JWEInvalid('JWE AAD incorrect type'); - } - if (jwe.header !== undefined && !isObject(jwe.header)) { - throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); - } - if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { - throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader = base64url(jwe.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } - catch { - throw new JWEInvalid('JWE Protected Header is invalid'); - } - } - if (!isDisjoint(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, - }; - validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== undefined) { - 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 && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && - validateAlgorithms('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 !== undefined) { - try { - encryptedKey = base64url(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; - } - let cek; - try { - cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); - } - catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err; - } - cek = generateCek(enc); - } - let iv; - let tag; - if (jwe.iv !== undefined) { - try { - iv = base64url(jwe.iv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the iv'); - } - } - if (jwe.tag !== undefined) { - try { - tag = base64url(jwe.tag); - } - catch { - throw new JWEInvalid('Failed to base64url decode the tag'); - } - } - const protectedHeader = encoder.encode(jwe.protected ?? ''); - let additionalData; - if (jwe.aad !== undefined) { - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); - } - else { - additionalData = protectedHeader; - } - let ciphertext; - try { - ciphertext = base64url(jwe.ciphertext); - } - catch { - throw new JWEInvalid('Failed to base64url decode the ciphertext'); - } - const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData); - const result = { plaintext }; - if (jwe.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== undefined) { - try { - result.additionalAuthenticatedData = base64url(jwe.aad); - } - catch { - throw new JWEInvalid('Failed to base64url decode the aad'); - } - } - if (jwe.unprotected !== undefined) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== undefined) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} diff --git a/dist/browser/jwe/flattened/encrypt.js b/dist/browser/jwe/flattened/encrypt.js deleted file mode 100644 index 8f40a94eb2..0000000000 --- a/dist/browser/jwe/flattened/encrypt.js +++ /dev/null @@ -1,153 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.js'; -import { unprotected } from '../../lib/private_symbols.js'; -import encrypt from '../../runtime/encrypt.js'; -import encryptKeyManagement from '../../lib/encrypt_key_management.js'; -import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import validateCrit from '../../lib/validate_crit.js'; -export class FlattenedEncrypt { - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError('plaintext must be an instance of Uint8Array'); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); - } - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader, - }; - validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== 'string' || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } - else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } - else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } - else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = encoder.encode(''); - } - if (this._aad) { - aadMember = base64url(this._aad); - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); - } - else { - additionalData = protectedHeader; - } - const { ciphertext, tag, iv } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: base64url(ciphertext), - }; - if (iv) { - jwe.iv = base64url(iv); - } - if (tag) { - jwe.tag = base64url(tag); - } - if (encryptedKey) { - jwe.encrypted_key = base64url(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; - } -} diff --git a/dist/browser/jwe/general/decrypt.js b/dist/browser/jwe/general/decrypt.js deleted file mode 100644 index 659958a8bc..0000000000 --- a/dist/browser/jwe/general/decrypt.js +++ /dev/null @@ -1,31 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.js'; -import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; -import isObject from '../../lib/is_object.js'; -export async function generalDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid('General JWE must be an object'); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { - throw new JWEInvalid('JWE Recipients missing or incorrect type'); - } - if (!jwe.recipients.length) { - throw new JWEInvalid('JWE Recipients has no members'); - } - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected, - }, key, options); - } - catch { - } - } - throw new JWEDecryptionFailed(); -} diff --git a/dist/browser/jwe/general/encrypt.js b/dist/browser/jwe/general/encrypt.js deleted file mode 100644 index aa9aa2ab20..0000000000 --- a/dist/browser/jwe/general/encrypt.js +++ /dev/null @@ -1,174 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.js'; -import { unprotected } from '../../lib/private_symbols.js'; -import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import generateCek from '../../lib/cek.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import encryptKeyManagement from '../../lib/encrypt_key_management.js'; -import { encode as base64url } from '../../runtime/base64url.js'; -import validateCrit from '../../lib/validate_crit.js'; -class IndividualRecipient { - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } -} -export class GeneralEncrypt { - constructor(plaintext) { - this._recipients = []; - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new JWEInvalid('at least one recipient must be added'); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .encrypt(recipient.key, { ...recipient.options }); - const jwe = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag, - }; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe.recipients[0].header = flattened.header; - return jwe; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === 'dir' || alg === 'ECDH-ES') { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } - else if (enc !== joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - } - const cek = generateCek(enc); - const jwe = { - ciphertext: '', - iv: '', - recipients: [], - tag: '', - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; - if (i === 0) { - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setContentEncryptionKey(cek) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .setKeyManagementParameters({ p2c }) - .encrypt(recipient.key, { - ...recipient.options, - [unprotected]: true, - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg || - this._protectedHeader?.alg || - this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = base64url(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } -} diff --git a/dist/browser/jwk/embedded.js b/dist/browser/jwk/embedded.js deleted file mode 100644 index aa43b2ff75..0000000000 --- a/dist/browser/jwk/embedded.js +++ /dev/null @@ -1,17 +0,0 @@ -import { importJWK } from '../key/import.js'; -import isObject from '../lib/is_object.js'; -import { JWSInvalid } from '../util/errors.js'; -export async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header, - }; - if (!isObject(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; -} diff --git a/dist/browser/jwk/thumbprint.js b/dist/browser/jwk/thumbprint.js deleted file mode 100644 index 0e99265e40..0000000000 --- a/dist/browser/jwk/thumbprint.js +++ /dev/null @@ -1,53 +0,0 @@ -import digest from '../runtime/digest.js'; -import { encode as base64url } from '../runtime/base64url.js'; -import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; -import { encoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -const check = (value, description) => { - if (typeof value !== 'string' || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } -}; -export async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object'); - } - digestAlgorithm ?? (digestAlgorithm = 'sha256'); - if (digestAlgorithm !== 'sha256' && - digestAlgorithm !== 'sha384' && - digestAlgorithm !== 'sha512') { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case 'EC': - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case 'OKP': - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case 'RSA': - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case 'oct': - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encoder.encode(JSON.stringify(components)); - return base64url(await digest(digestAlgorithm, data)); -} -export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ?? (digestAlgorithm = 'sha256'); - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; -} diff --git a/dist/browser/jwks/local.js b/dist/browser/jwks/local.js deleted file mode 100644 index 16db61e70d..0000000000 --- a/dist/browser/jwks/local.js +++ /dev/null @@ -1,121 +0,0 @@ -import { importJWK } from '../key/import.js'; -import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; -import isObject from '../lib/is_object.js'; -function getKtyFromAlg(alg) { - switch (typeof alg === 'string' && alg.slice(0, 2)) { - case 'RS': - case 'PS': - return 'RSA'; - case 'ES': - return 'EC'; - case 'Ed': - return 'OKP'; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return (jwks && - typeof jwks === 'object' && - Array.isArray(jwks.keys) && - jwks.keys.every(isJWKLike)); -} -function isJWKLike(key) { - return isObject(key); -} -function clone(obj) { - if (typeof structuredClone === 'function') { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); -} -class LocalJWKSet { - constructor(jwks) { - this._cached = new WeakMap(); - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid('JSON Web Key Set malformed'); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === 'string') { - candidate = kid === jwk.kid; - } - if (candidate && typeof jwk.alg === 'string') { - candidate = alg === jwk.alg; - } - if (candidate && typeof jwk.use === 'string') { - candidate = jwk.use === 'sig'; - } - if (candidate && Array.isArray(jwk.key_ops)) { - candidate = jwk.key_ops.includes('verify'); - } - if (candidate && alg === 'EdDSA') { - candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; - } - if (candidate) { - switch (alg) { - case 'ES256': - candidate = jwk.crv === 'P-256'; - break; - case 'ES256K': - candidate = jwk.crv === 'secp256k1'; - break; - case 'ES384': - candidate = jwk.crv === 'P-384'; - break; - case 'ES512': - candidate = jwk.crv === 'P-521'; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) { - try { - yield await importWithAlgCache(_cached, jwk, alg); - } - catch { } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } -} -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === undefined) { - const key = await importJWK({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWKSInvalid('JSON Web Key Set members must be public keys'); - } - cached[alg] = key; - } - return cached[alg]; -} -export function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return localJWKSet; -} diff --git a/dist/browser/jwks/remote.js b/dist/browser/jwks/remote.js deleted file mode 100644 index 0f27a66009..0000000000 --- a/dist/browser/jwks/remote.js +++ /dev/null @@ -1,139 +0,0 @@ -import fetchJwks from '../runtime/fetch_jwks.js'; -import { JWKSNoMatchingKey } from '../util/errors.js'; -import { createLocalJWKSet } from './local.js'; -import isObject from '../lib/is_object.js'; -function isCloudflareWorkers() { - return (typeof WebSocketPair !== 'undefined' || - (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || - (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); -} -let USER_AGENT; -if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { - const NAME = 'jose'; - const VERSION = 'v5.9.1'; - USER_AGENT = `${NAME}/${VERSION}`; -} -export const jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== 'object' || input === null) { - return false; - } - if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!('jwks' in input) || - !isObject(input.jwks) || - !Array.isArray(input.jwks.keys) || - !Array.prototype.every.call(input.jwks.keys, isObject)) { - return false; - } - return true; -} -class RemoteJWKSet { - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError('url must be an instance of URL'); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = - typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; - this._cooldownDuration = - typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; - this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; - if (options?.[jwksCache] !== undefined) { - this._cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = createLocalJWKSet(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cooldownDuration - : false; - } - fresh() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cacheMaxAge - : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } - catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = undefined; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has('User-Agent')) { - headers.set('User-Agent', USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) - .then((json) => { - this._local = createLocalJWKSet(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = undefined; - }) - .catch((err) => { - this._pendingFetch = undefined; - throw err; - })); - await this._pendingFetch; - } -} -export function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false, - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false, - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false, - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false, - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return remoteJWKSet; -} -export const experimental_jwksCache = jwksCache; diff --git a/dist/browser/jws/compact/sign.js b/dist/browser/jws/compact/sign.js deleted file mode 100644 index b8e5ba0e2b..0000000000 --- a/dist/browser/jws/compact/sign.js +++ /dev/null @@ -1,17 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.js'; -export class CompactSign { - constructor(payload) { - this._flattened = new FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === undefined) { - throw new TypeError('use the flattened module for creating JWS with b64: false'); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -} diff --git a/dist/browser/jws/compact/verify.js b/dist/browser/jws/compact/verify.js deleted file mode 100644 index c651ffb944..0000000000 --- a/dist/browser/jws/compact/verify.js +++ /dev/null @@ -1,21 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.js'; -import { JWSInvalid } from '../../util/errors.js'; -import { decoder } from '../../lib/buffer_utils.js'; -export async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== 'string') { - throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); - if (length !== 3) { - throw new JWSInvalid('Invalid Compact JWS'); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} diff --git a/dist/browser/jws/flattened/sign.js b/dist/browser/jws/flattened/sign.js deleted file mode 100644 index 0da3ebfc06..0000000000 --- a/dist/browser/jws/flattened/sign.js +++ /dev/null @@ -1,81 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.js'; -import sign from '../../runtime/sign.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import { JWSInvalid } from '../../util/errors.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js'; -import validateCrit from '../../lib/validate_crit.js'; -export class FlattenedSign { - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError('payload must be an instance of Uint8Array'); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); - } - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { - throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - }; - const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== 'boolean') { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyTypeWithJwk(alg, key, 'sign'); - let payload = this._payload; - if (b64) { - payload = encoder.encode(base64url(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = encoder.encode(''); - } - const data = concat(protectedHeader, encoder.encode('.'), payload); - const signature = await sign(alg, key, data); - const jws = { - signature: base64url(signature), - payload: '', - }; - if (b64) { - jws.payload = decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = decoder.decode(protectedHeader); - } - return jws; - } -} diff --git a/dist/browser/jws/flattened/verify.js b/dist/browser/jws/flattened/verify.js deleted file mode 100644 index 188cb92201..0000000000 --- a/dist/browser/jws/flattened/verify.js +++ /dev/null @@ -1,122 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.js'; -import verify from '../../runtime/verify.js'; -import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; -import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import isObject from '../../lib/is_object.js'; -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js'; -import validateCrit from '../../lib/validate_crit.js'; -import validateAlgorithms from '../../lib/validate_algorithms.js'; -import { isJWK } from '../../lib/is_jwk.js'; -import { importJWK } from '../../key/import.js'; -export async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid('Flattened JWS must be an object'); - } - if (jws.protected === undefined && jws.header === undefined) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== undefined && typeof jws.protected !== 'string') { - throw new JWSInvalid('JWS Protected Header incorrect type'); - } - if (jws.payload === undefined) { - throw new JWSInvalid('JWS Payload missing'); - } - if (typeof jws.signature !== 'string') { - throw new JWSInvalid('JWS Signature missing or incorrect type'); - } - if (jws.header !== undefined && !isObject(jws.header)) { - throw new JWSInvalid('JWS Unprotected Header incorrect type'); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = base64url(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } - catch { - throw new JWSInvalid('JWS Protected Header is invalid'); - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jws.header, - }; - const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = parsedProt.b64; - if (typeof b64 !== 'boolean') { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validateAlgorithms('algorithms', options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== 'string') { - throw new JWSInvalid('JWS Payload must be a string'); - } - } - else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jws); - resolvedKey = true; - checkKeyTypeWithJwk(alg, key, 'verify'); - if (isJWK(key)) { - key = await importJWK(key, alg); - } - } - else { - checkKeyTypeWithJwk(alg, key, 'verify'); - } - const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = base64url(jws.signature); - } - catch { - throw new JWSInvalid('Failed to base64url decode the signature'); - } - const verified = await verify(alg, key, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = base64url(jws.payload); - } - catch { - throw new JWSInvalid('Failed to base64url decode the payload'); - } - } - else if (typeof jws.payload === 'string') { - payload = encoder.encode(jws.payload); - } - else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jws.header !== undefined) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} diff --git a/dist/browser/jws/general/sign.js b/dist/browser/jws/general/sign.js deleted file mode 100644 index 0e0d645cac..0000000000 --- a/dist/browser/jws/general/sign.js +++ /dev/null @@ -1,67 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.js'; -import { JWSInvalid } from '../../util/errors.js'; -class IndividualSignature { - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } -} -export class GeneralSign { - constructor(payload) { - this._signatures = []; - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new JWSInvalid('at least one signature must be added'); - } - const jws = { - signatures: [], - payload: '', - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } - else if (jws.payload !== payload) { - throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); - } - jws.signatures.push(rest); - } - return jws; - } -} diff --git a/dist/browser/jws/general/verify.js b/dist/browser/jws/general/verify.js deleted file mode 100644 index c511b722dc..0000000000 --- a/dist/browser/jws/general/verify.js +++ /dev/null @@ -1,24 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.js'; -import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; -import isObject from '../../lib/is_object.js'; -export async function generalVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid('General JWS must be an object'); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { - throw new JWSInvalid('JWS Signatures missing or incorrect type'); - } - for (const signature of jws.signatures) { - try { - return await flattenedVerify({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature, - }, key, options); - } - catch { - } - } - throw new JWSSignatureVerificationFailed(); -} diff --git a/dist/browser/jwt/decrypt.js b/dist/browser/jwt/decrypt.js deleted file mode 100644 index c3a85fe5af..0000000000 --- a/dist/browser/jwt/decrypt.js +++ /dev/null @@ -1,23 +0,0 @@ -import { compactDecrypt } from '../jwe/compact/decrypt.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { JWTClaimValidationFailed } from '../util/errors.js'; -export async function jwtDecrypt(jwt, key, options) { - const decrypted = await compactDecrypt(jwt, key, options); - const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); - } - if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); - } - if (protectedHeader.aud !== undefined && - JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); - } - const result = { payload, protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} diff --git a/dist/browser/jwt/encrypt.js b/dist/browser/jwt/encrypt.js deleted file mode 100644 index 15252957ae..0000000000 --- a/dist/browser/jwt/encrypt.js +++ /dev/null @@ -1,68 +0,0 @@ -import { CompactEncrypt } from '../jwe/compact/encrypt.js'; -import { encoder } from '../lib/buffer_utils.js'; -import { ProduceJWT } from './produce.js'; -export class EncryptJWT extends ProduceJWT { - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } -} diff --git a/dist/browser/jwt/produce.js b/dist/browser/jwt/produce.js deleted file mode 100644 index c64a09bf2a..0000000000 --- a/dist/browser/jwt/produce.js +++ /dev/null @@ -1,75 +0,0 @@ -import epoch from '../lib/epoch.js'; -import isObject from '../lib/is_object.js'; -import secs from '../lib/secs.js'; -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -export class ProduceJWT { - constructor(payload = {}) { - if (!isObject(payload)) { - throw new TypeError('JWT Claims Set MUST be an object'); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) }; - } - else { - this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) }; - } - else { - this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === 'undefined') { - this._payload = { ...this._payload, iat: epoch(new Date()) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) }; - } - else if (typeof input === 'string') { - this._payload = { - ...this._payload, - iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)), - }; - } - else { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }; - } - return this; - } -} diff --git a/dist/browser/jwt/sign.js b/dist/browser/jwt/sign.js deleted file mode 100644 index caa6c4cabe..0000000000 --- a/dist/browser/jwt/sign.js +++ /dev/null @@ -1,20 +0,0 @@ -import { CompactSign } from '../jws/compact/sign.js'; -import { JWTInvalid } from '../util/errors.js'; -import { encoder } from '../lib/buffer_utils.js'; -import { ProduceJWT } from './produce.js'; -export class SignJWT extends ProduceJWT { - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && - this._protectedHeader.crit.includes('b64') && - this._protectedHeader.b64 === false) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - return sig.sign(key, options); - } -} diff --git a/dist/browser/jwt/unsecured.js b/dist/browser/jwt/unsecured.js deleted file mode 100644 index 41c7c33bb5..0000000000 --- a/dist/browser/jwt/unsecured.js +++ /dev/null @@ -1,32 +0,0 @@ -import * as base64url from '../runtime/base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import { JWTInvalid } from '../util/errors.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { ProduceJWT } from './produce.js'; -export class UnsecuredJWT extends ProduceJWT { - encode() { - const header = base64url.encode(JSON.stringify({ alg: 'none' })); - const payload = base64url.encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== 'string') { - throw new JWTInvalid('Unsecured JWT must be a string'); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); - if (length !== 3 || signature !== '') { - throw new JWTInvalid('Invalid Unsecured JWT'); - } - let header; - try { - header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); - if (header.alg !== 'none') - throw new Error(); - } - catch { - throw new JWTInvalid('Invalid Unsecured JWT'); - } - const payload = jwtPayload(header, base64url.decode(encodedPayload), options); - return { payload, header }; - } -} diff --git a/dist/browser/jwt/verify.js b/dist/browser/jwt/verify.js deleted file mode 100644 index f5d99d06b5..0000000000 --- a/dist/browser/jwt/verify.js +++ /dev/null @@ -1,15 +0,0 @@ -import { compactVerify } from '../jws/compact/verify.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { JWTInvalid } from '../util/errors.js'; -export async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - const payload = jwtPayload(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} diff --git a/dist/browser/key/export.js b/dist/browser/key/export.js deleted file mode 100644 index e4017047cd..0000000000 --- a/dist/browser/key/export.js +++ /dev/null @@ -1,12 +0,0 @@ -import { toSPKI as exportPublic } from '../runtime/asn1.js'; -import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; -import keyToJWK from '../runtime/key_to_jwk.js'; -export async function exportSPKI(key) { - return exportPublic(key); -} -export async function exportPKCS8(key) { - return exportPrivate(key); -} -export async function exportJWK(key) { - return keyToJWK(key); -} diff --git a/dist/browser/key/generate_key_pair.js b/dist/browser/key/generate_key_pair.js deleted file mode 100644 index 03b9ee54cd..0000000000 --- a/dist/browser/key/generate_key_pair.js +++ /dev/null @@ -1,4 +0,0 @@ -import { generateKeyPair as generate } from '../runtime/generate.js'; -export async function generateKeyPair(alg, options) { - return generate(alg, options); -} diff --git a/dist/browser/key/generate_secret.js b/dist/browser/key/generate_secret.js deleted file mode 100644 index 58f308a543..0000000000 --- a/dist/browser/key/generate_secret.js +++ /dev/null @@ -1,4 +0,0 @@ -import { generateSecret as generate } from '../runtime/generate.js'; -export async function generateSecret(alg, options) { - return generate(alg, options); -} diff --git a/dist/browser/key/import.js b/dist/browser/key/import.js deleted file mode 100644 index d2ddb2a1ad..0000000000 --- a/dist/browser/key/import.js +++ /dev/null @@ -1,45 +0,0 @@ -import { decode as decodeBase64URL } from '../runtime/base64url.js'; -import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js'; -import asKeyObject from '../runtime/jwk_to_key.js'; -import { JOSENotSupported } from '../util/errors.js'; -import isObject from '../lib/is_object.js'; -export async function importSPKI(spki, alg, options) { - if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return fromSPKI(spki, alg, options); -} -export async function importX509(x509, alg, options) { - if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return fromX509(x509, alg, options); -} -export async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return fromPKCS8(pkcs8, alg, options); -} -export async function importJWK(jwk, alg) { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object'); - } - alg || (alg = jwk.alg); - switch (jwk.kty) { - case 'oct': - if (typeof jwk.k !== 'string' || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return decodeBase64URL(jwk.k); - case 'RSA': - if (jwk.oth !== undefined) { - throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - case 'EC': - case 'OKP': - return asKeyObject({ ...jwk, alg }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} diff --git a/dist/browser/lib/aesgcmkw.js b/dist/browser/lib/aesgcmkw.js deleted file mode 100644 index 47d9d5e3b7..0000000000 --- a/dist/browser/lib/aesgcmkw.js +++ /dev/null @@ -1,16 +0,0 @@ -import encrypt from '../runtime/encrypt.js'; -import decrypt from '../runtime/decrypt.js'; -import { encode as base64url } from '../runtime/base64url.js'; -export async function wrap(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: base64url(wrapped.iv), - tag: base64url(wrapped.tag), - }; -} -export async function unwrap(alg, key, encryptedKey, iv, tag) { - const jweAlgorithm = alg.slice(0, 7); - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); -} diff --git a/dist/browser/lib/buffer_utils.js b/dist/browser/lib/buffer_utils.js deleted file mode 100644 index b261a58ed4..0000000000 --- a/dist/browser/lib/buffer_utils.js +++ /dev/null @@ -1,51 +0,0 @@ -import digest from '../runtime/digest.js'; -export const encoder = new TextEncoder(); -export const decoder = new TextDecoder(); -const MAX_INT32 = 2 ** 32; -export 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; -} -export function p2s(alg, p2sInput) { - return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); -} -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 & 0xff], offset); -} -export 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; -} -export function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -export function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -export 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('sha256', buf), iter * 32); - } - return res.slice(0, bits >> 3); -} diff --git a/dist/browser/lib/cek.js b/dist/browser/lib/cek.js deleted file mode 100644 index 34697d3ac2..0000000000 --- a/dist/browser/lib/cek.js +++ /dev/null @@ -1,20 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -import random from '../runtime/random.js'; -export function bitLength(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}`); - } -} -export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/browser/lib/check_iv_length.js b/dist/browser/lib/check_iv_length.js deleted file mode 100644 index dcd28d3a9d..0000000000 --- a/dist/browser/lib/check_iv_length.js +++ /dev/null @@ -1,8 +0,0 @@ -import { JWEInvalid } from '../util/errors.js'; -import { bitLength } from './iv.js'; -const checkIvLength = (enc, iv) => { - if (iv.length << 3 !== bitLength(enc)) { - throw new JWEInvalid('Invalid Initialization Vector length'); - } -}; -export default checkIvLength; diff --git a/dist/browser/lib/check_key_type.js b/dist/browser/lib/check_key_type.js deleted file mode 100644 index bcefa4ff61..0000000000 --- a/dist/browser/lib/check_key_type.js +++ /dev/null @@ -1,77 +0,0 @@ -import { withAlg as invalidKeyInput } from './invalid_key_input.js'; -import isKeyLike, { types } from '../runtime/is_key_like.js'; -import * as jwk from './is_jwk.js'; -const tag = (key) => key?.[Symbol.toStringTag]; -const jwkMatchesOp = (alg, key, usage) => { - if (key.use !== undefined && key.use !== 'sig') { - throw new TypeError('Invalid key for this operation, when present its use must be sig'); - } - if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== undefined && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; -}; -const symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && jwk.isJWK(key)) { - if (jwk.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 (!isKeyLike(key)) { - throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null)); - } - if (key.type !== 'secret') { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -const asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && jwk.isJWK(key)) { - switch (usage) { - case 'sign': - if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - case 'verify': - if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a public JWK`); - } - } - if (!isKeyLike(key)) { - throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null)); - } - if (key.type === 'secret') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === 'sign' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === 'decrypt' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === 'verify' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === 'encrypt' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith('HS') || - alg === 'dir' || - alg.startsWith('PBES2') || - /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } - else { - asymmetricTypeCheck(alg, key, usage, allowJwk); - } -} -export default checkKeyType.bind(undefined, false); -export const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true); diff --git a/dist/browser/lib/check_p2s.js b/dist/browser/lib/check_p2s.js deleted file mode 100644 index a65289fa7a..0000000000 --- a/dist/browser/lib/check_p2s.js +++ /dev/null @@ -1,6 +0,0 @@ -import { JWEInvalid } from '../util/errors.js'; -export default function checkP2s(p2s) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); - } -} diff --git a/dist/browser/lib/crypto_key.js b/dist/browser/lib/crypto_key.js deleted file mode 100644 index 807e951a53..0000000000 --- a/dist/browser/lib/crypto_key.js +++ /dev/null @@ -1,152 +0,0 @@ -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 getNamedCurve(alg) { - switch (alg) { - case 'ES256': - return 'P-256'; - case 'ES384': - return 'P-384'; - case 'ES512': - return 'P-521'; - default: - throw new Error('unreachable'); - } -} -function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = 'CryptoKey does not support this operation, its usages must include '; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(', ')}, or ${last}.`; - } - else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } - else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } -} -export function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': { - if (!isAlgorithm(key.algorithm, 'HMAC')) - throw unusable('HMAC'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'RS256': - case 'RS384': - case 'RS512': { - if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) - throw unusable('RSASSA-PKCS1-v1_5'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'PS256': - case 'PS384': - case 'PS512': { - if (!isAlgorithm(key.algorithm, 'RSA-PSS')) - throw unusable('RSA-PSS'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'EdDSA': { - if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { - throw unusable('Ed25519 or Ed448'); - } - break; - } - case 'ES256': - case 'ES384': - case 'ES512': { - if (!isAlgorithm(key.algorithm, 'ECDSA')) - throw unusable('ECDSA'); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, 'algorithm.namedCurve'); - break; - } - default: - throw new TypeError('CryptoKey does not support this operation'); - } - checkUsage(key, usages); -} -export function checkEncCryptoKey(key, alg, ...usages) { - 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': - case 'X448': - break; - default: - throw unusable('ECDH, X25519, or X448'); - } - 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, usages); -} diff --git a/dist/browser/lib/decrypt_key_management.js b/dist/browser/lib/decrypt_key_management.js deleted file mode 100644 index 8cbcdd518e..0000000000 --- a/dist/browser/lib/decrypt_key_management.js +++ /dev/null @@ -1,129 +0,0 @@ -import { unwrap as aesKw } from '../runtime/aeskw.js'; -import * as ECDH from '../runtime/ecdhes.js'; -import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; -import { decrypt as rsaEs } from '../runtime/rsaes.js'; -import { decode as base64url } from '../runtime/base64url.js'; -import normalize from '../runtime/normalize_key.js'; -import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; -import { bitLength as cekLength } from '../lib/cek.js'; -import { importJWK } from '../key/import.js'; -import checkKeyType from './check_key_type.js'; -import isObject from './is_object.js'; -import { unwrap as aesGcmKw } from './aesgcmkw.js'; -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - checkKeyType(alg, key, 'decrypt'); - key = (await normalize.normalizePrivateKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); - return key; - } - case 'ECDH-ES': - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ECDH.ecdhAllowed(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); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== undefined) { - if (typeof joseHeader.apu !== 'string') - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - try { - partyUInfo = base64url(joseHeader.apu); - } - catch { - throw new JWEInvalid('Failed to base64url decode the apu'); - } - } - if (joseHeader.apv !== undefined) { - if (typeof joseHeader.apv !== 'string') - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - try { - partyVInfo = base64url(joseHeader.apv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the apv'); - } - } - const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg === 'ECDH-ES') - return sharedSecret; - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return aesKw(alg.slice(-6), sharedSecret, encryptedKey); - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return rsaEs(alg, key, encryptedKey); - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - if (encryptedKey === undefined) - 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 || 10000; - 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 = base64url(joseHeader.p2s); - } - catch { - throw new JWEInvalid('Failed to base64url decode the p2s'); - } - return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s); - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return aesKw(alg, key, encryptedKey); - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - if (encryptedKey === undefined) - 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 = base64url(joseHeader.iv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the iv'); - } - let tag; - try { - tag = base64url(joseHeader.tag); - } - catch { - throw new JWEInvalid('Failed to base64url decode the tag'); - } - return aesGcmKw(alg, key, encryptedKey, iv, tag); - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } -} -export default decryptKeyManagement; diff --git a/dist/browser/lib/encrypt_key_management.js b/dist/browser/lib/encrypt_key_management.js deleted file mode 100644 index 0f8019299b..0000000000 --- a/dist/browser/lib/encrypt_key_management.js +++ /dev/null @@ -1,89 +0,0 @@ -import { wrap as aesKw } from '../runtime/aeskw.js'; -import * as ECDH from '../runtime/ecdhes.js'; -import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; -import { encrypt as rsaEs } from '../runtime/rsaes.js'; -import { encode as base64url } from '../runtime/base64url.js'; -import normalize from '../runtime/normalize_key.js'; -import generateCek, { bitLength as cekLength } from '../lib/cek.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { exportJWK } from '../key/export.js'; -import checkKeyType from './check_key_type.js'; -import { wrap as aesGcmKw } from './aesgcmkw.js'; -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - checkKeyType(alg, key, 'encrypt'); - key = (await normalize.normalizePublicKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - cek = key; - break; - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!ECDH.ecdhAllowed(key)) { - throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); - } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === 'EC') - parameters.epk.y = y; - if (apu) - parameters.apu = base64url(apu); - if (apv) - parameters.apv = base64url(apv); - if (alg === 'ECDH-ES') { - cek = sharedSecret; - break; - } - cek = providedCek || generateCek(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await aesKw(kwAlg, sharedSecret, cek); - break; - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - cek = providedCek || generateCek(enc); - encryptedKey = await rsaEs(alg, key, cek); - break; - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - cek = providedCek || generateCek(enc); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); - break; - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - cek = providedCek || generateCek(enc); - encryptedKey = await aesKw(alg, key, cek); - break; - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - cek = providedCek || generateCek(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - return { cek, encryptedKey, parameters }; -} -export default encryptKeyManagement; diff --git a/dist/browser/lib/epoch.js b/dist/browser/lib/epoch.js deleted file mode 100644 index e405e4b2df..0000000000 --- a/dist/browser/lib/epoch.js +++ /dev/null @@ -1 +0,0 @@ -export default (date) => Math.floor(date.getTime() / 1000); diff --git a/dist/browser/lib/format_pem.js b/dist/browser/lib/format_pem.js deleted file mode 100644 index 81673f256f..0000000000 --- a/dist/browser/lib/format_pem.js +++ /dev/null @@ -1,4 +0,0 @@ -export default (b64, descriptor) => { - const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); - return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; -}; diff --git a/dist/browser/lib/invalid_key_input.js b/dist/browser/lib/invalid_key_input.js deleted file mode 100644 index 5796a2eb69..0000000000 --- a/dist/browser/lib/invalid_key_input.js +++ /dev/null @@ -1,31 +0,0 @@ -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; -} -export default (actual, ...types) => { - return message('Key must be ', actual, ...types); -}; -export function withAlg(alg, actual, ...types) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types); -} diff --git a/dist/browser/lib/is_disjoint.js b/dist/browser/lib/is_disjoint.js deleted file mode 100644 index 6f643502dc..0000000000 --- a/dist/browser/lib/is_disjoint.js +++ /dev/null @@ -1,22 +0,0 @@ -const isDisjoint = (...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; -}; -export default isDisjoint; diff --git a/dist/browser/lib/is_jwk.js b/dist/browser/lib/is_jwk.js deleted file mode 100644 index 7e0321308a..0000000000 --- a/dist/browser/lib/is_jwk.js +++ /dev/null @@ -1,13 +0,0 @@ -import isObject from './is_object.js'; -export function isJWK(key) { - return isObject(key) && typeof key.kty === 'string'; -} -export function isPrivateJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'string'; -} -export function isPublicJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'undefined'; -} -export function isSecretJWK(key) { - return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string'; -} diff --git a/dist/browser/lib/is_object.js b/dist/browser/lib/is_object.js deleted file mode 100644 index 4955e93225..0000000000 --- a/dist/browser/lib/is_object.js +++ /dev/null @@ -1,16 +0,0 @@ -function isObjectLike(value) { - return typeof value === 'object' && value !== null; -} -export default function isObject(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; -} diff --git a/dist/browser/lib/iv.js b/dist/browser/lib/iv.js deleted file mode 100644 index cab2a12729..0000000000 --- a/dist/browser/lib/iv.js +++ /dev/null @@ -1,20 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -import random from '../runtime/random.js'; -export 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}`); - } -} -export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/browser/lib/jwt_claims_set.js b/dist/browser/lib/jwt_claims_set.js deleted file mode 100644 index 64b6bd0a39..0000000000 --- a/dist/browser/lib/jwt_claims_set.js +++ /dev/null @@ -1,103 +0,0 @@ -import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; -import { decoder } from './buffer_utils.js'; -import epoch from './epoch.js'; -import secs from './secs.js'; -import isObject from './is_object.js'; -const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); -const checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -export default (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } - catch { - } - if (!isObject(payload)) { - throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); - } - const { typ } = options; - if (typ && - (typeof protectedHeader.typ !== 'string' || - normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== undefined) - presenceCheck.push('iat'); - if (audience !== undefined) - presenceCheck.push('aud'); - if (subject !== undefined) - presenceCheck.push('sub'); - if (issuer !== undefined) - presenceCheck.push('iss'); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); - } - if (audience && - !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); - } - let tolerance; - switch (typeof options.clockTolerance) { - case 'string': - tolerance = secs(options.clockTolerance); - break; - case 'number': - tolerance = options.clockTolerance; - break; - case 'undefined': - tolerance = 0; - break; - default: - throw new TypeError('Invalid clockTolerance option type'); - } - const { currentDate } = options; - const now = epoch(currentDate || new Date()); - if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); - } - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); - } - } - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); - } - } - return payload; -}; diff --git a/dist/browser/lib/private_symbols.js b/dist/browser/lib/private_symbols.js deleted file mode 100644 index fce302b11e..0000000000 --- a/dist/browser/lib/private_symbols.js +++ /dev/null @@ -1 +0,0 @@ -export const unprotected = Symbol(); diff --git a/dist/browser/lib/secs.js b/dist/browser/lib/secs.js deleted file mode 100644 index c99507450a..0000000000 --- a/dist/browser/lib/secs.js +++ /dev/null @@ -1,55 +0,0 @@ -const minute = 60; -const hour = minute * 60; -const day = hour * 24; -const week = day * 7; -const year = day * 365.25; -const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -export default (str) => { - const matched = REGEX.exec(str); - if (!matched || (matched[4] && matched[1])) { - throw new TypeError('Invalid time period format'); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - numericDate = Math.round(value); - break; - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - numericDate = Math.round(value * minute); - break; - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - numericDate = Math.round(value * hour); - break; - case 'day': - case 'days': - case 'd': - numericDate = Math.round(value * day); - break; - case 'week': - case 'weeks': - case 'w': - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === '-' || matched[4] === 'ago') { - return -numericDate; - } - return numericDate; -}; diff --git a/dist/browser/lib/validate_algorithms.js b/dist/browser/lib/validate_algorithms.js deleted file mode 100644 index a6a7918571..0000000000 --- a/dist/browser/lib/validate_algorithms.js +++ /dev/null @@ -1,11 +0,0 @@ -const validateAlgorithms = (option, algorithms) => { - if (algorithms !== undefined && - (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return undefined; - } - return new Set(algorithms); -}; -export default validateAlgorithms; diff --git a/dist/browser/lib/validate_crit.js b/dist/browser/lib/validate_crit.js deleted file mode 100644 index 0d1b052c1e..0000000000 --- a/dist/browser/lib/validate_crit.js +++ /dev/null @@ -1,34 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === undefined) { - return 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 !== undefined) { - 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] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} -export default validateCrit; diff --git a/dist/browser/package.json b/dist/browser/package.json deleted file mode 100644 index 8fb7e8f61b..0000000000 --- a/dist/browser/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type":"module","sideEffects":false} diff --git a/dist/browser/runtime/aeskw.js b/dist/browser/runtime/aeskw.js deleted file mode 100644 index bb7dff8a5b..0000000000 --- a/dist/browser/runtime/aeskw.js +++ /dev/null @@ -1,32 +0,0 @@ -import bogusWebCrypto from './bogus.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -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 (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]); - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); -} -export const wrap = async (alg, key, cek) => { - const cryptoKey = await getCryptoKey(key, alg, 'wrapKey'); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); - return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')); -}; -export const unwrap = async (alg, key, encryptedKey) => { - const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey'); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto); - return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); -}; diff --git a/dist/browser/runtime/asn1.js b/dist/browser/runtime/asn1.js deleted file mode 100644 index 9b44f57b2f..0000000000 --- a/dist/browser/runtime/asn1.js +++ /dev/null @@ -1,201 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { encodeBase64, decodeBase64 } from './base64url.js'; -import formatPEM from '../lib/format_pem.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { types } from './is_key_like.js'; -const genericExport = async (keyType, keyFormat, key) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); -}; -export const toSPKI = (key) => { - return genericExport('public', 'spki', key); -}; -export const toPKCS8 = (key) => { - return genericExport('private', 'pkcs8', key); -}; -const findOid = (keyData, oid, from = 0) => { - if (from === 0) { - oid.unshift(oid.length); - oid.unshift(0x06); - } - const i = keyData.indexOf(oid[0], from); - if (i === -1) - return false; - const sub = keyData.subarray(i, i + oid.length); - if (sub.length !== oid.length) - return false; - return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); -}; -const getNamedCurve = (keyData) => { - switch (true) { - case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): - return 'P-256'; - case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): - return 'P-384'; - case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): - return 'P-521'; - case findOid(keyData, [0x2b, 0x65, 0x6e]): - return 'X25519'; - case findOid(keyData, [0x2b, 0x65, 0x6f]): - return 'X448'; - case findOid(keyData, [0x2b, 0x65, 0x70]): - return 'Ed25519'; - case findOid(keyData, [0x2b, 0x65, 0x71]): - return 'Ed448'; - default: - throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type'); - } -}; -const genericImport = async (replace, keyFormat, pem, alg, options) => { - let algorithm; - let keyUsages; - const keyData = new Uint8Array(atob(pem.replace(replace, '')) - .split('') - .map((c) => c.charCodeAt(0))); - const isPublic = keyFormat === 'spki'; - switch (alg) { - case 'PS256': - case 'PS384': - case 'PS512': - algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - case 'RS256': - case 'RS384': - case 'RS512': - algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - algorithm = { - name: 'RSA-OAEP', - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, - }; - keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey']; - break; - case 'ES256': - algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - case 'ES384': - algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - case 'ES512': - algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - const namedCurve = getNamedCurve(keyData); - algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve }; - keyUsages = isPublic ? [] : ['deriveBits']; - break; - } - case 'EdDSA': - algorithm = { name: getNamedCurve(keyData) }; - keyUsages = isPublic ? ['verify'] : ['sign']; - break; - default: - throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); - } - return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages); -}; -export const fromPKCS8 = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options); -}; -export const fromSPKI = (pem, alg, options) => { - return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options); -}; -function getElement(seq) { - const result = []; - let next = 0; - while (next < seq.length) { - const nextPart = parseElement(seq.subarray(next)); - result.push(nextPart); - next += nextPart.byteLength; - } - return result; -} -function parseElement(bytes) { - let position = 0; - let tag = bytes[0] & 0x1f; - position++; - if (tag === 0x1f) { - tag = 0; - while (bytes[position] >= 0x80) { - tag = tag * 128 + bytes[position] - 0x80; - position++; - } - tag = tag * 128 + bytes[position] - 0x80; - position++; - } - let length = 0; - if (bytes[position] < 0x80) { - length = bytes[position]; - position++; - } - else if (length === 0x80) { - length = 0; - while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { - if (length > bytes.byteLength) { - throw new TypeError('invalid indefinite form length'); - } - length++; - } - const byteLength = position + length + 2; - return { - byteLength, - contents: bytes.subarray(position, position + length), - raw: bytes.subarray(0, byteLength), - }; - } - else { - const numberOfDigits = bytes[position] & 0x7f; - position++; - length = 0; - for (let i = 0; i < numberOfDigits; i++) { - length = length * 256 + bytes[position]; - position++; - } - } - const byteLength = position + length; - return { - byteLength, - contents: bytes.subarray(position, byteLength), - raw: bytes.subarray(0, byteLength), - }; -} -function spkiFromX509(buf) { - const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); - return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw); -} -function getSPKI(x509) { - const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ''); - const raw = decodeBase64(pem); - return formatPEM(spkiFromX509(raw), 'PUBLIC KEY'); -} -export const fromX509 = (pem, alg, options) => { - let spki; - try { - spki = getSPKI(pem); - } - catch (cause) { - throw new TypeError('Failed to parse the X.509 certificate', { cause }); - } - return fromSPKI(spki, alg, options); -}; diff --git a/dist/browser/runtime/base64url.js b/dist/browser/runtime/base64url.js deleted file mode 100644 index 66d92027c7..0000000000 --- a/dist/browser/runtime/base64url.js +++ /dev/null @@ -1,37 +0,0 @@ -import { encoder, decoder } from '../lib/buffer_utils.js'; -export const encodeBase64 = (input) => { - let unencoded = input; - if (typeof unencoded === 'string') { - unencoded = encoder.encode(unencoded); - } - const CHUNK_SIZE = 0x8000; - const arr = []; - for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { - arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); - } - return btoa(arr.join('')); -}; -export const encode = (input) => { - return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); -}; -export const decodeBase64 = (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; -}; -export const decode = (input) => { - 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.'); - } -}; diff --git a/dist/browser/runtime/bogus.js b/dist/browser/runtime/bogus.js deleted file mode 100644 index 8fde604ebf..0000000000 --- a/dist/browser/runtime/bogus.js +++ /dev/null @@ -1,6 +0,0 @@ -const bogusWebCrypto = [ - { hash: 'SHA-256', name: 'HMAC' }, - true, - ['sign'], -]; -export default bogusWebCrypto; diff --git a/dist/browser/runtime/check_cek_length.js b/dist/browser/runtime/check_cek_length.js deleted file mode 100644 index ae89001215..0000000000 --- a/dist/browser/runtime/check_cek_length.js +++ /dev/null @@ -1,8 +0,0 @@ -import { JWEInvalid } from '../util/errors.js'; -const checkCekLength = (cek, expected) => { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } -}; -export default checkCekLength; diff --git a/dist/browser/runtime/check_key_length.js b/dist/browser/runtime/check_key_length.js deleted file mode 100644 index 33970068fe..0000000000 --- a/dist/browser/runtime/check_key_length.js +++ /dev/null @@ -1,8 +0,0 @@ -export 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`); - } - } -}; diff --git a/dist/browser/runtime/decrypt.js b/dist/browser/runtime/decrypt.js deleted file mode 100644 index d44509bd0a..0000000000 --- a/dist/browser/runtime/decrypt.js +++ /dev/null @@ -1,91 +0,0 @@ -import { concat, uint64be } from '../lib/buffer_utils.js'; -import checkIvLength from '../lib/check_iv_length.js'; -import checkCekLength from './check_cek_length.js'; -import timingSafeEqual from './timing_safe_equal.js'; -import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(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 = timingSafeEqual(tag, 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, tag, 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, tag))); - } - catch { - throw new JWEDecryptionFailed(); - } -} -const decrypt = async (enc, cek, ciphertext, iv, tag, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); - } - if (!iv) { - throw new JWEInvalid('JWE Initialization Vector missing'); - } - if (!tag) { - throw new JWEInvalid('JWE Authentication Tag missing'); - } - checkIvLength(enc, iv); - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc.slice(-3), 10)); - return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); - return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -export default decrypt; diff --git a/dist/browser/runtime/digest.js b/dist/browser/runtime/digest.js deleted file mode 100644 index 39099d3b1d..0000000000 --- a/dist/browser/runtime/digest.js +++ /dev/null @@ -1,6 +0,0 @@ -import crypto from './webcrypto.js'; -const digest = async (algorithm, data) => { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); -}; -export default digest; diff --git a/dist/browser/runtime/ecdhes.js b/dist/browser/runtime/ecdhes.js deleted file mode 100644 index b4f515e312..0000000000 --- a/dist/browser/runtime/ecdhes.js +++ /dev/null @@ -1,46 +0,0 @@ -import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - if (!isCryptoKey(publicKey)) { - throw new TypeError(invalidKeyInput(publicKey, ...types)); - } - checkEncCryptoKey(publicKey, 'ECDH'); - if (!isCryptoKey(privateKey)) { - throw new TypeError(invalidKeyInput(privateKey, ...types)); - } - 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 if (publicKey.algorithm.name === 'X448') { - length = 448; - } - else { - length = - Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-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); -} -export async function generateEpk(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']); -} -export function ecdhAllowed(key) { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) || - key.algorithm.name === 'X25519' || - key.algorithm.name === 'X448'); -} diff --git a/dist/browser/runtime/encrypt.js b/dist/browser/runtime/encrypt.js deleted file mode 100644 index 8f99a1ef80..0000000000 --- a/dist/browser/runtime/encrypt.js +++ /dev/null @@ -1,76 +0,0 @@ -import { concat, uint64be } from '../lib/buffer_utils.js'; -import checkIvLength from '../lib/check_iv_length.js'; -import checkCekLength from './check_cek_length.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import generateIv from '../lib/iv.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { types } from './is_key_like.js'; -async function cbcEncrypt(enc, plaintext, cek, iv, aad) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); - } - const keySize = parseInt(enc.slice(1, 4), 10); - const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']); - const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: 'HMAC', - }, false, ['sign']); - const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ - iv, - name: 'AES-CBC', - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); - return { ciphertext, tag, iv }; -} -async function gcmEncrypt(enc, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']); - } - else { - checkEncCryptoKey(cek, enc, 'encrypt'); - encKey = cek; - } - const encrypted = new Uint8Array(await crypto.subtle.encrypt({ - additionalData: aad, - iv, - name: 'AES-GCM', - tagLength: 128, - }, encKey, plaintext)); - const tag = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag, iv }; -} -const encrypt = async (enc, plaintext, cek, iv, aad) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); - } - if (iv) { - checkIvLength(enc, iv); - } - else { - iv = generateIv(enc); - } - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(-3), 10)); - } - return cbcEncrypt(enc, plaintext, cek, iv, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); - } - return gcmEncrypt(enc, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -export default encrypt; diff --git a/dist/browser/runtime/fetch_jwks.js b/dist/browser/runtime/fetch_jwks.js deleted file mode 100644 index 2a2fdc332c..0000000000 --- a/dist/browser/runtime/fetch_jwks.js +++ /dev/null @@ -1,34 +0,0 @@ -import { JOSEError, JWKSTimeout } from '../util/errors.js'; -const fetchJwks = async (url, timeout, options) => { - let controller; - let id; - let timedOut = false; - if (typeof AbortController === 'function') { - controller = new AbortController(); - id = setTimeout(() => { - timedOut = true; - controller.abort(); - }, timeout); - } - const response = await fetch(url.href, { - signal: controller ? controller.signal : undefined, - redirect: 'manual', - headers: options.headers, - }).catch((err) => { - if (timedOut) - throw new JWKSTimeout(); - throw err; - }); - if (id !== undefined) - clearTimeout(id); - if (response.status !== 200) { - throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); - } - try { - return await response.json(); - } - catch { - throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); - } -}; -export default fetchJwks; diff --git a/dist/browser/runtime/generate.js b/dist/browser/runtime/generate.js deleted file mode 100644 index 6d770a4f90..0000000000 --- a/dist/browser/runtime/generate.js +++ /dev/null @@ -1,139 +0,0 @@ -import crypto from './webcrypto.js'; -import { JOSENotSupported } from '../util/errors.js'; -import random from './random.js'; -export async function generateSecret(alg, options) { - let length; - let algorithm; - let keyUsages; - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - length = parseInt(alg.slice(-3), 10); - algorithm = { name: 'HMAC', hash: `SHA-${length}`, length }; - keyUsages = ['sign', 'verify']; - break; - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - length = parseInt(alg.slice(-3), 10); - return random(new Uint8Array(length >> 3)); - case 'A128KW': - case 'A192KW': - case 'A256KW': - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: 'AES-KW', length }; - keyUsages = ['wrapKey', 'unwrapKey']; - break; - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: 'AES-GCM', length }; - keyUsages = ['encrypt', 'decrypt']; - break; - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); -} -function getModulusLengthOption(options) { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); - } - return modulusLength; -} -export async function generateKeyPair(alg, options) { - let algorithm; - let keyUsages; - switch (alg) { - case 'PS256': - case 'PS384': - case 'PS512': - algorithm = { - name: 'RSA-PSS', - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - }; - keyUsages = ['sign', 'verify']; - break; - case 'RS256': - case 'RS384': - case 'RS512': - algorithm = { - name: 'RSASSA-PKCS1-v1_5', - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - }; - keyUsages = ['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(alg.slice(-3), 10) || 1}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - }; - keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey']; - break; - case 'ES256': - algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; - keyUsages = ['sign', 'verify']; - break; - case 'ES384': - algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; - keyUsages = ['sign', 'verify']; - break; - case 'ES512': - algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; - keyUsages = ['sign', 'verify']; - break; - case 'EdDSA': { - keyUsages = ['sign', 'verify']; - const crv = options?.crv ?? 'Ed25519'; - switch (crv) { - case 'Ed25519': - case 'Ed448': - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported('Invalid or unsupported crv option provided'); - } - break; - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - keyUsages = ['deriveKey', 'deriveBits']; - const crv = options?.crv ?? 'P-256'; - switch (crv) { - case 'P-256': - case 'P-384': - case 'P-521': { - algorithm = { name: 'ECDH', namedCurve: crv }; - break; - } - case 'X25519': - case 'X448': - algorithm = { name: crv }; - break; - default: - throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return (crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)); -} diff --git a/dist/browser/runtime/get_sign_verify_key.js b/dist/browser/runtime/get_sign_verify_key.js deleted file mode 100644 index 3c594046cb..0000000000 --- a/dist/browser/runtime/get_sign_verify_key.js +++ /dev/null @@ -1,24 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkSigCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -import normalize from './normalize_key.js'; -export default async function getCryptoKey(alg, key, usage) { - if (usage === 'sign') { - key = await normalize.normalizePrivateKey(key, alg); - } - if (usage === 'verify') { - key = await normalize.normalizePublicKey(key, alg); - } - if (isCryptoKey(key)) { - checkSigCryptoKey(key, alg, usage); - return key; - } - if (key instanceof Uint8Array) { - if (!alg.startsWith('HS')) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]); - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key')); -} diff --git a/dist/browser/runtime/is_key_like.js b/dist/browser/runtime/is_key_like.js deleted file mode 100644 index 78d6f4df46..0000000000 --- a/dist/browser/runtime/is_key_like.js +++ /dev/null @@ -1,8 +0,0 @@ -import { isCryptoKey } from './webcrypto.js'; -export default (key) => { - if (isCryptoKey(key)) { - return true; - } - return key?.[Symbol.toStringTag] === 'KeyObject'; -}; -export const types = ['CryptoKey']; diff --git a/dist/browser/runtime/jwk_to_key.js b/dist/browser/runtime/jwk_to_key.js deleted file mode 100644 index 54469ea204..0000000000 --- a/dist/browser/runtime/jwk_to_key.js +++ /dev/null @@ -1,100 +0,0 @@ -import crypto from './webcrypto.js'; -import { JOSENotSupported } from '../util/errors.js'; -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 'EdDSA': - algorithm = { name: jwk.crv }; - 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 }; -} -const parse = async (jwk) => { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm, keyUsages } = subtleMapping(jwk); - const rest = [ - algorithm, - jwk.ext ?? false, - jwk.key_ops ?? keyUsages, - ]; - const keyData = { ...jwk }; - delete keyData.alg; - delete keyData.use; - return crypto.subtle.importKey('jwk', keyData, ...rest); -}; -export default parse; diff --git a/dist/browser/runtime/key_to_jwk.js b/dist/browser/runtime/key_to_jwk.js deleted file mode 100644 index 438edfedc3..0000000000 --- a/dist/browser/runtime/key_to_jwk.js +++ /dev/null @@ -1,21 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { encode as base64url } from './base64url.js'; -import { types } from './is_key_like.js'; -const keyToJWK = async (key) => { - if (key instanceof Uint8Array) { - return { - kty: 'oct', - k: base64url(key), - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); - } - if (!key.extractable) { - throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK'); - } - const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key); - return jwk; -}; -export default keyToJWK; diff --git a/dist/browser/runtime/normalize_key.js b/dist/browser/runtime/normalize_key.js deleted file mode 100644 index a9fe7950fd..0000000000 --- a/dist/browser/runtime/normalize_key.js +++ /dev/null @@ -1,68 +0,0 @@ -import { isJWK } from '../lib/is_jwk.js'; -import { decode } from './base64url.js'; -import importJWK from './jwk_to_key.js'; -const exportKeyValue = (k) => decode(k); -let privCache; -let pubCache; -const isKeyObject = (key) => { - return key?.[Symbol.toStringTag] === 'KeyObject'; -}; -const importAndCache = async (cache, key, jwk, alg, freeze = false) => { - let cached = cache.get(key); - if (cached?.[alg]) { - return cached[alg]; - } - const cryptoKey = await importJWK({ ...jwk, alg }); - if (freeze) - Object.freeze(key); - if (!cached) { - cache.set(key, { [alg]: cryptoKey }); - } - else { - cached[alg] = cryptoKey; - } - return cryptoKey; -}; -const normalizePublicKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: 'jwk' }); - delete jwk.d; - delete jwk.dp; - delete jwk.dq; - delete jwk.p; - delete jwk.q; - delete jwk.qi; - if (jwk.k) { - return exportKeyValue(jwk.k); - } - pubCache || (pubCache = new WeakMap()); - return importAndCache(pubCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - pubCache || (pubCache = new WeakMap()); - const cryptoKey = importAndCache(pubCache, key, key, alg, true); - return cryptoKey; - } - return key; -}; -const normalizePrivateKey = (key, alg) => { - if (isKeyObject(key)) { - let jwk = key.export({ format: 'jwk' }); - if (jwk.k) { - return exportKeyValue(jwk.k); - } - privCache || (privCache = new WeakMap()); - return importAndCache(privCache, key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) - return decode(key.k); - privCache || (privCache = new WeakMap()); - const cryptoKey = importAndCache(privCache, key, key, alg, true); - return cryptoKey; - } - return key; -}; -export default { normalizePublicKey, normalizePrivateKey }; diff --git a/dist/browser/runtime/pbes2kw.js b/dist/browser/runtime/pbes2kw.js deleted file mode 100644 index 575304aa6b..0000000000 --- a/dist/browser/runtime/pbes2kw.js +++ /dev/null @@ -1,51 +0,0 @@ -import random from './random.js'; -import { p2s as concatSalt } from '../lib/buffer_utils.js'; -import { encode as base64url } from './base64url.js'; -import { wrap, unwrap } from './aeskw.js'; -import checkP2s from '../lib/check_p2s.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -function getCryptoKey(key, alg) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']); - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); - return key; - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); -} -async function deriveKey(p2s, alg, p2c, key) { - checkP2s(p2s); - 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 wrapAlg = { - length: keylen, - name: 'AES-KW', - }; - const cryptoKey = await getCryptoKey(key, alg); - if (cryptoKey.usages.includes('deriveBits')) { - return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); - } - if (cryptoKey.usages.includes('deriveKey')) { - return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']); - } - throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); -} -export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { - const derived = await deriveKey(p2s, alg, p2c, key); - const encryptedKey = await wrap(alg.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: base64url(p2s) }; -}; -export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { - const derived = await deriveKey(p2s, alg, p2c, key); - return unwrap(alg.slice(-6), derived, encryptedKey); -}; diff --git a/dist/browser/runtime/random.js b/dist/browser/runtime/random.js deleted file mode 100644 index e8e461124a..0000000000 --- a/dist/browser/runtime/random.js +++ /dev/null @@ -1,2 +0,0 @@ -import crypto from './webcrypto.js'; -export default crypto.getRandomValues.bind(crypto); diff --git a/dist/browser/runtime/rsaes.js b/dist/browser/runtime/rsaes.js deleted file mode 100644 index a1733769ec..0000000000 --- a/dist/browser/runtime/rsaes.js +++ /dev/null @@ -1,37 +0,0 @@ -import subtleAlgorithm from './subtle_rsaes.js'; -import bogusWebCrypto from './bogus.js'; -import crypto, { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import checkKeyLength from './check_key_length.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -export const encrypt = async (alg, key, cek) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey'); - checkKeyLength(alg, key); - if (key.usages.includes('encrypt')) { - return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)); - } - if (key.usages.includes('wrapKey')) { - const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); - return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg))); - } - throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); -}; -export const decrypt = async (alg, key, encryptedKey) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey'); - checkKeyLength(alg, key); - if (key.usages.includes('decrypt')) { - return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)); - } - if (key.usages.includes('unwrapKey')) { - const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto); - return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); - } - throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); -}; diff --git a/dist/browser/runtime/runtime.js b/dist/browser/runtime/runtime.js deleted file mode 100644 index f449e824a9..0000000000 --- a/dist/browser/runtime/runtime.js +++ /dev/null @@ -1 +0,0 @@ -export default 'WebCryptoAPI'; diff --git a/dist/browser/runtime/sign.js b/dist/browser/runtime/sign.js deleted file mode 100644 index 3ccb9e16c3..0000000000 --- a/dist/browser/runtime/sign.js +++ /dev/null @@ -1,11 +0,0 @@ -import subtleAlgorithm from './subtle_dsa.js'; -import crypto from './webcrypto.js'; -import checkKeyLength from './check_key_length.js'; -import getSignKey from './get_sign_verify_key.js'; -const sign = async (alg, key, data) => { - const cryptoKey = await getSignKey(alg, key, 'sign'); - checkKeyLength(alg, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -}; -export default sign; diff --git a/dist/browser/runtime/subtle_dsa.js b/dist/browser/runtime/subtle_dsa.js deleted file mode 100644 index 46586699f3..0000000000 --- a/dist/browser/runtime/subtle_dsa.js +++ /dev/null @@ -1,26 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -export default function subtleDsa(alg, algorithm) { - const hash = `SHA-${alg.slice(-3)}`; - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - return { hash, name: 'HMAC' }; - case 'PS256': - case 'PS384': - case 'PS512': - return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 }; - case 'RS256': - case 'RS384': - case 'RS512': - return { hash, name: 'RSASSA-PKCS1-v1_5' }; - case 'ES256': - case 'ES384': - case 'ES512': - return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve }; - case 'EdDSA': - return { name: algorithm.name }; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} diff --git a/dist/browser/runtime/subtle_rsaes.js b/dist/browser/runtime/subtle_rsaes.js deleted file mode 100644 index 3a399bcfa7..0000000000 --- a/dist/browser/runtime/subtle_rsaes.js +++ /dev/null @@ -1,12 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -export default function subtleRsaEs(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`); - } -} diff --git a/dist/browser/runtime/timing_safe_equal.js b/dist/browser/runtime/timing_safe_equal.js deleted file mode 100644 index 442cdccd20..0000000000 --- a/dist/browser/runtime/timing_safe_equal.js +++ /dev/null @@ -1,19 +0,0 @@ -const 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'); - } - if (a.length !== b.length) { - throw new TypeError('Input buffers must have the same length'); - } - const len = a.length; - let out = 0; - let i = -1; - while (++i < len) { - out |= a[i] ^ b[i]; - } - return out === 0; -}; -export default timingSafeEqual; diff --git a/dist/browser/runtime/verify.js b/dist/browser/runtime/verify.js deleted file mode 100644 index 5de223317c..0000000000 --- a/dist/browser/runtime/verify.js +++ /dev/null @@ -1,16 +0,0 @@ -import subtleAlgorithm from './subtle_dsa.js'; -import crypto from './webcrypto.js'; -import checkKeyLength from './check_key_length.js'; -import getVerifyKey from './get_sign_verify_key.js'; -const verify = async (alg, key, signature, data) => { - const cryptoKey = await getVerifyKey(alg, key, 'verify'); - checkKeyLength(alg, cryptoKey); - const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); - } - catch { - return false; - } -}; -export default verify; diff --git a/dist/browser/runtime/webcrypto.js b/dist/browser/runtime/webcrypto.js deleted file mode 100644 index f9e1e91539..0000000000 --- a/dist/browser/runtime/webcrypto.js +++ /dev/null @@ -1,2 +0,0 @@ -export default crypto; -export const isCryptoKey = (key) => key instanceof CryptoKey; diff --git a/dist/browser/util/base64url.js b/dist/browser/util/base64url.js deleted file mode 100644 index 88ce7556d6..0000000000 --- a/dist/browser/util/base64url.js +++ /dev/null @@ -1,3 +0,0 @@ -import * as base64url from '../runtime/base64url.js'; -export const encode = base64url.encode; -export const decode = base64url.decode; diff --git a/dist/browser/util/decode_jwt.js b/dist/browser/util/decode_jwt.js deleted file mode 100644 index b6f2602f95..0000000000 --- a/dist/browser/util/decode_jwt.js +++ /dev/null @@ -1,32 +0,0 @@ -import { decode as base64url } from './base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -import { JWTInvalid } from './errors.js'; -export function decodeJwt(jwt) { - if (typeof jwt !== 'string') - throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); - const { 1: payload, length } = jwt.split('.'); - if (length === 5) - throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); - if (length !== 3) - throw new JWTInvalid('Invalid JWT'); - if (!payload) - throw new JWTInvalid('JWTs must contain a payload'); - let decoded; - try { - decoded = base64url(payload); - } - catch { - throw new JWTInvalid('Failed to base64url decode the payload'); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } - catch { - throw new JWTInvalid('Failed to parse the decoded payload as JSON'); - } - if (!isObject(result)) - throw new JWTInvalid('Invalid JWT Claims Set'); - return result; -} diff --git a/dist/browser/util/decode_protected_header.js b/dist/browser/util/decode_protected_header.js deleted file mode 100644 index 04be31d8f2..0000000000 --- a/dist/browser/util/decode_protected_header.js +++ /dev/null @@ -1,34 +0,0 @@ -import { decode as base64url } from './base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -export function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === 'string') { - const parts = token.split('.'); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } - else if (typeof token === 'object' && token) { - if ('protected' in token) { - protectedB64u = token.protected; - } - else { - throw new TypeError('Token does not contain a Protected Header'); - } - } - try { - if (typeof protectedB64u !== 'string' || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(base64url(protectedB64u))); - if (!isObject(result)) { - throw new Error(); - } - return result; - } - catch { - throw new TypeError('Invalid Token or Protected Header formatting'); - } -} diff --git a/dist/browser/util/errors.js b/dist/browser/util/errors.js deleted file mode 100644 index 1839ad7bd3..0000000000 --- a/dist/browser/util/errors.js +++ /dev/null @@ -1,149 +0,0 @@ -export class JOSEError extends Error { - static get code() { - return 'ERR_JOSE_GENERIC'; - } - constructor(message) { - super(message); - this.code = 'ERR_JOSE_GENERIC'; - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -} -export class JWTClaimValidationFailed extends JOSEError { - static get code() { - return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - } - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -export class JWTExpired extends JOSEError { - static get code() { - return 'ERR_JWT_EXPIRED'; - } - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.code = 'ERR_JWT_EXPIRED'; - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -export class JOSEAlgNotAllowed extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; - } - static get code() { - return 'ERR_JOSE_ALG_NOT_ALLOWED'; - } -} -export class JOSENotSupported extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JOSE_NOT_SUPPORTED'; - } - static get code() { - return 'ERR_JOSE_NOT_SUPPORTED'; - } -} -export class JWEDecryptionFailed extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWE_DECRYPTION_FAILED'; - this.message = 'decryption operation failed'; - } - static get code() { - return 'ERR_JWE_DECRYPTION_FAILED'; - } -} -export class JWEInvalid extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWE_INVALID'; - } - static get code() { - return 'ERR_JWE_INVALID'; - } -} -export class JWSInvalid extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWS_INVALID'; - } - static get code() { - return 'ERR_JWS_INVALID'; - } -} -export class JWTInvalid extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWT_INVALID'; - } - static get code() { - return 'ERR_JWT_INVALID'; - } -} -export class JWKInvalid extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWK_INVALID'; - } - static get code() { - return 'ERR_JWK_INVALID'; - } -} -export class JWKSInvalid extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWKS_INVALID'; - } - static get code() { - return 'ERR_JWKS_INVALID'; - } -} -export class JWKSNoMatchingKey extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWKS_NO_MATCHING_KEY'; - this.message = 'no applicable key found in the JSON Web Key Set'; - } - static get code() { - return 'ERR_JWKS_NO_MATCHING_KEY'; - } -} -export class JWKSMultipleMatchingKeys extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - this.message = 'multiple matching keys found in the JSON Web Key Set'; - } - static get code() { - return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - } -} -Symbol.asyncIterator; -export class JWKSTimeout extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWKS_TIMEOUT'; - this.message = 'request timed out'; - } - static get code() { - return 'ERR_JWKS_TIMEOUT'; - } -} -export class JWSSignatureVerificationFailed extends JOSEError { - constructor() { - super(...arguments); - this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - this.message = 'signature verification failed'; - } - static get code() { - return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - } -} diff --git a/dist/browser/util/runtime.js b/dist/browser/util/runtime.js deleted file mode 100644 index 2a4718b909..0000000000 --- a/dist/browser/util/runtime.js +++ /dev/null @@ -1,2 +0,0 @@ -import value from '../runtime/runtime.js'; -export default value; diff --git a/dist/deno/README.md b/dist/deno/README.md deleted file mode 100644 index 8b302ac285..0000000000 --- a/dist/deno/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# `jose` API Documentation - -`jose` is JavaScript module for JSON Object Signing and Encryption, providing support for JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Key Set (JWKS), and more. The module is designed to work across various Web-interoperable runtimes including Node.js, browsers, Cloudflare Workers, Deno, Bun, and others. - -## [💗 Help the project](https://github.com/sponsors/panva) - -Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by [becoming a sponsor](https://github.com/sponsors/panva). - -## Available modules - -**`example`** Deno import -```js -import * as jose from 'https://deno.land/x/jose@v5.9.1/index.ts' -``` - -### JSON Web Tokens (JWT) - -The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation. - -- [JWT Claims Set Validation & Signature Verification](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwt_verify.jwtVerify.md) using the `jwtVerify` function - - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwks_remote.createRemoteJWKSet.md) - - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwks_local.createLocalJWKSet.md) -- [Signing](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwt_sign.SignJWT.md) using the `SignJWT` class -- Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md) - - [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v5.9.1/docs/functions/util_decode_jwt.decodeJwt.md) prior to its validation - -### Encrypted JSON Web Tokens - -The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation. - -- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwt_decrypt.jwtDecrypt.md) using the `jwtDecrypt` function -- [Encryption](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwt_encrypt.EncryptJWT.md) using the `EncryptJWT` class -- Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md) - -### Key Utilities - -The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK). - -- Key Import Functions - - [JWK Import](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_import.importJWK.md) - - [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_import.importSPKI.md) - - [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_import.importX509.md) - - [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_import.importPKCS8.md) -- Key and Secret Generation Functions - - [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_generate_key_pair.generateKeyPair.md) - - [Symmetric Secret Generation](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_generate_secret.generateSecret.md) -- Key Export Functions - - [JWK Export](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_export.exportJWK.md) - - [Private Key Export](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_export.exportPKCS8.md) - - [Public Key Export](https://github.com/panva/jose/blob/v5.9.1/docs/functions/key_export.exportSPKI.md) - -### JSON Web Signature (JWS) - -The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes. - -- Signing - [Compact](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jws_compact_sign.CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jws_flattened_sign.FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jws_general_sign.GeneralSign.md) -- Verification - [Compact](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jws_compact_verify.compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jws_flattened_verify.flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jws_general_verify.generalVerify.md) - - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwks_remote.createRemoteJWKSet.md) - - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwks_local.createLocalJWKSet.md) -- Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md) - -### JSON Web Encryption (JWE) - -The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes. - -- Encryption - [Compact](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwe_compact_encrypt.CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwe_general_encrypt.GeneralEncrypt.md) -- Decryption - [Compact](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwe_compact_decrypt.compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwe_general_decrypt.generalDecrypt.md) -- Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md) - -### Other - -The following are additional features and utilities provided by the `jose` module: - -- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwk_thumbprint.calculateJwkThumbprint.md) -- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md) -- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v5.9.1/docs/functions/jwk_embedded.EmbeddedJWK.md) -- [Unsecured JWT](https://github.com/panva/jose/blob/v5.9.1/docs/classes/jwt_unsecured.UnsecuredJWT.md) -- [JOSE Errors](https://github.com/panva/jose/blob/v5.9.1/docs/modules/util_errors.md) diff --git a/dist/deno/index.ts b/dist/deno/index.ts deleted file mode 100644 index 7c60d22054..0000000000 --- a/dist/deno/index.ts +++ /dev/null @@ -1,107 +0,0 @@ -export { compactDecrypt } from './jwe/compact/decrypt.ts' -export type { CompactDecryptGetKey } from './jwe/compact/decrypt.ts' -export { flattenedDecrypt } from './jwe/flattened/decrypt.ts' -export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.ts' -export { generalDecrypt } from './jwe/general/decrypt.ts' -export type { GeneralDecryptGetKey } from './jwe/general/decrypt.ts' -export { GeneralEncrypt } from './jwe/general/encrypt.ts' -export type { Recipient } from './jwe/general/encrypt.ts' - -export { compactVerify } from './jws/compact/verify.ts' -export type { CompactVerifyGetKey } from './jws/compact/verify.ts' -export { flattenedVerify } from './jws/flattened/verify.ts' -export type { FlattenedVerifyGetKey } from './jws/flattened/verify.ts' -export { generalVerify } from './jws/general/verify.ts' -export type { GeneralVerifyGetKey } from './jws/general/verify.ts' - -export { jwtVerify } from './jwt/verify.ts' -export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.ts' -export { jwtDecrypt } from './jwt/decrypt.ts' -export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.ts' -export type { ProduceJWT } from './jwt/produce.ts' - -export { CompactEncrypt } from './jwe/compact/encrypt.ts' -export { FlattenedEncrypt } from './jwe/flattened/encrypt.ts' - -export { CompactSign } from './jws/compact/sign.ts' -export { FlattenedSign } from './jws/flattened/sign.ts' -export { GeneralSign } from './jws/general/sign.ts' -export type { Signature } from './jws/general/sign.ts' - -export { SignJWT } from './jwt/sign.ts' -export { EncryptJWT } from './jwt/encrypt.ts' - -export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.ts' -export { EmbeddedJWK } from './jwk/embedded.ts' - -export { createLocalJWKSet } from './jwks/local.ts' -export { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote.ts' -export type { RemoteJWKSetOptions, JWKSCacheInput, ExportedJWKSCache } from './jwks/remote.ts' - -export { UnsecuredJWT } from './jwt/unsecured.ts' -export type { UnsecuredResult } from './jwt/unsecured.ts' - -export { exportPKCS8, exportSPKI, exportJWK } from './key/export.ts' - -export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.ts' -export type { PEMImportOptions } from './key/import.ts' - -export { decodeProtectedHeader } from './util/decode_protected_header.ts' -export { decodeJwt } from './util/decode_jwt.ts' -export type { ProtectedHeaderParameters } from './util/decode_protected_header.ts' - -export * as errors from './util/errors.ts' - -export { generateKeyPair } from './key/generate_key_pair.ts' -export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.ts' -export { generateSecret } from './key/generate_secret.ts' -export type { GenerateSecretOptions } from './key/generate_secret.ts' - -export * as base64url from './util/base64url.ts' - -export type { - KeyLike, - JWK, - JWKParameters, - JWK_OKP_Public, - JWK_OKP_Private, - JWK_EC_Public, - JWK_EC_Private, - JWK_RSA_Public, - JWK_RSA_Private, - JWK_oct, - FlattenedJWSInput, - GeneralJWSInput, - FlattenedJWS, - GeneralJWS, - JoseHeaderParameters, - JWSHeaderParameters, - JWEKeyManagementHeaderParameters, - FlattenedJWE, - GeneralJWE, - JWEHeaderParameters, - CritOption, - DecryptOptions, - EncryptOptions, - JWTClaimVerificationOptions, - VerifyOptions, - SignOptions, - JWTPayload, - FlattenedDecryptResult, - GeneralDecryptResult, - CompactDecryptResult, - FlattenedVerifyResult, - GeneralVerifyResult, - CompactVerifyResult, - JWTVerifyResult, - JWTDecryptResult, - ResolvedKey, - CompactJWEHeaderParameters, - CompactJWSHeaderParameters, - JWTHeaderParameters, - JSONWebKeySet, - CryptoRuntime, - GetKeyFunction, -} from './types.d.ts' - -export { default as cryptoRuntime } from './util/runtime.ts' diff --git a/dist/deno/jwe/compact/decrypt.ts b/dist/deno/jwe/compact/decrypt.ts deleted file mode 100644 index 59a00a873e..0000000000 --- a/dist/deno/jwe/compact/decrypt.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.ts' -import { JWEInvalid } from '../../util/errors.ts' -import { decoder } from '../../lib/buffer_utils.ts' -import type { - KeyLike, - DecryptOptions, - CompactJWEHeaderParameters, - GetKeyFunction, - FlattenedJWE, - CompactDecryptResult, - ResolvedKey, -} from '../../types.d.ts' - -/** - * Interface for Compact JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface CompactDecryptGetKey - extends GetKeyFunction {} - -/** - * Decrypts a Compact JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/compact/decrypt'`. - * - * @param jwe Compact JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export async function compactDecrypt( - jwe: string | Uint8Array, - key: KeyLike | Uint8Array, - options?: DecryptOptions, -): Promise -/** - * @param jwe Compact JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export async function compactDecrypt( - jwe: string | Uint8Array, - getKey: CompactDecryptGetKey, - options?: DecryptOptions, -): Promise> -export async function compactDecrypt( - jwe: string | Uint8Array, - key: KeyLike | Uint8Array | CompactDecryptGetKey, - options?: DecryptOptions, -) { - 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: tag, - length, - } = jwe.split('.') - - if (length !== 5) { - throw new JWEInvalid('Invalid Compact JWE') - } - - const decrypted = await flattenedDecrypt( - { - ciphertext, - iv: iv || undefined, - protected: protectedHeader, - tag: tag || undefined, - encrypted_key: encryptedKey || undefined, - }, - [1]>key, - options, - ) - - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader! } - - if (typeof key === 'function') { - return { ...result, key: decrypted.key } - } - - return result -} diff --git a/dist/deno/jwe/compact/encrypt.ts b/dist/deno/jwe/compact/encrypt.ts deleted file mode 100644 index ae2ebcff1a..0000000000 --- a/dist/deno/jwe/compact/encrypt.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.ts' -import type { - KeyLike, - JWEKeyManagementHeaderParameters, - CompactJWEHeaderParameters, - EncryptOptions, -} from '../../types.d.ts' - -/** - * The CompactEncrypt class is used to build and encrypt Compact JWE strings. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/compact/encrypt'`. - * - */ -export class CompactEncrypt { - private _flattened: FlattenedEncrypt - - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array) { - this._flattened = new FlattenedEncrypt(plaintext) - } - - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this { - this._flattened.setContentEncryptionKey(cek) - return this - } - - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this { - this._flattened.setInitializationVector(iv) - return this - } - - /** - * Sets the JWE Protected Header on the CompactEncrypt object. - * - * @param protectedHeader JWE Protected Header object. - */ - setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this { - this._flattened.setProtectedHeader(protectedHeader) - return this - } - - /** - * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. - * You do not need to invoke this method, it is only really intended for test and vector - * validation purposes. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this { - this._flattened.setKeyManagementParameters(parameters) - return this - } - - /** - * Encrypts and resolves the value of the Compact JWE string. - * - * @param key Public Key or Secret to encrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { - const jwe = await this._flattened.encrypt(key, options) - - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.') - } -} diff --git a/dist/deno/jwe/flattened/decrypt.ts b/dist/deno/jwe/flattened/decrypt.ts deleted file mode 100644 index 2a40d85d1e..0000000000 --- a/dist/deno/jwe/flattened/decrypt.ts +++ /dev/null @@ -1,250 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.ts' -import decrypt from '../../runtime/decrypt.ts' - -import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.ts' -import isDisjoint from '../../lib/is_disjoint.ts' -import isObject from '../../lib/is_object.ts' -import decryptKeyManagement from '../../lib/decrypt_key_management.ts' -import type { - FlattenedDecryptResult, - KeyLike, - FlattenedJWE, - JWEHeaderParameters, - DecryptOptions, - GetKeyFunction, - ResolvedKey, -} from '../../types.d.ts' -import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' -import generateCek from '../../lib/cek.ts' -import validateCrit from '../../lib/validate_crit.ts' -import validateAlgorithms from '../../lib/validate_algorithms.ts' - -/** - * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface FlattenedDecryptGetKey - extends GetKeyFunction {} - -/** - * Decrypts a Flattened JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/flattened/decrypt'`. - * - * @param jwe Flattened JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export function flattenedDecrypt( - jwe: FlattenedJWE, - key: KeyLike | Uint8Array, - options?: DecryptOptions, -): Promise -/** - * @param jwe Flattened JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export function flattenedDecrypt( - jwe: FlattenedJWE, - getKey: FlattenedDecryptGetKey, - options?: DecryptOptions, -): Promise> -export async function flattenedDecrypt( - jwe: FlattenedJWE, - key: KeyLike | Uint8Array | FlattenedDecryptGetKey, - options?: DecryptOptions, -) { - if (!isObject(jwe)) { - throw new JWEInvalid('Flattened JWE must be an object') - } - - if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { - throw new JWEInvalid('JOSE Header missing') - } - - if (jwe.iv !== undefined && 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 !== undefined && typeof jwe.tag !== 'string') { - throw new JWEInvalid('JWE Authentication Tag incorrect type') - } - - if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { - throw new JWEInvalid('JWE Protected Header incorrect type') - } - - if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { - throw new JWEInvalid('JWE Encrypted Key incorrect type') - } - - if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { - throw new JWEInvalid('JWE AAD incorrect type') - } - - if (jwe.header !== undefined && !isObject(jwe.header)) { - throw new JWEInvalid('JWE Shared Unprotected Header incorrect type') - } - - if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { - throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type') - } - - let parsedProt!: JWEHeaderParameters - if (jwe.protected) { - try { - const protectedHeader = base64url(jwe.protected) - parsedProt = JSON.parse(decoder.decode(protectedHeader)) - } catch { - throw new JWEInvalid('JWE Protected Header is invalid') - } - } - if (!isDisjoint(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: JWEHeaderParameters = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected, - } - - validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader) - - if (joseHeader.zip !== undefined) { - 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 && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms) - const contentEncryptionAlgorithms = - options && - validateAlgorithms('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!: Uint8Array - if (jwe.encrypted_key !== undefined) { - try { - encryptedKey = base64url(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 - } - - let cek: KeyLike | Uint8Array - try { - cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) - } catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err - } - // https://www.rfc-editor.org/rfc/rfc7516#section-11.5 - // To mitigate the attacks described in RFC 3218, the - // recipient MUST NOT distinguish between format, padding, and length - // errors of encrypted keys. It is strongly recommended, in the event - // of receiving an improperly formatted key, that the recipient - // substitute a randomly generated CEK and proceed to the next step, to - // mitigate timing attacks. - cek = generateCek(enc) - } - - let iv: Uint8Array | undefined - let tag: Uint8Array | undefined - if (jwe.iv !== undefined) { - try { - iv = base64url(jwe.iv) - } catch { - throw new JWEInvalid('Failed to base64url decode the iv') - } - } - if (jwe.tag !== undefined) { - try { - tag = base64url(jwe.tag) - } catch { - throw new JWEInvalid('Failed to base64url decode the tag') - } - } - - const protectedHeader: Uint8Array = encoder.encode(jwe.protected ?? '') - let additionalData: Uint8Array - - if (jwe.aad !== undefined) { - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)) - } else { - additionalData = protectedHeader - } - - let ciphertext: Uint8Array - try { - ciphertext = base64url(jwe.ciphertext) - } catch { - throw new JWEInvalid('Failed to base64url decode the ciphertext') - } - const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData) - - const result: FlattenedDecryptResult = { plaintext } - - if (jwe.protected !== undefined) { - result.protectedHeader = parsedProt - } - - if (jwe.aad !== undefined) { - try { - result.additionalAuthenticatedData = base64url(jwe.aad!) - } catch { - throw new JWEInvalid('Failed to base64url decode the aad') - } - } - - if (jwe.unprotected !== undefined) { - result.sharedUnprotectedHeader = jwe.unprotected - } - - if (jwe.header !== undefined) { - result.unprotectedHeader = jwe.header - } - - if (resolvedKey) { - return { ...result, key } - } - - return result -} diff --git a/dist/deno/jwe/flattened/encrypt.ts b/dist/deno/jwe/flattened/encrypt.ts deleted file mode 100644 index b823ce2450..0000000000 --- a/dist/deno/jwe/flattened/encrypt.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.ts' -import { unprotected } from '../../lib/private_symbols.ts' -import encrypt from '../../runtime/encrypt.ts' - -import type { - KeyLike, - FlattenedJWE, - JWEHeaderParameters, - JWEKeyManagementHeaderParameters, - EncryptOptions, -} from '../../types.d.ts' -import encryptKeyManagement from '../../lib/encrypt_key_management.ts' -import { JOSENotSupported, JWEInvalid } from '../../util/errors.ts' -import isDisjoint from '../../lib/is_disjoint.ts' -import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' -import validateCrit from '../../lib/validate_crit.ts' - -/** - * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/flattened/encrypt'`. - * - */ -export class FlattenedEncrypt { - private _plaintext: Uint8Array - - private _protectedHeader!: JWEHeaderParameters | undefined - - private _sharedUnprotectedHeader!: JWEHeaderParameters | undefined - - private _unprotectedHeader!: JWEHeaderParameters | undefined - - private _aad!: Uint8Array | undefined - - private _cek!: Uint8Array | undefined - - private _iv!: Uint8Array | undefined - - private _keyManagementParameters!: JWEKeyManagementHeaderParameters - - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError('plaintext must be an instance of Uint8Array') - } - this._plaintext = plaintext - } - - /** - * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is - * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or - * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed - * and missing. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once') - } - this._keyManagementParameters = parameters - return this - } - - /** - * Sets the JWE Protected Header on the FlattenedEncrypt object. - * - * @param protectedHeader JWE Protected Header. - */ - setProtectedHeader(protectedHeader: JWEHeaderParameters): this { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once') - } - this._protectedHeader = protectedHeader - return this - } - - /** - * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. - * - * @param sharedUnprotectedHeader JWE Shared Unprotected Header. - */ - setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this { - if (this._sharedUnprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once') - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader - return this - } - - /** - * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. - * - * @param unprotectedHeader JWE Per-Recipient Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): this { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once') - } - this._unprotectedHeader = unprotectedHeader - return this - } - - /** - * Sets the Additional Authenticated Data on the FlattenedEncrypt object. - * - * @param aad Additional Authenticated Data. - */ - setAdditionalAuthenticatedData(aad: Uint8Array): this { - this._aad = aad - return this - } - - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once') - } - this._cek = cek - return this - } - - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once') - } - this._iv = iv - return this - } - - /** - * Encrypts and resolves the value of the Flattened JWE object. - * - * @param key Public Key or Secret to encrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new JWEInvalid( - 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()', - ) - } - - if ( - !isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader) - ) { - throw new JWEInvalid( - 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', - ) - } - - const joseHeader: JWEHeaderParameters = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader, - } - - validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader) - - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported( - 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.', - ) - } - - const { alg, enc } = joseHeader - - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') - } - - if (typeof enc !== 'string' || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') - } - - let encryptedKey: Uint8Array | undefined - - if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { - throw new TypeError( - `setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`, - ) - } - - let cek: KeyLike | Uint8Array - { - let parameters: { [propName: string]: unknown } | undefined - ;({ cek, encryptedKey, parameters } = await encryptKeyManagement( - alg, - enc, - key, - this._cek, - this._keyManagementParameters, - )) - - if (parameters) { - if (options && unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters) - } else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters } - } - } else if (!this._protectedHeader) { - this.setProtectedHeader(parameters) - } else { - this._protectedHeader = { ...this._protectedHeader, ...parameters } - } - } - } - - let additionalData: Uint8Array - let protectedHeader: Uint8Array - let aadMember: string | undefined - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) - } else { - protectedHeader = encoder.encode('') - } - - if (this._aad) { - aadMember = base64url(this._aad) - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)) - } else { - additionalData = protectedHeader - } - - const { ciphertext, tag, iv } = await encrypt( - enc, - this._plaintext, - cek, - this._iv, - additionalData, - ) - - const jwe: FlattenedJWE = { - ciphertext: base64url(ciphertext), - } - - if (iv) { - jwe.iv = base64url(iv) - } - - if (tag) { - jwe.tag = base64url(tag) - } - - if (encryptedKey) { - jwe.encrypted_key = base64url(encryptedKey) - } - - if (aadMember) { - jwe.aad = aadMember - } - - if (this._protectedHeader) { - jwe.protected = decoder.decode(protectedHeader) - } - - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader - } - - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader - } - - return jwe - } -} diff --git a/dist/deno/jwe/general/decrypt.ts b/dist/deno/jwe/general/decrypt.ts deleted file mode 100644 index 66ef58fa53..0000000000 --- a/dist/deno/jwe/general/decrypt.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.ts' -import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.ts' -import type { - KeyLike, - DecryptOptions, - JWEHeaderParameters, - GetKeyFunction, - FlattenedJWE, - GeneralJWE, - GeneralDecryptResult, - ResolvedKey, -} from '../../types.d.ts' -import isObject from '../../lib/is_object.ts' - -/** - * Interface for General JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface GeneralDecryptGetKey extends GetKeyFunction {} - -/** - * Decrypts a General JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/general/decrypt'`. - * - * @param jwe General JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export function generalDecrypt( - jwe: GeneralJWE, - key: KeyLike | Uint8Array, - options?: DecryptOptions, -): Promise -/** - * @param jwe General JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export function generalDecrypt( - jwe: GeneralJWE, - getKey: GeneralDecryptGetKey, - options?: DecryptOptions, -): Promise> -export async function generalDecrypt( - jwe: GeneralJWE, - key: KeyLike | Uint8Array | GeneralDecryptGetKey, - options?: DecryptOptions, -) { - if (!isObject(jwe)) { - throw new JWEInvalid('General JWE must be an object') - } - - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { - throw new JWEInvalid('JWE Recipients missing or incorrect type') - } - - if (!jwe.recipients.length) { - throw new JWEInvalid('JWE Recipients has no members') - } - - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt( - { - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected, - }, - [1]>key, - options, - ) - } catch { - // - } - } - throw new JWEDecryptionFailed() -} diff --git a/dist/deno/jwe/general/encrypt.ts b/dist/deno/jwe/general/encrypt.ts deleted file mode 100644 index 41082dd55d..0000000000 --- a/dist/deno/jwe/general/encrypt.ts +++ /dev/null @@ -1,281 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.ts' -import { unprotected } from '../../lib/private_symbols.ts' -import { JOSENotSupported, JWEInvalid } from '../../util/errors.ts' -import generateCek from '../../lib/cek.ts' -import isDisjoint from '../../lib/is_disjoint.ts' -import encryptKeyManagement from '../../lib/encrypt_key_management.ts' -import { encode as base64url } from '../../runtime/base64url.ts' -import validateCrit from '../../lib/validate_crit.ts' - -import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption } from '../../types.d.ts' - -export interface Recipient { - /** - * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. - * - * @param unprotectedHeader JWE Per-Recipient Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient - - /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ - addRecipient(...args: Parameters): Recipient - - /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ - encrypt(...args: Parameters): Promise - - /** Returns the enclosing GeneralEncrypt */ - done(): GeneralEncrypt -} - -class IndividualRecipient implements Recipient { - private parent: GeneralEncrypt - unprotectedHeader?: JWEHeaderParameters - key: KeyLike | Uint8Array - options: CritOption - - constructor(enc: GeneralEncrypt, key: KeyLike | Uint8Array, options: CritOption) { - this.parent = enc - this.key = key - this.options = options - } - - setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once') - } - this.unprotectedHeader = unprotectedHeader - return this - } - - addRecipient(...args: Parameters) { - return this.parent.addRecipient(...args) - } - - encrypt(...args: Parameters) { - return this.parent.encrypt(...args) - } - - done() { - return this.parent - } -} - -/** - * The GeneralEncrypt class is used to build and encrypt General JWE objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/general/encrypt'`. - * - */ -export class GeneralEncrypt { - private _plaintext: Uint8Array - - private _recipients: IndividualRecipient[] = [] - - private _protectedHeader!: JWEHeaderParameters - - private _unprotectedHeader!: JWEHeaderParameters - - private _aad!: Uint8Array - - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array) { - this._plaintext = plaintext - } - - /** - * Adds an additional recipient for the General JWE object. - * - * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. - * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }) - this._recipients.push(recipient) - return recipient - } - - /** - * Sets the JWE Protected Header on the GeneralEncrypt object. - * - * @param protectedHeader JWE Protected Header object. - */ - setProtectedHeader(protectedHeader: JWEHeaderParameters): this { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once') - } - this._protectedHeader = protectedHeader - return this - } - - /** - * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. - * - * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. - */ - setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this { - if (this._unprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once') - } - this._unprotectedHeader = sharedUnprotectedHeader - return this - } - - /** - * Sets the Additional Authenticated Data on the GeneralEncrypt object. - * - * @param aad Additional Authenticated Data. - */ - setAdditionalAuthenticatedData(aad: Uint8Array): this { - this._aad = aad - return this - } - - /** Encrypts and resolves the value of the General JWE object. */ - async encrypt(): Promise { - if (!this._recipients.length) { - throw new JWEInvalid('at least one recipient must be added') - } - - if (this._recipients.length === 1) { - const [recipient] = this._recipients - - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader!) - .encrypt(recipient.key, { ...recipient.options }) - - const jwe: GeneralJWE = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag, - } - - if (flattened.aad) jwe.aad = flattened.aad - if (flattened.protected) jwe.protected = flattened.protected - if (flattened.unprotected) jwe.unprotected = flattened.unprotected - if (flattened.encrypted_key) jwe.recipients![0].encrypted_key = flattened.encrypted_key - if (flattened.header) jwe.recipients![0].header = flattened.header - - return jwe - } - - let enc!: string - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i] - if ( - !isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader) - ) { - throw new JWEInvalid( - 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', - ) - } - - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - } - - const { alg } = joseHeader - - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') - } - - if (alg === 'dir' || alg === 'ECDH-ES') { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient') - } - - if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') - } - - if (!enc) { - enc = joseHeader.enc - } else if (enc !== joseHeader.enc) { - throw new JWEInvalid( - 'JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients', - ) - } - - validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader) - - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported( - 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.', - ) - } - } - - const cek = generateCek(enc) - - const jwe: GeneralJWE = { - ciphertext: '', - iv: '', - recipients: [], - tag: '', - } - - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i] - const target: Record = {} - jwe.recipients!.push(target) - - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - } - - const p2c = joseHeader.alg!.startsWith('PBES2') ? 2048 + i : undefined - - if (i === 0) { - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setContentEncryptionKey(cek) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader!) - .setKeyManagementParameters({ p2c }) - .encrypt(recipient.key, { - ...recipient.options, - // @ts-expect-error - [unprotected]: true, - }) - - jwe.ciphertext = flattened.ciphertext - jwe.iv = flattened.iv - jwe.tag = flattened.tag - - if (flattened.aad) jwe.aad = flattened.aad - if (flattened.protected) jwe.protected = flattened.protected - if (flattened.unprotected) jwe.unprotected = flattened.unprotected - - target.encrypted_key = flattened.encrypted_key! - if (flattened.header) target.header = flattened.header - - continue - } - - const { encryptedKey, parameters } = await encryptKeyManagement( - recipient.unprotectedHeader?.alg! || - this._protectedHeader?.alg! || - this._unprotectedHeader?.alg!, - enc, - recipient.key, - cek, - { p2c }, - ) - target.encrypted_key = base64url(encryptedKey!) - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters } - } - - return jwe - } -} diff --git a/dist/deno/jwk/embedded.ts b/dist/deno/jwk/embedded.ts deleted file mode 100644 index 18a7120d3b..0000000000 --- a/dist/deno/jwk/embedded.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { KeyLike, FlattenedJWSInput, JWSHeaderParameters } from '../types.d.ts' -import { importJWK } from '../key/import.ts' -import isObject from '../lib/is_object.ts' -import { JWSInvalid } from '../util/errors.ts' - -/** - * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify - * operations whenever you need to opt-in to verify signatures with a public key embedded in the - * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify - * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/embedded'`. - * - */ -export async function EmbeddedJWK( - protectedHeader?: JWSHeaderParameters, - token?: FlattenedJWSInput, -): Promise { - const joseHeader = { - ...protectedHeader, - ...token?.header, - } - if (!isObject(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object') - } - - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg!) - - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key') - } - - return key -} diff --git a/dist/deno/jwk/thumbprint.ts b/dist/deno/jwk/thumbprint.ts deleted file mode 100644 index 24f94c59f4..0000000000 --- a/dist/deno/jwk/thumbprint.ts +++ /dev/null @@ -1,94 +0,0 @@ -import digest from '../runtime/digest.ts' -import { encode as base64url } from '../runtime/base64url.ts' - -import { JOSENotSupported, JWKInvalid } from '../util/errors.ts' -import { encoder } from '../lib/buffer_utils.ts' -import type { JWK } from '../types.d.ts' -import isObject from '../lib/is_object.ts' - -const check = (value: unknown, description: string) => { - if (typeof value !== 'string' || !value) { - throw new JWKInvalid(`${description} missing or invalid`) - } -} - -/** - * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/thumbprint'`. - * - * @param jwk JSON Web Key. - * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is - * "sha256". - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638} - */ -export async function calculateJwkThumbprint( - jwk: JWK, - digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', -): Promise { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object') - } - - digestAlgorithm ??= 'sha256' - - if ( - digestAlgorithm !== 'sha256' && - digestAlgorithm !== 'sha384' && - digestAlgorithm !== 'sha512' - ) { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"') - } - - let components: JWK - switch (jwk.kty) { - case 'EC': - check(jwk.crv, '"crv" (Curve) Parameter') - check(jwk.x, '"x" (X Coordinate) Parameter') - check(jwk.y, '"y" (Y Coordinate) Parameter') - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } - break - case 'OKP': - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter') - check(jwk.x, '"x" (Public Key) Parameter') - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x } - break - case 'RSA': - check(jwk.e, '"e" (Exponent) Parameter') - check(jwk.n, '"n" (Modulus) Parameter') - components = { e: jwk.e, kty: jwk.kty, n: jwk.n } - break - case 'oct': - check(jwk.k, '"k" (Key Value) Parameter') - components = { k: jwk.k, kty: jwk.kty } - break - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported') - } - - const data = encoder.encode(JSON.stringify(components)) - return base64url(await digest(digestAlgorithm, data)) -} - -/** - * Calculates a JSON Web Key (JWK) Thumbprint URI - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/thumbprint'`. - * - * @param jwk JSON Web Key. - * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is - * "sha256". - * - * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278} - */ -export async function calculateJwkThumbprintUri( - jwk: JWK, - digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', -): Promise { - digestAlgorithm ??= 'sha256' - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm) - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}` -} diff --git a/dist/deno/jwks/local.ts b/dist/deno/jwks/local.ts deleted file mode 100644 index ee0689ef57..0000000000 --- a/dist/deno/jwks/local.ts +++ /dev/null @@ -1,215 +0,0 @@ -import type { - KeyLike, - JWSHeaderParameters, - JWK, - JSONWebKeySet, - FlattenedJWSInput, -} from '../types.d.ts' -import { importJWK } from '../key/import.ts' -import { - JWKSInvalid, - JOSENotSupported, - JWKSNoMatchingKey, - JWKSMultipleMatchingKeys, -} from '../util/errors.ts' -import isObject from '../lib/is_object.ts' - -function getKtyFromAlg(alg: unknown) { - switch (typeof alg === 'string' && alg.slice(0, 2)) { - case 'RS': - case 'PS': - return 'RSA' - case 'ES': - return 'EC' - case 'Ed': - return 'OKP' - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set') - } -} - -interface Cache { - [alg: string]: KeyLikeType -} - -function isJWKSLike(jwks: unknown): jwks is JSONWebKeySet { - return ( - jwks && - typeof jwks === 'object' && - // @ts-expect-error - Array.isArray(jwks.keys) && - // @ts-expect-error - jwks.keys.every(isJWKLike) - ) -} - -function isJWKLike(key: unknown) { - return isObject(key) -} - -function clone(obj: T): T { - // @ts-ignore - if (typeof structuredClone === 'function') { - // @ts-ignore - return structuredClone(obj) - } - - return JSON.parse(JSON.stringify(obj)) -} - -class LocalJWKSet { - private _jwks?: JSONWebKeySet - - private _cached: WeakMap> = new WeakMap() - - constructor(jwks: unknown) { - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid('JSON Web Key Set malformed') - } - - this._jwks = clone(jwks) - } - - async getKey( - protectedHeader?: JWSHeaderParameters, - token?: FlattenedJWSInput, - ): Promise { - const { alg, kid } = { ...protectedHeader, ...token?.header } - const kty = getKtyFromAlg(alg) - - const candidates = this._jwks!.keys.filter((jwk) => { - // filter keys based on the mapping of signature algorithms to Key Type - let candidate = kty === jwk.kty - - // filter keys based on the JWK Key ID in the header - if (candidate && typeof kid === 'string') { - candidate = kid === jwk.kid - } - - // filter keys based on the key's declared Algorithm - if (candidate && typeof jwk.alg === 'string') { - candidate = alg === jwk.alg - } - - // filter keys based on the key's declared Public Key Use - if (candidate && typeof jwk.use === 'string') { - candidate = jwk.use === 'sig' - } - - // filter keys based on the key's declared Key Operations - if (candidate && Array.isArray(jwk.key_ops)) { - candidate = jwk.key_ops.includes('verify') - } - - // filter out non-applicable OKP Sub Types - if (candidate && alg === 'EdDSA') { - candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448' - } - - // filter out non-applicable EC curves - if (candidate) { - switch (alg) { - case 'ES256': - candidate = jwk.crv === 'P-256' - break - case 'ES256K': - candidate = jwk.crv === 'secp256k1' - break - case 'ES384': - candidate = jwk.crv === 'P-384' - break - case 'ES512': - candidate = jwk.crv === 'P-521' - break - } - } - - return candidate - }) - - const { 0: jwk, length } = candidates - - if (length === 0) { - throw new JWKSNoMatchingKey() - } - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys() - - const { _cached } = this - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) { - try { - yield await importWithAlgCache(_cached, jwk, alg!) - } catch {} - } - } - - throw error - } - - return importWithAlgCache(this._cached, jwk, alg!) - } -} - -async function importWithAlgCache( - cache: WeakMap>, - jwk: JWK, - alg: string, -) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk)! - if (cached[alg] === undefined) { - const key = await importJWK({ ...jwk, ext: true }, alg) - - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWKSInvalid('JSON Web Key Set members must be public keys') - } - - cached[alg] = key - } - - return cached[alg] -} - -/** - * Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored, - * or otherwise available, JSON Web Key Set. - * - * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), - * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if - * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key - * Operations) Parameters (if they are present on the JWK). - * - * Only a single public key must match the selection process. As shown in the example below when - * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt - * verification in an iterative manner. - * - * Note: The function's purpose is to resolve public keys used for verifying signatures and will not - * work for public encryption keys. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwks/local'`. - * - * @param jwks JSON Web Key Set formatted object. - */ -export function createLocalJWKSet( - jwks: JSONWebKeySet, -): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise { - const set = new LocalJWKSet(jwks) - - const localJWKSet = async ( - protectedHeader?: JWSHeaderParameters, - token?: FlattenedJWSInput, - ): Promise => set.getKey(protectedHeader, token) - - Object.defineProperties(localJWKSet, { - jwks: { - // @ts-expect-error - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false, - }, - }) - - return localJWKSet -} diff --git a/dist/deno/jwks/remote.ts b/dist/deno/jwks/remote.ts deleted file mode 100644 index 5aa89a383b..0000000000 --- a/dist/deno/jwks/remote.ts +++ /dev/null @@ -1,345 +0,0 @@ -import fetchJwks from '../runtime/fetch_jwks.ts' - -import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput, JSONWebKeySet } from '../types.d.ts' -import { JWKSNoMatchingKey } from '../util/errors.ts' - -import { createLocalJWKSet } from './local.ts' -import isObject from '../lib/is_object.ts' - -function isCloudflareWorkers() { - return ( - // @ts-ignore - typeof WebSocketPair !== 'undefined' || - // @ts-ignore - (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || - // @ts-ignore - (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel') - ) -} - -// An explicit user-agent in browser environment is a trigger for CORS preflight requests which -// are not needed for our request, so we're omitting setting a default user-agent in browser -// environments. -let USER_AGENT: string -// @ts-ignore -if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { - const NAME = 'jose' - const VERSION = 'v5.9.1' - USER_AGENT = `${NAME}/${VERSION}` -} - -/** - * DANGER ZONE - This option has security implications that must be understood, assessed for - * applicability, and accepted before use. It is critical that the JSON Web Key Set cache only be - * writable by your own code. - * - * This option is intended for cloud computing runtimes that cannot keep an in memory cache between - * their code's invocations. Use in runtimes where an in memory cache between requests is available - * is not desirable. - * - * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the passed in - * object to: - * - * - Serve as an initial value for the JSON Web Key Set that the module would otherwise need to - * trigger an HTTP request for - * - Have the JSON Web Key Set the function optionally ended up triggering an HTTP request for - * assigned to it as properties - * - * The intended use pattern is: - * - * - Before verifying with {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} you pull the - * previously cached object from a low-latency key-value store offered by the cloud computing - * runtime it is executed on; - * - Default to an empty object `{}` instead when there's no previously cached value; - * - Pass it in as {@link RemoteJWKSetOptions[jwksCache]}; - * - Afterwards, update the key-value storage if the {@link ExportedJWKSCache.uat `uat`} property of - * the object has changed. - * - * import * as jose from 'jose' - * - * // Prerequisites - * let url!: URL - * let jwt!: string - * - * // Load JSON Web Key Set cache - * const jwksCache: jose.JWKSCacheInput = (await getPreviouslyCachedJWKS()) || {} - * const { uat } = jwksCache - * - * const JWKS = jose.createRemoteJWKSet(url, { - * [jose.jwksCache]: jwksCache, - * }) - * - * // Use JSON Web Key Set cache - * await jose.jwtVerify(jwt, JWKS) - * - * if (uat !== jwksCache.uat) { - * // Update JSON Web Key Set cache - * await storeNewJWKScache(jwksCache) - * } - * ``` - */ -export const jwksCache: unique symbol = Symbol() - -/** Options for the remote JSON Web Key Set. */ -export interface RemoteJWKSetOptions { - /** - * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and - * the verification will fail. Default is 5000 (5 seconds). - */ - timeoutDuration?: number - - /** - * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous - * successful fetch. Default is 30000 (30 seconds). - */ - cooldownDuration?: number - - /** - * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 - * minutes). - */ - cacheMaxAge?: number | typeof Infinity - - /** - * An instance of {@link https://nodejs.org/api/http.html#class-httpagent http.Agent} or - * {@link https://nodejs.org/api/https.html#class-httpsagent https.Agent} to pass to the - * {@link https://nodejs.org/api/http.html#httpgetoptions-callback http.get} or - * {@link https://nodejs.org/api/https.html#httpsgetoptions-callback https.get} method's options. - * Use when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when - * used outside of Node.js runtime. - */ - agent?: any - - /** - * Headers to be sent with the HTTP request. Default is that `User-Agent: jose/v${version}` header - * is added unless the runtime is a browser in which adding an explicit headers fetch - * configuration would cause an unnecessary CORS preflight request. - */ - headers?: Record - - /** See {@link jwksCache}. */ - [jwksCache]?: JWKSCacheInput -} - -export interface ExportedJWKSCache { - jwks: JSONWebKeySet - uat: number -} - -export type JWKSCacheInput = ExportedJWKSCache | Record - -function isFreshJwksCache(input: unknown, cacheMaxAge: number): input is ExportedJWKSCache { - if (typeof input !== 'object' || input === null) { - return false - } - - if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { - return false - } - - if ( - !('jwks' in input) || - !isObject(input.jwks) || - !Array.isArray(input.jwks.keys) || - !Array.prototype.every.call(input.jwks.keys, isObject) - ) { - return false - } - - return true -} - -class RemoteJWKSet { - private _url: URL - - private _timeoutDuration: number - - private _cooldownDuration: number - - private _cacheMaxAge: number - - private _jwksTimestamp?: number - - private _pendingFetch?: Promise - - private _options: Pick - - private _local!: ReturnType> - - private _cache?: JWKSCacheInput - - constructor(url: unknown, options?: RemoteJWKSetOptions) { - if (!(url instanceof URL)) { - throw new TypeError('url must be an instance of URL') - } - this._url = new URL(url.href) - this._options = { agent: options?.agent, headers: options?.headers } - this._timeoutDuration = - typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000 - this._cooldownDuration = - typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000 - this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000 - - if (options?.[jwksCache] !== undefined) { - this._cache = options?.[jwksCache] - if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat - this._local = createLocalJWKSet(this._cache.jwks) - } - } - } - - coolingDown() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cooldownDuration - : false - } - - fresh() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cacheMaxAge - : false - } - - async getKey( - protectedHeader?: JWSHeaderParameters, - token?: FlattenedJWSInput, - ): Promise { - if (!this._local || !this.fresh()) { - await this.reload() - } - - try { - return await this._local(protectedHeader, token) - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload() - return this._local(protectedHeader, token) - } - } - throw err - } - } - - async reload() { - // Do not assume a fetch created in another request reliably resolves - // see https://github.com/panva/jose/issues/355 and https://github.com/panva/jose/issues/509 - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = undefined - } - - const headers = new Headers(this._options.headers) - if (USER_AGENT && !headers.has('User-Agent')) { - headers.set('User-Agent', USER_AGENT) - this._options.headers = Object.fromEntries(headers.entries()) - } - - this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options) - .then((json) => { - this._local = createLocalJWKSet((json)) - if (this._cache) { - this._cache.uat = Date.now() - this._cache.jwks = (json) - } - this._jwksTimestamp = Date.now() - this._pendingFetch = undefined - }) - .catch((err: Error) => { - this._pendingFetch = undefined - throw err - }) - - await this._pendingFetch - } -} - -/** - * Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a - * remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC - * jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as - * frequently as the `cooldownDuration` option allows to prevent abuse. - * - * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), - * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if - * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key - * Operations) Parameters (if they are present on the JWK). - * - * Only a single public key must match the selection process. As shown in the example below when - * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt - * verification in an iterative manner. - * - * Note: The function's purpose is to resolve public keys used for verifying signatures and will not - * work for public encryption keys. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwks/remote'`. - * - * @param url URL to fetch the JSON Web Key Set from. - * @param options Options for the remote JSON Web Key Set. - */ -export function createRemoteJWKSet( - url: URL, - options?: RemoteJWKSetOptions, -): { - (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise - /** @ignore */ - coolingDown: boolean - /** @ignore */ - fresh: boolean - /** @ignore */ - reloading: boolean - /** @ignore */ - reload: () => Promise - /** @ignore */ - jwks: () => JSONWebKeySet | undefined -} { - const set = new RemoteJWKSet(url, options) - - const remoteJWKSet = async ( - protectedHeader?: JWSHeaderParameters, - token?: FlattenedJWSInput, - ): Promise => set.getKey(protectedHeader, token) - - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false, - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false, - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false, - }, - reloading: { - // @ts-expect-error - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false, - }, - jwks: { - // @ts-expect-error - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false, - }, - }) - - // @ts-expect-error - return remoteJWKSet -} - -/** - * @ignore - * - * @deprecated Use {@link jwksCache}. - */ -export const experimental_jwksCache = jwksCache diff --git a/dist/deno/jws/compact/sign.ts b/dist/deno/jws/compact/sign.ts deleted file mode 100644 index e300bdcaa3..0000000000 --- a/dist/deno/jws/compact/sign.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.ts' -import type { JWK, CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types.d.ts' - -/** - * The CompactSign class is used to build and sign Compact JWS strings. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/compact/sign'`. - * - */ -export class CompactSign { - private _flattened: FlattenedSign - - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array) { - this._flattened = new FlattenedSign(payload) - } - - /** - * Sets the JWS Protected Header on the Sign object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: CompactJWSHeaderParameters): this { - this._flattened.setProtectedHeader(protectedHeader) - return this - } - - /** - * Signs and resolves the value of the Compact JWS string. - * - * @param key Private Key or Secret to sign the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - async sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise { - const jws = await this._flattened.sign(key, options) - - if (jws.payload === undefined) { - throw new TypeError('use the flattened module for creating JWS with b64: false') - } - - return `${jws.protected}.${jws.payload}.${jws.signature}` - } -} diff --git a/dist/deno/jws/compact/verify.ts b/dist/deno/jws/compact/verify.ts deleted file mode 100644 index 0709125952..0000000000 --- a/dist/deno/jws/compact/verify.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.ts' -import { JWSInvalid } from '../../util/errors.ts' -import { decoder } from '../../lib/buffer_utils.ts' -import type { - JWK, - CompactVerifyResult, - FlattenedJWSInput, - GenericGetKeyFunction, - CompactJWSHeaderParameters, - KeyLike, - VerifyOptions, - ResolvedKey, -} from '../../types.d.ts' - -/** - * Interface for Compact JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface CompactVerifyGetKey - extends GenericGetKeyFunction< - CompactJWSHeaderParameters, - FlattenedJWSInput, - KeyLike | JWK | Uint8Array - > {} - -/** - * Verifies the signature and format of and afterwards decodes the Compact JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/compact/verify'`. - * - * @param jws Compact JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function compactVerify( - jws: string | Uint8Array, - key: KeyLike | Uint8Array | JWK, - options?: VerifyOptions, -): Promise -/** - * @param jws Compact JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function compactVerify( - jws: string | Uint8Array, - getKey: CompactVerifyGetKey, - options?: VerifyOptions, -): Promise> -export async function compactVerify( - jws: string | Uint8Array, - key: KeyLike | Uint8Array | JWK | CompactVerifyGetKey, - options?: VerifyOptions, -) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws) - } - - if (typeof jws !== 'string') { - throw new JWSInvalid('Compact JWS must be a string or Uint8Array') - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.') - - if (length !== 3) { - throw new JWSInvalid('Invalid Compact JWS') - } - - const verified = await flattenedVerify( - { payload, protected: protectedHeader, signature }, - [1]>key, - options, - ) - - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader! } - - if (typeof key === 'function') { - return { ...result, key: verified.key } - } - - return result -} diff --git a/dist/deno/jws/flattened/sign.ts b/dist/deno/jws/flattened/sign.ts deleted file mode 100644 index 1c78f59a5e..0000000000 --- a/dist/deno/jws/flattened/sign.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.ts' -import sign from '../../runtime/sign.ts' - -import isDisjoint from '../../lib/is_disjoint.ts' -import { JWSInvalid } from '../../util/errors.ts' -import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' -import type { JWK, KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types.d.ts' -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.ts' -import validateCrit from '../../lib/validate_crit.ts' - -/** - * The FlattenedSign class is used to build and sign Flattened JWS objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/flattened/sign'`. - * - */ -export class FlattenedSign { - private _payload: Uint8Array - - private _protectedHeader!: JWSHeaderParameters - - private _unprotectedHeader!: JWSHeaderParameters - - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError('payload must be an instance of Uint8Array') - } - this._payload = payload - } - - /** - * Sets the JWS Protected Header on the FlattenedSign object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: JWSHeaderParameters): this { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once') - } - this._protectedHeader = protectedHeader - return this - } - - /** - * Sets the JWS Unprotected Header on the FlattenedSign object. - * - * @param unprotectedHeader JWS Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): this { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once') - } - this._unprotectedHeader = unprotectedHeader - return this - } - - /** - * Signs and resolves the value of the Flattened JWS object. - * - * @param key Private Key or Secret to sign the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - async sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new JWSInvalid( - 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', - ) - } - - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { - throw new JWSInvalid( - 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', - ) - } - - const joseHeader: JWSHeaderParameters = { - ...this._protectedHeader, - ...this._unprotectedHeader, - } - - const extensions = validateCrit( - JWSInvalid, - new Map([['b64', true]]), - options?.crit, - this._protectedHeader, - joseHeader, - ) - - let b64 = true - if (extensions.has('b64')) { - b64 = this._protectedHeader.b64! - if (typeof b64 !== 'boolean') { - throw new JWSInvalid( - 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', - ) - } - } - - const { alg } = joseHeader - - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') - } - - checkKeyTypeWithJwk(alg, key, 'sign') - - let payload = this._payload - if (b64) { - payload = encoder.encode(base64url(payload)) - } - - let protectedHeader: Uint8Array - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) - } else { - protectedHeader = encoder.encode('') - } - - const data = concat(protectedHeader, encoder.encode('.'), payload) - - const signature = await sign(alg, key, data) - - const jws: FlattenedJWS = { - signature: base64url(signature), - payload: '', - } - - if (b64) { - jws.payload = decoder.decode(payload) - } - - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader - } - - if (this._protectedHeader) { - jws.protected = decoder.decode(protectedHeader) - } - - return jws - } -} diff --git a/dist/deno/jws/flattened/verify.ts b/dist/deno/jws/flattened/verify.ts deleted file mode 100644 index 18e59097d1..0000000000 --- a/dist/deno/jws/flattened/verify.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.ts' -import verify from '../../runtime/verify.ts' - -import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts' -import { concat, encoder, decoder } from '../../lib/buffer_utils.ts' -import isDisjoint from '../../lib/is_disjoint.ts' -import isObject from '../../lib/is_object.ts' -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.ts' -import validateCrit from '../../lib/validate_crit.ts' -import validateAlgorithms from '../../lib/validate_algorithms.ts' - -import type { - JWK, - FlattenedVerifyResult, - KeyLike, - FlattenedJWSInput, - JWSHeaderParameters, - VerifyOptions, - GenericGetKeyFunction, - ResolvedKey, -} from '../../types.d.ts' -import { isJWK } from '../../lib/is_jwk.ts' -import { importJWK } from '../../key/import.ts' - -/** - * Interface for Flattened JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface FlattenedVerifyGetKey - extends GenericGetKeyFunction< - JWSHeaderParameters | undefined, - FlattenedJWSInput, - KeyLike | JWK | Uint8Array - > {} - -/** - * Verifies the signature and format of and afterwards decodes the Flattened JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/flattened/verify'`. - * - * @param jws Flattened JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function flattenedVerify( - jws: FlattenedJWSInput, - key: KeyLike | Uint8Array | JWK, - options?: VerifyOptions, -): Promise -/** - * @param jws Flattened JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function flattenedVerify( - jws: FlattenedJWSInput, - getKey: FlattenedVerifyGetKey, - options?: VerifyOptions, -): Promise> -export async function flattenedVerify( - jws: FlattenedJWSInput, - key: KeyLike | Uint8Array | JWK | FlattenedVerifyGetKey, - options?: VerifyOptions, -) { - if (!isObject(jws)) { - throw new JWSInvalid('Flattened JWS must be an object') - } - - if (jws.protected === undefined && jws.header === undefined) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members') - } - - if (jws.protected !== undefined && typeof jws.protected !== 'string') { - throw new JWSInvalid('JWS Protected Header incorrect type') - } - - if (jws.payload === undefined) { - throw new JWSInvalid('JWS Payload missing') - } - - if (typeof jws.signature !== 'string') { - throw new JWSInvalid('JWS Signature missing or incorrect type') - } - - if (jws.header !== undefined && !isObject(jws.header)) { - throw new JWSInvalid('JWS Unprotected Header incorrect type') - } - - let parsedProt: JWSHeaderParameters = {} - if (jws.protected) { - try { - const protectedHeader = base64url(jws.protected) - parsedProt = JSON.parse(decoder.decode(protectedHeader)) - } catch { - throw new JWSInvalid('JWS Protected Header is invalid') - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid( - 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', - ) - } - - const joseHeader: JWSHeaderParameters = { - ...parsedProt, - ...jws.header, - } - - const extensions = validateCrit( - JWSInvalid, - new Map([['b64', true]]), - options?.crit, - parsedProt, - joseHeader, - ) - - let b64 = true - if (extensions.has('b64')) { - b64 = parsedProt.b64! - if (typeof b64 !== 'boolean') { - throw new JWSInvalid( - 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', - ) - } - } - - const { alg } = joseHeader - - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') - } - - const algorithms = options && validateAlgorithms('algorithms', options.algorithms) - - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed') - } - - if (b64) { - if (typeof jws.payload !== 'string') { - throw new JWSInvalid('JWS Payload must be a string') - } - } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance') - } - - let resolvedKey = false - if (typeof key === 'function') { - key = await key(parsedProt, jws) - resolvedKey = true - checkKeyTypeWithJwk(alg, key, 'verify') - if (isJWK(key)) { - key = await importJWK(key, alg) - } - } else { - checkKeyTypeWithJwk(alg, key, 'verify') - } - - const data = concat( - encoder.encode(jws.protected ?? ''), - encoder.encode('.'), - typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload, - ) - let signature: Uint8Array - try { - signature = base64url(jws.signature) - } catch { - throw new JWSInvalid('Failed to base64url decode the signature') - } - const verified = await verify(alg, key, signature, data) - - if (!verified) { - throw new JWSSignatureVerificationFailed() - } - - let payload: Uint8Array - if (b64) { - try { - payload = base64url(jws.payload) - } catch { - throw new JWSInvalid('Failed to base64url decode the payload') - } - } else if (typeof jws.payload === 'string') { - payload = encoder.encode(jws.payload) - } else { - payload = jws.payload - } - - const result: FlattenedVerifyResult = { payload } - - if (jws.protected !== undefined) { - result.protectedHeader = parsedProt - } - - if (jws.header !== undefined) { - result.unprotectedHeader = jws.header - } - - if (resolvedKey) { - return { ...result, key } - } - - return result -} diff --git a/dist/deno/jws/general/sign.ts b/dist/deno/jws/general/sign.ts deleted file mode 100644 index 3681f1c66d..0000000000 --- a/dist/deno/jws/general/sign.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.ts' -import { JWSInvalid } from '../../util/errors.ts' - -import type { JWK, KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types.d.ts' - -export interface Signature { - /** - * Sets the JWS Protected Header on the Signature object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature - - /** - * Sets the JWS Unprotected Header on the Signature object. - * - * @param unprotectedHeader JWS Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature - - /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ - addSignature(...args: Parameters): Signature - - /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ - sign(...args: Parameters): Promise - - /** Returns the enclosing GeneralSign */ - done(): GeneralSign -} - -class IndividualSignature implements Signature { - private parent: GeneralSign - - protectedHeader?: JWSHeaderParameters - unprotectedHeader?: JWSHeaderParameters - options?: SignOptions - key: KeyLike | Uint8Array | JWK - - constructor(sig: GeneralSign, key: KeyLike | Uint8Array | JWK, options?: SignOptions) { - this.parent = sig - this.key = key - this.options = options - } - - setProtectedHeader(protectedHeader: JWSHeaderParameters) { - if (this.protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once') - } - this.protectedHeader = protectedHeader - return this - } - - setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once') - } - this.unprotectedHeader = unprotectedHeader - return this - } - - addSignature(...args: Parameters) { - return this.parent.addSignature(...args) - } - - sign(...args: Parameters) { - return this.parent.sign(...args) - } - - done() { - return this.parent - } -} - -/** - * The GeneralSign class is used to build and sign General JWS objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/general/sign'`. - * - */ -export class GeneralSign { - private _payload: Uint8Array - - private _signatures: IndividualSignature[] = [] - - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array) { - this._payload = payload - } - - /** - * Adds an additional signature for the General JWS object. - * - * @param key Private Key or Secret to sign the individual JWS signature with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - addSignature(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Signature { - const signature = new IndividualSignature(this, key, options) - this._signatures.push(signature) - return signature - } - - /** Signs and resolves the value of the General JWS object. */ - async sign(): Promise { - if (!this._signatures.length) { - throw new JWSInvalid('at least one signature must be added') - } - - const jws: GeneralJWS = { - signatures: [], - payload: '', - } - - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i] - const flattened = new FlattenedSign(this._payload) - - flattened.setProtectedHeader(signature.protectedHeader!) - flattened.setUnprotectedHeader(signature.unprotectedHeader!) - - const { payload, ...rest } = await flattened.sign(signature.key, signature.options) - if (i === 0) { - jws.payload = payload - } else if (jws.payload !== payload) { - throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)') - } - jws.signatures.push(rest) - } - - return jws - } -} diff --git a/dist/deno/jws/general/verify.ts b/dist/deno/jws/general/verify.ts deleted file mode 100644 index 2eb84ec6f0..0000000000 --- a/dist/deno/jws/general/verify.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.ts' -import type { - JWK, - GeneralJWSInput, - GeneralVerifyResult, - FlattenedJWSInput, - GenericGetKeyFunction, - JWSHeaderParameters, - KeyLike, - VerifyOptions, - ResolvedKey, -} from '../../types.d.ts' -import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts' -import isObject from '../../lib/is_object.ts' - -/** - * Interface for General JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface GeneralVerifyGetKey - extends GenericGetKeyFunction< - JWSHeaderParameters, - FlattenedJWSInput, - KeyLike | JWK | Uint8Array - > {} - -/** - * Verifies the signature and format of and afterwards decodes the General JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/general/verify'`. - * - * @param jws General JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function generalVerify( - jws: GeneralJWSInput, - key: KeyLike | Uint8Array | JWK, - options?: VerifyOptions, -): Promise -/** - * @param jws General JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export function generalVerify( - jws: GeneralJWSInput, - getKey: GeneralVerifyGetKey, - options?: VerifyOptions, -): Promise> -export async function generalVerify( - jws: GeneralJWSInput, - key: KeyLike | Uint8Array | JWK | GeneralVerifyGetKey, - options?: VerifyOptions, -) { - if (!isObject(jws)) { - throw new JWSInvalid('General JWS must be an object') - } - - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { - throw new JWSInvalid('JWS Signatures missing or incorrect type') - } - - for (const signature of jws.signatures) { - try { - return await flattenedVerify( - { - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature, - }, - [1]>key, - options, - ) - } catch { - // - } - } - throw new JWSSignatureVerificationFailed() -} diff --git a/dist/deno/jwt/decrypt.ts b/dist/deno/jwt/decrypt.ts deleted file mode 100644 index 4756055b57..0000000000 --- a/dist/deno/jwt/decrypt.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { compactDecrypt } from '../jwe/compact/decrypt.ts' -import type { - JWTPayload, - KeyLike, - DecryptOptions, - JWTClaimVerificationOptions, - GetKeyFunction, - CompactJWEHeaderParameters, - FlattenedJWE, - JWTDecryptResult, - ResolvedKey, -} from '../types.d.ts' -import jwtPayload from '../lib/jwt_claims_set.ts' -import { JWTClaimValidationFailed } from '../util/errors.ts' - -/** Combination of JWE Decryption options and JWT Claims Set verification options. */ -export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions {} - -/** - * Interface for JWT Decryption dynamic key resolution. No token components have been verified at - * the time of this function call. - */ -export interface JWTDecryptGetKey - extends GetKeyFunction {} - -/** - * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT - * Claims Set. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/decrypt'`. - * - * @param jwt JSON Web Token value (encoded as JWE). - * @param key Private Key or Secret to decrypt and verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export async function jwtDecrypt( - jwt: string | Uint8Array, - key: KeyLike | Uint8Array, - options?: JWTDecryptOptions, -): Promise> -/** - * @param jwt JSON Web Token value (encoded as JWE). - * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export async function jwtDecrypt( - jwt: string | Uint8Array, - getKey: JWTDecryptGetKey, - options?: JWTDecryptOptions, -): Promise & ResolvedKey> -export async function jwtDecrypt( - jwt: string | Uint8Array, - key: KeyLike | Uint8Array | JWTDecryptGetKey, - options?: JWTDecryptOptions, -) { - const decrypted = await compactDecrypt(jwt, [1]>key, options) - const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options) - - const { protectedHeader } = decrypted - - if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed( - 'replicated "iss" claim header parameter mismatch', - payload, - 'iss', - 'mismatch', - ) - } - - if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed( - 'replicated "sub" claim header parameter mismatch', - payload, - 'sub', - 'mismatch', - ) - } - - if ( - protectedHeader.aud !== undefined && - JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud) - ) { - throw new JWTClaimValidationFailed( - 'replicated "aud" claim header parameter mismatch', - payload, - 'aud', - 'mismatch', - ) - } - - const result = { payload, protectedHeader } - - if (typeof key === 'function') { - return { ...result, key: decrypted.key } - } - - return result -} diff --git a/dist/deno/jwt/encrypt.ts b/dist/deno/jwt/encrypt.ts deleted file mode 100644 index 1e36e3b935..0000000000 --- a/dist/deno/jwt/encrypt.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { CompactEncrypt } from '../jwe/compact/encrypt.ts' -import type { - EncryptOptions, - CompactJWEHeaderParameters, - JWEKeyManagementHeaderParameters, - KeyLike, -} from '../types.d.ts' -import { encoder } from '../lib/buffer_utils.ts' -import { ProduceJWT } from './produce.ts' - -/** - * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/encrypt'`. - * - */ -export class EncryptJWT extends ProduceJWT { - private _cek!: Uint8Array - - private _iv!: Uint8Array - - private _keyManagementParameters!: JWEKeyManagementHeaderParameters - - private _protectedHeader!: CompactJWEHeaderParameters - - private _replicateIssuerAsHeader!: boolean - - private _replicateSubjectAsHeader!: boolean - - private _replicateAudienceAsHeader!: boolean - - /** - * Sets the JWE Protected Header on the EncryptJWT object. - * - * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" - * (JWE Encryption Algorithm) properties. - */ - setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once') - } - this._protectedHeader = protectedHeader - return this - } - - /** - * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is - * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or - * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed - * and missing. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once') - } - this._keyManagementParameters = parameters - return this - } - - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once') - } - this._cek = cek - return this - } - - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once') - } - this._iv = iv - return this - } - - /** - * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateIssuerAsHeader(): this { - this._replicateIssuerAsHeader = true - return this - } - - /** - * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateSubjectAsHeader(): this { - this._replicateSubjectAsHeader = true - return this - } - - /** - * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateAudienceAsHeader(): this { - this._replicateAudienceAsHeader = true - return this - } - - /** - * Encrypts and returns the JWT. - * - * @param key Public Key or Secret to encrypt the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { - const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))) - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss } - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub } - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud } - } - enc.setProtectedHeader(this._protectedHeader) - if (this._iv) { - enc.setInitializationVector(this._iv) - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek) - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters) - } - return enc.encrypt(key, options) - } -} diff --git a/dist/deno/jwt/produce.ts b/dist/deno/jwt/produce.ts deleted file mode 100644 index 228617f414..0000000000 --- a/dist/deno/jwt/produce.ts +++ /dev/null @@ -1,173 +0,0 @@ -import type { JWTPayload } from '../types.d.ts' -import epoch from '../lib/epoch.ts' -import isObject from '../lib/is_object.ts' -import secs from '../lib/secs.ts' - -function validateInput(label: string, input: number) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`) - } - - return input -} - -/** Generic class for JWT producing. */ -export class ProduceJWT { - protected _payload!: JWTPayload - - /** @param payload The JWT Claims Set object. Defaults to an empty object. */ - constructor(payload: JWTPayload = {}) { - if (!isObject(payload)) { - throw new TypeError('JWT Claims Set MUST be an object') - } - this._payload = payload - } - - /** - * Set the "iss" (Issuer) Claim. - * - * @param issuer "Issuer" Claim value to set on the JWT Claims Set. - */ - setIssuer(issuer: string): this { - this._payload = { ...this._payload, iss: issuer } - return this - } - - /** - * Set the "sub" (Subject) Claim. - * - * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. - */ - setSubject(subject: string): this { - this._payload = { ...this._payload, sub: subject } - return this - } - - /** - * Set the "aud" (Audience) Claim. - * - * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. - */ - setAudience(audience: string | string[]): this { - this._payload = { ...this._payload, aud: audience } - return this - } - - /** - * Set the "jti" (JWT ID) Claim. - * - * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. - */ - setJti(jwtId: string): this { - this._payload = { ...this._payload, jti: jwtId } - return this - } - - /** - * Set the "nbf" (Not Before) Claim. - * - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. - */ - setNotBefore(input: number | string | Date): this { - if (typeof input === 'number') { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) } - } else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) } - } else { - this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) } - } - return this - } - - /** - * Set the "exp" (Expiration Time) Claim. - * - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. - */ - setExpirationTime(input: number | string | Date): this { - if (typeof input === 'number') { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) } - } else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) } - } else { - this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) } - } - return this - } - - /** - * Set the "iat" (Issued At) Claim. - * - * - If no argument is used the current unix timestamp is used as the claim. - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "iat" (Expiration Time) Claim value to set on the JWT Claims Set. - */ - setIssuedAt(input?: number | string | Date): this { - if (typeof input === 'undefined') { - this._payload = { ...this._payload, iat: epoch(new Date()) } - } else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) } - } else if (typeof input === 'string') { - this._payload = { - ...this._payload, - iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)), - } - } else { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) } - } - return this - } -} diff --git a/dist/deno/jwt/sign.ts b/dist/deno/jwt/sign.ts deleted file mode 100644 index 7b47d06c52..0000000000 --- a/dist/deno/jwt/sign.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { CompactSign } from '../jws/compact/sign.ts' -import { JWTInvalid } from '../util/errors.ts' -import type { JWK, JWTHeaderParameters, KeyLike, SignOptions } from '../types.d.ts' -import { encoder } from '../lib/buffer_utils.ts' -import { ProduceJWT } from './produce.ts' - -/** - * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/sign'`. - * - */ -export class SignJWT extends ProduceJWT { - private _protectedHeader!: JWTHeaderParameters - - /** - * Sets the JWS Protected Header on the SignJWT object. - * - * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. - */ - setProtectedHeader(protectedHeader: JWTHeaderParameters): this { - this._protectedHeader = protectedHeader - return this - } - - /** - * Signs and returns the JWT. - * - * @param key Private Key or Secret to sign the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Sign options. - */ - async sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise { - const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))) - sig.setProtectedHeader(this._protectedHeader) - if ( - Array.isArray(this._protectedHeader?.crit) && - this._protectedHeader.crit.includes('b64') && - // @ts-expect-error - this._protectedHeader.b64 === false - ) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload') - } - return sig.sign(key, options) - } -} diff --git a/dist/deno/jwt/unsecured.ts b/dist/deno/jwt/unsecured.ts deleted file mode 100644 index 6d735bcf9f..0000000000 --- a/dist/deno/jwt/unsecured.ts +++ /dev/null @@ -1,65 +0,0 @@ -import * as base64url from '../runtime/base64url.ts' - -import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types.d.ts' -import { decoder } from '../lib/buffer_utils.ts' -import { JWTInvalid } from '../util/errors.ts' -import jwtPayload from '../lib/jwt_claims_set.ts' -import { ProduceJWT } from './produce.ts' - -export interface UnsecuredResult { - payload: PayloadType & JWTPayload - header: JWSHeaderParameters -} - -/** - * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/unsecured'`. - * - */ -export class UnsecuredJWT extends ProduceJWT { - /** Encodes the Unsecured JWT. */ - encode(): string { - const header = base64url.encode(JSON.stringify({ alg: 'none' })) - const payload = base64url.encode(JSON.stringify(this._payload)) - - return `${header}.${payload}.` - } - - /** - * Decodes an unsecured JWT. - * - * @param jwt Unsecured JWT to decode the payload of. - * @param options JWT Claims Set validation options. - */ - static decode( - jwt: string, - options?: JWTClaimVerificationOptions, - ): UnsecuredResult { - if (typeof jwt !== 'string') { - throw new JWTInvalid('Unsecured JWT must be a string') - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.') - - if (length !== 3 || signature !== '') { - throw new JWTInvalid('Invalid Unsecured JWT') - } - - let header: JWSHeaderParameters - try { - header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))) - if (header.alg !== 'none') throw new Error() - } catch { - throw new JWTInvalid('Invalid Unsecured JWT') - } - - const payload = jwtPayload( - header, - base64url.decode(encodedPayload), - options, - ) as UnsecuredResult['payload'] - - return { payload, header } - } -} diff --git a/dist/deno/jwt/verify.ts b/dist/deno/jwt/verify.ts deleted file mode 100644 index 164c211df5..0000000000 --- a/dist/deno/jwt/verify.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { compactVerify } from '../jws/compact/verify.ts' -import type { - JWK, - JWTPayload, - KeyLike, - VerifyOptions, - JWTClaimVerificationOptions, - JWTHeaderParameters, - GenericGetKeyFunction, - FlattenedJWSInput, - JWTVerifyResult, - ResolvedKey, -} from '../types.d.ts' -import jwtPayload from '../lib/jwt_claims_set.ts' -import { JWTInvalid } from '../util/errors.ts' - -/** Combination of JWS Verification options and JWT Claims Set verification options. */ -export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions {} - -/** - * Interface for JWT Verification dynamic key resolution. No token components have been verified at - * the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface JWTVerifyGetKey - extends GenericGetKeyFunction< - JWTHeaderParameters, - FlattenedJWSInput, - KeyLike | JWK | Uint8Array - > {} - -/** - * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the - * JWT Claims Set. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/verify'`. - * - * @param jwt JSON Web Token value (encoded as JWS). - * @param key Key to verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export async function jwtVerify( - jwt: string | Uint8Array, - key: KeyLike | Uint8Array | JWK, - options?: JWTVerifyOptions, -): Promise> - -/** - * @param jwt JSON Web Token value (encoded as JWS). - * @param getKey Function resolving a key to verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export async function jwtVerify( - jwt: string | Uint8Array, - getKey: JWTVerifyGetKey, - options?: JWTVerifyOptions, -): Promise & ResolvedKey> - -export async function jwtVerify( - jwt: string | Uint8Array, - key: KeyLike | Uint8Array | JWK | JWTVerifyGetKey, - options?: JWTVerifyOptions, -) { - const verified = await compactVerify(jwt, [1]>key, options) - if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload') - } - const payload = jwtPayload(verified.protectedHeader, verified.payload, options) - const result = { payload, protectedHeader: verified.protectedHeader } - if (typeof key === 'function') { - return { ...result, key: verified.key } - } - return result -} diff --git a/dist/deno/key/export.ts b/dist/deno/key/export.ts deleted file mode 100644 index c334cc2408..0000000000 --- a/dist/deno/key/export.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { toSPKI as exportPublic } from '../runtime/asn1.ts' -import { toPKCS8 as exportPrivate } from '../runtime/asn1.ts' -import keyToJWK from '../runtime/key_to_jwk.ts' - -import type { JWK, KeyLike } from '../types.d.ts' - -/** - * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded - * SPKI string format. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to transform to a PEM-encoded SPKI string format. - */ -export async function exportSPKI(key: KeyLike): Promise { - return exportPublic(key) -} - -/** - * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded - * PKCS8 string format. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to transform to a PEM-encoded PKCS8 string format. - */ -export async function exportPKCS8(key: KeyLike): Promise { - return exportPrivate(key) -} - -/** - * Exports a runtime-specific key representation (KeyLike) to a JWK. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to export as JWK. - */ -export async function exportJWK(key: KeyLike | Uint8Array): Promise { - return keyToJWK(key) -} diff --git a/dist/deno/key/generate_key_pair.ts b/dist/deno/key/generate_key_pair.ts deleted file mode 100644 index 127f1dd848..0000000000 --- a/dist/deno/key/generate_key_pair.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { generateKeyPair as generate } from '../runtime/generate.ts' - -import type { KeyLike } from '../types.d.ts' - -export interface GenerateKeyPairResult { - /** The generated Private Key. */ - privateKey: KeyLikeType - - /** Public Key corresponding to the generated Private Key. */ - publicKey: KeyLikeType -} - -export interface GenerateKeyPairOptions { - /** - * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be - * both supported on the runtime as well as applicable for the given JWA algorithm identifier. - */ - crv?: string - - /** - * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). - * JOSE requires 2048 bits or larger. Default is 2048. - */ - modulusLength?: number - - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} - * `extractable` argument. Default is false. - * - */ - extractable?: boolean -} - -/** - * Generates a private and a public key for a given JWA algorithm identifier. This can only generate - * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. - * - * Note: Under Web Crypto API runtime the `privateKey` is generated with `extractable` set to - * `false` by default. See {@link GenerateKeyPairOptions.extractable} to generate an extractable - * `privateKey`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/generate/keypair'`. - * - * @param alg JWA Algorithm Identifier to be used with the generated key pair. - * @param options Additional options passed down to the key pair generation. - */ -export async function generateKeyPair( - alg: string, - options?: GenerateKeyPairOptions, -): Promise> { - // @ts-ignore - return generate(alg, options) -} diff --git a/dist/deno/key/generate_secret.ts b/dist/deno/key/generate_secret.ts deleted file mode 100644 index 376e0de815..0000000000 --- a/dist/deno/key/generate_secret.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { generateSecret as generate } from '../runtime/generate.ts' - -import type { KeyLike } from '../types.d.ts' - -export interface GenerateSecretOptions { - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} - * `extractable` argument. Default is false. - */ - extractable?: boolean -} - -/** - * Generates a symmetric secret key for a given JWA algorithm identifier. - * - * Note: Under Web Crypto API runtime the secret key is generated with `extractable` set to `false` - * by default. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/generate/secret'`. - * - * @param alg JWA Algorithm Identifier to be used with the generated secret. - * @param options Additional options passed down to the secret generation. - */ -export async function generateSecret( - alg: string, - options?: GenerateSecretOptions, -): Promise { - // @ts-ignore - return generate(alg, options) -} diff --git a/dist/deno/key/import.ts b/dist/deno/key/import.ts deleted file mode 100644 index 1ddd642882..0000000000 --- a/dist/deno/key/import.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { decode as decodeBase64URL } from '../runtime/base64url.ts' -import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.ts' -import asKeyObject from '../runtime/jwk_to_key.ts' - -import { JOSENotSupported } from '../util/errors.ts' -import isObject from '../lib/is_object.ts' -import type { JWK, KeyLike } from '../types.d.ts' - -export interface PEMImportOptions { - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey()} - * `extractable` argument. Default is false. - */ - extractable?: boolean -} - -/** - * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or - * CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param spki PEM-encoded SPKI string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export async function importSPKI( - spki: string, - alg: string, - options?: PEMImportOptions, -): Promise { - if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { - throw new TypeError('"spki" must be SPKI formatted string') - } - // @ts-ignore - return fromSPKI(spki, alg, options) -} - -/** - * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation - * (KeyObject or CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param x509 X.509 certificate string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export async function importX509( - x509: string, - alg: string, - options?: PEMImportOptions, -): Promise { - if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { - throw new TypeError('"x509" must be X.509 formatted string') - } - // @ts-ignore - return fromX509(x509, alg, options) -} - -/** - * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject - * or CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param pkcs8 PEM-encoded PKCS#8 string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export async function importPKCS8( - pkcs8: string, - alg: string, - options?: PEMImportOptions, -): Promise { - if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string') - } - // @ts-ignore - return fromPKCS8(pkcs8, alg, options) -} - -/** - * Imports a JWK to a runtime-specific key representation (KeyLike). Either the JWK "alg" - * (Algorithm) Parameter, or the optional "alg" argument, must be present. - * - * Note: When the runtime is using {@link https://w3c.github.io/webcrypto/ Web Cryptography API} the - * jwk parameters "use", "key_ops", and "ext" are also used in the resulting `CryptoKey`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param jwk JSON Web Key. - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key. Default is the "alg" property on the JWK, its presence is only enforced - * in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export async function importJWK( - jwk: JWK, - alg?: string, -): Promise { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object') - } - - alg ||= jwk.alg - - switch (jwk.kty) { - case 'oct': - if (typeof jwk.k !== 'string' || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value') - } - - return decodeBase64URL(jwk.k) - case 'RSA': - if (jwk.oth !== undefined) { - throw new JOSENotSupported( - 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported', - ) - } - case 'EC': - case 'OKP': - // @ts-ignore - return asKeyObject({ ...jwk, alg }) - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value') - } -} diff --git a/dist/deno/lib/aesgcmkw.ts b/dist/deno/lib/aesgcmkw.ts deleted file mode 100644 index f3bfcb5157..0000000000 --- a/dist/deno/lib/aesgcmkw.ts +++ /dev/null @@ -1,26 +0,0 @@ -import encrypt from '../runtime/encrypt.ts' -import decrypt from '../runtime/decrypt.ts' -import { encode as base64url } from '../runtime/base64url.ts' - -export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint8Array) { - const jweAlgorithm = alg.slice(0, 7) - - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)) - - return { - encryptedKey: wrapped.ciphertext, - iv: base64url(wrapped.iv!), - tag: base64url(wrapped.tag!), - } -} - -export async function unwrap( - alg: string, - key: unknown, - encryptedKey: Uint8Array, - iv: Uint8Array, - tag: Uint8Array, -) { - const jweAlgorithm = alg.slice(0, 7) - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)) -} diff --git a/dist/deno/lib/buffer_utils.ts b/dist/deno/lib/buffer_utils.ts deleted file mode 100644 index 049e6c259e..0000000000 --- a/dist/deno/lib/buffer_utils.ts +++ /dev/null @@ -1,60 +0,0 @@ -import digest from '../runtime/digest.ts' - -export const encoder = new TextEncoder() -export const decoder = new TextDecoder() - -const MAX_INT32 = 2 ** 32 - -export function concat(...buffers: Uint8Array[]): Uint8Array { - 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 -} - -export function p2s(alg: string, p2sInput: Uint8Array) { - return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput) -} - -function writeUInt32BE(buf: Uint8Array, value: number, offset?: number) { - 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 & 0xff], offset) -} - -export function uint64be(value: number) { - 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 -} - -export function uint32be(value: number) { - const buf = new Uint8Array(4) - writeUInt32BE(buf, value) - return buf -} - -export function lengthAndInput(input: Uint8Array) { - return concat(uint32be(input.length), input) -} - -export async function concatKdf(secret: Uint8Array, bits: number, value: Uint8Array) { - 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('sha256', buf), iter * 32) - } - return res.slice(0, bits >> 3) -} diff --git a/dist/deno/lib/cek.ts b/dist/deno/lib/cek.ts deleted file mode 100644 index 22cb0bb1a7..0000000000 --- a/dist/deno/lib/cek.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { JOSENotSupported } from '../util/errors.ts' -import random from '../runtime/random.ts' - -export function bitLength(alg: string) { - 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}`) - } -} -export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) diff --git a/dist/deno/lib/check_iv_length.ts b/dist/deno/lib/check_iv_length.ts deleted file mode 100644 index d63a2b280a..0000000000 --- a/dist/deno/lib/check_iv_length.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { JWEInvalid } from '../util/errors.ts' -import { bitLength } from './iv.ts' - -const checkIvLength = (enc: string, iv: Uint8Array) => { - if (iv.length << 3 !== bitLength(enc)) { - throw new JWEInvalid('Invalid Initialization Vector length') - } -} - -export default checkIvLength diff --git a/dist/deno/lib/check_key_type.ts b/dist/deno/lib/check_key_type.ts deleted file mode 100644 index d4babcb6a3..0000000000 --- a/dist/deno/lib/check_key_type.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { withAlg as invalidKeyInput } from './invalid_key_input.ts' -import isKeyLike, { types } from '../runtime/is_key_like.ts' -import * as jwk from './is_jwk.ts' -import { JWK } from '../types.d.ts' - -// @ts-expect-error -const tag = (key: unknown): string => key?.[Symbol.toStringTag] - -const jwkMatchesOp = (alg: string, key: JWK, usage: Usage) => { - if (key.use !== undefined && key.use !== 'sig') { - throw new TypeError('Invalid key for this operation, when present its use must be sig') - } - - if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { - throw new TypeError( - `Invalid key for this operation, when present its key_ops must include ${usage}`, - ) - } - - if (key.alg !== undefined && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`) - } - - return true -} - -const symmetricTypeCheck = (alg: string, key: unknown, usage: Usage, allowJwk: boolean) => { - if (key instanceof Uint8Array) return - - if (allowJwk && jwk.isJWK(key)) { - if (jwk.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 (!isKeyLike(key)) { - throw new TypeError( - invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null), - ) - } - - if (key.type !== 'secret') { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`) - } -} - -const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage, allowJwk: boolean) => { - if (allowJwk && jwk.isJWK(key)) { - switch (usage) { - case 'sign': - if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return - throw new TypeError(`JSON Web Key for this operation be a private JWK`) - case 'verify': - if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return - throw new TypeError(`JSON Web Key for this operation be a public JWK`) - } - } - - if (!isKeyLike(key)) { - throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null)) - } - - if (key.type === 'secret') { - throw new TypeError( - `${tag(key)} instances for asymmetric algorithms must not be of type "secret"`, - ) - } - - if (usage === 'sign' && key.type === 'public') { - throw new TypeError( - `${tag(key)} instances for asymmetric algorithm signing must be of type "private"`, - ) - } - - if (usage === 'decrypt' && key.type === 'public') { - throw new TypeError( - `${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`, - ) - } - - // KeyObject allows this but CryptoKey does not. - if ((key).algorithm && usage === 'verify' && key.type === 'private') { - throw new TypeError( - `${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`, - ) - } - - // KeyObject allows this but CryptoKey does not. - if ((key).algorithm && usage === 'encrypt' && key.type === 'private') { - throw new TypeError( - `${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`, - ) - } -} - -type Usage = 'sign' | 'verify' | 'encrypt' | 'decrypt' - -function checkKeyType(allowJwk: boolean, alg: string, key: unknown, usage: Usage): void { - const symmetric = - alg.startsWith('HS') || - alg === 'dir' || - alg.startsWith('PBES2') || - /^A\d{3}(?:GCM)?KW$/.test(alg) - - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk) - } else { - asymmetricTypeCheck(alg, key, usage, allowJwk) - } -} - -export default checkKeyType.bind(undefined, false) -export const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true) diff --git a/dist/deno/lib/check_p2s.ts b/dist/deno/lib/check_p2s.ts deleted file mode 100644 index 53c6d9c85f..0000000000 --- a/dist/deno/lib/check_p2s.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { JWEInvalid } from '../util/errors.ts' - -export default function checkP2s(p2s: Uint8Array) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets') - } -} diff --git a/dist/deno/lib/crypto_key.ts b/dist/deno/lib/crypto_key.ts deleted file mode 100644 index 73fc26bef9..0000000000 --- a/dist/deno/lib/crypto_key.ts +++ /dev/null @@ -1,148 +0,0 @@ -function unusable(name: string | number, prop = 'algorithm.name') { - return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`) -} - -function isAlgorithm( - algorithm: KeyAlgorithm, - name: string, -): algorithm is T { - return algorithm.name === name -} - -function getHashLength(hash: KeyAlgorithm) { - return parseInt(hash.name.slice(4), 10) -} - -function getNamedCurve(alg: string) { - switch (alg) { - case 'ES256': - return 'P-256' - case 'ES384': - return 'P-384' - case 'ES512': - return 'P-521' - default: - throw new Error('unreachable') - } -} - -function checkUsage(key: CryptoKey, usages: KeyUsage[]) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = 'CryptoKey does not support this operation, its usages must include ' - if (usages.length > 2) { - const last = usages.pop() - msg += `one of ${usages.join(', ')}, or ${last}.` - } else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.` - } else { - msg += `${usages[0]}.` - } - - throw new TypeError(msg) - } -} - -export function checkSigCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': { - if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC') - const expected = parseInt(alg.slice(2), 10) - const actual = getHashLength(key.algorithm.hash) - if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') - break - } - case 'RS256': - case 'RS384': - case 'RS512': { - if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) - throw unusable('RSASSA-PKCS1-v1_5') - const expected = parseInt(alg.slice(2), 10) - const actual = getHashLength(key.algorithm.hash) - if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') - break - } - case 'PS256': - case 'PS384': - case 'PS512': { - if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS') - const expected = parseInt(alg.slice(2), 10) - const actual = getHashLength(key.algorithm.hash) - if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') - break - } - case 'EdDSA': { - if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { - throw unusable('Ed25519 or Ed448') - } - break - } - case 'ES256': - case 'ES384': - case 'ES512': { - if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA') - const expected = getNamedCurve(alg) - const actual = key.algorithm.namedCurve - if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve') - break - } - default: - throw new TypeError('CryptoKey does not support this operation') - } - - checkUsage(key, usages) -} - -export function checkEncCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { - 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': - case 'X448': - break - default: - throw unusable('ECDH, X25519, or X448') - } - 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, usages) -} diff --git a/dist/deno/lib/decrypt_key_management.ts b/dist/deno/lib/decrypt_key_management.ts deleted file mode 100644 index af8f8f0a62..0000000000 --- a/dist/deno/lib/decrypt_key_management.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { unwrap as aesKw } from '../runtime/aeskw.ts' -import * as ECDH from '../runtime/ecdhes.ts' -import { decrypt as pbes2Kw } from '../runtime/pbes2kw.ts' -import { decrypt as rsaEs } from '../runtime/rsaes.ts' -import { decode as base64url } from '../runtime/base64url.ts' -import normalize from '../runtime/normalize_key.ts' - -import type { DecryptOptions, JWEHeaderParameters, KeyLike, JWK } from '../types.d.ts' -import { JOSENotSupported, JWEInvalid } from '../util/errors.ts' -import { bitLength as cekLength } from '../lib/cek.ts' -import { importJWK } from '../key/import.ts' -import checkKeyType from './check_key_type.ts' -import isObject from './is_object.ts' -import { unwrap as aesGcmKw } from './aesgcmkw.ts' - -async function decryptKeyManagement( - alg: string, - key: KeyLike | Uint8Array, - encryptedKey: Uint8Array | undefined, - joseHeader: JWEHeaderParameters, - options?: DecryptOptions, -): Promise { - checkKeyType(alg, key, 'decrypt') - - // @ts-ignore - key = (await normalize.normalizePrivateKey?.(key, alg)) || key - - switch (alg) { - case 'dir': { - // Direct Encryption - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') - - return key - } - case 'ECDH-ES': - // Direct Key Agreement - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') - - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - // Direct Key Agreement - if (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`) - - if (!ECDH.ecdhAllowed(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) - let partyUInfo!: Uint8Array - let partyVInfo!: Uint8Array - - if (joseHeader.apu !== undefined) { - if (typeof joseHeader.apu !== 'string') - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`) - try { - partyUInfo = base64url(joseHeader.apu) - } catch { - throw new JWEInvalid('Failed to base64url decode the apu') - } - } - - if (joseHeader.apv !== undefined) { - if (typeof joseHeader.apv !== 'string') - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`) - try { - partyVInfo = base64url(joseHeader.apv) - } catch { - throw new JWEInvalid('Failed to base64url decode the apv') - } - } - - const sharedSecret = await ECDH.deriveKey( - epk, - key, - alg === 'ECDH-ES' ? joseHeader.enc! : alg, - alg === 'ECDH-ES' ? cekLength(joseHeader.enc!) : parseInt(alg.slice(-5, -2), 10), - partyUInfo, - partyVInfo, - ) - - if (alg === 'ECDH-ES') return sharedSecret - - // Key Agreement with Key Wrapping - if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') - - return aesKw(alg.slice(-6), sharedSecret, encryptedKey) - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - // Key Encryption (RSA) - if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') - - return rsaEs(alg, key, encryptedKey) - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - // Key Encryption (PBES2) - if (encryptedKey === undefined) 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 || 10_000 - - 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: Uint8Array - try { - p2s = base64url(joseHeader.p2s) - } catch { - throw new JWEInvalid('Failed to base64url decode the p2s') - } - return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s) - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - // Key Wrapping (AES KW) - if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') - - return aesKw(alg, key, encryptedKey) - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - // Key Wrapping (AES GCM KW) - if (encryptedKey === undefined) 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: Uint8Array - try { - iv = base64url(joseHeader.iv) - } catch { - throw new JWEInvalid('Failed to base64url decode the iv') - } - let tag: Uint8Array - try { - tag = base64url(joseHeader.tag) - } catch { - throw new JWEInvalid('Failed to base64url decode the tag') - } - - return aesGcmKw(alg, key, encryptedKey, iv, tag) - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') - } - } -} - -export default decryptKeyManagement diff --git a/dist/deno/lib/encrypt_key_management.ts b/dist/deno/lib/encrypt_key_management.ts deleted file mode 100644 index 9e0a1fd186..0000000000 --- a/dist/deno/lib/encrypt_key_management.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { wrap as aesKw } from '../runtime/aeskw.ts' -import * as ECDH from '../runtime/ecdhes.ts' -import { encrypt as pbes2Kw } from '../runtime/pbes2kw.ts' -import { encrypt as rsaEs } from '../runtime/rsaes.ts' -import { encode as base64url } from '../runtime/base64url.ts' -import normalize from '../runtime/normalize_key.ts' - -import type { - KeyLike, - JWEKeyManagementHeaderParameters, - JWEHeaderParameters, - JWK, -} from '../types.d.ts' -import generateCek, { bitLength as cekLength } from '../lib/cek.ts' -import { JOSENotSupported } from '../util/errors.ts' -import { exportJWK } from '../key/export.ts' -import checkKeyType from './check_key_type.ts' -import { wrap as aesGcmKw } from './aesgcmkw.ts' - -async function encryptKeyManagement( - alg: string, - enc: string, - key: KeyLike | Uint8Array, - providedCek?: Uint8Array, - providedParameters: JWEKeyManagementHeaderParameters = {}, -): Promise<{ - cek: KeyLike | Uint8Array - encryptedKey?: Uint8Array - parameters?: JWEHeaderParameters -}> { - let encryptedKey: Uint8Array | undefined - let parameters: (JWEHeaderParameters & { epk?: JWK }) | undefined - let cek: KeyLike | Uint8Array - - checkKeyType(alg, key, 'encrypt') - - // @ts-ignore - key = (await normalize.normalizePublicKey?.(key, alg)) || key - - switch (alg) { - case 'dir': { - // Direct Encryption - cek = key - break - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - // Direct Key Agreement - if (!ECDH.ecdhAllowed(key)) { - throw new JOSENotSupported( - 'ECDH with the provided key is not allowed or not supported by your javascript runtime', - ) - } - const { apu, apv } = providedParameters - let { epk: ephemeralKey } = providedParameters - ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey - const { x, y, crv, kty } = await exportJWK(ephemeralKey!) - const sharedSecret = await ECDH.deriveKey( - key, - ephemeralKey, - alg === 'ECDH-ES' ? enc : alg, - alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), - apu, - apv, - ) - parameters = { epk: { x, crv, kty } } - if (kty === 'EC') parameters.epk!.y = y - if (apu) parameters.apu = base64url(apu) - if (apv) parameters.apv = base64url(apv) - - if (alg === 'ECDH-ES') { - cek = sharedSecret - break - } - - // Key Agreement with Key Wrapping - cek = providedCek || generateCek(enc) - const kwAlg = alg.slice(-6) - encryptedKey = await aesKw(kwAlg, sharedSecret, cek) - break - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - // Key Encryption (RSA) - cek = providedCek || generateCek(enc) - encryptedKey = await rsaEs(alg, key, cek) - break - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - // Key Encryption (PBES2) - cek = providedCek || generateCek(enc) - const { p2c, p2s } = providedParameters - ;({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)) - break - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - // Key Wrapping (AES KW) - cek = providedCek || generateCek(enc) - encryptedKey = await aesKw(alg, key, cek) - break - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - // Key Wrapping (AES GCM KW) - cek = providedCek || generateCek(enc) - const { iv } = providedParameters - ;({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)) - break - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') - } - } - - return { cek, encryptedKey, parameters } -} - -export default encryptKeyManagement diff --git a/dist/deno/lib/epoch.ts b/dist/deno/lib/epoch.ts deleted file mode 100644 index 616795a52e..0000000000 --- a/dist/deno/lib/epoch.ts +++ /dev/null @@ -1 +0,0 @@ -export default (date: Date) => Math.floor(date.getTime() / 1000) diff --git a/dist/deno/lib/format_pem.ts b/dist/deno/lib/format_pem.ts deleted file mode 100644 index ff54c795dd..0000000000 --- a/dist/deno/lib/format_pem.ts +++ /dev/null @@ -1,4 +0,0 @@ -export default (b64: string, descriptor: string) => { - const newlined = (b64.match(/.{1,64}/g) || []).join('\n') - return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----` -} diff --git a/dist/deno/lib/invalid_key_input.ts b/dist/deno/lib/invalid_key_input.ts deleted file mode 100644 index d2e29ec503..0000000000 --- a/dist/deno/lib/invalid_key_input.ts +++ /dev/null @@ -1,31 +0,0 @@ -function message(msg: string, actual: unknown, ...types: Array) { - 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 -} - -export default (actual: unknown, ...types: string[]) => { - return message('Key must be ', actual, ...types) -} - -export function withAlg(alg: string, actual: unknown, ...types: Array) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types) -} diff --git a/dist/deno/lib/is_disjoint.ts b/dist/deno/lib/is_disjoint.ts deleted file mode 100644 index c260352e76..0000000000 --- a/dist/deno/lib/is_disjoint.ts +++ /dev/null @@ -1,26 +0,0 @@ -const isDisjoint = (...headers: Array) => { - const sources = headers.filter(Boolean) - - if (sources.length === 0 || sources.length === 1) { - return true - } - - let acc!: Set - 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 -} -export default isDisjoint diff --git a/dist/deno/lib/is_jwk.ts b/dist/deno/lib/is_jwk.ts deleted file mode 100644 index e58485e713..0000000000 --- a/dist/deno/lib/is_jwk.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { JWK } from '../types.d.ts' -import isObject from './is_object.ts' - -export function isJWK(key: unknown): key is JWK & { kty: string } { - return isObject(key) && typeof key.kty === 'string' -} - -export function isPrivateJWK(key: JWK & { kty: string }) { - return key.kty !== 'oct' && typeof key.d === 'string' -} - -export function isPublicJWK(key: JWK & { kty: string }) { - return key.kty !== 'oct' && typeof key.d === 'undefined' -} - -export function isSecretJWK(key: JWK & { kty: string }) { - return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string' -} diff --git a/dist/deno/lib/is_object.ts b/dist/deno/lib/is_object.ts deleted file mode 100644 index 50aa4f6a5c..0000000000 --- a/dist/deno/lib/is_object.ts +++ /dev/null @@ -1,17 +0,0 @@ -function isObjectLike(value: unknown) { - return typeof value === 'object' && value !== null -} - -export default function isObject(input: unknown): input is T { - 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 -} diff --git a/dist/deno/lib/iv.ts b/dist/deno/lib/iv.ts deleted file mode 100644 index 93eb2ca8d8..0000000000 --- a/dist/deno/lib/iv.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { JOSENotSupported } from '../util/errors.ts' -import random from '../runtime/random.ts' - -export function bitLength(alg: string) { - 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}`) - } -} -export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) diff --git a/dist/deno/lib/jwt_claims_set.ts b/dist/deno/lib/jwt_claims_set.ts deleted file mode 100644 index 705033f8bd..0000000000 --- a/dist/deno/lib/jwt_claims_set.ts +++ /dev/null @@ -1,178 +0,0 @@ -import type { - JWTPayload, - JWTClaimVerificationOptions, - JWEHeaderParameters, - JWSHeaderParameters, -} from '../types.d.ts' -import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.ts' -import { decoder } from './buffer_utils.ts' -import epoch from './epoch.ts' -import secs from './secs.ts' -import isObject from './is_object.ts' - -const normalizeTyp = (value: string) => value.toLowerCase().replace(/^application\//, '') - -const checkAudiencePresence = (audPayload: unknown, audOption: unknown[]) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload) - } - - if (Array.isArray(audPayload)) { - // Each principal intended to process the JWT MUST - // identify itself with a value in the audience claim - return audOption.some(Set.prototype.has.bind(new Set(audPayload))) - } - - return false -} - -export default ( - protectedHeader: JWEHeaderParameters | JWSHeaderParameters, - encodedPayload: Uint8Array, - options: JWTClaimVerificationOptions = {}, -) => { - let payload!: { [propName: string]: unknown } - try { - payload = JSON.parse(decoder.decode(encodedPayload)) - } catch { - // - } - - if (!isObject(payload)) { - throw new JWTInvalid('JWT Claims Set must be a top-level JSON object') - } - - const { typ } = options - if ( - typ && - (typeof protectedHeader!.typ !== 'string' || - normalizeTyp(protectedHeader!.typ) !== normalizeTyp(typ)) - ) { - throw new JWTClaimValidationFailed( - 'unexpected "typ" JWT header value', - payload, - 'typ', - 'check_failed', - ) - } - - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options - - const presenceCheck = [...requiredClaims] - - if (maxTokenAge !== undefined) presenceCheck.push('iat') - if (audience !== undefined) presenceCheck.push('aud') - if (subject !== undefined) presenceCheck.push('sub') - if (issuer !== undefined) presenceCheck.push('iss') - - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed( - `missing required "${claim}" claim`, - payload, - claim, - 'missing', - ) - } - } - - if (issuer && !((Array.isArray(issuer) ? issuer : [issuer])).includes(payload.iss!)) { - throw new JWTClaimValidationFailed( - 'unexpected "iss" claim value', - payload, - 'iss', - 'check_failed', - ) - } - - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed( - 'unexpected "sub" claim value', - payload, - 'sub', - 'check_failed', - ) - } - - if ( - audience && - !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience) - ) { - throw new JWTClaimValidationFailed( - 'unexpected "aud" claim value', - payload, - 'aud', - 'check_failed', - ) - } - - let tolerance: number - switch (typeof options.clockTolerance) { - case 'string': - tolerance = secs(options.clockTolerance) - break - case 'number': - tolerance = options.clockTolerance - break - case 'undefined': - tolerance = 0 - break - default: - throw new TypeError('Invalid clockTolerance option type') - } - - const { currentDate } = options - const now = epoch(currentDate || new Date()) - - if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid') - } - - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid') - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed( - '"nbf" claim timestamp check failed', - payload, - 'nbf', - 'check_failed', - ) - } - } - - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid') - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed') - } - } - - if (maxTokenAge) { - const age = now - payload.iat! - const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge) - - if (age - tolerance > max) { - throw new JWTExpired( - '"iat" claim timestamp check failed (too far in the past)', - payload, - 'iat', - 'check_failed', - ) - } - - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed( - '"iat" claim timestamp check failed (it should be in the past)', - payload, - 'iat', - 'check_failed', - ) - } - } - - return payload -} diff --git a/dist/deno/lib/private_symbols.ts b/dist/deno/lib/private_symbols.ts deleted file mode 100644 index 5cb1e2b394..0000000000 --- a/dist/deno/lib/private_symbols.ts +++ /dev/null @@ -1 +0,0 @@ -export const unprotected = Symbol() diff --git a/dist/deno/lib/secs.ts b/dist/deno/lib/secs.ts deleted file mode 100644 index 0abc825f8c..0000000000 --- a/dist/deno/lib/secs.ts +++ /dev/null @@ -1,65 +0,0 @@ -const minute = 60 -const hour = minute * 60 -const day = hour * 24 -const week = day * 7 -const year = day * 365.25 - -const REGEX = - /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i - -export default (str: string): number => { - const matched = REGEX.exec(str) - - if (!matched || (matched[4] && matched[1])) { - throw new TypeError('Invalid time period format') - } - - const value = parseFloat(matched[2]) - const unit = matched[3].toLowerCase() - - let numericDate: number - - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - numericDate = Math.round(value) - break - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - numericDate = Math.round(value * minute) - break - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - numericDate = Math.round(value * hour) - break - case 'day': - case 'days': - case 'd': - numericDate = Math.round(value * day) - break - case 'week': - case 'weeks': - case 'w': - numericDate = Math.round(value * week) - break - // years matched - default: - numericDate = Math.round(value * year) - break - } - - if (matched[1] === '-' || matched[4] === 'ago') { - return -numericDate - } - - return numericDate -} diff --git a/dist/deno/lib/validate_algorithms.ts b/dist/deno/lib/validate_algorithms.ts deleted file mode 100644 index 870efaa6ef..0000000000 --- a/dist/deno/lib/validate_algorithms.ts +++ /dev/null @@ -1,16 +0,0 @@ -const validateAlgorithms = (option: string, algorithms?: string[]) => { - if ( - algorithms !== undefined && - (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string')) - ) { - throw new TypeError(`"${option}" option must be an array of strings`) - } - - if (!algorithms) { - return undefined - } - - return new Set(algorithms) -} - -export default validateAlgorithms diff --git a/dist/deno/lib/validate_crit.ts b/dist/deno/lib/validate_crit.ts deleted file mode 100644 index a2657c155b..0000000000 --- a/dist/deno/lib/validate_crit.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.ts' - -interface CritCheckHeader { - b64?: boolean - crit?: string[] - [propName: string]: unknown -} - -function validateCrit( - Err: typeof JWEInvalid | typeof JWSInvalid, - recognizedDefault: Map, - recognizedOption: { [propName: string]: boolean } | undefined, - protectedHeader: CritCheckHeader | undefined, - joseHeader: CritCheckHeader, -) { - if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected') - } - - if (!protectedHeader || protectedHeader.crit === undefined) { - return new Set() - } - - if ( - !Array.isArray(protectedHeader.crit) || - protectedHeader.crit.length === 0 || - protectedHeader.crit.some((input: string) => 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: Map - if (recognizedOption !== undefined) { - 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] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`) - } - if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`) - } - } - - return new Set(protectedHeader.crit) -} - -export default validateCrit diff --git a/dist/deno/runtime/aeskw.ts b/dist/deno/runtime/aeskw.ts deleted file mode 100644 index 72da0ef4a7..0000000000 --- a/dist/deno/runtime/aeskw.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { AesKwUnwrapFunction, AesKwWrapFunction } from './interfaces.d.ts' -import bogusWebCrypto from './bogus.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' - -function checkKeySize(key: CryptoKey, alg: string) { - if ((key.algorithm).length !== parseInt(alg.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg}`) - } -} - -function getCryptoKey(key: unknown, alg: string, usage: KeyUsage) { - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, usage) - return key - } - - if (key instanceof Uint8Array) { - return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]) - } - - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) -} - -export const wrap: AesKwWrapFunction = async (alg: string, key: unknown, cek: Uint8Array) => { - const cryptoKey = await getCryptoKey(key, alg, 'wrapKey') - - checkKeySize(cryptoKey, alg) - - // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant - const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) - - return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')) -} - -export const unwrap: AesKwUnwrapFunction = async ( - alg: string, - key: unknown, - encryptedKey: Uint8Array, -) => { - const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey') - - checkKeySize(cryptoKey, alg) - - const cryptoKeyCek = await crypto.subtle.unwrapKey( - 'raw', - encryptedKey, - cryptoKey, - 'AES-KW', - ...bogusWebCrypto, - ) - - return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) -} diff --git a/dist/deno/runtime/asn1.ts b/dist/deno/runtime/asn1.ts deleted file mode 100644 index 54bbe92aed..0000000000 --- a/dist/deno/runtime/asn1.ts +++ /dev/null @@ -1,249 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.ts' -import type { PEMExportFunction, PEMImportFunction } from './interfaces.d.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { encodeBase64, decodeBase64 } from './base64url.ts' -import formatPEM from '../lib/format_pem.ts' -import { JOSENotSupported } from '../util/errors.ts' -import { types } from './is_key_like.ts' - -import type { PEMImportOptions } from '../key/import.ts' - -const genericExport = async ( - keyType: 'private' | 'public', - keyFormat: 'spki' | 'pkcs8', - key: unknown, -) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable') - } - - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`) - } - - return formatPEM( - encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), - `${keyType.toUpperCase()} KEY`, - ) -} - -export const toSPKI: PEMExportFunction = (key) => { - return genericExport('public', 'spki', key) -} - -export const toPKCS8: PEMExportFunction = (key) => { - return genericExport('private', 'pkcs8', key) -} - -const findOid = (keyData: Uint8Array, oid: number[], from = 0): boolean => { - if (from === 0) { - oid.unshift(oid.length) - oid.unshift(0x06) - } - const i = keyData.indexOf(oid[0], from) - if (i === -1) return false - const sub = keyData.subarray(i, i + oid.length) - if (sub.length !== oid.length) return false - return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1) -} - -const getNamedCurve = (keyData: Uint8Array): string => { - switch (true) { - case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): - return 'P-256' - case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): - return 'P-384' - case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): - return 'P-521' - case findOid(keyData, [0x2b, 0x65, 0x6e]): - return 'X25519' - case findOid(keyData, [0x2b, 0x65, 0x6f]): - return 'X448' - case findOid(keyData, [0x2b, 0x65, 0x70]): - return 'Ed25519' - case findOid(keyData, [0x2b, 0x65, 0x71]): - return 'Ed448' - default: - throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type') - } -} - -const genericImport = async ( - replace: RegExp, - keyFormat: 'spki' | 'pkcs8', - pem: string, - alg: string, - options?: PEMImportOptions, -) => { - let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm - let keyUsages: KeyUsage[] - - const keyData = new Uint8Array( - atob(pem.replace(replace, '')) - .split('') - .map((c) => c.charCodeAt(0)), - ) - - const isPublic = keyFormat === 'spki' - - switch (alg) { - case 'PS256': - case 'PS384': - case 'PS512': - algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - case 'RS256': - case 'RS384': - case 'RS512': - algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - algorithm = { - name: 'RSA-OAEP', - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, - } - keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'] - break - case 'ES256': - algorithm = { name: 'ECDSA', namedCurve: 'P-256' } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - case 'ES384': - algorithm = { name: 'ECDSA', namedCurve: 'P-384' } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - case 'ES512': - algorithm = { name: 'ECDSA', namedCurve: 'P-521' } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - const namedCurve = getNamedCurve(keyData) - algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve } - keyUsages = isPublic ? [] : ['deriveBits'] - break - } - case 'EdDSA': - algorithm = { name: getNamedCurve(keyData) } - keyUsages = isPublic ? ['verify'] : ['sign'] - break - default: - throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value') - } - - return crypto.subtle.importKey( - keyFormat, - keyData, - algorithm, - options?.extractable ?? false, - keyUsages, - ) -} - -export const fromPKCS8: PEMImportFunction = (pem, alg, options?) => { - return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options) -} - -export const fromSPKI: PEMImportFunction = (pem, alg, options?) => { - return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options) -} - -function getElement(seq: Uint8Array) { - const result = [] - let next = 0 - - while (next < seq.length) { - const nextPart = parseElement(seq.subarray(next)) - result.push(nextPart) - next += nextPart.byteLength - } - return result -} - -function parseElement(bytes: Uint8Array) { - let position = 0 - - // tag - let tag = bytes[0] & 0x1f - position++ - if (tag === 0x1f) { - tag = 0 - while (bytes[position] >= 0x80) { - tag = tag * 128 + bytes[position] - 0x80 - position++ - } - tag = tag * 128 + bytes[position] - 0x80 - position++ - } - - // length - let length = 0 - if (bytes[position] < 0x80) { - length = bytes[position] - position++ - } else if (length === 0x80) { - length = 0 - - while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { - if (length > bytes.byteLength) { - throw new TypeError('invalid indefinite form length') - } - length++ - } - - const byteLength = position + length + 2 - return { - byteLength, - contents: bytes.subarray(position, position + length), - raw: bytes.subarray(0, byteLength), - } - } else { - const numberOfDigits = bytes[position] & 0x7f - position++ - length = 0 - for (let i = 0; i < numberOfDigits; i++) { - length = length * 256 + bytes[position] - position++ - } - } - - const byteLength = position + length - return { - byteLength, - contents: bytes.subarray(position, byteLength), - raw: bytes.subarray(0, byteLength), - } -} - -function spkiFromX509(buf: Uint8Array) { - const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents) - return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw) -} - -function getSPKI(x509: string): string { - const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '') - const raw = decodeBase64(pem) - return formatPEM(spkiFromX509(raw), 'PUBLIC KEY') -} - -export const fromX509: PEMImportFunction = (pem, alg, options?) => { - let spki: string - try { - spki = getSPKI(pem) - } catch (cause) { - // @ts-ignore - throw new TypeError('Failed to parse the X.509 certificate', { cause }) - } - return fromSPKI(spki, alg, options) -} diff --git a/dist/deno/runtime/base64url.ts b/dist/deno/runtime/base64url.ts deleted file mode 100644 index 45dff570c3..0000000000 --- a/dist/deno/runtime/base64url.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { encoder, decoder } from '../lib/buffer_utils.ts' - -export const encodeBase64 = (input: Uint8Array | string) => { - let unencoded = input - if (typeof unencoded === 'string') { - unencoded = encoder.encode(unencoded) - } - const CHUNK_SIZE = 0x8000 - const arr = [] - for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { - // @ts-expect-error - arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))) - } - return btoa(arr.join('')) -} - -export const encode = (input: Uint8Array | string) => { - return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') -} - -export const decodeBase64 = (encoded: string): Uint8Array => { - 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 -} - -export const decode = (input: Uint8Array | string) => { - 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.') - } -} diff --git a/dist/deno/runtime/bogus.ts b/dist/deno/runtime/bogus.ts deleted file mode 100644 index 3f7bcfdf66..0000000000 --- a/dist/deno/runtime/bogus.ts +++ /dev/null @@ -1,7 +0,0 @@ -const bogusWebCrypto: [HmacImportParams, boolean, KeyUsage[]] = [ - { hash: 'SHA-256', name: 'HMAC' }, - true, - ['sign'], -] - -export default bogusWebCrypto diff --git a/dist/deno/runtime/check_cek_length.ts b/dist/deno/runtime/check_cek_length.ts deleted file mode 100644 index 44aeda9684..0000000000 --- a/dist/deno/runtime/check_cek_length.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { JWEInvalid } from '../util/errors.ts' - -const checkCekLength = (cek: Uint8Array, expected: number) => { - const actual = cek.byteLength << 3 - if (actual !== expected) { - throw new JWEInvalid( - `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`, - ) - } -} - -export default checkCekLength diff --git a/dist/deno/runtime/check_key_length.ts b/dist/deno/runtime/check_key_length.ts deleted file mode 100644 index fac5e16f32..0000000000 --- a/dist/deno/runtime/check_key_length.ts +++ /dev/null @@ -1,8 +0,0 @@ -export default (alg: string, key: CryptoKey) => { - 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`) - } - } -} diff --git a/dist/deno/runtime/decrypt.ts b/dist/deno/runtime/decrypt.ts deleted file mode 100644 index 6b40983848..0000000000 --- a/dist/deno/runtime/decrypt.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { concat, uint64be } from '../lib/buffer_utils.ts' - -import type { DecryptFunction } from './interfaces.d.ts' -import checkIvLength from '../lib/check_iv_length.ts' -import checkCekLength from './check_cek_length.ts' -import timingSafeEqual from './timing_safe_equal.ts' -import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' - -async function cbcDecrypt( - enc: string, - cek: Uint8Array | CryptoKey, - ciphertext: Uint8Array, - iv: Uint8Array, - tag: Uint8Array, - aad: Uint8Array, -) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(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!: boolean - try { - macCheckPassed = timingSafeEqual(tag, expectedTag) - } catch { - // - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed() - } - - let plaintext!: Uint8Array - 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: string, - cek: Uint8Array | CryptoKey, - ciphertext: Uint8Array, - iv: Uint8Array, - tag: Uint8Array, - aad: Uint8Array, -) { - let encKey: CryptoKey - 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, tag), - ), - ) - } catch { - throw new JWEDecryptionFailed() - } -} - -const decrypt: DecryptFunction = async ( - enc: string, - cek: unknown, - ciphertext: Uint8Array, - iv: Uint8Array | undefined, - tag: Uint8Array | undefined, - aad: Uint8Array, -) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) - } - - if (!iv) { - throw new JWEInvalid('JWE Initialization Vector missing') - } - if (!tag) { - throw new JWEInvalid('JWE Authentication Tag missing') - } - - checkIvLength(enc, iv) - - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)) - return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) - return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') - } -} - -export default decrypt diff --git a/dist/deno/runtime/digest.ts b/dist/deno/runtime/digest.ts deleted file mode 100644 index 58a6e302a1..0000000000 --- a/dist/deno/runtime/digest.ts +++ /dev/null @@ -1,11 +0,0 @@ -import crypto from './webcrypto.ts' -import type { DigestFunction } from './interfaces.d.ts' - -const digest: DigestFunction = async ( - algorithm: 'sha256' | 'sha384' | 'sha512', - data: Uint8Array, -): Promise => { - const subtleDigest = `SHA-${algorithm.slice(-3)}` - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)) -} -export default digest diff --git a/dist/deno/runtime/ecdhes.ts b/dist/deno/runtime/ecdhes.ts deleted file mode 100644 index d5f67827fb..0000000000 --- a/dist/deno/runtime/ecdhes.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' - -export async function deriveKey( - publicKey: unknown, - privateKey: unknown, - algorithm: string, - keyLength: number, - apu: Uint8Array = new Uint8Array(0), - apv: Uint8Array = new Uint8Array(0), -) { - if (!isCryptoKey(publicKey)) { - throw new TypeError(invalidKeyInput(publicKey, ...types)) - } - checkEncCryptoKey(publicKey, 'ECDH') - if (!isCryptoKey(privateKey)) { - throw new TypeError(invalidKeyInput(privateKey, ...types)) - } - checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits') - - const value = concat( - lengthAndInput(encoder.encode(algorithm)), - lengthAndInput(apu), - lengthAndInput(apv), - uint32be(keyLength), - ) - - let length: number - if (publicKey.algorithm.name === 'X25519') { - length = 256 - } else if (publicKey.algorithm.name === 'X448') { - length = 448 - } else { - length = - Math.ceil(parseInt((publicKey.algorithm).namedCurve.substr(-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) -} - -export async function generateEpk(key: unknown) { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - - return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']) -} - -export function ecdhAllowed(key: unknown) { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - return ( - ['P-256', 'P-384', 'P-521'].includes((key.algorithm).namedCurve) || - key.algorithm.name === 'X25519' || - key.algorithm.name === 'X448' - ) -} diff --git a/dist/deno/runtime/encrypt.ts b/dist/deno/runtime/encrypt.ts deleted file mode 100644 index bed48ad5fb..0000000000 --- a/dist/deno/runtime/encrypt.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { concat, uint64be } from '../lib/buffer_utils.ts' -import type { EncryptFunction } from './interfaces.d.ts' -import checkIvLength from '../lib/check_iv_length.ts' -import checkCekLength from './check_cek_length.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import generateIv from '../lib/iv.ts' -import { JOSENotSupported } from '../util/errors.ts' -import { types } from './is_key_like.ts' - -async function cbcEncrypt( - enc: string, - plaintext: Uint8Array, - cek: Uint8Array | CryptoKey, - iv: Uint8Array, - aad: Uint8Array, -) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, 'Uint8Array')) - } - const keySize = parseInt(enc.slice(1, 4), 10) - const encKey = await crypto.subtle.importKey( - 'raw', - cek.subarray(keySize >> 3), - 'AES-CBC', - false, - ['encrypt'], - ) - const macKey = await crypto.subtle.importKey( - 'raw', - cek.subarray(0, keySize >> 3), - { - hash: `SHA-${keySize << 1}`, - name: 'HMAC', - }, - false, - ['sign'], - ) - - const ciphertext = new Uint8Array( - await crypto.subtle.encrypt( - { - iv, - name: 'AES-CBC', - }, - encKey, - plaintext, - ), - ) - - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) - const tag = new Uint8Array( - (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3), - ) - - return { ciphertext, tag, iv } -} - -async function gcmEncrypt( - enc: string, - plaintext: Uint8Array, - cek: Uint8Array | CryptoKey, - iv: Uint8Array, - aad: Uint8Array, -) { - let encKey: CryptoKey - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']) - } else { - checkEncCryptoKey(cek, enc, 'encrypt') - encKey = cek - } - - const encrypted = new Uint8Array( - await crypto.subtle.encrypt( - { - additionalData: aad, - iv, - name: 'AES-GCM', - tagLength: 128, - }, - encKey, - plaintext, - ), - ) - - const tag = encrypted.slice(-16) - const ciphertext = encrypted.slice(0, -16) - - return { ciphertext, tag, iv } -} - -const encrypt: EncryptFunction = async ( - enc: string, - plaintext: Uint8Array, - cek: unknown, - iv: Uint8Array | undefined, - aad: Uint8Array, -) => { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) - } - - if (iv) { - checkIvLength(enc, iv) - } else { - iv = generateIv(enc) - } - - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(-3), 10)) - } - return cbcEncrypt(enc, plaintext, cek, iv, aad) - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) - } - return gcmEncrypt(enc, plaintext, cek, iv, aad) - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') - } -} - -export default encrypt diff --git a/dist/deno/runtime/fetch_jwks.ts b/dist/deno/runtime/fetch_jwks.ts deleted file mode 100644 index 6b7aad808f..0000000000 --- a/dist/deno/runtime/fetch_jwks.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { FetchFunction } from './interfaces.d.ts' -import { JOSEError, JWKSTimeout } from '../util/errors.ts' - -type AcceptedRequestOptions = Pick - -const fetchJwks: FetchFunction = async ( - url: URL, - timeout: number, - options: AcceptedRequestOptions, -) => { - let controller!: AbortController - let id!: ReturnType - let timedOut = false - if (typeof AbortController === 'function') { - controller = new AbortController() - id = setTimeout(() => { - timedOut = true - controller.abort() - }, timeout) - } - - const response = await fetch(url.href, { - signal: controller ? controller.signal : undefined, - redirect: 'manual', - headers: options.headers, - }).catch((err) => { - if (timedOut) throw new JWKSTimeout() - throw err - }) - - if (id !== undefined) clearTimeout(id) - - if (response.status !== 200) { - throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response') - } - - try { - return await response.json() - } catch { - throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON') - } -} -export default fetchJwks diff --git a/dist/deno/runtime/generate.ts b/dist/deno/runtime/generate.ts deleted file mode 100644 index ece5838e50..0000000000 --- a/dist/deno/runtime/generate.ts +++ /dev/null @@ -1,155 +0,0 @@ -import crypto from './webcrypto.ts' -import { JOSENotSupported } from '../util/errors.ts' -import random from './random.ts' -import type { GenerateKeyPairOptions } from '../key/generate_key_pair.ts' -import type { GenerateSecretOptions } from '../key/generate_secret.ts' - -export async function generateSecret(alg: string, options?: GenerateSecretOptions) { - let length: number - let algorithm: AesKeyGenParams | HmacKeyGenParams - let keyUsages: KeyUsage[] - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - length = parseInt(alg.slice(-3), 10) - algorithm = { name: 'HMAC', hash: `SHA-${length}`, length } - keyUsages = ['sign', 'verify'] - break - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - length = parseInt(alg.slice(-3), 10) - return random(new Uint8Array(length >> 3)) - case 'A128KW': - case 'A192KW': - case 'A256KW': - length = parseInt(alg.slice(1, 4), 10) - algorithm = { name: 'AES-KW', length } - keyUsages = ['wrapKey', 'unwrapKey'] - break - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - length = parseInt(alg.slice(1, 4), 10) - algorithm = { name: 'AES-GCM', length } - keyUsages = ['encrypt', 'decrypt'] - break - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') - } - - return >( - (crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)) - ) -} - -function getModulusLengthOption(options?: GenerateKeyPairOptions) { - const modulusLength = options?.modulusLength ?? 2048 - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new JOSENotSupported( - 'Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used', - ) - } - return modulusLength -} - -export async function generateKeyPair(alg: string, options?: GenerateKeyPairOptions) { - let algorithm: RsaHashedKeyGenParams | EcKeyGenParams | KeyAlgorithm - let keyUsages: KeyUsage[] - - switch (alg) { - case 'PS256': - case 'PS384': - case 'PS512': - algorithm = { - name: 'RSA-PSS', - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - } - keyUsages = ['sign', 'verify'] - break - case 'RS256': - case 'RS384': - case 'RS512': - algorithm = { - name: 'RSASSA-PKCS1-v1_5', - hash: `SHA-${alg.slice(-3)}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - } - keyUsages = ['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(alg.slice(-3), 10) || 1}`, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - modulusLength: getModulusLengthOption(options), - } - keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'] - break - case 'ES256': - algorithm = { name: 'ECDSA', namedCurve: 'P-256' } - keyUsages = ['sign', 'verify'] - break - case 'ES384': - algorithm = { name: 'ECDSA', namedCurve: 'P-384' } - keyUsages = ['sign', 'verify'] - break - case 'ES512': - algorithm = { name: 'ECDSA', namedCurve: 'P-521' } - keyUsages = ['sign', 'verify'] - break - case 'EdDSA': { - keyUsages = ['sign', 'verify'] - const crv = options?.crv ?? 'Ed25519' - switch (crv) { - case 'Ed25519': - case 'Ed448': - algorithm = { name: crv } - break - default: - throw new JOSENotSupported('Invalid or unsupported crv option provided') - } - break - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - keyUsages = ['deriveKey', 'deriveBits'] - const crv = options?.crv ?? 'P-256' - switch (crv) { - case 'P-256': - case 'P-384': - case 'P-521': { - algorithm = { name: 'ECDH', namedCurve: crv } - break - } - case 'X25519': - case 'X448': - algorithm = { name: crv } - break - default: - throw new JOSENotSupported( - 'Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448', - ) - } - break - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') - } - - return >( - crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) - ) -} diff --git a/dist/deno/runtime/get_sign_verify_key.ts b/dist/deno/runtime/get_sign_verify_key.ts deleted file mode 100644 index 45a37b7eda..0000000000 --- a/dist/deno/runtime/get_sign_verify_key.ts +++ /dev/null @@ -1,35 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkSigCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' -import normalize from './normalize_key.ts' - -export default async function getCryptoKey(alg: string, key: unknown, usage: KeyUsage) { - if (usage === 'sign') { - key = await normalize.normalizePrivateKey(key, alg) - } - - if (usage === 'verify') { - key = await normalize.normalizePublicKey(key, alg) - } - - if (isCryptoKey(key)) { - checkSigCryptoKey(key, alg, usage) - return key - } - - if (key instanceof Uint8Array) { - if (!alg.startsWith('HS')) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - return crypto.subtle.importKey( - 'raw', - key, - { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, - false, - [usage], - ) - } - - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key')) -} diff --git a/dist/deno/runtime/interfaces.d.ts b/dist/deno/runtime/interfaces.d.ts deleted file mode 100644 index 3f0887fa92..0000000000 --- a/dist/deno/runtime/interfaces.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type { JWK, KeyLike } from '../types.d.ts' -import type { PEMImportOptions } from '../key/import.ts' - -type AsyncOrSync = Promise | T - -export interface TimingSafeEqual { - (a: Uint8Array, b: Uint8Array): boolean -} -export interface SignFunction { - (alg: string, key: unknown, data: Uint8Array): Promise -} -export interface VerifyFunction { - (alg: string, key: unknown, signature: Uint8Array, data: Uint8Array): Promise -} -export interface AesKwWrapFunction { - (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync -} -export interface AesKwUnwrapFunction { - (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync -} -export interface RsaEsEncryptFunction { - (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync -} -export interface RsaEsDecryptFunction { - (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync -} -export interface Pbes2KWEncryptFunction { - ( - alg: string, - key: unknown, - cek: Uint8Array, - p2c?: number, - p2s?: Uint8Array, - ): Promise<{ - encryptedKey: Uint8Array - p2c: number - p2s: string - }> -} -export interface Pbes2KWDecryptFunction { - ( - alg: string, - key: unknown, - encryptedKey: Uint8Array, - p2c: number, - p2s: Uint8Array, - ): Promise -} -export interface EncryptFunction { - ( - enc: string, - plaintext: Uint8Array, - cek: unknown, - iv: Uint8Array | undefined, - aad: Uint8Array, - ): AsyncOrSync<{ - ciphertext: Uint8Array - tag: Uint8Array | undefined - iv: Uint8Array | undefined - }> -} -export interface DecryptFunction { - ( - enc: string, - cek: unknown, - ciphertext: Uint8Array, - iv: Uint8Array | undefined, - tag: Uint8Array | undefined, - additionalData: Uint8Array, - ): AsyncOrSync -} -export interface FetchFunction { - (url: URL, timeout: number, options?: any): Promise<{ [propName: string]: unknown }> -} -export interface DigestFunction { - (digest: 'sha256' | 'sha384' | 'sha512', data: Uint8Array): AsyncOrSync -} -export interface PEMImportFunction { - (pem: string, alg: string, options?: PEMImportOptions): AsyncOrSync -} -interface ExportFunction { - (key: unknown): AsyncOrSync -} -export type JWKExportFunction = ExportFunction -export type PEMExportFunction = ExportFunction diff --git a/dist/deno/runtime/is_key_like.ts b/dist/deno/runtime/is_key_like.ts deleted file mode 100644 index 508c19b4b9..0000000000 --- a/dist/deno/runtime/is_key_like.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { KeyLike } from '../types.d.ts' -import { isCryptoKey } from './webcrypto.ts' - -export default (key: unknown): key is KeyLike => { - if (isCryptoKey(key)) { - return true - } - - // @ts-expect-error - return key?.[Symbol.toStringTag] === 'KeyObject' -} - -export const types = ['CryptoKey'] diff --git a/dist/deno/runtime/jwk_to_key.ts b/dist/deno/runtime/jwk_to_key.ts deleted file mode 100644 index dfc5e9a903..0000000000 --- a/dist/deno/runtime/jwk_to_key.ts +++ /dev/null @@ -1,110 +0,0 @@ -import crypto from './webcrypto.ts' -import { JOSENotSupported } from '../util/errors.ts' -import type { JWK } from '../types.d.ts' - -function subtleMapping(jwk: JWK): { - algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm - keyUsages: KeyUsage[] -} { - let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm - let keyUsages: KeyUsage[] - - 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 'EdDSA': - algorithm = { name: jwk.crv! } - 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 } -} - -const parse = async (jwk: JWK): Promise => { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present') - } - - const { algorithm, keyUsages } = subtleMapping(jwk) - const rest: [RsaHashedImportParams | EcKeyAlgorithm | Algorithm, boolean, KeyUsage[]] = [ - algorithm, - jwk.ext ?? false, - jwk.key_ops ?? keyUsages, - ] - - const keyData: JWK = { ...jwk } - delete keyData.alg - delete keyData.use - return crypto.subtle.importKey('jwk', keyData, ...rest) -} -export default parse diff --git a/dist/deno/runtime/key_to_jwk.ts b/dist/deno/runtime/key_to_jwk.ts deleted file mode 100644 index c279b618cc..0000000000 --- a/dist/deno/runtime/key_to_jwk.ts +++ /dev/null @@ -1,25 +0,0 @@ -import crypto, { isCryptoKey } from './webcrypto.ts' -import type { JWKExportFunction } from './interfaces.d.ts' -import type { JWK } from '../types.d.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { encode as base64url } from './base64url.ts' -import { types } from './is_key_like.ts' - -const keyToJWK: JWKExportFunction = async (key: unknown): Promise => { - if (key instanceof Uint8Array) { - return { - kty: 'oct', - k: base64url(key), - } - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) - } - if (!key.extractable) { - throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK') - } - const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key) - - return jwk -} -export default keyToJWK diff --git a/dist/deno/runtime/normalize_key.ts b/dist/deno/runtime/normalize_key.ts deleted file mode 100644 index 3b1bbeeac8..0000000000 --- a/dist/deno/runtime/normalize_key.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { isJWK } from '../lib/is_jwk.ts' -import type { JWK, KeyLike } from '../types.d.ts' -import { decode } from './base64url.ts' -import importJWK from './jwk_to_key.ts' - -const exportKeyValue = (k: string) => decode(k) - -let privCache: WeakMap> -let pubCache: WeakMap> - -const isKeyObject = (key: unknown): key is KeyLike => { - // @ts-expect-error - return key?.[Symbol.toStringTag] === 'KeyObject' -} - -const importAndCache = async ( - cache: typeof privCache | typeof pubCache, - key: KeyLike | JWK, - jwk: JWK, - alg: string, - freeze = false, -) => { - let cached = cache.get(key) - if (cached?.[alg]) { - return cached[alg] - } - - const cryptoKey = await importJWK({ ...jwk, alg }) - if (freeze) Object.freeze(key) - if (!cached) { - cache.set(key, { [alg]: cryptoKey }) - } else { - cached[alg] = cryptoKey - } - return cryptoKey -} - -const normalizePublicKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: string) => { - if (isKeyObject(key)) { - // @ts-expect-error - let jwk: JWK = key.export({ format: 'jwk' }) - delete jwk.d - delete jwk.dp - delete jwk.dq - delete jwk.p - delete jwk.q - delete jwk.qi - if (jwk.k) { - return exportKeyValue(jwk.k) - } - - pubCache ||= new WeakMap() - return importAndCache(pubCache, key, jwk, alg) - } - - if (isJWK(key)) { - if (key.k) return decode(key.k) - pubCache ||= new WeakMap() - const cryptoKey = importAndCache(pubCache, key, key, alg, true) - return cryptoKey - } - - return key -} - -const normalizePrivateKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: string) => { - if (isKeyObject(key)) { - // @ts-expect-error - let jwk: JWK = key.export({ format: 'jwk' }) - if (jwk.k) { - return exportKeyValue(jwk.k) - } - - privCache ||= new WeakMap() - return importAndCache(privCache, key, jwk, alg) - } - - if (isJWK(key)) { - if (key.k) return decode(key.k) - privCache ||= new WeakMap() - const cryptoKey = importAndCache(privCache, key, key, alg, true) - return cryptoKey - } - - return key -} - -export default { normalizePublicKey, normalizePrivateKey } diff --git a/dist/deno/runtime/pbes2kw.ts b/dist/deno/runtime/pbes2kw.ts deleted file mode 100644 index ebaafc32a9..0000000000 --- a/dist/deno/runtime/pbes2kw.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type { Pbes2KWDecryptFunction, Pbes2KWEncryptFunction } from './interfaces.d.ts' -import random from './random.ts' -import { p2s as concatSalt } from '../lib/buffer_utils.ts' -import { encode as base64url } from './base64url.ts' -import { wrap, unwrap } from './aeskw.ts' -import checkP2s from '../lib/check_p2s.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' - -function getCryptoKey(key: unknown, alg: string) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']) - } - - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey') - return key - } - - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) -} - -async function deriveKey(p2s: Uint8Array, alg: string, p2c: number, key: unknown) { - checkP2s(p2s) - - 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 wrapAlg = { - length: keylen, - name: 'AES-KW', - } - - const cryptoKey = await getCryptoKey(key, alg) - - if (cryptoKey.usages.includes('deriveBits')) { - return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)) - } - - if (cryptoKey.usages.includes('deriveKey')) { - return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']) - } - - throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"') -} - -export const encrypt: Pbes2KWEncryptFunction = async ( - alg: string, - key: unknown, - cek: Uint8Array, - p2c = 2048, - p2s: Uint8Array = random(new Uint8Array(16)), -) => { - const derived = await deriveKey(p2s, alg, p2c, key) - - const encryptedKey = await wrap(alg.slice(-6), derived, cek) - - return { encryptedKey, p2c, p2s: base64url(p2s) } -} - -export const decrypt: Pbes2KWDecryptFunction = async ( - alg: string, - key: unknown, - encryptedKey: Uint8Array, - p2c: number, - p2s: Uint8Array, -) => { - const derived = await deriveKey(p2s, alg, p2c, key) - - return unwrap(alg.slice(-6), derived, encryptedKey) -} diff --git a/dist/deno/runtime/random.ts b/dist/deno/runtime/random.ts deleted file mode 100644 index b885796ffb..0000000000 --- a/dist/deno/runtime/random.ts +++ /dev/null @@ -1,3 +0,0 @@ -import crypto from './webcrypto.ts' - -export default crypto.getRandomValues.bind(crypto) diff --git a/dist/deno/runtime/rsaes.ts b/dist/deno/runtime/rsaes.ts deleted file mode 100644 index e5e4bd514e..0000000000 --- a/dist/deno/runtime/rsaes.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { RsaEsDecryptFunction, RsaEsEncryptFunction } from './interfaces.d.ts' -import subtleAlgorithm from './subtle_rsaes.ts' -import bogusWebCrypto from './bogus.ts' -import crypto, { isCryptoKey } from './webcrypto.ts' -import { checkEncCryptoKey } from '../lib/crypto_key.ts' -import checkKeyLength from './check_key_length.ts' -import invalidKeyInput from '../lib/invalid_key_input.ts' -import { types } from './is_key_like.ts' - -export const encrypt: RsaEsEncryptFunction = async (alg: string, key: unknown, cek: Uint8Array) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey') - checkKeyLength(alg, key) - - if (key.usages.includes('encrypt')) { - return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)) - } - - if (key.usages.includes('wrapKey')) { - // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant - const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) - return new Uint8Array( - await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)), - ) - } - - throw new TypeError( - 'RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation', - ) -} - -export const decrypt: RsaEsDecryptFunction = async ( - alg: string, - key: unknown, - encryptedKey: Uint8Array, -) => { - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, ...types)) - } - checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey') - checkKeyLength(alg, key) - - if (key.usages.includes('decrypt')) { - return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)) - } - - if (key.usages.includes('unwrapKey')) { - const cryptoKeyCek = await crypto.subtle.unwrapKey( - 'raw', - encryptedKey, - key, - subtleAlgorithm(alg), - ...bogusWebCrypto, - ) - - return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) - } - - throw new TypeError( - 'RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation', - ) -} diff --git a/dist/deno/runtime/runtime.ts b/dist/deno/runtime/runtime.ts deleted file mode 100644 index 0c7d6bc3cd..0000000000 --- a/dist/deno/runtime/runtime.ts +++ /dev/null @@ -1 +0,0 @@ -export default 'WebCryptoAPI' diff --git a/dist/deno/runtime/sign.ts b/dist/deno/runtime/sign.ts deleted file mode 100644 index 8a0c5af1b6..0000000000 --- a/dist/deno/runtime/sign.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { SignFunction } from './interfaces.d.ts' -import subtleAlgorithm from './subtle_dsa.ts' -import crypto from './webcrypto.ts' -import checkKeyLength from './check_key_length.ts' -import getSignKey from './get_sign_verify_key.ts' - -const sign: SignFunction = async (alg, key: unknown, data) => { - const cryptoKey = await getSignKey(alg, key, 'sign') - checkKeyLength(alg, cryptoKey) - const signature = await crypto.subtle.sign( - subtleAlgorithm(alg, cryptoKey.algorithm), - cryptoKey, - data, - ) - return new Uint8Array(signature) -} - -export default sign diff --git a/dist/deno/runtime/subtle_dsa.ts b/dist/deno/runtime/subtle_dsa.ts deleted file mode 100644 index b76897b0bb..0000000000 --- a/dist/deno/runtime/subtle_dsa.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { JOSENotSupported } from '../util/errors.ts' - -export default function subtleDsa(alg: string, algorithm: KeyAlgorithm | EcKeyAlgorithm) { - const hash = `SHA-${alg.slice(-3)}` - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - return { hash, name: 'HMAC' } - case 'PS256': - case 'PS384': - case 'PS512': - // @ts-expect-error - return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 } - case 'RS256': - case 'RS384': - case 'RS512': - return { hash, name: 'RSASSA-PKCS1-v1_5' } - case 'ES256': - case 'ES384': - case 'ES512': - return { hash, name: 'ECDSA', namedCurve: (algorithm).namedCurve } - case 'EdDSA': - return { name: algorithm.name } - default: - throw new JOSENotSupported( - `alg ${alg} is not supported either by JOSE or your javascript runtime`, - ) - } -} diff --git a/dist/deno/runtime/subtle_rsaes.ts b/dist/deno/runtime/subtle_rsaes.ts deleted file mode 100644 index 16fb3d3c59..0000000000 --- a/dist/deno/runtime/subtle_rsaes.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { JOSENotSupported } from '../util/errors.ts' - -export default function subtleRsaEs(alg: string) { - 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`, - ) - } -} diff --git a/dist/deno/runtime/timing_safe_equal.ts b/dist/deno/runtime/timing_safe_equal.ts deleted file mode 100644 index 53bc719686..0000000000 --- a/dist/deno/runtime/timing_safe_equal.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { TimingSafeEqual } from './interfaces.d.ts' - -const timingSafeEqual: 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') - } - if (a.length !== b.length) { - throw new TypeError('Input buffers must have the same length') - } - - const len = a.length - let out = 0 - let i = -1 - while (++i < len) { - out |= a[i] ^ b[i] - } - return out === 0 -} - -export default timingSafeEqual diff --git a/dist/deno/runtime/verify.ts b/dist/deno/runtime/verify.ts deleted file mode 100644 index c904d9422e..0000000000 --- a/dist/deno/runtime/verify.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { VerifyFunction } from './interfaces.d.ts' -import subtleAlgorithm from './subtle_dsa.ts' -import crypto from './webcrypto.ts' -import checkKeyLength from './check_key_length.ts' -import getVerifyKey from './get_sign_verify_key.ts' - -const verify: VerifyFunction = async (alg, key: unknown, signature, data) => { - const cryptoKey = await getVerifyKey(alg, key, 'verify') - checkKeyLength(alg, cryptoKey) - const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm) - try { - return await crypto.subtle.verify(algorithm, cryptoKey, signature, data) - } catch { - return false - } -} - -export default verify diff --git a/dist/deno/runtime/webcrypto.ts b/dist/deno/runtime/webcrypto.ts deleted file mode 100644 index fd524e1fe4..0000000000 --- a/dist/deno/runtime/webcrypto.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default crypto - -export const isCryptoKey = (key: unknown): key is CryptoKey => key instanceof CryptoKey diff --git a/dist/deno/types.d.ts b/dist/deno/types.d.ts deleted file mode 100644 index 7c85b17481..0000000000 --- a/dist/deno/types.d.ts +++ /dev/null @@ -1,716 +0,0 @@ -/** - * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are - * instances of {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} and - * additionally {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} in Node.js - * runtime. - * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array Uint8Array} - * instances are also accepted as symmetric secret representation only. - * - * [Key Import Functions](../modules/key_import.md) can be used to import PEM, or JWK formatted - * asymmetric keys and certificates to these runtime-specific representations. - * - * In Node.js the {@link https://nodejs.org/api/buffer.html#buffer Buffer} class is a subclass of - * Uint8Array and so Buffer can be provided for symmetric secrets as well. - * - * {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} is a representation of a - * key/secret available in the Node.js runtime. In addition to the import functions of this library - * you may use the runtime APIs - * {@link https://nodejs.org/api/crypto.html#cryptocreatepublickeykey crypto.createPublicKey}, - * {@link https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey crypto.createPrivateKey}, and - * {@link https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding crypto.createSecretKey} - * to obtain a `KeyObject` from your existing key material. - * - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} is a representation - * of a key/secret available in the Browser and Web-interoperable runtimes. In addition to the - * import functions of this library you may use the - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey} - * API to obtain a CryptoKey from your existing key material. - * - */ -export type KeyLike = { type: string } - -/** Generic JSON Web Key Parameters. */ -export interface JWKParameters { - /** JWK "kty" (Key Type) Parameter. */ - kty: string - /** JWK "alg" (Algorithm) Parameter. */ - alg?: string - /** JWK "key_ops" (Key Operations) Parameter. */ - key_ops?: string[] - /** JWK "ext" (Extractable) Parameter. */ - ext?: boolean - /** JWK "use" (Public Key Use) Parameter. */ - use?: string - /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ - x5c?: string[] - /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ - x5t?: string - /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ - 'x5t#S256'?: string - /** JWK "x5u" (X.509 URL) Parameter. */ - x5u?: string - /** JWK "kid" (Key ID) Parameter. */ - kid?: string - - [propName: string]: unknown -} - -/** Convenience interface for Public OKP JSON Web Keys */ -export interface JWK_OKP_Public extends JWKParameters { - /** The Subtype of Key Pair */ - crv: string - /** The public key */ - x: string - - [propName: string]: unknown -} - -/** Convenience interface for Private OKP JSON Web Keys */ -export interface JWK_OKP_Private extends JWK_OKP_Public, JWKParameters { - /** The Private Key */ - d: string - - [propName: string]: unknown -} - -/** Convenience interface for Public EC JSON Web Keys */ -export interface JWK_EC_Public extends JWKParameters { - /** Curve */ - crv: string - /** X Coordinate */ - x: string - /** Y Coordinate */ - y: string - - [propName: string]: unknown -} - -/** Convenience interface for Private EC JSON Web Keys */ -export interface JWK_EC_Private extends JWK_EC_Public, JWKParameters { - /** ECC Private Key */ - d: string - - [propName: string]: unknown -} - -/** Convenience interface for Public RSA JSON Web Keys */ -export interface JWK_RSA_Public extends JWKParameters { - /** Exponent */ - e: string - /** Modulus */ - n: string - - [propName: string]: unknown -} - -/** Convenience interface for Private RSA JSON Web Keys */ -export interface JWK_RSA_Private extends JWK_RSA_Public, JWKParameters { - /** Private Exponent */ - d: string - /** First Factor CRT Exponent */ - dp: string - /** Second Factor CRT Exponent */ - dq: string - /** Other Primes Info. This parameter is not supported. */ - oth?: Array<{ - d?: string - r?: string - t?: string - }> - /** First Prime Factor */ - p: string - /** Second Prime Factor */ - q: string - /** First CRT Coefficient */ - qi: string - - [propName: string]: unknown -} - -/** Convenience interface for oct JSON Web Keys */ -export interface JWK_oct extends JWKParameters { - /** Key Value */ - k: string - - [propName: string]: unknown -} - -/** - * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct" - * key types are supported. - * - * @see {@link JWK_OKP_Public} - * @see {@link JWK_OKP_Private} - * @see {@link JWK_EC_Public} - * @see {@link JWK_EC_Private} - * @see {@link JWK_RSA_Public} - * @see {@link JWK_RSA_Private} - * @see {@link JWK_oct} - */ -export interface JWK extends JWKParameters { - /** - * - (EC) Curve - * - (OKP) The Subtype of Key Pair - */ - crv?: string - /** - * - (Private RSA) Private Exponent - * - (Private EC) ECC Private Key - * - (Private OKP) The Private Key - */ - d?: string - /** (Private RSA) First Factor CRT Exponent */ - dp?: string - /** (Private RSA) Second Factor CRT Exponent */ - dq?: string - /** (RSA) Exponent */ - e?: string - /** (oct) Key Value */ - k?: string - /** (RSA) Modulus */ - n?: string - /** (Private RSA) Other Primes Info. This parameter is not supported. */ - oth?: Array<{ - d?: string - r?: string - t?: string - }> - /** (Private RSA) First Prime Factor */ - p?: string - /** (Private RSA) Second Prime Factor */ - q?: string - /** (Private RSA) First CRT Coefficient */ - qi?: string - /** - * - (EC) X Coordinate - * - (OKP) The public key - */ - x?: string - /** (EC) Y Coordinate */ - y?: string - - [propName: string]: unknown -} - -/** - * @private - * - * @internal - */ -export interface GenericGetKeyFunction { - /** - * Dynamic key resolution function. No token components have been verified at the time of this - * function call. - * - * If you cannot match a key suitable for the token, throw an error instead. - * - * @param protectedHeader JWE or JWS Protected Header. - * @param token The consumed JWE or JWS token. - */ - (protectedHeader: IProtectedHeader, token: IToken): Promise | ReturnKeyTypes -} - -/** - * Generic Interface for consuming operations dynamic key resolution. - * - * @param IProtectedHeader Type definition of the JWE or JWS Protected Header. - * @param IToken Type definition of the consumed JWE or JWS token. - */ -export interface GetKeyFunction - extends GenericGetKeyFunction {} - -/** - * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached - * signature validation. - */ -export interface FlattenedJWSInput { - /** - * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS - * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented - * as an unencoded JSON object, rather than as a string. These Header Parameter values are not - * integrity protected. - */ - header?: JWSHeaderParameters - - /** - * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 - * "b64": false is used the value passed may also be a Uint8Array. - */ - payload: string | Uint8Array - - /** - * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected - * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These - * Header Parameter values are integrity protected. - */ - protected?: string - - /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ - signature: string -} - -/** - * General JWS definition for verify function inputs, allows payload as Uint8Array for detached - * signature validation. - */ -export interface GeneralJWSInput { - /** - * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when - * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is - * used the value passed may also be a Uint8Array. - */ - payload: string | Uint8Array - - /** - * The "signatures" member value MUST be an array of JSON objects. Each object represents a - * signature or MAC over the JWS Payload and the JWS Protected Header. - */ - signatures: Omit[] -} - -/** - * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload - * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. - */ -export interface FlattenedJWS extends Partial { - payload: string - signature: string -} - -/** - * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload - * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. - */ -export interface GeneralJWS { - payload: string - signatures: Omit[] -} - -export interface JoseHeaderParameters { - /** "kid" (Key ID) Header Parameter. */ - kid?: string - - /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ - x5t?: string - - /** "x5c" (X.509 Certificate Chain) Header Parameter. */ - x5c?: string[] - - /** "x5u" (X.509 URL) Header Parameter. */ - x5u?: string - - /** "jku" (JWK Set URL) Header Parameter. */ - jku?: string - - /** "jwk" (JSON Web Key) Header Parameter. */ - jwk?: Pick - - /** "typ" (Type) Header Parameter. */ - typ?: string - - /** "cty" (Content Type) Header Parameter. */ - cty?: string -} - -/** Recognized JWS Header Parameters, any other Header Members may also be present. */ -export interface JWSHeaderParameters extends JoseHeaderParameters { - /** JWS "alg" (Algorithm) Header Parameter. */ - alg?: string - - /** - * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing - * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}. - */ - b64?: boolean - - /** JWS "crit" (Critical) Header Parameter. */ - crit?: string[] - - /** Any other JWS Header member. */ - [propName: string]: unknown -} - -/** Recognized JWE Key Management-related Header Parameters. */ -export interface JWEKeyManagementHeaderParameters { - apu?: Uint8Array - apv?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - p2c?: number - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - p2s?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - iv?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - epk?: KeyLike -} - -/** Flattened JWE definition. */ -export interface FlattenedJWE { - /** - * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD - * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a - * base64url-encoded value to be integrity protected but not encrypted. - */ - aad?: string - - /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ - ciphertext: string - - /** - * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) - * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. - */ - encrypted_key?: string - - /** - * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header - * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. - * This value is represented as an unencoded JSON object, rather than as a string. These Header - * Parameter values are not integrity protected. - */ - header?: JWEHeaderParameters - - /** - * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when - * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. - */ - iv?: string - - /** - * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected - * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These - * Header Parameter values are integrity protected. - */ - protected?: string - - /** - * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when - * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. - */ - tag?: string - - /** - * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header - * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This - * value is represented as an unencoded JSON object, rather than as a string. These Header - * Parameter values are not integrity protected. - */ - unprotected?: JWEHeaderParameters -} - -export interface GeneralJWE extends Omit { - recipients: Pick[] -} - -/** Recognized JWE Header Parameters, any other Header members may also be present. */ -export interface JWEHeaderParameters extends JoseHeaderParameters { - /** JWE "alg" (Algorithm) Header Parameter. */ - alg?: string - - /** JWE "enc" (Encryption Algorithm) Header Parameter. */ - enc?: string - - /** JWE "crit" (Critical) Header Parameter. */ - crit?: string[] - - /** - * JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore. - * - * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed - * data often reveals information about the plaintext. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} - */ - zip?: string - - /** Any other JWE Header member. */ - [propName: string]: unknown -} - -/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ -export interface CritOption { - /** - * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value - * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity - * protected, `false` when it's irrelevant. - * - * This makes the "Extension Header Parameter "..." is not recognized" error go away. - * - * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" - * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically - * correct when provided and that it is optionally integrity protected. It will not process the - * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the - * Header Parameter was present and process it according to the profile's validation steps after - * the operation succeeds. - * - * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other - * registered Header Parameters that need this kind of default built-in treatment are currently - * available. - */ - crit?: { - [propName: string]: boolean - } -} - -/** JWE Decryption options. */ -export interface DecryptOptions extends CritOption { - /** - * A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg" - * (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for - * all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option. - */ - keyManagementAlgorithms?: string[] - - /** - * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all - * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. - */ - contentEncryptionAlgorithms?: string[] - - /** - * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter - * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default - * this value is set to 10000. - */ - maxPBES2Count?: number -} - -/** JWE Encryption options. */ -export interface EncryptOptions extends CritOption {} - -/** JWT Claims Set verification options. */ -export interface JWTClaimVerificationOptions { - /** - * Expected JWT "aud" (Audience) Claim value(s). - * - * This option makes the JWT "aud" (Audience) Claim presence required. - */ - audience?: string | string[] - - /** - * Expected clock tolerance - * - * - In seconds when number (e.g. 5) - * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). - */ - clockTolerance?: string | number - - /** - * Expected JWT "iss" (Issuer) Claim value(s). - * - * This option makes the JWT "iss" (Issuer) Claim presence required. - */ - issuer?: string | string[] - - /** - * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. - * - * - In seconds when number (e.g. 5) - * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). - * - * This option makes the JWT "iat" (Issued At) Claim presence required. - */ - maxTokenAge?: string | number - - /** - * Expected JWT "sub" (Subject) Claim value. - * - * This option makes the JWT "sub" (Subject) Claim presence required. - */ - subject?: string - - /** - * Expected JWT "typ" (Type) Header Parameter value. - * - * This option makes the JWT "typ" (Type) Header Parameter presence required. - */ - typ?: string - - /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ - currentDate?: Date - - /** - * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if - * the {@link JWTClaimVerificationOptions.issuer `issuer` option} is set, then JWT "iss" (Issuer) - * Claim must be present; if the {@link JWTClaimVerificationOptions.audience `audience` option} is - * set, then JWT "aud" (Audience) Claim must be present; if the - * {@link JWTClaimVerificationOptions.subject `subject` option} is set, then JWT "sub" (Subject) - * Claim must be present; if the - * {@link JWTClaimVerificationOptions.maxTokenAge `maxTokenAge` option} is set, then JWT "iat" - * (Issued At) Claim must be present. - */ - requiredClaims?: string[] -} - -/** JWS Verification options. */ -export interface VerifyOptions extends CritOption { - /** - * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" - * (Algorithm) values applicable for the used key/secret are allowed. - * - * Note: Unsecured JWTs (`{ "alg": "none" }`) are never accepted by this API. - */ - algorithms?: string[] -} - -/** JWS Signing options. */ -export interface SignOptions extends CritOption {} - -/** Recognized JWT Claims Set members, any other members may also be present. */ -export interface JWTPayload { - /** - * JWT Issuer - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1} - */ - iss?: string - - /** - * JWT Subject - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2} - */ - sub?: string - - /** - * JWT Audience - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3} - */ - aud?: string | string[] - - /** - * JWT ID - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7} - */ - jti?: string - - /** - * JWT Not Before - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5} - */ - nbf?: number - - /** - * JWT Expiration Time - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4} - */ - exp?: number - - /** - * JWT Issued At - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6} - */ - iat?: number - - /** Any other JWT Claim Set member. */ - [propName: string]: unknown -} - -export interface FlattenedDecryptResult { - /** JWE AAD. */ - additionalAuthenticatedData?: Uint8Array - - /** Plaintext. */ - plaintext: Uint8Array - - /** JWE Protected Header. */ - protectedHeader?: JWEHeaderParameters - - /** JWE Shared Unprotected Header. */ - sharedUnprotectedHeader?: JWEHeaderParameters - - /** JWE Per-Recipient Unprotected Header. */ - unprotectedHeader?: JWEHeaderParameters -} - -export interface GeneralDecryptResult extends FlattenedDecryptResult {} - -export interface CompactDecryptResult { - /** Plaintext. */ - plaintext: Uint8Array - - /** JWE Protected Header. */ - protectedHeader: CompactJWEHeaderParameters -} - -export interface FlattenedVerifyResult { - /** JWS Payload. */ - payload: Uint8Array - - /** JWS Protected Header. */ - protectedHeader?: JWSHeaderParameters - - /** JWS Unprotected Header. */ - unprotectedHeader?: JWSHeaderParameters -} - -export interface GeneralVerifyResult extends FlattenedVerifyResult {} - -export interface CompactVerifyResult { - /** JWS Payload. */ - payload: Uint8Array - - /** JWS Protected Header. */ - protectedHeader: CompactJWSHeaderParameters -} - -export interface JWTVerifyResult { - /** JWT Claims Set. */ - payload: PayloadType & JWTPayload - - /** JWS Protected Header. */ - protectedHeader: JWTHeaderParameters -} - -export interface JWTDecryptResult { - /** JWT Claims Set. */ - payload: PayloadType & JWTPayload - - /** JWE Protected Header. */ - protectedHeader: CompactJWEHeaderParameters -} - -export interface ResolvedKey { - /** Key resolved from the key resolver function. */ - key: KeyLikeType | Uint8Array -} - -/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ -export interface CompactJWSHeaderParameters extends JWSHeaderParameters { - alg: string -} - -/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ -export interface JWTHeaderParameters extends CompactJWSHeaderParameters { - b64?: true -} - -/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ -export interface CompactJWEHeaderParameters extends JWEHeaderParameters { - alg: string - enc: string -} - -/** JSON Web Key Set */ -export interface JSONWebKeySet { - keys: JWK[] -} - -export type CryptoRuntime = 'WebCryptoAPI' | 'node:crypto' diff --git a/dist/deno/util/base64url.ts b/dist/deno/util/base64url.ts deleted file mode 100644 index f3d76163fc..0000000000 --- a/dist/deno/util/base64url.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as base64url from '../runtime/base64url.ts' - -/** - * Utility function to encode a string or Uint8Array as a base64url string. - * - * @param input Value that will be base64url-encoded. - */ -interface Base64UrlEncode { - (input: Uint8Array | string): string -} -/** - * Utility function to decode a base64url encoded string. - * - * @param input Value that will be base64url-decoded. - */ -interface Base64UrlDecode { - (input: Uint8Array | string): Uint8Array -} - -export const encode: Base64UrlEncode = base64url.encode -export const decode: Base64UrlDecode = base64url.decode diff --git a/dist/deno/util/decode_jwt.ts b/dist/deno/util/decode_jwt.ts deleted file mode 100644 index 297545afbd..0000000000 --- a/dist/deno/util/decode_jwt.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { decode as base64url } from './base64url.ts' -import { decoder } from '../lib/buffer_utils.ts' -import isObject from '../lib/is_object.ts' -import type { JWTPayload } from '../types.d.ts' -import { JWTInvalid } from './errors.ts' - -/** - * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or - * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation - * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation - * and JWE decryption use `jose.jwtDecrypt()`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/decode'`. - * - * @param jwt JWT token in compact JWS serialization. - */ -export function decodeJwt(jwt: string): PayloadType & JWTPayload { - if (typeof jwt !== 'string') - throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string') - - const { 1: payload, length } = jwt.split('.') - - if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded') - if (length !== 3) throw new JWTInvalid('Invalid JWT') - if (!payload) throw new JWTInvalid('JWTs must contain a payload') - - let decoded: Uint8Array - try { - decoded = base64url(payload) - } catch { - throw new JWTInvalid('Failed to base64url decode the payload') - } - - let result: unknown - try { - result = JSON.parse(decoder.decode(decoded)) - } catch { - throw new JWTInvalid('Failed to parse the decoded payload as JSON') - } - - if (!isObject(result)) throw new JWTInvalid('Invalid JWT Claims Set') - - return result -} diff --git a/dist/deno/util/decode_protected_header.ts b/dist/deno/util/decode_protected_header.ts deleted file mode 100644 index fd4c80cdf1..0000000000 --- a/dist/deno/util/decode_protected_header.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { decode as base64url } from './base64url.ts' -import { decoder } from '../lib/buffer_utils.ts' -import isObject from '../lib/is_object.ts' -import type { JWSHeaderParameters, JWEHeaderParameters } from '../types.d.ts' - -export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters - -/** - * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/decode/protected_header'`. - * - * @param token JWE/JWS/JWT token in any JOSE serialization. - */ -export function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters { - let protectedB64u!: unknown - - if (typeof token === 'string') { - const parts = token.split('.') - if (parts.length === 3 || parts.length === 5) { - ;[protectedB64u] = parts - } - } else if (typeof token === 'object' && token) { - if ('protected' in token) { - protectedB64u = token.protected - } else { - throw new TypeError('Token does not contain a Protected Header') - } - } - - try { - if (typeof protectedB64u !== 'string' || !protectedB64u) { - throw new Error() - } - const result = JSON.parse(decoder.decode(base64url(protectedB64u!))) - if (!isObject(result)) { - throw new Error() - } - return result - } catch { - throw new TypeError('Invalid Token or Protected Header formatting') - } -} diff --git a/dist/deno/util/errors.ts b/dist/deno/util/errors.ts deleted file mode 100644 index d4198dd8b2..0000000000 --- a/dist/deno/util/errors.ts +++ /dev/null @@ -1,266 +0,0 @@ -import type { JWTPayload, KeyLike } from '../types.d.ts' - -/** - * A generic Error that all other JOSE specific Error subclasses extend. - * - */ -export class JOSEError extends Error { - /** - * A unique error code for the particular error subclass. - * - * @ignore - */ - static get code(): string { - return 'ERR_JOSE_GENERIC' - } - - /** A unique error code for this particular error subclass. */ - code = 'ERR_JOSE_GENERIC' - - /** @ignore */ - constructor(message?: string) { - super(message) - this.name = this.constructor.name - // @ts-ignore - Error.captureStackTrace?.(this, this.constructor) - } -} - -/** - * An error subclass thrown when a JWT Claim Set member validation fails. - * - */ -export class JWTClaimValidationFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED' { - return 'ERR_JWT_CLAIM_VALIDATION_FAILED' - } - - code = 'ERR_JWT_CLAIM_VALIDATION_FAILED' - - /** The Claim for which the validation failed. */ - claim: string - - /** Reason code for the validation failure. */ - reason: string - - /** - * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at - * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity - * has however been verified. Claims Set verification happens after the JWS Signature or JWE - * Decryption processes. - */ - payload: JWTPayload - - /** @ignore */ - constructor(message: string, payload: JWTPayload, claim = 'unspecified', reason = 'unspecified') { - super(message) - this.claim = claim - this.reason = reason - this.payload = payload - } -} - -/** - * An error subclass thrown when a JWT is expired. - * - */ -export class JWTExpired extends JOSEError implements JWTClaimValidationFailed { - /** @ignore */ - static get code(): 'ERR_JWT_EXPIRED' { - return 'ERR_JWT_EXPIRED' - } - - code = 'ERR_JWT_EXPIRED' - - /** The Claim for which the validation failed. */ - claim: string - - /** Reason code for the validation failure. */ - reason: string - - /** - * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at - * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity - * has however been verified. Claims Set verification happens after the JWS Signature or JWE - * Decryption processes. - */ - payload: JWTPayload - - /** @ignore */ - constructor(message: string, payload: JWTPayload, claim = 'unspecified', reason = 'unspecified') { - super(message) - this.claim = claim - this.reason = reason - this.payload = payload - } -} - -/** - * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. - * - */ -export class JOSEAlgNotAllowed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED' { - return 'ERR_JOSE_ALG_NOT_ALLOWED' - } - - code = 'ERR_JOSE_ALG_NOT_ALLOWED' -} - -/** - * An error subclass thrown when a particular feature or algorithm is not supported by this - * implementation or JOSE in general. - * - */ -export class JOSENotSupported extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JOSE_NOT_SUPPORTED' { - return 'ERR_JOSE_NOT_SUPPORTED' - } - - code = 'ERR_JOSE_NOT_SUPPORTED' -} - -/** - * An error subclass thrown when a JWE ciphertext decryption fails. - * - */ -export class JWEDecryptionFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWE_DECRYPTION_FAILED' { - return 'ERR_JWE_DECRYPTION_FAILED' - } - - code = 'ERR_JWE_DECRYPTION_FAILED' - - message = 'decryption operation failed' -} - -/** - * An error subclass thrown when a JWE is invalid. - * - */ -export class JWEInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWE_INVALID' { - return 'ERR_JWE_INVALID' - } - - code = 'ERR_JWE_INVALID' -} - -/** - * An error subclass thrown when a JWS is invalid. - * - */ -export class JWSInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWS_INVALID' { - return 'ERR_JWS_INVALID' - } - - code = 'ERR_JWS_INVALID' -} - -/** - * An error subclass thrown when a JWT is invalid. - * - */ -export class JWTInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWT_INVALID' { - return 'ERR_JWT_INVALID' - } - - code = 'ERR_JWT_INVALID' -} - -/** - * An error subclass thrown when a JWK is invalid. - * - */ -export class JWKInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWK_INVALID' { - return 'ERR_JWK_INVALID' - } - - code = 'ERR_JWK_INVALID' -} - -/** - * An error subclass thrown when a JWKS is invalid. - * - */ -export class JWKSInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_INVALID' { - return 'ERR_JWKS_INVALID' - } - - code = 'ERR_JWKS_INVALID' -} - -/** - * An error subclass thrown when no keys match from a JWKS. - * - */ -export class JWKSNoMatchingKey extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_NO_MATCHING_KEY' { - return 'ERR_JWKS_NO_MATCHING_KEY' - } - - code = 'ERR_JWKS_NO_MATCHING_KEY' - - message = 'no applicable key found in the JSON Web Key Set' -} - -/** - * An error subclass thrown when multiple keys match from a JWKS. - * - */ -export class JWKSMultipleMatchingKeys extends JOSEError { - /** @ignore */ - [Symbol.asyncIterator]!: () => AsyncIterableIterator - - static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' { - return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' - } - - code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' - - message = 'multiple matching keys found in the JSON Web Key Set' -} - -/** - * Timeout was reached when retrieving the JWKS response. - * - */ -export class JWKSTimeout extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_TIMEOUT' { - return 'ERR_JWKS_TIMEOUT' - } - - code = 'ERR_JWKS_TIMEOUT' - - message = 'request timed out' -} - -/** - * An error subclass thrown when JWS signature verification fails. - * - */ -export class JWSSignatureVerificationFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' { - return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' - } - - code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' - - message = 'signature verification failed' -} diff --git a/dist/deno/util/runtime.ts b/dist/deno/util/runtime.ts deleted file mode 100644 index a8d5e7d832..0000000000 --- a/dist/deno/util/runtime.ts +++ /dev/null @@ -1,3 +0,0 @@ -import value from '../runtime/runtime.ts' -import type { CryptoRuntime } from '../types.d.ts' -export default value as CryptoRuntime diff --git a/dist/node/cjs/index.js b/dist/node/cjs/index.js deleted file mode 100644 index 0605d816e5..0000000000 --- a/dist/node/cjs/index.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0; -var decrypt_js_1 = require("./jwe/compact/decrypt.js"); -Object.defineProperty(exports, "compactDecrypt", { enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } }); -var decrypt_js_2 = require("./jwe/flattened/decrypt.js"); -Object.defineProperty(exports, "flattenedDecrypt", { enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } }); -var decrypt_js_3 = require("./jwe/general/decrypt.js"); -Object.defineProperty(exports, "generalDecrypt", { enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } }); -var encrypt_js_1 = require("./jwe/general/encrypt.js"); -Object.defineProperty(exports, "GeneralEncrypt", { enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } }); -var verify_js_1 = require("./jws/compact/verify.js"); -Object.defineProperty(exports, "compactVerify", { enumerable: true, get: function () { return verify_js_1.compactVerify; } }); -var verify_js_2 = require("./jws/flattened/verify.js"); -Object.defineProperty(exports, "flattenedVerify", { enumerable: true, get: function () { return verify_js_2.flattenedVerify; } }); -var verify_js_3 = require("./jws/general/verify.js"); -Object.defineProperty(exports, "generalVerify", { enumerable: true, get: function () { return verify_js_3.generalVerify; } }); -var verify_js_4 = require("./jwt/verify.js"); -Object.defineProperty(exports, "jwtVerify", { enumerable: true, get: function () { return verify_js_4.jwtVerify; } }); -var decrypt_js_4 = require("./jwt/decrypt.js"); -Object.defineProperty(exports, "jwtDecrypt", { enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } }); -var encrypt_js_2 = require("./jwe/compact/encrypt.js"); -Object.defineProperty(exports, "CompactEncrypt", { enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } }); -var encrypt_js_3 = require("./jwe/flattened/encrypt.js"); -Object.defineProperty(exports, "FlattenedEncrypt", { enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } }); -var sign_js_1 = require("./jws/compact/sign.js"); -Object.defineProperty(exports, "CompactSign", { enumerable: true, get: function () { return sign_js_1.CompactSign; } }); -var sign_js_2 = require("./jws/flattened/sign.js"); -Object.defineProperty(exports, "FlattenedSign", { enumerable: true, get: function () { return sign_js_2.FlattenedSign; } }); -var sign_js_3 = require("./jws/general/sign.js"); -Object.defineProperty(exports, "GeneralSign", { enumerable: true, get: function () { return sign_js_3.GeneralSign; } }); -var sign_js_4 = require("./jwt/sign.js"); -Object.defineProperty(exports, "SignJWT", { enumerable: true, get: function () { return sign_js_4.SignJWT; } }); -var encrypt_js_4 = require("./jwt/encrypt.js"); -Object.defineProperty(exports, "EncryptJWT", { enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } }); -var thumbprint_js_1 = require("./jwk/thumbprint.js"); -Object.defineProperty(exports, "calculateJwkThumbprint", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } }); -Object.defineProperty(exports, "calculateJwkThumbprintUri", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } }); -var embedded_js_1 = require("./jwk/embedded.js"); -Object.defineProperty(exports, "EmbeddedJWK", { enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } }); -var local_js_1 = require("./jwks/local.js"); -Object.defineProperty(exports, "createLocalJWKSet", { enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } }); -var remote_js_1 = require("./jwks/remote.js"); -Object.defineProperty(exports, "createRemoteJWKSet", { enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } }); -Object.defineProperty(exports, "jwksCache", { enumerable: true, get: function () { return remote_js_1.jwksCache; } }); -Object.defineProperty(exports, "experimental_jwksCache", { enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } }); -var unsecured_js_1 = require("./jwt/unsecured.js"); -Object.defineProperty(exports, "UnsecuredJWT", { enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } }); -var export_js_1 = require("./key/export.js"); -Object.defineProperty(exports, "exportPKCS8", { enumerable: true, get: function () { return export_js_1.exportPKCS8; } }); -Object.defineProperty(exports, "exportSPKI", { enumerable: true, get: function () { return export_js_1.exportSPKI; } }); -Object.defineProperty(exports, "exportJWK", { enumerable: true, get: function () { return export_js_1.exportJWK; } }); -var import_js_1 = require("./key/import.js"); -Object.defineProperty(exports, "importSPKI", { enumerable: true, get: function () { return import_js_1.importSPKI; } }); -Object.defineProperty(exports, "importPKCS8", { enumerable: true, get: function () { return import_js_1.importPKCS8; } }); -Object.defineProperty(exports, "importX509", { enumerable: true, get: function () { return import_js_1.importX509; } }); -Object.defineProperty(exports, "importJWK", { enumerable: true, get: function () { return import_js_1.importJWK; } }); -var decode_protected_header_js_1 = require("./util/decode_protected_header.js"); -Object.defineProperty(exports, "decodeProtectedHeader", { enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } }); -var decode_jwt_js_1 = require("./util/decode_jwt.js"); -Object.defineProperty(exports, "decodeJwt", { enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } }); -exports.errors = require("./util/errors.js"); -var generate_key_pair_js_1 = require("./key/generate_key_pair.js"); -Object.defineProperty(exports, "generateKeyPair", { enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } }); -var generate_secret_js_1 = require("./key/generate_secret.js"); -Object.defineProperty(exports, "generateSecret", { enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } }); -exports.base64url = require("./util/base64url.js"); -var runtime_js_1 = require("./util/runtime.js"); -Object.defineProperty(exports, "cryptoRuntime", { enumerable: true, get: function () { return runtime_js_1.default; } }); diff --git a/dist/node/cjs/jwe/compact/decrypt.js b/dist/node/cjs/jwe/compact/decrypt.js deleted file mode 100644 index 9b175ac2bd..0000000000 --- a/dist/node/cjs/jwe/compact/decrypt.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.compactDecrypt = void 0; -const decrypt_js_1 = require("../flattened/decrypt.js"); -const errors_js_1 = require("../../util/errors.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -async function compactDecrypt(jwe, key, options) { - if (jwe instanceof Uint8Array) { - jwe = buffer_utils_js_1.decoder.decode(jwe); - } - if (typeof jwe !== 'string') { - throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); - if (length !== 5) { - throw new errors_js_1.JWEInvalid('Invalid Compact JWE'); - } - const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({ - ciphertext, - iv: iv || undefined, - protected: protectedHeader, - tag: tag || undefined, - encrypted_key: encryptedKey || undefined, - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} -exports.compactDecrypt = compactDecrypt; diff --git a/dist/node/cjs/jwe/compact/encrypt.js b/dist/node/cjs/jwe/compact/encrypt.js deleted file mode 100644 index fe0dc7d411..0000000000 --- a/dist/node/cjs/jwe/compact/encrypt.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompactEncrypt = void 0; -const encrypt_js_1 = require("../flattened/encrypt.js"); -class CompactEncrypt { - _flattened; - constructor(plaintext) { - this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); - } -} -exports.CompactEncrypt = CompactEncrypt; diff --git a/dist/node/cjs/jwe/flattened/decrypt.js b/dist/node/cjs/jwe/flattened/decrypt.js deleted file mode 100644 index 77c968e5ef..0000000000 --- a/dist/node/cjs/jwe/flattened/decrypt.js +++ /dev/null @@ -1,165 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.flattenedDecrypt = void 0; -const base64url_js_1 = require("../../runtime/base64url.js"); -const decrypt_js_1 = require("../../runtime/decrypt.js"); -const errors_js_1 = require("../../util/errors.js"); -const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); -const is_object_js_1 = require("../../lib/is_object.js"); -const decrypt_key_management_js_1 = require("../../lib/decrypt_key_management.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -const cek_js_1 = require("../../lib/cek.js"); -const validate_crit_js_1 = require("../../lib/validate_crit.js"); -const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); -async function flattenedDecrypt(jwe, key, options) { - if (!(0, is_object_js_1.default)(jwe)) { - throw new errors_js_1.JWEInvalid('Flattened JWE must be an object'); - } - if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { - throw new errors_js_1.JWEInvalid('JOSE Header missing'); - } - if (jwe.iv !== undefined && typeof jwe.iv !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type'); - } - if (typeof jwe.ciphertext !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type'); - } - if (jwe.tag !== undefined && typeof jwe.tag !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type'); - } - if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type'); - } - if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type'); - } - if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { - throw new errors_js_1.JWEInvalid('JWE AAD incorrect type'); - } - if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) { - throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type'); - } - if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) { - throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader = (0, base64url_js_1.decode)(jwe.protected); - parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); - } - catch { - throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid'); - } - } - if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected, - }; - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); - } - if (typeof enc !== 'string' || !enc) { - throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); - } - const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && - (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); - if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) || - (!keyManagementAlgorithms && alg.startsWith('PBES2'))) { - throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { - throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); - } - let encryptedKey; - if (jwe.encrypted_key !== undefined) { - try { - encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key'); - } - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jwe); - resolvedKey = true; - } - let cek; - try { - cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options); - } - catch (err) { - if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) { - throw err; - } - cek = (0, cek_js_1.default)(enc); - } - let iv; - let tag; - if (jwe.iv !== undefined) { - try { - iv = (0, base64url_js_1.decode)(jwe.iv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); - } - } - if (jwe.tag !== undefined) { - try { - tag = (0, base64url_js_1.decode)(jwe.tag); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); - } - } - const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? ''); - let additionalData; - if (jwe.aad !== undefined) { - additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad)); - } - else { - additionalData = protectedHeader; - } - let ciphertext; - try { - ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext'); - } - const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData); - const result = { plaintext }; - if (jwe.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== undefined) { - try { - result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad'); - } - } - if (jwe.unprotected !== undefined) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== undefined) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} -exports.flattenedDecrypt = flattenedDecrypt; diff --git a/dist/node/cjs/jwe/flattened/encrypt.js b/dist/node/cjs/jwe/flattened/encrypt.js deleted file mode 100644 index dd82620da3..0000000000 --- a/dist/node/cjs/jwe/flattened/encrypt.js +++ /dev/null @@ -1,165 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FlattenedEncrypt = void 0; -const base64url_js_1 = require("../../runtime/base64url.js"); -const private_symbols_js_1 = require("../../lib/private_symbols.js"); -const encrypt_js_1 = require("../../runtime/encrypt.js"); -const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); -const errors_js_1 = require("../../util/errors.js"); -const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -const validate_crit_js_1 = require("../../lib/validate_crit.js"); -class FlattenedEncrypt { - _plaintext; - _protectedHeader; - _sharedUnprotectedHeader; - _unprotectedHeader; - _aad; - _cek; - _iv; - _keyManagementParameters; - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError('plaintext must be an instance of Uint8Array'); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); - } - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader, - }; - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== 'string' || !enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && private_symbols_js_1.unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } - else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } - else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } - else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = buffer_utils_js_1.encoder.encode(''); - } - if (this._aad) { - aadMember = (0, base64url_js_1.encode)(this._aad); - additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember)); - } - else { - additionalData = protectedHeader; - } - const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: (0, base64url_js_1.encode)(ciphertext), - }; - if (iv) { - jwe.iv = (0, base64url_js_1.encode)(iv); - } - if (tag) { - jwe.tag = (0, base64url_js_1.encode)(tag); - } - if (encryptedKey) { - jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; - } -} -exports.FlattenedEncrypt = FlattenedEncrypt; diff --git a/dist/node/cjs/jwe/general/decrypt.js b/dist/node/cjs/jwe/general/decrypt.js deleted file mode 100644 index accb23aa6a..0000000000 --- a/dist/node/cjs/jwe/general/decrypt.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generalDecrypt = void 0; -const decrypt_js_1 = require("../flattened/decrypt.js"); -const errors_js_1 = require("../../util/errors.js"); -const is_object_js_1 = require("../../lib/is_object.js"); -async function generalDecrypt(jwe, key, options) { - if (!(0, is_object_js_1.default)(jwe)) { - throw new errors_js_1.JWEInvalid('General JWE must be an object'); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) { - throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type'); - } - if (!jwe.recipients.length) { - throw new errors_js_1.JWEInvalid('JWE Recipients has no members'); - } - for (const recipient of jwe.recipients) { - try { - return await (0, decrypt_js_1.flattenedDecrypt)({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected, - }, key, options); - } - catch { - } - } - throw new errors_js_1.JWEDecryptionFailed(); -} -exports.generalDecrypt = generalDecrypt; diff --git a/dist/node/cjs/jwe/general/encrypt.js b/dist/node/cjs/jwe/general/encrypt.js deleted file mode 100644 index c976a3acb2..0000000000 --- a/dist/node/cjs/jwe/general/encrypt.js +++ /dev/null @@ -1,186 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GeneralEncrypt = void 0; -const encrypt_js_1 = require("../flattened/encrypt.js"); -const private_symbols_js_1 = require("../../lib/private_symbols.js"); -const errors_js_1 = require("../../util/errors.js"); -const cek_js_1 = require("../../lib/cek.js"); -const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); -const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); -const base64url_js_1 = require("../../runtime/base64url.js"); -const validate_crit_js_1 = require("../../lib/validate_crit.js"); -class IndividualRecipient { - parent; - unprotectedHeader; - key; - options; - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } -} -class GeneralEncrypt { - _plaintext; - _recipients = []; - _protectedHeader; - _unprotectedHeader; - _aad; - constructor(plaintext) { - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new errors_js_1.JWEInvalid('at least one recipient must be added'); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .encrypt(recipient.key, { ...recipient.options }); - const jwe = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag, - }; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe.recipients[0].header = flattened.header; - return jwe; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === 'dir' || alg === 'ECDH-ES') { - throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } - else if (enc !== joseHeader.enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - } - const cek = (0, cek_js_1.default)(enc); - const jwe = { - ciphertext: '', - iv: '', - recipients: [], - tag: '', - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; - if (i === 0) { - const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setContentEncryptionKey(cek) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .setKeyManagementParameters({ p2c }) - .encrypt(recipient.key, { - ...recipient.options, - [private_symbols_js_1.unprotected]: true, - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg || - this._protectedHeader?.alg || - this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } -} -exports.GeneralEncrypt = GeneralEncrypt; diff --git a/dist/node/cjs/jwk/embedded.js b/dist/node/cjs/jwk/embedded.js deleted file mode 100644 index cf21f70a87..0000000000 --- a/dist/node/cjs/jwk/embedded.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EmbeddedJWK = void 0; -const import_js_1 = require("../key/import.js"); -const is_object_js_1 = require("../lib/is_object.js"); -const errors_js_1 = require("../util/errors.js"); -async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header, - }; - if (!(0, is_object_js_1.default)(joseHeader.jwk)) { - throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; -} -exports.EmbeddedJWK = EmbeddedJWK; diff --git a/dist/node/cjs/jwk/thumbprint.js b/dist/node/cjs/jwk/thumbprint.js deleted file mode 100644 index 210b933a8d..0000000000 --- a/dist/node/cjs/jwk/thumbprint.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = void 0; -const digest_js_1 = require("../runtime/digest.js"); -const base64url_js_1 = require("../runtime/base64url.js"); -const errors_js_1 = require("../util/errors.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const is_object_js_1 = require("../lib/is_object.js"); -const check = (value, description) => { - if (typeof value !== 'string' || !value) { - throw new errors_js_1.JWKInvalid(`${description} missing or invalid`); - } -}; -async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!(0, is_object_js_1.default)(jwk)) { - throw new TypeError('JWK must be an object'); - } - digestAlgorithm ??= 'sha256'; - if (digestAlgorithm !== 'sha256' && - digestAlgorithm !== 'sha384' && - digestAlgorithm !== 'sha512') { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case 'EC': - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case 'OKP': - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case 'RSA': - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case 'oct': - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components)); - return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data)); -} -exports.calculateJwkThumbprint = calculateJwkThumbprint; -async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ??= 'sha256'; - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; -} -exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; diff --git a/dist/node/cjs/jwks/local.js b/dist/node/cjs/jwks/local.js deleted file mode 100644 index feea91b6d1..0000000000 --- a/dist/node/cjs/jwks/local.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createLocalJWKSet = void 0; -const import_js_1 = require("../key/import.js"); -const errors_js_1 = require("../util/errors.js"); -const is_object_js_1 = require("../lib/is_object.js"); -function getKtyFromAlg(alg) { - switch (typeof alg === 'string' && alg.slice(0, 2)) { - case 'RS': - case 'PS': - return 'RSA'; - case 'ES': - return 'EC'; - case 'Ed': - return 'OKP'; - default: - throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return (jwks && - typeof jwks === 'object' && - Array.isArray(jwks.keys) && - jwks.keys.every(isJWKLike)); -} -function isJWKLike(key) { - return (0, is_object_js_1.default)(key); -} -function clone(obj) { - if (typeof structuredClone === 'function') { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); -} -class LocalJWKSet { - _jwks; - _cached = new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) { - throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === 'string') { - candidate = kid === jwk.kid; - } - if (candidate && typeof jwk.alg === 'string') { - candidate = alg === jwk.alg; - } - if (candidate && typeof jwk.use === 'string') { - candidate = jwk.use === 'sig'; - } - if (candidate && Array.isArray(jwk.key_ops)) { - candidate = jwk.key_ops.includes('verify'); - } - if (candidate && alg === 'EdDSA') { - candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; - } - if (candidate) { - switch (alg) { - case 'ES256': - candidate = jwk.crv === 'P-256'; - break; - case 'ES256K': - candidate = jwk.crv === 'secp256k1'; - break; - case 'ES384': - candidate = jwk.crv === 'P-384'; - break; - case 'ES512': - candidate = jwk.crv === 'P-521'; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new errors_js_1.JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new errors_js_1.JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) { - try { - yield await importWithAlgCache(_cached, jwk, alg); - } - catch { } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } -} -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === undefined) { - const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys'); - } - cached[alg] = key; - } - return cached[alg]; -} -function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return localJWKSet; -} -exports.createLocalJWKSet = createLocalJWKSet; diff --git a/dist/node/cjs/jwks/remote.js b/dist/node/cjs/jwks/remote.js deleted file mode 100644 index b8337f230a..0000000000 --- a/dist/node/cjs/jwks/remote.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.experimental_jwksCache = exports.createRemoteJWKSet = exports.jwksCache = void 0; -const fetch_jwks_js_1 = require("../runtime/fetch_jwks.js"); -const errors_js_1 = require("../util/errors.js"); -const local_js_1 = require("./local.js"); -const is_object_js_1 = require("../lib/is_object.js"); -function isCloudflareWorkers() { - return (typeof WebSocketPair !== 'undefined' || - (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || - (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); -} -let USER_AGENT; -if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { - const NAME = 'jose'; - const VERSION = 'v5.9.1'; - USER_AGENT = `${NAME}/${VERSION}`; -} -exports.jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== 'object' || input === null) { - return false; - } - if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!('jwks' in input) || - !(0, is_object_js_1.default)(input.jwks) || - !Array.isArray(input.jwks.keys) || - !Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) { - return false; - } - return true; -} -class RemoteJWKSet { - _url; - _timeoutDuration; - _cooldownDuration; - _cacheMaxAge; - _jwksTimestamp; - _pendingFetch; - _options; - _local; - _cache; - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError('url must be an instance of URL'); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = - typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; - this._cooldownDuration = - typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; - this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; - if (options?.[exports.jwksCache] !== undefined) { - this._cache = options?.[exports.jwksCache]; - if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cooldownDuration - : false; - } - fresh() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cacheMaxAge - : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } - catch (err) { - if (err instanceof errors_js_1.JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = undefined; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has('User-Agent')) { - headers.set('User-Agent', USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options) - .then((json) => { - this._local = (0, local_js_1.createLocalJWKSet)(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = undefined; - }) - .catch((err) => { - this._pendingFetch = undefined; - throw err; - }); - await this._pendingFetch; - } -} -function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false, - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false, - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false, - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false, - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return remoteJWKSet; -} -exports.createRemoteJWKSet = createRemoteJWKSet; -exports.experimental_jwksCache = exports.jwksCache; diff --git a/dist/node/cjs/jws/compact/sign.js b/dist/node/cjs/jws/compact/sign.js deleted file mode 100644 index 14776ec413..0000000000 --- a/dist/node/cjs/jws/compact/sign.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompactSign = void 0; -const sign_js_1 = require("../flattened/sign.js"); -class CompactSign { - _flattened; - constructor(payload) { - this._flattened = new sign_js_1.FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === undefined) { - throw new TypeError('use the flattened module for creating JWS with b64: false'); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -} -exports.CompactSign = CompactSign; diff --git a/dist/node/cjs/jws/compact/verify.js b/dist/node/cjs/jws/compact/verify.js deleted file mode 100644 index b7e672477f..0000000000 --- a/dist/node/cjs/jws/compact/verify.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.compactVerify = void 0; -const verify_js_1 = require("../flattened/verify.js"); -const errors_js_1 = require("../../util/errors.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = buffer_utils_js_1.decoder.decode(jws); - } - if (typeof jws !== 'string') { - throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); - if (length !== 3) { - throw new errors_js_1.JWSInvalid('Invalid Compact JWS'); - } - const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} -exports.compactVerify = compactVerify; diff --git a/dist/node/cjs/jws/flattened/sign.js b/dist/node/cjs/jws/flattened/sign.js deleted file mode 100644 index 838e1b38f4..0000000000 --- a/dist/node/cjs/jws/flattened/sign.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FlattenedSign = void 0; -const base64url_js_1 = require("../../runtime/base64url.js"); -const sign_js_1 = require("../../runtime/sign.js"); -const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); -const errors_js_1 = require("../../util/errors.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -const check_key_type_js_1 = require("../../lib/check_key_type.js"); -const validate_crit_js_1 = require("../../lib/validate_crit.js"); -class FlattenedSign { - _payload; - _protectedHeader; - _unprotectedHeader; - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError('payload must be an instance of Uint8Array'); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); - } - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) { - throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - }; - const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== 'boolean') { - throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign'); - let payload = this._payload; - if (b64) { - payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = buffer_utils_js_1.encoder.encode(''); - } - const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload); - const signature = await (0, sign_js_1.default)(alg, key, data); - const jws = { - signature: (0, base64url_js_1.encode)(signature), - payload: '', - }; - if (b64) { - jws.payload = buffer_utils_js_1.decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader); - } - return jws; - } -} -exports.FlattenedSign = FlattenedSign; diff --git a/dist/node/cjs/jws/flattened/verify.js b/dist/node/cjs/jws/flattened/verify.js deleted file mode 100644 index 8417390a1c..0000000000 --- a/dist/node/cjs/jws/flattened/verify.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.flattenedVerify = void 0; -const base64url_js_1 = require("../../runtime/base64url.js"); -const verify_js_1 = require("../../runtime/verify.js"); -const errors_js_1 = require("../../util/errors.js"); -const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); -const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); -const is_object_js_1 = require("../../lib/is_object.js"); -const check_key_type_js_1 = require("../../lib/check_key_type.js"); -const validate_crit_js_1 = require("../../lib/validate_crit.js"); -const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); -const is_jwk_js_1 = require("../../lib/is_jwk.js"); -const import_js_1 = require("../../key/import.js"); -async function flattenedVerify(jws, key, options) { - if (!(0, is_object_js_1.default)(jws)) { - throw new errors_js_1.JWSInvalid('Flattened JWS must be an object'); - } - if (jws.protected === undefined && jws.header === undefined) { - throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== undefined && typeof jws.protected !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type'); - } - if (jws.payload === undefined) { - throw new errors_js_1.JWSInvalid('JWS Payload missing'); - } - if (typeof jws.signature !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type'); - } - if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) { - throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type'); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = (0, base64url_js_1.decode)(jws.protected); - parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); - } - catch { - throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid'); - } - } - if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) { - throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jws.header, - }; - const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = parsedProt.b64; - if (typeof b64 !== 'boolean') { - throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Payload must be a string'); - } - } - else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { - throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jws); - resolvedKey = true; - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); - if ((0, is_jwk_js_1.isJWK)(key)) { - key = await (0, import_js_1.importJWK)(key, alg); - } - } - else { - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); - } - const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = (0, base64url_js_1.decode)(jws.signature); - } - catch { - throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature'); - } - const verified = await (0, verify_js_1.default)(alg, key, signature, data); - if (!verified) { - throw new errors_js_1.JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = (0, base64url_js_1.decode)(jws.payload); - } - catch { - throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload'); - } - } - else if (typeof jws.payload === 'string') { - payload = buffer_utils_js_1.encoder.encode(jws.payload); - } - else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jws.header !== undefined) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} -exports.flattenedVerify = flattenedVerify; diff --git a/dist/node/cjs/jws/general/sign.js b/dist/node/cjs/jws/general/sign.js deleted file mode 100644 index 917a3fd656..0000000000 --- a/dist/node/cjs/jws/general/sign.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GeneralSign = void 0; -const sign_js_1 = require("../flattened/sign.js"); -const errors_js_1 = require("../../util/errors.js"); -class IndividualSignature { - parent; - protectedHeader; - unprotectedHeader; - options; - key; - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } -} -class GeneralSign { - _payload; - _signatures = []; - constructor(payload) { - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new errors_js_1.JWSInvalid('at least one signature must be added'); - } - const jws = { - signatures: [], - payload: '', - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new sign_js_1.FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } - else if (jws.payload !== payload) { - throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); - } - jws.signatures.push(rest); - } - return jws; - } -} -exports.GeneralSign = GeneralSign; diff --git a/dist/node/cjs/jws/general/verify.js b/dist/node/cjs/jws/general/verify.js deleted file mode 100644 index 9d4a07a296..0000000000 --- a/dist/node/cjs/jws/general/verify.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generalVerify = void 0; -const verify_js_1 = require("../flattened/verify.js"); -const errors_js_1 = require("../../util/errors.js"); -const is_object_js_1 = require("../../lib/is_object.js"); -async function generalVerify(jws, key, options) { - if (!(0, is_object_js_1.default)(jws)) { - throw new errors_js_1.JWSInvalid('General JWS must be an object'); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) { - throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type'); - } - for (const signature of jws.signatures) { - try { - return await (0, verify_js_1.flattenedVerify)({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature, - }, key, options); - } - catch { - } - } - throw new errors_js_1.JWSSignatureVerificationFailed(); -} -exports.generalVerify = generalVerify; diff --git a/dist/node/cjs/jwt/decrypt.js b/dist/node/cjs/jwt/decrypt.js deleted file mode 100644 index 1d922766de..0000000000 --- a/dist/node/cjs/jwt/decrypt.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.jwtDecrypt = void 0; -const decrypt_js_1 = require("../jwe/compact/decrypt.js"); -const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); -const errors_js_1 = require("../util/errors.js"); -async function jwtDecrypt(jwt, key, options) { - const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options); - const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); - } - if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); - } - if (protectedHeader.aud !== undefined && - JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); - } - const result = { payload, protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} -exports.jwtDecrypt = jwtDecrypt; diff --git a/dist/node/cjs/jwt/encrypt.js b/dist/node/cjs/jwt/encrypt.js deleted file mode 100644 index 62ae9aa59c..0000000000 --- a/dist/node/cjs/jwt/encrypt.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EncryptJWT = void 0; -const encrypt_js_1 = require("../jwe/compact/encrypt.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const produce_js_1 = require("./produce.js"); -class EncryptJWT extends produce_js_1.ProduceJWT { - _cek; - _iv; - _keyManagementParameters; - _protectedHeader; - _replicateIssuerAsHeader; - _replicateSubjectAsHeader; - _replicateAudienceAsHeader; - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } -} -exports.EncryptJWT = EncryptJWT; diff --git a/dist/node/cjs/jwt/produce.js b/dist/node/cjs/jwt/produce.js deleted file mode 100644 index 0434a917d3..0000000000 --- a/dist/node/cjs/jwt/produce.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProduceJWT = void 0; -const epoch_js_1 = require("../lib/epoch.js"); -const is_object_js_1 = require("../lib/is_object.js"); -const secs_js_1 = require("../lib/secs.js"); -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -class ProduceJWT { - _payload; - constructor(payload = {}) { - if (!(0, is_object_js_1.default)(payload)) { - throw new TypeError('JWT Claims Set MUST be an object'); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) }; - } - else { - this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) }; - } - else { - this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === 'undefined') { - this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) }; - } - else if (typeof input === 'string') { - this._payload = { - ...this._payload, - iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input)), - }; - } - else { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }; - } - return this; - } -} -exports.ProduceJWT = ProduceJWT; diff --git a/dist/node/cjs/jwt/sign.js b/dist/node/cjs/jwt/sign.js deleted file mode 100644 index ac1d5357c9..0000000000 --- a/dist/node/cjs/jwt/sign.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SignJWT = void 0; -const sign_js_1 = require("../jws/compact/sign.js"); -const errors_js_1 = require("../util/errors.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const produce_js_1 = require("./produce.js"); -class SignJWT extends produce_js_1.ProduceJWT { - _protectedHeader; - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && - this._protectedHeader.crit.includes('b64') && - this._protectedHeader.b64 === false) { - throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - return sig.sign(key, options); - } -} -exports.SignJWT = SignJWT; diff --git a/dist/node/cjs/jwt/unsecured.js b/dist/node/cjs/jwt/unsecured.js deleted file mode 100644 index 482782fed1..0000000000 --- a/dist/node/cjs/jwt/unsecured.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UnsecuredJWT = void 0; -const base64url = require("../runtime/base64url.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const errors_js_1 = require("../util/errors.js"); -const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); -const produce_js_1 = require("./produce.js"); -class UnsecuredJWT extends produce_js_1.ProduceJWT { - encode() { - const header = base64url.encode(JSON.stringify({ alg: 'none' })); - const payload = base64url.encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== 'string') { - throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string'); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); - if (length !== 3 || signature !== '') { - throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); - } - let header; - try { - header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader))); - if (header.alg !== 'none') - throw new Error(); - } - catch { - throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); - } - const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options); - return { payload, header }; - } -} -exports.UnsecuredJWT = UnsecuredJWT; diff --git a/dist/node/cjs/jwt/verify.js b/dist/node/cjs/jwt/verify.js deleted file mode 100644 index 76c91e5dc2..0000000000 --- a/dist/node/cjs/jwt/verify.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.jwtVerify = void 0; -const verify_js_1 = require("../jws/compact/verify.js"); -const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); -const errors_js_1 = require("../util/errors.js"); -async function jwtVerify(jwt, key, options) { - const verified = await (0, verify_js_1.compactVerify)(jwt, key, options); - if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { - throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} -exports.jwtVerify = jwtVerify; diff --git a/dist/node/cjs/key/export.js b/dist/node/cjs/key/export.js deleted file mode 100644 index 1c083efe72..0000000000 --- a/dist/node/cjs/key/export.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.exportJWK = exports.exportPKCS8 = exports.exportSPKI = void 0; -const asn1_js_1 = require("../runtime/asn1.js"); -const asn1_js_2 = require("../runtime/asn1.js"); -const key_to_jwk_js_1 = require("../runtime/key_to_jwk.js"); -async function exportSPKI(key) { - return (0, asn1_js_1.toSPKI)(key); -} -exports.exportSPKI = exportSPKI; -async function exportPKCS8(key) { - return (0, asn1_js_2.toPKCS8)(key); -} -exports.exportPKCS8 = exportPKCS8; -async function exportJWK(key) { - return (0, key_to_jwk_js_1.default)(key); -} -exports.exportJWK = exportJWK; diff --git a/dist/node/cjs/key/generate_key_pair.js b/dist/node/cjs/key/generate_key_pair.js deleted file mode 100644 index 3d14da5c3e..0000000000 --- a/dist/node/cjs/key/generate_key_pair.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateKeyPair = void 0; -const generate_js_1 = require("../runtime/generate.js"); -async function generateKeyPair(alg, options) { - return (0, generate_js_1.generateKeyPair)(alg, options); -} -exports.generateKeyPair = generateKeyPair; diff --git a/dist/node/cjs/key/generate_secret.js b/dist/node/cjs/key/generate_secret.js deleted file mode 100644 index 5f3c9ba214..0000000000 --- a/dist/node/cjs/key/generate_secret.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateSecret = void 0; -const generate_js_1 = require("../runtime/generate.js"); -async function generateSecret(alg, options) { - return (0, generate_js_1.generateSecret)(alg, options); -} -exports.generateSecret = generateSecret; diff --git a/dist/node/cjs/key/import.js b/dist/node/cjs/key/import.js deleted file mode 100644 index 268119301b..0000000000 --- a/dist/node/cjs/key/import.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.importJWK = exports.importPKCS8 = exports.importX509 = exports.importSPKI = void 0; -const base64url_js_1 = require("../runtime/base64url.js"); -const asn1_js_1 = require("../runtime/asn1.js"); -const jwk_to_key_js_1 = require("../runtime/jwk_to_key.js"); -const errors_js_1 = require("../util/errors.js"); -const is_object_js_1 = require("../lib/is_object.js"); -async function importSPKI(spki, alg, options) { - if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return (0, asn1_js_1.fromSPKI)(spki, alg, options); -} -exports.importSPKI = importSPKI; -async function importX509(x509, alg, options) { - if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return (0, asn1_js_1.fromX509)(x509, alg, options); -} -exports.importX509 = importX509; -async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options); -} -exports.importPKCS8 = importPKCS8; -async function importJWK(jwk, alg) { - if (!(0, is_object_js_1.default)(jwk)) { - throw new TypeError('JWK must be an object'); - } - alg ||= jwk.alg; - switch (jwk.kty) { - case 'oct': - if (typeof jwk.k !== 'string' || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return (0, base64url_js_1.decode)(jwk.k); - case 'RSA': - if (jwk.oth !== undefined) { - throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - case 'EC': - case 'OKP': - return (0, jwk_to_key_js_1.default)({ ...jwk, alg }); - default: - throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} -exports.importJWK = importJWK; diff --git a/dist/node/cjs/lib/aesgcmkw.js b/dist/node/cjs/lib/aesgcmkw.js deleted file mode 100644 index 6ba6cdde4e..0000000000 --- a/dist/node/cjs/lib/aesgcmkw.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.unwrap = exports.wrap = void 0; -const encrypt_js_1 = require("../runtime/encrypt.js"); -const decrypt_js_1 = require("../runtime/decrypt.js"); -const base64url_js_1 = require("../runtime/base64url.js"); -async function wrap(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: (0, base64url_js_1.encode)(wrapped.iv), - tag: (0, base64url_js_1.encode)(wrapped.tag), - }; -} -exports.wrap = wrap; -async function unwrap(alg, key, encryptedKey, iv, tag) { - const jweAlgorithm = alg.slice(0, 7); - return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); -} -exports.unwrap = unwrap; diff --git a/dist/node/cjs/lib/buffer_utils.js b/dist/node/cjs/lib/buffer_utils.js deleted file mode 100644 index 4fa1db82ff..0000000000 --- a/dist/node/cjs/lib/buffer_utils.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.concatKdf = exports.lengthAndInput = exports.uint32be = exports.uint64be = exports.p2s = exports.concat = exports.decoder = exports.encoder = void 0; -const digest_js_1 = require("../runtime/digest.js"); -exports.encoder = new TextEncoder(); -exports.decoder = new TextDecoder(); -const 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; -} -exports.concat = concat; -function p2s(alg, p2sInput) { - return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput); -} -exports.p2s = p2s; -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 & 0xff], 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; -} -exports.uint64be = uint64be; -function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -exports.uint32be = uint32be; -function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -exports.lengthAndInput = lengthAndInput; -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 (0, digest_js_1.default)('sha256', buf), iter * 32); - } - return res.slice(0, bits >> 3); -} -exports.concatKdf = concatKdf; diff --git a/dist/node/cjs/lib/cek.js b/dist/node/cjs/lib/cek.js deleted file mode 100644 index e4a0133909..0000000000 --- a/dist/node/cjs/lib/cek.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bitLength = void 0; -const errors_js_1 = require("../util/errors.js"); -const random_js_1 = require("../runtime/random.js"); -function bitLength(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 errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); - } -} -exports.bitLength = bitLength; -exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/node/cjs/lib/check_iv_length.js b/dist/node/cjs/lib/check_iv_length.js deleted file mode 100644 index 3fbee85bb0..0000000000 --- a/dist/node/cjs/lib/check_iv_length.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -const iv_js_1 = require("./iv.js"); -const checkIvLength = (enc, iv) => { - if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) { - throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length'); - } -}; -exports.default = checkIvLength; diff --git a/dist/node/cjs/lib/check_key_type.js b/dist/node/cjs/lib/check_key_type.js deleted file mode 100644 index 0ab1642e63..0000000000 --- a/dist/node/cjs/lib/check_key_type.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.checkKeyTypeWithJwk = void 0; -const invalid_key_input_js_1 = require("./invalid_key_input.js"); -const is_key_like_js_1 = require("../runtime/is_key_like.js"); -const jwk = require("./is_jwk.js"); -const tag = (key) => key?.[Symbol.toStringTag]; -const jwkMatchesOp = (alg, key, usage) => { - if (key.use !== undefined && key.use !== 'sig') { - throw new TypeError('Invalid key for this operation, when present its use must be sig'); - } - if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== undefined && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; -}; -const symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && jwk.isJWK(key)) { - if (jwk.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 (!(0, is_key_like_js_1.default)(key)) { - throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null)); - } - if (key.type !== 'secret') { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -const asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && jwk.isJWK(key)) { - switch (usage) { - case 'sign': - if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - case 'verify': - if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a public JWK`); - } - } - if (!(0, is_key_like_js_1.default)(key)) { - throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, allowJwk ? 'JSON Web Key' : null)); - } - if (key.type === 'secret') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === 'sign' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === 'decrypt' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === 'verify' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === 'encrypt' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith('HS') || - alg === 'dir' || - alg.startsWith('PBES2') || - /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } - else { - asymmetricTypeCheck(alg, key, usage, allowJwk); - } -} -exports.default = checkKeyType.bind(undefined, false); -exports.checkKeyTypeWithJwk = checkKeyType.bind(undefined, true); diff --git a/dist/node/cjs/lib/check_p2s.js b/dist/node/cjs/lib/check_p2s.js deleted file mode 100644 index 4bdeaa766c..0000000000 --- a/dist/node/cjs/lib/check_p2s.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -function checkP2s(p2s) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets'); - } -} -exports.default = checkP2s; diff --git a/dist/node/cjs/lib/crypto_key.js b/dist/node/cjs/lib/crypto_key.js deleted file mode 100644 index b1acdbd0bc..0000000000 --- a/dist/node/cjs/lib/crypto_key.js +++ /dev/null @@ -1,157 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.checkEncCryptoKey = exports.checkSigCryptoKey = void 0; -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 getNamedCurve(alg) { - switch (alg) { - case 'ES256': - return 'P-256'; - case 'ES384': - return 'P-384'; - case 'ES512': - return 'P-521'; - default: - throw new Error('unreachable'); - } -} -function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = 'CryptoKey does not support this operation, its usages must include '; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(', ')}, or ${last}.`; - } - else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } - else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } -} -function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': { - if (!isAlgorithm(key.algorithm, 'HMAC')) - throw unusable('HMAC'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'RS256': - case 'RS384': - case 'RS512': { - if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) - throw unusable('RSASSA-PKCS1-v1_5'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'PS256': - case 'PS384': - case 'PS512': { - if (!isAlgorithm(key.algorithm, 'RSA-PSS')) - throw unusable('RSA-PSS'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'EdDSA': { - if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { - throw unusable('Ed25519 or Ed448'); - } - break; - } - case 'ES256': - case 'ES384': - case 'ES512': { - if (!isAlgorithm(key.algorithm, 'ECDSA')) - throw unusable('ECDSA'); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, 'algorithm.namedCurve'); - break; - } - default: - throw new TypeError('CryptoKey does not support this operation'); - } - checkUsage(key, usages); -} -exports.checkSigCryptoKey = checkSigCryptoKey; -function checkEncCryptoKey(key, alg, ...usages) { - 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': - case 'X448': - break; - default: - throw unusable('ECDH, X25519, or X448'); - } - 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, usages); -} -exports.checkEncCryptoKey = checkEncCryptoKey; diff --git a/dist/node/cjs/lib/decrypt_key_management.js b/dist/node/cjs/lib/decrypt_key_management.js deleted file mode 100644 index ecb10f3af0..0000000000 --- a/dist/node/cjs/lib/decrypt_key_management.js +++ /dev/null @@ -1,131 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const aeskw_js_1 = require("../runtime/aeskw.js"); -const ECDH = require("../runtime/ecdhes.js"); -const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); -const rsaes_js_1 = require("../runtime/rsaes.js"); -const base64url_js_1 = require("../runtime/base64url.js"); -const normalize_key_js_1 = require("../runtime/normalize_key.js"); -const errors_js_1 = require("../util/errors.js"); -const cek_js_1 = require("../lib/cek.js"); -const import_js_1 = require("../key/import.js"); -const check_key_type_js_1 = require("./check_key_type.js"); -const is_object_js_1 = require("./is_object.js"); -const aesgcmkw_js_1 = require("./aesgcmkw.js"); -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - (0, check_key_type_js_1.default)(alg, key, 'decrypt'); - key = (await normalize_key_js_1.default.normalizePrivateKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - if (encryptedKey !== undefined) - throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); - return key; - } - case 'ECDH-ES': - if (encryptedKey !== undefined) - throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!(0, is_object_js_1.default)(joseHeader.epk)) - throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ECDH.ecdhAllowed(key)) - throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); - const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== undefined) { - if (typeof joseHeader.apu !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - try { - partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu'); - } - } - if (joseHeader.apv !== undefined) { - if (typeof joseHeader.apv !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - try { - partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv'); - } - } - const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg === 'ECDH-ES') - return sharedSecret; - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey); - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey); - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - if (typeof joseHeader.p2c !== 'number') - throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); - const p2cLimit = options?.maxPBES2Count || 10_000; - if (joseHeader.p2c > p2cLimit) - throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); - if (typeof joseHeader.p2s !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); - let p2s; - try { - p2s = (0, base64url_js_1.decode)(joseHeader.p2s); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s'); - } - return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s); - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey); - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - if (typeof joseHeader.iv !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); - if (typeof joseHeader.tag !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); - let iv; - try { - iv = (0, base64url_js_1.decode)(joseHeader.iv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); - } - let tag; - try { - tag = (0, base64url_js_1.decode)(joseHeader.tag); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); - } - return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag); - } - default: { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } -} -exports.default = decryptKeyManagement; diff --git a/dist/node/cjs/lib/encrypt_key_management.js b/dist/node/cjs/lib/encrypt_key_management.js deleted file mode 100644 index ca07e93733..0000000000 --- a/dist/node/cjs/lib/encrypt_key_management.js +++ /dev/null @@ -1,91 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const aeskw_js_1 = require("../runtime/aeskw.js"); -const ECDH = require("../runtime/ecdhes.js"); -const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); -const rsaes_js_1 = require("../runtime/rsaes.js"); -const base64url_js_1 = require("../runtime/base64url.js"); -const normalize_key_js_1 = require("../runtime/normalize_key.js"); -const cek_js_1 = require("../lib/cek.js"); -const errors_js_1 = require("../util/errors.js"); -const export_js_1 = require("../key/export.js"); -const check_key_type_js_1 = require("./check_key_type.js"); -const aesgcmkw_js_1 = require("./aesgcmkw.js"); -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - (0, check_key_type_js_1.default)(alg, key, 'encrypt'); - key = (await normalize_key_js_1.default.normalizePublicKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - cek = key; - break; - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!ECDH.ecdhAllowed(key)) { - throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); - } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey; - const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey); - const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === 'EC') - parameters.epk.y = y; - if (apu) - parameters.apu = (0, base64url_js_1.encode)(apu); - if (apv) - parameters.apv = (0, base64url_js_1.encode)(apv); - if (alg === 'ECDH-ES') { - cek = sharedSecret; - break; - } - cek = providedCek || (0, cek_js_1.default)(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek); - break; - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - cek = providedCek || (0, cek_js_1.default)(enc); - encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek); - break; - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - cek = providedCek || (0, cek_js_1.default)(enc); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s)); - break; - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - cek = providedCek || (0, cek_js_1.default)(enc); - encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek); - break; - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - cek = providedCek || (0, cek_js_1.default)(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv)); - break; - } - default: { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - return { cek, encryptedKey, parameters }; -} -exports.default = encryptKeyManagement; diff --git a/dist/node/cjs/lib/epoch.js b/dist/node/cjs/lib/epoch.js deleted file mode 100644 index a0792b4f7f..0000000000 --- a/dist/node/cjs/lib/epoch.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = (date) => Math.floor(date.getTime() / 1000); diff --git a/dist/node/cjs/lib/invalid_key_input.js b/dist/node/cjs/lib/invalid_key_input.js deleted file mode 100644 index 0dd070925c..0000000000 --- a/dist/node/cjs/lib/invalid_key_input.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.withAlg = void 0; -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; -} -exports.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); -} -exports.withAlg = withAlg; diff --git a/dist/node/cjs/lib/is_disjoint.js b/dist/node/cjs/lib/is_disjoint.js deleted file mode 100644 index 66c2fc6c82..0000000000 --- a/dist/node/cjs/lib/is_disjoint.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const isDisjoint = (...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; -}; -exports.default = isDisjoint; diff --git a/dist/node/cjs/lib/is_jwk.js b/dist/node/cjs/lib/is_jwk.js deleted file mode 100644 index 78bc458f15..0000000000 --- a/dist/node/cjs/lib/is_jwk.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isSecretJWK = exports.isPublicJWK = exports.isPrivateJWK = exports.isJWK = void 0; -const is_object_js_1 = require("./is_object.js"); -function isJWK(key) { - return (0, is_object_js_1.default)(key) && typeof key.kty === 'string'; -} -exports.isJWK = isJWK; -function isPrivateJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'string'; -} -exports.isPrivateJWK = isPrivateJWK; -function isPublicJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'undefined'; -} -exports.isPublicJWK = isPublicJWK; -function isSecretJWK(key) { - return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string'; -} -exports.isSecretJWK = isSecretJWK; diff --git a/dist/node/cjs/lib/is_object.js b/dist/node/cjs/lib/is_object.js deleted file mode 100644 index 870938b59b..0000000000 --- a/dist/node/cjs/lib/is_object.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function isObjectLike(value) { - return typeof value === 'object' && value !== null; -} -function isObject(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; -} -exports.default = isObject; diff --git a/dist/node/cjs/lib/iv.js b/dist/node/cjs/lib/iv.js deleted file mode 100644 index db7d3a5912..0000000000 --- a/dist/node/cjs/lib/iv.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bitLength = void 0; -const errors_js_1 = require("../util/errors.js"); -const random_js_1 = require("../runtime/random.js"); -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 errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); - } -} -exports.bitLength = bitLength; -exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/node/cjs/lib/jwt_claims_set.js b/dist/node/cjs/lib/jwt_claims_set.js deleted file mode 100644 index 605d7436b9..0000000000 --- a/dist/node/cjs/lib/jwt_claims_set.js +++ /dev/null @@ -1,105 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -const buffer_utils_js_1 = require("./buffer_utils.js"); -const epoch_js_1 = require("./epoch.js"); -const secs_js_1 = require("./secs.js"); -const is_object_js_1 = require("./is_object.js"); -const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); -const checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -exports.default = (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload)); - } - catch { - } - if (!(0, is_object_js_1.default)(payload)) { - throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object'); - } - const { typ } = options; - if (typ && - (typeof protectedHeader.typ !== 'string' || - normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== undefined) - presenceCheck.push('iat'); - if (audience !== undefined) - presenceCheck.push('aud'); - if (subject !== undefined) - presenceCheck.push('sub'); - if (issuer !== undefined) - presenceCheck.push('iss'); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); - } - if (subject && payload.sub !== subject) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); - } - if (audience && - !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); - } - let tolerance; - switch (typeof options.clockTolerance) { - case 'string': - tolerance = (0, secs_js_1.default)(options.clockTolerance); - break; - case 'number': - tolerance = options.clockTolerance; - break; - case 'undefined': - tolerance = 0; - break; - default: - throw new TypeError('Invalid clockTolerance option type'); - } - const { currentDate } = options; - const now = (0, epoch_js_1.default)(currentDate || new Date()); - if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); - } - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); - } - if (payload.nbf > now + tolerance) { - throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); - } - } - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); - } - if (payload.exp <= now - tolerance) { - throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === 'number' ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge); - if (age - tolerance > max) { - throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); - } - if (age < 0 - tolerance) { - throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); - } - } - return payload; -}; diff --git a/dist/node/cjs/lib/private_symbols.js b/dist/node/cjs/lib/private_symbols.js deleted file mode 100644 index 36e4ecd93b..0000000000 --- a/dist/node/cjs/lib/private_symbols.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.unprotected = void 0; -exports.unprotected = Symbol(); diff --git a/dist/node/cjs/lib/secs.js b/dist/node/cjs/lib/secs.js deleted file mode 100644 index 340849817e..0000000000 --- a/dist/node/cjs/lib/secs.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const minute = 60; -const hour = minute * 60; -const day = hour * 24; -const week = day * 7; -const year = day * 365.25; -const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -exports.default = (str) => { - const matched = REGEX.exec(str); - if (!matched || (matched[4] && matched[1])) { - throw new TypeError('Invalid time period format'); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - numericDate = Math.round(value); - break; - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - numericDate = Math.round(value * minute); - break; - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - numericDate = Math.round(value * hour); - break; - case 'day': - case 'days': - case 'd': - numericDate = Math.round(value * day); - break; - case 'week': - case 'weeks': - case 'w': - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === '-' || matched[4] === 'ago') { - return -numericDate; - } - return numericDate; -}; diff --git a/dist/node/cjs/lib/validate_algorithms.js b/dist/node/cjs/lib/validate_algorithms.js deleted file mode 100644 index 29f4e80df9..0000000000 --- a/dist/node/cjs/lib/validate_algorithms.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const validateAlgorithms = (option, algorithms) => { - if (algorithms !== undefined && - (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return undefined; - } - return new Set(algorithms); -}; -exports.default = validateAlgorithms; diff --git a/dist/node/cjs/lib/validate_crit.js b/dist/node/cjs/lib/validate_crit.js deleted file mode 100644 index 593c1db87f..0000000000 --- a/dist/node/cjs/lib/validate_crit.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === undefined) { - return 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 !== undefined) { - recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - } - else { - recognized = recognizedDefault; - } - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) { - throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - } - if (joseHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} -exports.default = validateCrit; diff --git a/dist/node/cjs/runtime/aeskw.js b/dist/node/cjs/runtime/aeskw.js deleted file mode 100644 index e27098ba99..0000000000 --- a/dist/node/cjs/runtime/aeskw.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.unwrap = exports.wrap = void 0; -const node_buffer_1 = require("node:buffer"); -const node_crypto_1 = require("node:crypto"); -const errors_js_1 = require("../util/errors.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const ciphers_js_1 = require("./ciphers.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -function checkKeySize(key, alg) { - if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg}`); - } -} -function ensureKeyObject(key, alg, usage) { - if ((0, is_key_object_js_1.default)(key)) { - return key; - } - if (key instanceof Uint8Array) { - return (0, node_crypto_1.createSecretKey)(key); - } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage); - return node_crypto_1.KeyObject.from(key); - } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); -} -const wrap = (alg, key, cek) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'wrapKey'); - checkKeySize(keyObject, alg); - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); - return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final()); -}; -exports.wrap = wrap; -const unwrap = (alg, key, encryptedKey) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); - checkKeySize(keyObject, alg); - const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); - return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final()); -}; -exports.unwrap = unwrap; diff --git a/dist/node/cjs/runtime/asn1.js b/dist/node/cjs/runtime/asn1.js deleted file mode 100644 index 5754f8c4ec..0000000000 --- a/dist/node/cjs/runtime/asn1.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0; -const node_crypto_1 = require("node:crypto"); -const node_buffer_1 = require("node:buffer"); -const webcrypto_js_1 = require("./webcrypto.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const genericExport = (keyType, keyFormat, key) => { - let keyObject; - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - keyObject = node_crypto_1.KeyObject.from(key); - } - else if ((0, is_key_object_js_1.default)(key)) { - keyObject = key; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); - } - if (keyObject.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return keyObject.export({ format: 'pem', type: keyFormat }); -}; -const toSPKI = (key) => { - return genericExport('public', 'spki', key); -}; -exports.toSPKI = toSPKI; -const toPKCS8 = (key) => { - return genericExport('private', 'pkcs8', key); -}; -exports.toPKCS8 = toPKCS8; -const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({ - key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), - type: 'pkcs8', - format: 'der', -}); -exports.fromPKCS8 = fromPKCS8; -const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({ - key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), - type: 'spki', - format: 'der', -}); -exports.fromSPKI = fromSPKI; -const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({ - key: pem, - type: 'spki', - format: 'pem', -}); -exports.fromX509 = fromX509; diff --git a/dist/node/cjs/runtime/base64url.js b/dist/node/cjs/runtime/base64url.js deleted file mode 100644 index cddd648fe0..0000000000 --- a/dist/node/cjs/runtime/base64url.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0; -const node_buffer_1 = require("node:buffer"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -function normalize(input) { - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = buffer_utils_js_1.decoder.decode(encoded); - } - return encoded; -} -const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url'); -exports.encode = encode; -const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64')); -exports.decodeBase64 = decodeBase64; -const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64'); -exports.encodeBase64 = encodeBase64; -const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64url')); -exports.decode = decode; diff --git a/dist/node/cjs/runtime/cbc_tag.js b/dist/node/cjs/runtime/cbc_tag.js deleted file mode 100644 index 7fc21d7cd8..0000000000 --- a/dist/node/cjs/runtime/cbc_tag.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { - const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3)); - const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey); - hmac.update(macData); - return hmac.digest().slice(0, keySize >> 3); -} -exports.default = cbcTag; diff --git a/dist/node/cjs/runtime/check_cek_length.js b/dist/node/cjs/runtime/check_cek_length.js deleted file mode 100644 index 5192e750db..0000000000 --- a/dist/node/cjs/runtime/check_cek_length.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const checkCekLength = (enc, cek) => { - let expected; - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - expected = parseInt(enc.slice(-3), 10); - break; - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - expected = parseInt(enc.slice(1, 4), 10); - break; - default: - throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); - } - if (cek instanceof Uint8Array) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } - return; - } - if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') { - const actual = cek.symmetricKeySize << 3; - if (actual !== expected) { - throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } - return; - } - throw new TypeError('Invalid Content Encryption Key type'); -}; -exports.default = checkCekLength; diff --git a/dist/node/cjs/runtime/check_key_length.js b/dist/node/cjs/runtime/check_key_length.js deleted file mode 100644 index fb523bf895..0000000000 --- a/dist/node/cjs/runtime/check_key_length.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -exports.default = (key, alg) => { - let modulusLength; - try { - if (key instanceof node_crypto_1.KeyObject) { - modulusLength = key.asymmetricKeyDetails?.modulusLength; - } - else { - modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3; - } - } - catch { } - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); - } -}; diff --git a/dist/node/cjs/runtime/ciphers.js b/dist/node/cjs/runtime/ciphers.js deleted file mode 100644 index 7a3f479236..0000000000 --- a/dist/node/cjs/runtime/ciphers.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -let ciphers; -exports.default = (algorithm) => { - ciphers ||= new Set((0, node_crypto_1.getCiphers)()); - return ciphers.has(algorithm); -}; diff --git a/dist/node/cjs/runtime/decrypt.js b/dist/node/cjs/runtime/decrypt.js deleted file mode 100644 index df2598df22..0000000000 --- a/dist/node/cjs/runtime/decrypt.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const check_iv_length_js_1 = require("../lib/check_iv_length.js"); -const check_cek_length_js_1 = require("./check_cek_length.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const errors_js_1 = require("../util/errors.js"); -const timing_safe_equal_js_1 = require("./timing_safe_equal.js"); -const cbc_tag_js_1 = require("./cbc_tag.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const ciphers_js_1 = require("./ciphers.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if ((0, is_key_object_js_1.default)(cek)) { - cek = cek.export(); - } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const macSize = parseInt(enc.slice(-3), 10); - const algorithm = `aes-${keySize}-cbc`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); - let macCheckPassed; - try { - macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag); - } - catch { - } - if (!macCheckPassed) { - throw new errors_js_1.JWEDecryptionFailed(); - } - let plaintext; - try { - const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv); - plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final()); - } - catch { - } - if (!plaintext) { - throw new errors_js_1.JWEDecryptionFailed(); - } - return plaintext; -} -function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - try { - const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 }); - decipher.setAuthTag(tag); - if (aad.byteLength) { - decipher.setAAD(aad, { plaintextLength: ciphertext.length }); - } - const plaintext = decipher.update(ciphertext); - decipher.final(); - return plaintext; - } - catch { - throw new errors_js_1.JWEDecryptionFailed(); - } -} -const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(cek)) { - (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt'); - key = node_crypto_1.KeyObject.from(cek); - } - else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { - key = cek; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); - } - if (!iv) { - throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing'); - } - if (!tag) { - throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing'); - } - (0, check_cek_length_js_1.default)(enc, key); - (0, check_iv_length_js_1.default)(enc, iv); - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); - default: - throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -exports.default = decrypt; diff --git a/dist/node/cjs/runtime/digest.js b/dist/node/cjs/runtime/digest.js deleted file mode 100644 index 86035560a6..0000000000 --- a/dist/node/cjs/runtime/digest.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest(); -exports.default = digest; diff --git a/dist/node/cjs/runtime/dsa_digest.js b/dist/node/cjs/runtime/dsa_digest.js deleted file mode 100644 index fde4883e81..0000000000 --- a/dist/node/cjs/runtime/dsa_digest.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -function dsaDigest(alg) { - switch (alg) { - case 'PS256': - case 'RS256': - case 'ES256': - case 'ES256K': - return 'sha256'; - case 'PS384': - case 'RS384': - case 'ES384': - return 'sha384'; - case 'PS512': - case 'RS512': - case 'ES512': - return 'sha512'; - case 'EdDSA': - return undefined; - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} -exports.default = dsaDigest; diff --git a/dist/node/cjs/runtime/ecdhes.js b/dist/node/cjs/runtime/ecdhes.js deleted file mode 100644 index 7c2c825b7d..0000000000 --- a/dist/node/cjs/runtime/ecdhes.js +++ /dev/null @@ -1,70 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ecdhAllowed = exports.generateEpk = exports.deriveKey = void 0; -const node_crypto_1 = require("node:crypto"); -const node_util_1 = require("node:util"); -const get_named_curve_js_1 = require("./get_named_curve.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const errors_js_1 = require("../util/errors.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); -async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - let publicKey; - if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) { - (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH'); - publicKey = node_crypto_1.KeyObject.from(publicKee); - } - else if ((0, is_key_object_js_1.default)(publicKee)) { - publicKey = publicKee; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types)); - } - let privateKey; - if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) { - (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits'); - privateKey = node_crypto_1.KeyObject.from(privateKee); - } - else if ((0, is_key_object_js_1.default)(privateKee)) { - privateKey = privateKee; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types)); - } - const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength)); - const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey }); - return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value); -} -exports.deriveKey = deriveKey; -async function generateEpk(kee) { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(kee)) { - key = node_crypto_1.KeyObject.from(kee); - } - else if ((0, is_key_object_js_1.default)(kee)) { - key = kee; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); - } - switch (key.asymmetricKeyType) { - case 'x25519': - return generateKeyPair('x25519'); - case 'x448': { - return generateKeyPair('x448'); - } - case 'ec': { - const namedCurve = (0, get_named_curve_js_1.default)(key); - return generateKeyPair('ec', { namedCurve }); - } - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK'); - } -} -exports.generateEpk = generateEpk; -const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key)); -exports.ecdhAllowed = ecdhAllowed; diff --git a/dist/node/cjs/runtime/encrypt.js b/dist/node/cjs/runtime/encrypt.js deleted file mode 100644 index 7aa62b8e11..0000000000 --- a/dist/node/cjs/runtime/encrypt.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const check_iv_length_js_1 = require("../lib/check_iv_length.js"); -const check_cek_length_js_1 = require("./check_cek_length.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const cbc_tag_js_1 = require("./cbc_tag.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const iv_js_1 = require("../lib/iv.js"); -const errors_js_1 = require("../util/errors.js"); -const ciphers_js_1 = require("./ciphers.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -function cbcEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if ((0, is_key_object_js_1.default)(cek)) { - cek = cek.export(); - } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const algorithm = `aes-${keySize}-cbc`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv); - const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final()); - const macSize = parseInt(enc.slice(-3), 10); - const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); - return { ciphertext, tag, iv }; -} -function gcmEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 }); - if (aad.byteLength) { - cipher.setAAD(aad, { plaintextLength: plaintext.length }); - } - const ciphertext = cipher.update(plaintext); - cipher.final(); - const tag = cipher.getAuthTag(); - return { ciphertext, tag, iv }; -} -const encrypt = (enc, plaintext, cek, iv, aad) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(cek)) { - (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt'); - key = node_crypto_1.KeyObject.from(cek); - } - else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { - key = cek; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); - } - (0, check_cek_length_js_1.default)(enc, key); - if (iv) { - (0, check_iv_length_js_1.default)(enc, iv); - } - else { - iv = (0, iv_js_1.default)(enc); - } - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcEncrypt(enc, plaintext, key, iv, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmEncrypt(enc, plaintext, key, iv, aad); - default: - throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -exports.default = encrypt; diff --git a/dist/node/cjs/runtime/fetch_jwks.js b/dist/node/cjs/runtime/fetch_jwks.js deleted file mode 100644 index 7786806473..0000000000 --- a/dist/node/cjs/runtime/fetch_jwks.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const http = require("node:http"); -const https = require("node:https"); -const node_events_1 = require("node:events"); -const errors_js_1 = require("../util/errors.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const fetchJwks = async (url, timeout, options) => { - let get; - switch (url.protocol) { - case 'https:': - get = https.get; - break; - case 'http:': - get = http.get; - break; - default: - throw new TypeError('Unsupported URL protocol.'); - } - const { agent, headers } = options; - const req = get(url.href, { - agent, - timeout, - headers, - }); - const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')])); - if (!response) { - req.destroy(); - throw new errors_js_1.JWKSTimeout(); - } - if (response.statusCode !== 200) { - throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); - } - const parts = []; - for await (const part of response) { - parts.push(part); - } - try { - return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts))); - } - catch { - throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); - } -}; -exports.default = fetchJwks; diff --git a/dist/node/cjs/runtime/generate.js b/dist/node/cjs/runtime/generate.js deleted file mode 100644 index 87a9170938..0000000000 --- a/dist/node/cjs/runtime/generate.js +++ /dev/null @@ -1,102 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateKeyPair = exports.generateSecret = void 0; -const node_crypto_1 = require("node:crypto"); -const node_util_1 = require("node:util"); -const random_js_1 = require("./random.js"); -const errors_js_1 = require("../util/errors.js"); -const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); -async function generateSecret(alg, options) { - let length; - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - length = parseInt(alg.slice(-3), 10); - break; - case 'A128KW': - case 'A192KW': - case 'A256KW': - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - length = parseInt(alg.slice(1, 4), 10); - break; - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3))); -} -exports.generateSecret = generateSecret; -async function generateKeyPair(alg, options) { - switch (alg) { - case 'RS256': - case 'RS384': - case 'RS512': - case 'PS256': - case 'PS384': - case 'PS512': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - case 'RSA1_5': { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); - } - const keypair = await generate('rsa', { - modulusLength, - publicExponent: 0x10001, - }); - return keypair; - } - case 'ES256': - return generate('ec', { namedCurve: 'P-256' }); - case 'ES256K': - return generate('ec', { namedCurve: 'secp256k1' }); - case 'ES384': - return generate('ec', { namedCurve: 'P-384' }); - case 'ES512': - return generate('ec', { namedCurve: 'P-521' }); - case 'EdDSA': { - switch (options?.crv) { - case undefined: - case 'Ed25519': - return generate('ed25519'); - case 'Ed448': - return generate('ed448'); - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); - } - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - const crv = options?.crv ?? 'P-256'; - switch (crv) { - case undefined: - case 'P-256': - case 'P-384': - case 'P-521': - return generate('ec', { namedCurve: crv }); - case 'X25519': - return generate('x25519'); - case 'X448': - return generate('x448'); - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); - } - } - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } -} -exports.generateKeyPair = generateKeyPair; diff --git a/dist/node/cjs/runtime/get_named_curve.js b/dist/node/cjs/runtime/get_named_curve.js deleted file mode 100644 index b32f16659a..0000000000 --- a/dist/node/cjs/runtime/get_named_curve.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.weakMap = void 0; -const node_crypto_1 = require("node:crypto"); -const errors_js_1 = require("../util/errors.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const is_jwk_js_1 = require("../lib/is_jwk.js"); -exports.weakMap = new WeakMap(); -const namedCurveToJOSE = (namedCurve) => { - switch (namedCurve) { - case 'prime256v1': - return 'P-256'; - case 'secp384r1': - return 'P-384'; - case 'secp521r1': - return 'P-521'; - case 'secp256k1': - return 'secp256k1'; - default: - throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); - } -}; -const getNamedCurve = (kee, raw) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(kee)) { - key = node_crypto_1.KeyObject.from(kee); - } - else if ((0, is_key_object_js_1.default)(kee)) { - key = kee; - } - else if ((0, is_jwk_js_1.isJWK)(kee)) { - return kee.crv; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); - } - if (key.type === 'secret') { - throw new TypeError('only "private" or "public" type keys can be used for this operation'); - } - switch (key.asymmetricKeyType) { - case 'ed25519': - case 'ed448': - return `Ed${key.asymmetricKeyType.slice(2)}`; - case 'x25519': - case 'x448': - return `X${key.asymmetricKeyType.slice(1)}`; - case 'ec': { - const namedCurve = key.asymmetricKeyDetails.namedCurve; - if (raw) { - return namedCurve; - } - return namedCurveToJOSE(namedCurve); - } - default: - throw new TypeError('Invalid asymmetric key type for this operation'); - } -}; -exports.default = getNamedCurve; diff --git a/dist/node/cjs/runtime/get_sign_verify_key.js b/dist/node/cjs/runtime/get_sign_verify_key.js deleted file mode 100644 index fe4092ff12..0000000000 --- a/dist/node/cjs/runtime/get_sign_verify_key.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const jwk = require("../lib/is_jwk.js"); -function getSignVerifyKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith('HS')) { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); - } - return (0, node_crypto_1.createSecretKey)(key); - } - if (key instanceof node_crypto_1.KeyObject) { - return key; - } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage); - return node_crypto_1.KeyObject.from(key); - } - if (jwk.isJWK(key)) { - if (alg.startsWith('HS')) { - return (0, node_crypto_1.createSecretKey)(Buffer.from(key.k, 'base64url')); - } - return key; - } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array', 'JSON Web Key')); -} -exports.default = getSignVerifyKey; diff --git a/dist/node/cjs/runtime/hmac_digest.js b/dist/node/cjs/runtime/hmac_digest.js deleted file mode 100644 index c3935124c7..0000000000 --- a/dist/node/cjs/runtime/hmac_digest.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const errors_js_1 = require("../util/errors.js"); -function hmacDigest(alg) { - switch (alg) { - case 'HS256': - return 'sha256'; - case 'HS384': - return 'sha384'; - case 'HS512': - return 'sha512'; - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} -exports.default = hmacDigest; diff --git a/dist/node/cjs/runtime/is_key_like.js b/dist/node/cjs/runtime/is_key_like.js deleted file mode 100644 index 454fdd9724..0000000000 --- a/dist/node/cjs/runtime/is_key_like.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.types = void 0; -const webcrypto_js_1 = require("./webcrypto.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -exports.default = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key); -const types = ['KeyObject']; -exports.types = types; -if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) { - types.push('CryptoKey'); -} diff --git a/dist/node/cjs/runtime/is_key_object.js b/dist/node/cjs/runtime/is_key_object.js deleted file mode 100644 index ae02e2eefc..0000000000 --- a/dist/node/cjs/runtime/is_key_object.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const util = require("node:util"); -exports.default = (obj) => util.types.isKeyObject(obj); diff --git a/dist/node/cjs/runtime/jwk_to_key.js b/dist/node/cjs/runtime/jwk_to_key.js deleted file mode 100644 index 80e83c4df1..0000000000 --- a/dist/node/cjs/runtime/jwk_to_key.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const parse = (jwk) => { - return (jwk.d ? node_crypto_1.createPrivateKey : node_crypto_1.createPublicKey)({ format: 'jwk', key: jwk }); -}; -exports.default = parse; diff --git a/dist/node/cjs/runtime/key_to_jwk.js b/dist/node/cjs/runtime/key_to_jwk.js deleted file mode 100644 index 2dff813216..0000000000 --- a/dist/node/cjs/runtime/key_to_jwk.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const base64url_js_1 = require("./base64url.js"); -const errors_js_1 = require("../util/errors.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const keyToJWK = (key) => { - let keyObject; - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - keyObject = node_crypto_1.KeyObject.from(key); - } - else if ((0, is_key_object_js_1.default)(key)) { - keyObject = key; - } - else if (key instanceof Uint8Array) { - return { - kty: 'oct', - k: (0, base64url_js_1.encode)(key), - }; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); - } - if (keyObject.type !== 'secret' && - !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { - throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); - } - return keyObject.export({ format: 'jwk' }); -}; -exports.default = keyToJWK; diff --git a/dist/node/cjs/runtime/node_key.js b/dist/node/cjs/runtime/node_key.js deleted file mode 100644 index 8e5f06571c..0000000000 --- a/dist/node/cjs/runtime/node_key.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const get_named_curve_js_1 = require("./get_named_curve.js"); -const errors_js_1 = require("../util/errors.js"); -const check_key_length_js_1 = require("./check_key_length.js"); -const ecCurveAlgMap = new Map([ - ['ES256', 'P-256'], - ['ES256K', 'secp256k1'], - ['ES384', 'P-384'], - ['ES512', 'P-521'], -]); -function keyForCrypto(alg, key) { - let asymmetricKeyType; - let asymmetricKeyDetails; - let isJWK; - if (key instanceof node_crypto_1.KeyObject) { - asymmetricKeyType = key.asymmetricKeyType; - asymmetricKeyDetails = key.asymmetricKeyDetails; - } - else { - isJWK = true; - switch (key.kty) { - case 'RSA': - asymmetricKeyType = 'rsa'; - break; - case 'EC': - asymmetricKeyType = 'ec'; - break; - case 'OKP': { - if (key.crv === 'Ed25519') { - asymmetricKeyType = 'ed25519'; - break; - } - if (key.crv === 'Ed448') { - asymmetricKeyType = 'ed448'; - break; - } - throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448'); - } - default: - throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC'); - } - } - let options; - switch (alg) { - case 'EdDSA': - if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); - } - break; - case 'RS256': - case 'RS384': - case 'RS512': - if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); - } - (0, check_key_length_js_1.default)(key, alg); - break; - case 'PS256': - case 'PS384': - case 'PS512': - if (asymmetricKeyType === 'rsa-pss') { - const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails; - const length = parseInt(alg.slice(-3), 10); - if (hashAlgorithm !== undefined && - (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); - } - if (saltLength !== undefined && saltLength > length >> 3) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); - } - } - else if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); - } - (0, check_key_length_js_1.default)(key, alg); - options = { - padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING, - saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST, - }; - break; - case 'ES256': - case 'ES256K': - case 'ES384': - case 'ES512': { - if (asymmetricKeyType !== 'ec') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); - } - const actual = (0, get_named_curve_js_1.default)(key); - const expected = ecCurveAlgMap.get(alg); - if (actual !== expected) { - throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); - } - options = { dsaEncoding: 'ieee-p1363' }; - break; - } - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - if (isJWK) { - return { format: 'jwk', key, ...options }; - } - return options ? { ...options, key } : key; -} -exports.default = keyForCrypto; diff --git a/dist/node/cjs/runtime/normalize_key.js b/dist/node/cjs/runtime/normalize_key.js deleted file mode 100644 index 2367d855d5..0000000000 --- a/dist/node/cjs/runtime/normalize_key.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = {}; diff --git a/dist/node/cjs/runtime/pbes2kw.js b/dist/node/cjs/runtime/pbes2kw.js deleted file mode 100644 index 2696af9e08..0000000000 --- a/dist/node/cjs/runtime/pbes2kw.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decrypt = exports.encrypt = void 0; -const node_util_1 = require("node:util"); -const node_crypto_1 = require("node:crypto"); -const random_js_1 = require("./random.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const base64url_js_1 = require("./base64url.js"); -const aeskw_js_1 = require("./aeskw.js"); -const check_p2s_js_1 = require("../lib/check_p2s.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2); -function getPassword(key, alg) { - if ((0, is_key_object_js_1.default)(key)) { - return key.export(); - } - if (key instanceof Uint8Array) { - return key; - } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey'); - return node_crypto_1.KeyObject.from(key).export(); - } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); -} -const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => { - (0, check_p2s_js_1.default)(p2s); - const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek); - return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) }; -}; -exports.encrypt = encrypt; -const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { - (0, check_p2s_js_1.default)(p2s); - const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey); -}; -exports.decrypt = decrypt; diff --git a/dist/node/cjs/runtime/random.js b/dist/node/cjs/runtime/random.js deleted file mode 100644 index f16e4fb369..0000000000 --- a/dist/node/cjs/runtime/random.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = void 0; -var node_crypto_1 = require("node:crypto"); -Object.defineProperty(exports, "default", { enumerable: true, get: function () { return node_crypto_1.randomFillSync; } }); diff --git a/dist/node/cjs/runtime/rsaes.js b/dist/node/cjs/runtime/rsaes.js deleted file mode 100644 index aee6aa26c1..0000000000 --- a/dist/node/cjs/runtime/rsaes.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decrypt = exports.encrypt = void 0; -const node_crypto_1 = require("node:crypto"); -const node_util_1 = require("node:util"); -const check_key_length_js_1 = require("./check_key_length.js"); -const webcrypto_js_1 = require("./webcrypto.js"); -const crypto_key_js_1 = require("../lib/crypto_key.js"); -const is_key_object_js_1 = require("./is_key_object.js"); -const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); -const is_key_like_js_1 = require("./is_key_like.js"); -const checkKey = (key, alg) => { - if (key.asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); - } - (0, check_key_length_js_1.default)(key, alg); -}; -const RSA1_5 = (0, node_util_1.deprecate)(() => node_crypto_1.constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'); -const resolvePadding = (alg) => { - switch (alg) { - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING; - case 'RSA1_5': - return RSA1_5(); - default: - return undefined; - } -}; -const resolveOaepHash = (alg) => { - switch (alg) { - case 'RSA-OAEP': - return 'sha1'; - case 'RSA-OAEP-256': - return 'sha256'; - case 'RSA-OAEP-384': - return 'sha384'; - case 'RSA-OAEP-512': - return 'sha512'; - default: - return undefined; - } -}; -function ensureKeyObject(key, alg, ...usages) { - if ((0, is_key_object_js_1.default)(key)) { - return key; - } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages); - return node_crypto_1.KeyObject.from(key); - } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); -} -const encrypt = (alg, key, cek) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); - checkKey(keyObject, alg); - return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek); -}; -exports.encrypt = encrypt; -const decrypt = (alg, key, encryptedKey) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); - checkKey(keyObject, alg); - return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey); -}; -exports.decrypt = decrypt; diff --git a/dist/node/cjs/runtime/runtime.js b/dist/node/cjs/runtime/runtime.js deleted file mode 100644 index 89c48ad048..0000000000 --- a/dist/node/cjs/runtime/runtime.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = 'node:crypto'; diff --git a/dist/node/cjs/runtime/sign.js b/dist/node/cjs/runtime/sign.js deleted file mode 100644 index 7a8471442e..0000000000 --- a/dist/node/cjs/runtime/sign.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const crypto = require("node:crypto"); -const node_util_1 = require("node:util"); -const dsa_digest_js_1 = require("./dsa_digest.js"); -const hmac_digest_js_1 = require("./hmac_digest.js"); -const node_key_js_1 = require("./node_key.js"); -const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); -const oneShotSign = (0, node_util_1.promisify)(crypto.sign); -const sign = async (alg, key, data) => { - const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign'); - if (alg.startsWith('HS')) { - const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), k); - hmac.update(data); - return hmac.digest(); - } - return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, k)); -}; -exports.default = sign; diff --git a/dist/node/cjs/runtime/timing_safe_equal.js b/dist/node/cjs/runtime/timing_safe_equal.js deleted file mode 100644 index db4c97d964..0000000000 --- a/dist/node/cjs/runtime/timing_safe_equal.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const timingSafeEqual = node_crypto_1.timingSafeEqual; -exports.default = timingSafeEqual; diff --git a/dist/node/cjs/runtime/verify.js b/dist/node/cjs/runtime/verify.js deleted file mode 100644 index f92deb65f2..0000000000 --- a/dist/node/cjs/runtime/verify.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const crypto = require("node:crypto"); -const node_util_1 = require("node:util"); -const dsa_digest_js_1 = require("./dsa_digest.js"); -const node_key_js_1 = require("./node_key.js"); -const sign_js_1 = require("./sign.js"); -const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); -const oneShotVerify = (0, node_util_1.promisify)(crypto.verify); -const verify = async (alg, key, signature, data) => { - const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify'); - if (alg.startsWith('HS')) { - const expected = await (0, sign_js_1.default)(alg, k, data); - const actual = signature; - try { - return crypto.timingSafeEqual(actual, expected); - } - catch { - return false; - } - } - const algorithm = (0, dsa_digest_js_1.default)(alg); - const keyInput = (0, node_key_js_1.default)(alg, k); - try { - return await oneShotVerify(algorithm, data, keyInput, signature); - } - catch { - return false; - } -}; -exports.default = verify; diff --git a/dist/node/cjs/runtime/webcrypto.js b/dist/node/cjs/runtime/webcrypto.js deleted file mode 100644 index 42fac2850f..0000000000 --- a/dist/node/cjs/runtime/webcrypto.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isCryptoKey = void 0; -const crypto = require("node:crypto"); -const util = require("node:util"); -const webcrypto = crypto.webcrypto; -exports.default = webcrypto; -const isCryptoKey = (key) => util.types.isCryptoKey(key); -exports.isCryptoKey = isCryptoKey; diff --git a/dist/node/cjs/util/base64url.js b/dist/node/cjs/util/base64url.js deleted file mode 100644 index 4d383b5167..0000000000 --- a/dist/node/cjs/util/base64url.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decode = exports.encode = void 0; -const base64url = require("../runtime/base64url.js"); -exports.encode = base64url.encode; -exports.decode = base64url.decode; diff --git a/dist/node/cjs/util/decode_jwt.js b/dist/node/cjs/util/decode_jwt.js deleted file mode 100644 index d481e77e07..0000000000 --- a/dist/node/cjs/util/decode_jwt.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeJwt = void 0; -const base64url_js_1 = require("./base64url.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const is_object_js_1 = require("../lib/is_object.js"); -const errors_js_1 = require("./errors.js"); -function decodeJwt(jwt) { - if (typeof jwt !== 'string') - throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); - const { 1: payload, length } = jwt.split('.'); - if (length === 5) - throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); - if (length !== 3) - throw new errors_js_1.JWTInvalid('Invalid JWT'); - if (!payload) - throw new errors_js_1.JWTInvalid('JWTs must contain a payload'); - let decoded; - try { - decoded = (0, base64url_js_1.decode)(payload); - } - catch { - throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload'); - } - let result; - try { - result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded)); - } - catch { - throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON'); - } - if (!(0, is_object_js_1.default)(result)) - throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set'); - return result; -} -exports.decodeJwt = decodeJwt; diff --git a/dist/node/cjs/util/decode_protected_header.js b/dist/node/cjs/util/decode_protected_header.js deleted file mode 100644 index 601ebb7297..0000000000 --- a/dist/node/cjs/util/decode_protected_header.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeProtectedHeader = void 0; -const base64url_js_1 = require("./base64url.js"); -const buffer_utils_js_1 = require("../lib/buffer_utils.js"); -const is_object_js_1 = require("../lib/is_object.js"); -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === 'string') { - const parts = token.split('.'); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } - else if (typeof token === 'object' && token) { - if ('protected' in token) { - protectedB64u = token.protected; - } - else { - throw new TypeError('Token does not contain a Protected Header'); - } - } - try { - if (typeof protectedB64u !== 'string' || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u))); - if (!(0, is_object_js_1.default)(result)) { - throw new Error(); - } - return result; - } - catch { - throw new TypeError('Invalid Token or Protected Header formatting'); - } -} -exports.decodeProtectedHeader = decodeProtectedHeader; diff --git a/dist/node/cjs/util/errors.js b/dist/node/cjs/util/errors.js deleted file mode 100644 index 397f1834e4..0000000000 --- a/dist/node/cjs/util/errors.js +++ /dev/null @@ -1,137 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0; -class JOSEError extends Error { - static get code() { - return 'ERR_JOSE_GENERIC'; - } - code = 'ERR_JOSE_GENERIC'; - constructor(message) { - super(message); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -} -exports.JOSEError = JOSEError; -class JWTClaimValidationFailed extends JOSEError { - static get code() { - return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - } - code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -exports.JWTClaimValidationFailed = JWTClaimValidationFailed; -class JWTExpired extends JOSEError { - static get code() { - return 'ERR_JWT_EXPIRED'; - } - code = 'ERR_JWT_EXPIRED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -exports.JWTExpired = JWTExpired; -class JOSEAlgNotAllowed extends JOSEError { - static get code() { - return 'ERR_JOSE_ALG_NOT_ALLOWED'; - } - code = 'ERR_JOSE_ALG_NOT_ALLOWED'; -} -exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed; -class JOSENotSupported extends JOSEError { - static get code() { - return 'ERR_JOSE_NOT_SUPPORTED'; - } - code = 'ERR_JOSE_NOT_SUPPORTED'; -} -exports.JOSENotSupported = JOSENotSupported; -class JWEDecryptionFailed extends JOSEError { - static get code() { - return 'ERR_JWE_DECRYPTION_FAILED'; - } - code = 'ERR_JWE_DECRYPTION_FAILED'; - message = 'decryption operation failed'; -} -exports.JWEDecryptionFailed = JWEDecryptionFailed; -class JWEInvalid extends JOSEError { - static get code() { - return 'ERR_JWE_INVALID'; - } - code = 'ERR_JWE_INVALID'; -} -exports.JWEInvalid = JWEInvalid; -class JWSInvalid extends JOSEError { - static get code() { - return 'ERR_JWS_INVALID'; - } - code = 'ERR_JWS_INVALID'; -} -exports.JWSInvalid = JWSInvalid; -class JWTInvalid extends JOSEError { - static get code() { - return 'ERR_JWT_INVALID'; - } - code = 'ERR_JWT_INVALID'; -} -exports.JWTInvalid = JWTInvalid; -class JWKInvalid extends JOSEError { - static get code() { - return 'ERR_JWK_INVALID'; - } - code = 'ERR_JWK_INVALID'; -} -exports.JWKInvalid = JWKInvalid; -class JWKSInvalid extends JOSEError { - static get code() { - return 'ERR_JWKS_INVALID'; - } - code = 'ERR_JWKS_INVALID'; -} -exports.JWKSInvalid = JWKSInvalid; -class JWKSNoMatchingKey extends JOSEError { - static get code() { - return 'ERR_JWKS_NO_MATCHING_KEY'; - } - code = 'ERR_JWKS_NO_MATCHING_KEY'; - message = 'no applicable key found in the JSON Web Key Set'; -} -exports.JWKSNoMatchingKey = JWKSNoMatchingKey; -class JWKSMultipleMatchingKeys extends JOSEError { - [Symbol.asyncIterator]; - static get code() { - return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - } - code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - message = 'multiple matching keys found in the JSON Web Key Set'; -} -exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys; -class JWKSTimeout extends JOSEError { - static get code() { - return 'ERR_JWKS_TIMEOUT'; - } - code = 'ERR_JWKS_TIMEOUT'; - message = 'request timed out'; -} -exports.JWKSTimeout = JWKSTimeout; -class JWSSignatureVerificationFailed extends JOSEError { - static get code() { - return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - } - code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - message = 'signature verification failed'; -} -exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed; diff --git a/dist/node/cjs/util/runtime.js b/dist/node/cjs/util/runtime.js deleted file mode 100644 index ac211f85da..0000000000 --- a/dist/node/cjs/util/runtime.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const runtime_js_1 = require("../runtime/runtime.js"); -exports.default = runtime_js_1.default; diff --git a/dist/node/esm/index.js b/dist/node/esm/index.js deleted file mode 100644 index 386fbf5fef..0000000000 --- a/dist/node/esm/index.js +++ /dev/null @@ -1,30 +0,0 @@ -export { compactDecrypt } from './jwe/compact/decrypt.js'; -export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; -export { generalDecrypt } from './jwe/general/decrypt.js'; -export { GeneralEncrypt } from './jwe/general/encrypt.js'; -export { compactVerify } from './jws/compact/verify.js'; -export { flattenedVerify } from './jws/flattened/verify.js'; -export { generalVerify } from './jws/general/verify.js'; -export { jwtVerify } from './jwt/verify.js'; -export { jwtDecrypt } from './jwt/decrypt.js'; -export { CompactEncrypt } from './jwe/compact/encrypt.js'; -export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; -export { CompactSign } from './jws/compact/sign.js'; -export { FlattenedSign } from './jws/flattened/sign.js'; -export { GeneralSign } from './jws/general/sign.js'; -export { SignJWT } from './jwt/sign.js'; -export { EncryptJWT } from './jwt/encrypt.js'; -export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; -export { EmbeddedJWK } from './jwk/embedded.js'; -export { createLocalJWKSet } from './jwks/local.js'; -export { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote.js'; -export { UnsecuredJWT } from './jwt/unsecured.js'; -export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; -export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; -export { decodeProtectedHeader } from './util/decode_protected_header.js'; -export { decodeJwt } from './util/decode_jwt.js'; -export * as errors from './util/errors.js'; -export { generateKeyPair } from './key/generate_key_pair.js'; -export { generateSecret } from './key/generate_secret.js'; -export * as base64url from './util/base64url.js'; -export { default as cryptoRuntime } from './util/runtime.js'; diff --git a/dist/node/esm/jwe/compact/decrypt.js b/dist/node/esm/jwe/compact/decrypt.js deleted file mode 100644 index d74a67b134..0000000000 --- a/dist/node/esm/jwe/compact/decrypt.js +++ /dev/null @@ -1,27 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.js'; -import { JWEInvalid } from '../../util/errors.js'; -import { decoder } from '../../lib/buffer_utils.js'; -export 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: tag, length, } = jwe.split('.'); - if (length !== 5) { - throw new JWEInvalid('Invalid Compact JWE'); - } - const decrypted = await flattenedDecrypt({ - ciphertext, - iv: iv || undefined, - protected: protectedHeader, - tag: tag || undefined, - encrypted_key: encryptedKey || undefined, - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} diff --git a/dist/node/esm/jwe/compact/encrypt.js b/dist/node/esm/jwe/compact/encrypt.js deleted file mode 100644 index e4a44d0cee..0000000000 --- a/dist/node/esm/jwe/compact/encrypt.js +++ /dev/null @@ -1,27 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.js'; -export class CompactEncrypt { - _flattened; - constructor(plaintext) { - this._flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); - } -} diff --git a/dist/node/esm/jwe/flattened/decrypt.js b/dist/node/esm/jwe/flattened/decrypt.js deleted file mode 100644 index 8b963a3873..0000000000 --- a/dist/node/esm/jwe/flattened/decrypt.js +++ /dev/null @@ -1,161 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.js'; -import decrypt from '../../runtime/decrypt.js'; -import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import isObject from '../../lib/is_object.js'; -import decryptKeyManagement from '../../lib/decrypt_key_management.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import generateCek from '../../lib/cek.js'; -import validateCrit from '../../lib/validate_crit.js'; -import validateAlgorithms from '../../lib/validate_algorithms.js'; -export async function flattenedDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid('Flattened JWE must be an object'); - } - if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { - throw new JWEInvalid('JOSE Header missing'); - } - if (jwe.iv !== undefined && 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 !== undefined && typeof jwe.tag !== 'string') { - throw new JWEInvalid('JWE Authentication Tag incorrect type'); - } - if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { - throw new JWEInvalid('JWE Protected Header incorrect type'); - } - if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { - throw new JWEInvalid('JWE Encrypted Key incorrect type'); - } - if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { - throw new JWEInvalid('JWE AAD incorrect type'); - } - if (jwe.header !== undefined && !isObject(jwe.header)) { - throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); - } - if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { - throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader = base64url(jwe.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } - catch { - throw new JWEInvalid('JWE Protected Header is invalid'); - } - } - if (!isDisjoint(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, - }; - validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== undefined) { - 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 && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && - validateAlgorithms('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 !== undefined) { - try { - encryptedKey = base64url(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; - } - let cek; - try { - cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); - } - catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err; - } - cek = generateCek(enc); - } - let iv; - let tag; - if (jwe.iv !== undefined) { - try { - iv = base64url(jwe.iv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the iv'); - } - } - if (jwe.tag !== undefined) { - try { - tag = base64url(jwe.tag); - } - catch { - throw new JWEInvalid('Failed to base64url decode the tag'); - } - } - const protectedHeader = encoder.encode(jwe.protected ?? ''); - let additionalData; - if (jwe.aad !== undefined) { - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); - } - else { - additionalData = protectedHeader; - } - let ciphertext; - try { - ciphertext = base64url(jwe.ciphertext); - } - catch { - throw new JWEInvalid('Failed to base64url decode the ciphertext'); - } - const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData); - const result = { plaintext }; - if (jwe.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== undefined) { - try { - result.additionalAuthenticatedData = base64url(jwe.aad); - } - catch { - throw new JWEInvalid('Failed to base64url decode the aad'); - } - } - if (jwe.unprotected !== undefined) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== undefined) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} diff --git a/dist/node/esm/jwe/flattened/encrypt.js b/dist/node/esm/jwe/flattened/encrypt.js deleted file mode 100644 index 70bbc92081..0000000000 --- a/dist/node/esm/jwe/flattened/encrypt.js +++ /dev/null @@ -1,161 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.js'; -import { unprotected } from '../../lib/private_symbols.js'; -import encrypt from '../../runtime/encrypt.js'; -import encryptKeyManagement from '../../lib/encrypt_key_management.js'; -import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import validateCrit from '../../lib/validate_crit.js'; -export class FlattenedEncrypt { - _plaintext; - _protectedHeader; - _sharedUnprotectedHeader; - _unprotectedHeader; - _aad; - _cek; - _iv; - _keyManagementParameters; - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError('plaintext must be an instance of Uint8Array'); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); - } - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader, - }; - validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== 'string' || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } - else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } - else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } - else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = encoder.encode(''); - } - if (this._aad) { - aadMember = base64url(this._aad); - additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); - } - else { - additionalData = protectedHeader; - } - const { ciphertext, tag, iv } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: base64url(ciphertext), - }; - if (iv) { - jwe.iv = base64url(iv); - } - if (tag) { - jwe.tag = base64url(tag); - } - if (encryptedKey) { - jwe.encrypted_key = base64url(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; - } -} diff --git a/dist/node/esm/jwe/general/decrypt.js b/dist/node/esm/jwe/general/decrypt.js deleted file mode 100644 index 659958a8bc..0000000000 --- a/dist/node/esm/jwe/general/decrypt.js +++ /dev/null @@ -1,31 +0,0 @@ -import { flattenedDecrypt } from '../flattened/decrypt.js'; -import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; -import isObject from '../../lib/is_object.js'; -export async function generalDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid('General JWE must be an object'); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { - throw new JWEInvalid('JWE Recipients missing or incorrect type'); - } - if (!jwe.recipients.length) { - throw new JWEInvalid('JWE Recipients has no members'); - } - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected, - }, key, options); - } - catch { - } - } - throw new JWEDecryptionFailed(); -} diff --git a/dist/node/esm/jwe/general/encrypt.js b/dist/node/esm/jwe/general/encrypt.js deleted file mode 100644 index e3c07cbb1a..0000000000 --- a/dist/node/esm/jwe/general/encrypt.js +++ /dev/null @@ -1,182 +0,0 @@ -import { FlattenedEncrypt } from '../flattened/encrypt.js'; -import { unprotected } from '../../lib/private_symbols.js'; -import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; -import generateCek from '../../lib/cek.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import encryptKeyManagement from '../../lib/encrypt_key_management.js'; -import { encode as base64url } from '../../runtime/base64url.js'; -import validateCrit from '../../lib/validate_crit.js'; -class IndividualRecipient { - parent; - unprotectedHeader; - key; - options; - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } -} -export class GeneralEncrypt { - _plaintext; - _recipients = []; - _protectedHeader; - _unprotectedHeader; - _aad; - constructor(plaintext) { - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new JWEInvalid('at least one recipient must be added'); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .encrypt(recipient.key, { ...recipient.options }); - const jwe = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag, - }; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe.recipients[0].header = flattened.header; - return jwe; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === 'dir' || alg === 'ECDH-ES') { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } - else if (enc !== joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - } - const cek = generateCek(enc); - const jwe = { - ciphertext: '', - iv: '', - recipients: [], - tag: '', - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; - if (i === 0) { - const flattened = await new FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setContentEncryptionKey(cek) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .setKeyManagementParameters({ p2c }) - .encrypt(recipient.key, { - ...recipient.options, - [unprotected]: true, - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg || - this._protectedHeader?.alg || - this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = base64url(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } -} diff --git a/dist/node/esm/jwk/embedded.js b/dist/node/esm/jwk/embedded.js deleted file mode 100644 index aa43b2ff75..0000000000 --- a/dist/node/esm/jwk/embedded.js +++ /dev/null @@ -1,17 +0,0 @@ -import { importJWK } from '../key/import.js'; -import isObject from '../lib/is_object.js'; -import { JWSInvalid } from '../util/errors.js'; -export async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header, - }; - if (!isObject(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; -} diff --git a/dist/node/esm/jwk/thumbprint.js b/dist/node/esm/jwk/thumbprint.js deleted file mode 100644 index 7ae043a1e8..0000000000 --- a/dist/node/esm/jwk/thumbprint.js +++ /dev/null @@ -1,53 +0,0 @@ -import digest from '../runtime/digest.js'; -import { encode as base64url } from '../runtime/base64url.js'; -import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; -import { encoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -const check = (value, description) => { - if (typeof value !== 'string' || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } -}; -export async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object'); - } - digestAlgorithm ??= 'sha256'; - if (digestAlgorithm !== 'sha256' && - digestAlgorithm !== 'sha384' && - digestAlgorithm !== 'sha512') { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case 'EC': - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case 'OKP': - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case 'RSA': - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case 'oct': - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encoder.encode(JSON.stringify(components)); - return base64url(await digest(digestAlgorithm, data)); -} -export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ??= 'sha256'; - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; -} diff --git a/dist/node/esm/jwks/local.js b/dist/node/esm/jwks/local.js deleted file mode 100644 index b65375d3e0..0000000000 --- a/dist/node/esm/jwks/local.js +++ /dev/null @@ -1,122 +0,0 @@ -import { importJWK } from '../key/import.js'; -import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; -import isObject from '../lib/is_object.js'; -function getKtyFromAlg(alg) { - switch (typeof alg === 'string' && alg.slice(0, 2)) { - case 'RS': - case 'PS': - return 'RSA'; - case 'ES': - return 'EC'; - case 'Ed': - return 'OKP'; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return (jwks && - typeof jwks === 'object' && - Array.isArray(jwks.keys) && - jwks.keys.every(isJWKLike)); -} -function isJWKLike(key) { - return isObject(key); -} -function clone(obj) { - if (typeof structuredClone === 'function') { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); -} -class LocalJWKSet { - _jwks; - _cached = new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid('JSON Web Key Set malformed'); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === 'string') { - candidate = kid === jwk.kid; - } - if (candidate && typeof jwk.alg === 'string') { - candidate = alg === jwk.alg; - } - if (candidate && typeof jwk.use === 'string') { - candidate = jwk.use === 'sig'; - } - if (candidate && Array.isArray(jwk.key_ops)) { - candidate = jwk.key_ops.includes('verify'); - } - if (candidate && alg === 'EdDSA') { - candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; - } - if (candidate) { - switch (alg) { - case 'ES256': - candidate = jwk.crv === 'P-256'; - break; - case 'ES256K': - candidate = jwk.crv === 'secp256k1'; - break; - case 'ES384': - candidate = jwk.crv === 'P-384'; - break; - case 'ES512': - candidate = jwk.crv === 'P-521'; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) { - try { - yield await importWithAlgCache(_cached, jwk, alg); - } - catch { } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } -} -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === undefined) { - const key = await importJWK({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new JWKSInvalid('JSON Web Key Set members must be public keys'); - } - cached[alg] = key; - } - return cached[alg]; -} -export function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return localJWKSet; -} diff --git a/dist/node/esm/jwks/remote.js b/dist/node/esm/jwks/remote.js deleted file mode 100644 index 6f112042bb..0000000000 --- a/dist/node/esm/jwks/remote.js +++ /dev/null @@ -1,148 +0,0 @@ -import fetchJwks from '../runtime/fetch_jwks.js'; -import { JWKSNoMatchingKey } from '../util/errors.js'; -import { createLocalJWKSet } from './local.js'; -import isObject from '../lib/is_object.js'; -function isCloudflareWorkers() { - return (typeof WebSocketPair !== 'undefined' || - (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || - (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); -} -let USER_AGENT; -if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { - const NAME = 'jose'; - const VERSION = 'v5.9.1'; - USER_AGENT = `${NAME}/${VERSION}`; -} -export const jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== 'object' || input === null) { - return false; - } - if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!('jwks' in input) || - !isObject(input.jwks) || - !Array.isArray(input.jwks.keys) || - !Array.prototype.every.call(input.jwks.keys, isObject)) { - return false; - } - return true; -} -class RemoteJWKSet { - _url; - _timeoutDuration; - _cooldownDuration; - _cacheMaxAge; - _jwksTimestamp; - _pendingFetch; - _options; - _local; - _cache; - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError('url must be an instance of URL'); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = - typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; - this._cooldownDuration = - typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; - this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; - if (options?.[jwksCache] !== undefined) { - this._cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = createLocalJWKSet(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cooldownDuration - : false; - } - fresh() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cacheMaxAge - : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } - catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = undefined; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has('User-Agent')) { - headers.set('User-Agent', USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options) - .then((json) => { - this._local = createLocalJWKSet(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = undefined; - }) - .catch((err) => { - this._pendingFetch = undefined; - throw err; - }); - await this._pendingFetch; - } -} -export function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false, - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false, - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false, - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false, - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return remoteJWKSet; -} -export const experimental_jwksCache = jwksCache; diff --git a/dist/node/esm/jws/compact/sign.js b/dist/node/esm/jws/compact/sign.js deleted file mode 100644 index ff40853643..0000000000 --- a/dist/node/esm/jws/compact/sign.js +++ /dev/null @@ -1,18 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.js'; -export class CompactSign { - _flattened; - constructor(payload) { - this._flattened = new FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === undefined) { - throw new TypeError('use the flattened module for creating JWS with b64: false'); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -} diff --git a/dist/node/esm/jws/compact/verify.js b/dist/node/esm/jws/compact/verify.js deleted file mode 100644 index c651ffb944..0000000000 --- a/dist/node/esm/jws/compact/verify.js +++ /dev/null @@ -1,21 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.js'; -import { JWSInvalid } from '../../util/errors.js'; -import { decoder } from '../../lib/buffer_utils.js'; -export async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== 'string') { - throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); - if (length !== 3) { - throw new JWSInvalid('Invalid Compact JWS'); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} diff --git a/dist/node/esm/jws/flattened/sign.js b/dist/node/esm/jws/flattened/sign.js deleted file mode 100644 index 97fab65f9b..0000000000 --- a/dist/node/esm/jws/flattened/sign.js +++ /dev/null @@ -1,84 +0,0 @@ -import { encode as base64url } from '../../runtime/base64url.js'; -import sign from '../../runtime/sign.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import { JWSInvalid } from '../../util/errors.js'; -import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js'; -import validateCrit from '../../lib/validate_crit.js'; -export class FlattenedSign { - _payload; - _protectedHeader; - _unprotectedHeader; - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError('payload must be an instance of Uint8Array'); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); - } - if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { - throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - }; - const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== 'boolean') { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyTypeWithJwk(alg, key, 'sign'); - let payload = this._payload; - if (b64) { - payload = encoder.encode(base64url(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = encoder.encode(''); - } - const data = concat(protectedHeader, encoder.encode('.'), payload); - const signature = await sign(alg, key, data); - const jws = { - signature: base64url(signature), - payload: '', - }; - if (b64) { - jws.payload = decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = decoder.decode(protectedHeader); - } - return jws; - } -} diff --git a/dist/node/esm/jws/flattened/verify.js b/dist/node/esm/jws/flattened/verify.js deleted file mode 100644 index 188cb92201..0000000000 --- a/dist/node/esm/jws/flattened/verify.js +++ /dev/null @@ -1,122 +0,0 @@ -import { decode as base64url } from '../../runtime/base64url.js'; -import verify from '../../runtime/verify.js'; -import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; -import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; -import isDisjoint from '../../lib/is_disjoint.js'; -import isObject from '../../lib/is_object.js'; -import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js'; -import validateCrit from '../../lib/validate_crit.js'; -import validateAlgorithms from '../../lib/validate_algorithms.js'; -import { isJWK } from '../../lib/is_jwk.js'; -import { importJWK } from '../../key/import.js'; -export async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid('Flattened JWS must be an object'); - } - if (jws.protected === undefined && jws.header === undefined) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== undefined && typeof jws.protected !== 'string') { - throw new JWSInvalid('JWS Protected Header incorrect type'); - } - if (jws.payload === undefined) { - throw new JWSInvalid('JWS Payload missing'); - } - if (typeof jws.signature !== 'string') { - throw new JWSInvalid('JWS Signature missing or incorrect type'); - } - if (jws.header !== undefined && !isObject(jws.header)) { - throw new JWSInvalid('JWS Unprotected Header incorrect type'); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = base64url(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } - catch { - throw new JWSInvalid('JWS Protected Header is invalid'); - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jws.header, - }; - const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = parsedProt.b64; - if (typeof b64 !== 'boolean') { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validateAlgorithms('algorithms', options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== 'string') { - throw new JWSInvalid('JWS Payload must be a string'); - } - } - else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jws); - resolvedKey = true; - checkKeyTypeWithJwk(alg, key, 'verify'); - if (isJWK(key)) { - key = await importJWK(key, alg); - } - } - else { - checkKeyTypeWithJwk(alg, key, 'verify'); - } - const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = base64url(jws.signature); - } - catch { - throw new JWSInvalid('Failed to base64url decode the signature'); - } - const verified = await verify(alg, key, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = base64url(jws.payload); - } - catch { - throw new JWSInvalid('Failed to base64url decode the payload'); - } - } - else if (typeof jws.payload === 'string') { - payload = encoder.encode(jws.payload); - } - else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jws.header !== undefined) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} diff --git a/dist/node/esm/jws/general/sign.js b/dist/node/esm/jws/general/sign.js deleted file mode 100644 index 620dd48fe3..0000000000 --- a/dist/node/esm/jws/general/sign.js +++ /dev/null @@ -1,73 +0,0 @@ -import { FlattenedSign } from '../flattened/sign.js'; -import { JWSInvalid } from '../../util/errors.js'; -class IndividualSignature { - parent; - protectedHeader; - unprotectedHeader; - options; - key; - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } -} -export class GeneralSign { - _payload; - _signatures = []; - constructor(payload) { - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new JWSInvalid('at least one signature must be added'); - } - const jws = { - signatures: [], - payload: '', - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } - else if (jws.payload !== payload) { - throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); - } - jws.signatures.push(rest); - } - return jws; - } -} diff --git a/dist/node/esm/jws/general/verify.js b/dist/node/esm/jws/general/verify.js deleted file mode 100644 index c511b722dc..0000000000 --- a/dist/node/esm/jws/general/verify.js +++ /dev/null @@ -1,24 +0,0 @@ -import { flattenedVerify } from '../flattened/verify.js'; -import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; -import isObject from '../../lib/is_object.js'; -export async function generalVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid('General JWS must be an object'); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { - throw new JWSInvalid('JWS Signatures missing or incorrect type'); - } - for (const signature of jws.signatures) { - try { - return await flattenedVerify({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature, - }, key, options); - } - catch { - } - } - throw new JWSSignatureVerificationFailed(); -} diff --git a/dist/node/esm/jwt/decrypt.js b/dist/node/esm/jwt/decrypt.js deleted file mode 100644 index c3a85fe5af..0000000000 --- a/dist/node/esm/jwt/decrypt.js +++ /dev/null @@ -1,23 +0,0 @@ -import { compactDecrypt } from '../jwe/compact/decrypt.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { JWTClaimValidationFailed } from '../util/errors.js'; -export async function jwtDecrypt(jwt, key, options) { - const decrypted = await compactDecrypt(jwt, key, options); - const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); - } - if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); - } - if (protectedHeader.aud !== undefined && - JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); - } - const result = { payload, protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} diff --git a/dist/node/esm/jwt/encrypt.js b/dist/node/esm/jwt/encrypt.js deleted file mode 100644 index 2035989810..0000000000 --- a/dist/node/esm/jwt/encrypt.js +++ /dev/null @@ -1,75 +0,0 @@ -import { CompactEncrypt } from '../jwe/compact/encrypt.js'; -import { encoder } from '../lib/buffer_utils.js'; -import { ProduceJWT } from './produce.js'; -export class EncryptJWT extends ProduceJWT { - _cek; - _iv; - _keyManagementParameters; - _protectedHeader; - _replicateIssuerAsHeader; - _replicateSubjectAsHeader; - _replicateAudienceAsHeader; - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } -} diff --git a/dist/node/esm/jwt/produce.js b/dist/node/esm/jwt/produce.js deleted file mode 100644 index 7954c65b8c..0000000000 --- a/dist/node/esm/jwt/produce.js +++ /dev/null @@ -1,76 +0,0 @@ -import epoch from '../lib/epoch.js'; -import isObject from '../lib/is_object.js'; -import secs from '../lib/secs.js'; -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -export class ProduceJWT { - _payload; - constructor(payload = {}) { - if (!isObject(payload)) { - throw new TypeError('JWT Claims Set MUST be an object'); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) }; - } - else { - this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) }; - } - else { - this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === 'undefined') { - this._payload = { ...this._payload, iat: epoch(new Date()) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) }; - } - else if (typeof input === 'string') { - this._payload = { - ...this._payload, - iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)), - }; - } - else { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }; - } - return this; - } -} diff --git a/dist/node/esm/jwt/sign.js b/dist/node/esm/jwt/sign.js deleted file mode 100644 index 16bf9f4360..0000000000 --- a/dist/node/esm/jwt/sign.js +++ /dev/null @@ -1,21 +0,0 @@ -import { CompactSign } from '../jws/compact/sign.js'; -import { JWTInvalid } from '../util/errors.js'; -import { encoder } from '../lib/buffer_utils.js'; -import { ProduceJWT } from './produce.js'; -export class SignJWT extends ProduceJWT { - _protectedHeader; - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && - this._protectedHeader.crit.includes('b64') && - this._protectedHeader.b64 === false) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - return sig.sign(key, options); - } -} diff --git a/dist/node/esm/jwt/unsecured.js b/dist/node/esm/jwt/unsecured.js deleted file mode 100644 index 41c7c33bb5..0000000000 --- a/dist/node/esm/jwt/unsecured.js +++ /dev/null @@ -1,32 +0,0 @@ -import * as base64url from '../runtime/base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import { JWTInvalid } from '../util/errors.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { ProduceJWT } from './produce.js'; -export class UnsecuredJWT extends ProduceJWT { - encode() { - const header = base64url.encode(JSON.stringify({ alg: 'none' })); - const payload = base64url.encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== 'string') { - throw new JWTInvalid('Unsecured JWT must be a string'); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); - if (length !== 3 || signature !== '') { - throw new JWTInvalid('Invalid Unsecured JWT'); - } - let header; - try { - header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); - if (header.alg !== 'none') - throw new Error(); - } - catch { - throw new JWTInvalid('Invalid Unsecured JWT'); - } - const payload = jwtPayload(header, base64url.decode(encodedPayload), options); - return { payload, header }; - } -} diff --git a/dist/node/esm/jwt/verify.js b/dist/node/esm/jwt/verify.js deleted file mode 100644 index f5d99d06b5..0000000000 --- a/dist/node/esm/jwt/verify.js +++ /dev/null @@ -1,15 +0,0 @@ -import { compactVerify } from '../jws/compact/verify.js'; -import jwtPayload from '../lib/jwt_claims_set.js'; -import { JWTInvalid } from '../util/errors.js'; -export async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { - throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - const payload = jwtPayload(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} diff --git a/dist/node/esm/key/export.js b/dist/node/esm/key/export.js deleted file mode 100644 index e4017047cd..0000000000 --- a/dist/node/esm/key/export.js +++ /dev/null @@ -1,12 +0,0 @@ -import { toSPKI as exportPublic } from '../runtime/asn1.js'; -import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; -import keyToJWK from '../runtime/key_to_jwk.js'; -export async function exportSPKI(key) { - return exportPublic(key); -} -export async function exportPKCS8(key) { - return exportPrivate(key); -} -export async function exportJWK(key) { - return keyToJWK(key); -} diff --git a/dist/node/esm/key/generate_key_pair.js b/dist/node/esm/key/generate_key_pair.js deleted file mode 100644 index 03b9ee54cd..0000000000 --- a/dist/node/esm/key/generate_key_pair.js +++ /dev/null @@ -1,4 +0,0 @@ -import { generateKeyPair as generate } from '../runtime/generate.js'; -export async function generateKeyPair(alg, options) { - return generate(alg, options); -} diff --git a/dist/node/esm/key/generate_secret.js b/dist/node/esm/key/generate_secret.js deleted file mode 100644 index 58f308a543..0000000000 --- a/dist/node/esm/key/generate_secret.js +++ /dev/null @@ -1,4 +0,0 @@ -import { generateSecret as generate } from '../runtime/generate.js'; -export async function generateSecret(alg, options) { - return generate(alg, options); -} diff --git a/dist/node/esm/key/import.js b/dist/node/esm/key/import.js deleted file mode 100644 index d53f3716b4..0000000000 --- a/dist/node/esm/key/import.js +++ /dev/null @@ -1,45 +0,0 @@ -import { decode as decodeBase64URL } from '../runtime/base64url.js'; -import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js'; -import asKeyObject from '../runtime/jwk_to_key.js'; -import { JOSENotSupported } from '../util/errors.js'; -import isObject from '../lib/is_object.js'; -export async function importSPKI(spki, alg, options) { - if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return fromSPKI(spki, alg, options); -} -export async function importX509(x509, alg, options) { - if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return fromX509(x509, alg, options); -} -export async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return fromPKCS8(pkcs8, alg, options); -} -export async function importJWK(jwk, alg) { - if (!isObject(jwk)) { - throw new TypeError('JWK must be an object'); - } - alg ||= jwk.alg; - switch (jwk.kty) { - case 'oct': - if (typeof jwk.k !== 'string' || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return decodeBase64URL(jwk.k); - case 'RSA': - if (jwk.oth !== undefined) { - throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - case 'EC': - case 'OKP': - return asKeyObject({ ...jwk, alg }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} diff --git a/dist/node/esm/lib/aesgcmkw.js b/dist/node/esm/lib/aesgcmkw.js deleted file mode 100644 index 47d9d5e3b7..0000000000 --- a/dist/node/esm/lib/aesgcmkw.js +++ /dev/null @@ -1,16 +0,0 @@ -import encrypt from '../runtime/encrypt.js'; -import decrypt from '../runtime/decrypt.js'; -import { encode as base64url } from '../runtime/base64url.js'; -export async function wrap(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: base64url(wrapped.iv), - tag: base64url(wrapped.tag), - }; -} -export async function unwrap(alg, key, encryptedKey, iv, tag) { - const jweAlgorithm = alg.slice(0, 7); - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); -} diff --git a/dist/node/esm/lib/buffer_utils.js b/dist/node/esm/lib/buffer_utils.js deleted file mode 100644 index b261a58ed4..0000000000 --- a/dist/node/esm/lib/buffer_utils.js +++ /dev/null @@ -1,51 +0,0 @@ -import digest from '../runtime/digest.js'; -export const encoder = new TextEncoder(); -export const decoder = new TextDecoder(); -const MAX_INT32 = 2 ** 32; -export 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; -} -export function p2s(alg, p2sInput) { - return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); -} -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 & 0xff], offset); -} -export 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; -} -export function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -export function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -export 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('sha256', buf), iter * 32); - } - return res.slice(0, bits >> 3); -} diff --git a/dist/node/esm/lib/cek.js b/dist/node/esm/lib/cek.js deleted file mode 100644 index 34697d3ac2..0000000000 --- a/dist/node/esm/lib/cek.js +++ /dev/null @@ -1,20 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -import random from '../runtime/random.js'; -export function bitLength(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}`); - } -} -export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/node/esm/lib/check_iv_length.js b/dist/node/esm/lib/check_iv_length.js deleted file mode 100644 index dcd28d3a9d..0000000000 --- a/dist/node/esm/lib/check_iv_length.js +++ /dev/null @@ -1,8 +0,0 @@ -import { JWEInvalid } from '../util/errors.js'; -import { bitLength } from './iv.js'; -const checkIvLength = (enc, iv) => { - if (iv.length << 3 !== bitLength(enc)) { - throw new JWEInvalid('Invalid Initialization Vector length'); - } -}; -export default checkIvLength; diff --git a/dist/node/esm/lib/check_key_type.js b/dist/node/esm/lib/check_key_type.js deleted file mode 100644 index bcefa4ff61..0000000000 --- a/dist/node/esm/lib/check_key_type.js +++ /dev/null @@ -1,77 +0,0 @@ -import { withAlg as invalidKeyInput } from './invalid_key_input.js'; -import isKeyLike, { types } from '../runtime/is_key_like.js'; -import * as jwk from './is_jwk.js'; -const tag = (key) => key?.[Symbol.toStringTag]; -const jwkMatchesOp = (alg, key, usage) => { - if (key.use !== undefined && key.use !== 'sig') { - throw new TypeError('Invalid key for this operation, when present its use must be sig'); - } - if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== undefined && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; -}; -const symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && jwk.isJWK(key)) { - if (jwk.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 (!isKeyLike(key)) { - throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null)); - } - if (key.type !== 'secret') { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -const asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && jwk.isJWK(key)) { - switch (usage) { - case 'sign': - if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - case 'verify': - if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a public JWK`); - } - } - if (!isKeyLike(key)) { - throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null)); - } - if (key.type === 'secret') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === 'sign' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === 'decrypt' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === 'verify' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === 'encrypt' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith('HS') || - alg === 'dir' || - alg.startsWith('PBES2') || - /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } - else { - asymmetricTypeCheck(alg, key, usage, allowJwk); - } -} -export default checkKeyType.bind(undefined, false); -export const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true); diff --git a/dist/node/esm/lib/check_p2s.js b/dist/node/esm/lib/check_p2s.js deleted file mode 100644 index a65289fa7a..0000000000 --- a/dist/node/esm/lib/check_p2s.js +++ /dev/null @@ -1,6 +0,0 @@ -import { JWEInvalid } from '../util/errors.js'; -export default function checkP2s(p2s) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); - } -} diff --git a/dist/node/esm/lib/crypto_key.js b/dist/node/esm/lib/crypto_key.js deleted file mode 100644 index 807e951a53..0000000000 --- a/dist/node/esm/lib/crypto_key.js +++ /dev/null @@ -1,152 +0,0 @@ -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 getNamedCurve(alg) { - switch (alg) { - case 'ES256': - return 'P-256'; - case 'ES384': - return 'P-384'; - case 'ES512': - return 'P-521'; - default: - throw new Error('unreachable'); - } -} -function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = 'CryptoKey does not support this operation, its usages must include '; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(', ')}, or ${last}.`; - } - else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } - else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } -} -export function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': { - if (!isAlgorithm(key.algorithm, 'HMAC')) - throw unusable('HMAC'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'RS256': - case 'RS384': - case 'RS512': { - if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) - throw unusable('RSASSA-PKCS1-v1_5'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'PS256': - case 'PS384': - case 'PS512': { - if (!isAlgorithm(key.algorithm, 'RSA-PSS')) - throw unusable('RSA-PSS'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'EdDSA': { - if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { - throw unusable('Ed25519 or Ed448'); - } - break; - } - case 'ES256': - case 'ES384': - case 'ES512': { - if (!isAlgorithm(key.algorithm, 'ECDSA')) - throw unusable('ECDSA'); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, 'algorithm.namedCurve'); - break; - } - default: - throw new TypeError('CryptoKey does not support this operation'); - } - checkUsage(key, usages); -} -export function checkEncCryptoKey(key, alg, ...usages) { - 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': - case 'X448': - break; - default: - throw unusable('ECDH, X25519, or X448'); - } - 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, usages); -} diff --git a/dist/node/esm/lib/decrypt_key_management.js b/dist/node/esm/lib/decrypt_key_management.js deleted file mode 100644 index 62205c441e..0000000000 --- a/dist/node/esm/lib/decrypt_key_management.js +++ /dev/null @@ -1,129 +0,0 @@ -import { unwrap as aesKw } from '../runtime/aeskw.js'; -import * as ECDH from '../runtime/ecdhes.js'; -import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; -import { decrypt as rsaEs } from '../runtime/rsaes.js'; -import { decode as base64url } from '../runtime/base64url.js'; -import normalize from '../runtime/normalize_key.js'; -import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; -import { bitLength as cekLength } from '../lib/cek.js'; -import { importJWK } from '../key/import.js'; -import checkKeyType from './check_key_type.js'; -import isObject from './is_object.js'; -import { unwrap as aesGcmKw } from './aesgcmkw.js'; -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - checkKeyType(alg, key, 'decrypt'); - key = (await normalize.normalizePrivateKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); - return key; - } - case 'ECDH-ES': - if (encryptedKey !== undefined) - throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ECDH.ecdhAllowed(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); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== undefined) { - if (typeof joseHeader.apu !== 'string') - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - try { - partyUInfo = base64url(joseHeader.apu); - } - catch { - throw new JWEInvalid('Failed to base64url decode the apu'); - } - } - if (joseHeader.apv !== undefined) { - if (typeof joseHeader.apv !== 'string') - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - try { - partyVInfo = base64url(joseHeader.apv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the apv'); - } - } - const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg === 'ECDH-ES') - return sharedSecret; - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return aesKw(alg.slice(-6), sharedSecret, encryptedKey); - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return rsaEs(alg, key, encryptedKey); - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - if (encryptedKey === undefined) - 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 || 10_000; - 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 = base64url(joseHeader.p2s); - } - catch { - throw new JWEInvalid('Failed to base64url decode the p2s'); - } - return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s); - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - if (encryptedKey === undefined) - throw new JWEInvalid('JWE Encrypted Key missing'); - return aesKw(alg, key, encryptedKey); - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - if (encryptedKey === undefined) - 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 = base64url(joseHeader.iv); - } - catch { - throw new JWEInvalid('Failed to base64url decode the iv'); - } - let tag; - try { - tag = base64url(joseHeader.tag); - } - catch { - throw new JWEInvalid('Failed to base64url decode the tag'); - } - return aesGcmKw(alg, key, encryptedKey, iv, tag); - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } -} -export default decryptKeyManagement; diff --git a/dist/node/esm/lib/encrypt_key_management.js b/dist/node/esm/lib/encrypt_key_management.js deleted file mode 100644 index 5923ed0040..0000000000 --- a/dist/node/esm/lib/encrypt_key_management.js +++ /dev/null @@ -1,89 +0,0 @@ -import { wrap as aesKw } from '../runtime/aeskw.js'; -import * as ECDH from '../runtime/ecdhes.js'; -import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; -import { encrypt as rsaEs } from '../runtime/rsaes.js'; -import { encode as base64url } from '../runtime/base64url.js'; -import normalize from '../runtime/normalize_key.js'; -import generateCek, { bitLength as cekLength } from '../lib/cek.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { exportJWK } from '../key/export.js'; -import checkKeyType from './check_key_type.js'; -import { wrap as aesGcmKw } from './aesgcmkw.js'; -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - checkKeyType(alg, key, 'encrypt'); - key = (await normalize.normalizePublicKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - cek = key; - break; - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!ECDH.ecdhAllowed(key)) { - throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); - } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey; - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === 'EC') - parameters.epk.y = y; - if (apu) - parameters.apu = base64url(apu); - if (apv) - parameters.apv = base64url(apv); - if (alg === 'ECDH-ES') { - cek = sharedSecret; - break; - } - cek = providedCek || generateCek(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await aesKw(kwAlg, sharedSecret, cek); - break; - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - cek = providedCek || generateCek(enc); - encryptedKey = await rsaEs(alg, key, cek); - break; - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - cek = providedCek || generateCek(enc); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); - break; - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - cek = providedCek || generateCek(enc); - encryptedKey = await aesKw(alg, key, cek); - break; - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - cek = providedCek || generateCek(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } - return { cek, encryptedKey, parameters }; -} -export default encryptKeyManagement; diff --git a/dist/node/esm/lib/epoch.js b/dist/node/esm/lib/epoch.js deleted file mode 100644 index e405e4b2df..0000000000 --- a/dist/node/esm/lib/epoch.js +++ /dev/null @@ -1 +0,0 @@ -export default (date) => Math.floor(date.getTime() / 1000); diff --git a/dist/node/esm/lib/invalid_key_input.js b/dist/node/esm/lib/invalid_key_input.js deleted file mode 100644 index 5796a2eb69..0000000000 --- a/dist/node/esm/lib/invalid_key_input.js +++ /dev/null @@ -1,31 +0,0 @@ -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; -} -export default (actual, ...types) => { - return message('Key must be ', actual, ...types); -}; -export function withAlg(alg, actual, ...types) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types); -} diff --git a/dist/node/esm/lib/is_disjoint.js b/dist/node/esm/lib/is_disjoint.js deleted file mode 100644 index 6f643502dc..0000000000 --- a/dist/node/esm/lib/is_disjoint.js +++ /dev/null @@ -1,22 +0,0 @@ -const isDisjoint = (...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; -}; -export default isDisjoint; diff --git a/dist/node/esm/lib/is_jwk.js b/dist/node/esm/lib/is_jwk.js deleted file mode 100644 index 7e0321308a..0000000000 --- a/dist/node/esm/lib/is_jwk.js +++ /dev/null @@ -1,13 +0,0 @@ -import isObject from './is_object.js'; -export function isJWK(key) { - return isObject(key) && typeof key.kty === 'string'; -} -export function isPrivateJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'string'; -} -export function isPublicJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'undefined'; -} -export function isSecretJWK(key) { - return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string'; -} diff --git a/dist/node/esm/lib/is_object.js b/dist/node/esm/lib/is_object.js deleted file mode 100644 index 4955e93225..0000000000 --- a/dist/node/esm/lib/is_object.js +++ /dev/null @@ -1,16 +0,0 @@ -function isObjectLike(value) { - return typeof value === 'object' && value !== null; -} -export default function isObject(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; -} diff --git a/dist/node/esm/lib/iv.js b/dist/node/esm/lib/iv.js deleted file mode 100644 index cab2a12729..0000000000 --- a/dist/node/esm/lib/iv.js +++ /dev/null @@ -1,20 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -import random from '../runtime/random.js'; -export 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}`); - } -} -export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); diff --git a/dist/node/esm/lib/jwt_claims_set.js b/dist/node/esm/lib/jwt_claims_set.js deleted file mode 100644 index 64b6bd0a39..0000000000 --- a/dist/node/esm/lib/jwt_claims_set.js +++ /dev/null @@ -1,103 +0,0 @@ -import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; -import { decoder } from './buffer_utils.js'; -import epoch from './epoch.js'; -import secs from './secs.js'; -import isObject from './is_object.js'; -const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); -const checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -export default (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } - catch { - } - if (!isObject(payload)) { - throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); - } - const { typ } = options; - if (typ && - (typeof protectedHeader.typ !== 'string' || - normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== undefined) - presenceCheck.push('iat'); - if (audience !== undefined) - presenceCheck.push('aud'); - if (subject !== undefined) - presenceCheck.push('sub'); - if (issuer !== undefined) - presenceCheck.push('iss'); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); - } - if (audience && - !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); - } - let tolerance; - switch (typeof options.clockTolerance) { - case 'string': - tolerance = secs(options.clockTolerance); - break; - case 'number': - tolerance = options.clockTolerance; - break; - case 'undefined': - tolerance = 0; - break; - default: - throw new TypeError('Invalid clockTolerance option type'); - } - const { currentDate } = options; - const now = epoch(currentDate || new Date()); - if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); - } - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); - } - } - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); - } - } - return payload; -}; diff --git a/dist/node/esm/lib/private_symbols.js b/dist/node/esm/lib/private_symbols.js deleted file mode 100644 index fce302b11e..0000000000 --- a/dist/node/esm/lib/private_symbols.js +++ /dev/null @@ -1 +0,0 @@ -export const unprotected = Symbol(); diff --git a/dist/node/esm/lib/secs.js b/dist/node/esm/lib/secs.js deleted file mode 100644 index c99507450a..0000000000 --- a/dist/node/esm/lib/secs.js +++ /dev/null @@ -1,55 +0,0 @@ -const minute = 60; -const hour = minute * 60; -const day = hour * 24; -const week = day * 7; -const year = day * 365.25; -const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -export default (str) => { - const matched = REGEX.exec(str); - if (!matched || (matched[4] && matched[1])) { - throw new TypeError('Invalid time period format'); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - numericDate = Math.round(value); - break; - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - numericDate = Math.round(value * minute); - break; - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - numericDate = Math.round(value * hour); - break; - case 'day': - case 'days': - case 'd': - numericDate = Math.round(value * day); - break; - case 'week': - case 'weeks': - case 'w': - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === '-' || matched[4] === 'ago') { - return -numericDate; - } - return numericDate; -}; diff --git a/dist/node/esm/lib/validate_algorithms.js b/dist/node/esm/lib/validate_algorithms.js deleted file mode 100644 index a6a7918571..0000000000 --- a/dist/node/esm/lib/validate_algorithms.js +++ /dev/null @@ -1,11 +0,0 @@ -const validateAlgorithms = (option, algorithms) => { - if (algorithms !== undefined && - (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return undefined; - } - return new Set(algorithms); -}; -export default validateAlgorithms; diff --git a/dist/node/esm/lib/validate_crit.js b/dist/node/esm/lib/validate_crit.js deleted file mode 100644 index 0d1b052c1e..0000000000 --- a/dist/node/esm/lib/validate_crit.js +++ /dev/null @@ -1,34 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === undefined) { - return 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 !== undefined) { - 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] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} -export default validateCrit; diff --git a/dist/node/esm/package.json b/dist/node/esm/package.json deleted file mode 100644 index 8fb7e8f61b..0000000000 --- a/dist/node/esm/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type":"module","sideEffects":false} diff --git a/dist/node/esm/runtime/aeskw.js b/dist/node/esm/runtime/aeskw.js deleted file mode 100644 index b0667fe052..0000000000 --- a/dist/node/esm/runtime/aeskw.js +++ /dev/null @@ -1,50 +0,0 @@ -import { Buffer } from 'node:buffer'; -import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'node:crypto'; -import { JOSENotSupported } from '../util/errors.js'; -import { concat } from '../lib/buffer_utils.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import supported from './ciphers.js'; -import { types } from './is_key_like.js'; -function checkKeySize(key, alg) { - if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg}`); - } -} -function ensureKeyObject(key, alg, usage) { - if (isKeyObject(key)) { - return key; - } - if (key instanceof Uint8Array) { - return createSecretKey(key); - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, usage); - return KeyObject.from(key); - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); -} -export const wrap = (alg, key, cek) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'wrapKey'); - checkKeySize(keyObject, alg); - const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); - return concat(cipher.update(cek), cipher.final()); -}; -export const unwrap = (alg, key, encryptedKey) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); - checkKeySize(keyObject, alg); - const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); - return concat(cipher.update(encryptedKey), cipher.final()); -}; diff --git a/dist/node/esm/runtime/asn1.js b/dist/node/esm/runtime/asn1.js deleted file mode 100644 index 201ec232c8..0000000000 --- a/dist/node/esm/runtime/asn1.js +++ /dev/null @@ -1,46 +0,0 @@ -import { createPrivateKey, createPublicKey, KeyObject } from 'node:crypto'; -import { Buffer } from 'node:buffer'; -import { isCryptoKey } from './webcrypto.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -const genericExport = (keyType, keyFormat, key) => { - let keyObject; - if (isCryptoKey(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - keyObject = KeyObject.from(key); - } - else if (isKeyObject(key)) { - keyObject = key; - } - else { - throw new TypeError(invalidKeyInput(key, ...types)); - } - if (keyObject.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return keyObject.export({ format: 'pem', type: keyFormat }); -}; -export const toSPKI = (key) => { - return genericExport('public', 'spki', key); -}; -export const toPKCS8 = (key) => { - return genericExport('private', 'pkcs8', key); -}; -export const fromPKCS8 = (pem) => createPrivateKey({ - key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), - type: 'pkcs8', - format: 'der', -}); -export const fromSPKI = (pem) => createPublicKey({ - key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), - type: 'spki', - format: 'der', -}); -export const fromX509 = (pem) => createPublicKey({ - key: pem, - type: 'spki', - format: 'pem', -}); diff --git a/dist/node/esm/runtime/base64url.js b/dist/node/esm/runtime/base64url.js deleted file mode 100644 index e4edb45107..0000000000 --- a/dist/node/esm/runtime/base64url.js +++ /dev/null @@ -1,14 +0,0 @@ -import { Buffer } from 'node:buffer'; -import { decoder } from '../lib/buffer_utils.js'; -function normalize(input) { - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = decoder.decode(encoded); - } - return encoded; -} -const encode = (input) => Buffer.from(input).toString('base64url'); -export const decodeBase64 = (input) => new Uint8Array(Buffer.from(input, 'base64')); -export const encodeBase64 = (input) => Buffer.from(input).toString('base64'); -export { encode }; -export const decode = (input) => new Uint8Array(Buffer.from(normalize(input), 'base64url')); diff --git a/dist/node/esm/runtime/cbc_tag.js b/dist/node/esm/runtime/cbc_tag.js deleted file mode 100644 index 3e951f17fb..0000000000 --- a/dist/node/esm/runtime/cbc_tag.js +++ /dev/null @@ -1,8 +0,0 @@ -import { createHmac } from 'node:crypto'; -import { concat, uint64be } from '../lib/buffer_utils.js'; -export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const hmac = createHmac(`sha${macSize}`, macKey); - hmac.update(macData); - return hmac.digest().slice(0, keySize >> 3); -} diff --git a/dist/node/esm/runtime/check_cek_length.js b/dist/node/esm/runtime/check_cek_length.js deleted file mode 100644 index 60884c0ea5..0000000000 --- a/dist/node/esm/runtime/check_cek_length.js +++ /dev/null @@ -1,35 +0,0 @@ -import { JWEInvalid, JOSENotSupported } from '../util/errors.js'; -import isKeyObject from './is_key_object.js'; -const checkCekLength = (enc, cek) => { - let expected; - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - expected = parseInt(enc.slice(-3), 10); - break; - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - expected = parseInt(enc.slice(1, 4), 10); - break; - default: - throw new JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); - } - if (cek instanceof Uint8Array) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } - return; - } - if (isKeyObject(cek) && cek.type === 'secret') { - const actual = cek.symmetricKeySize << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } - return; - } - throw new TypeError('Invalid Content Encryption Key type'); -}; -export default checkCekLength; diff --git a/dist/node/esm/runtime/check_key_length.js b/dist/node/esm/runtime/check_key_length.js deleted file mode 100644 index 38da02fbbd..0000000000 --- a/dist/node/esm/runtime/check_key_length.js +++ /dev/null @@ -1,16 +0,0 @@ -import { KeyObject } from 'node:crypto'; -export default (key, alg) => { - let modulusLength; - try { - if (key instanceof KeyObject) { - modulusLength = key.asymmetricKeyDetails?.modulusLength; - } - else { - modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3; - } - } - catch { } - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); - } -}; diff --git a/dist/node/esm/runtime/ciphers.js b/dist/node/esm/runtime/ciphers.js deleted file mode 100644 index 3063d48078..0000000000 --- a/dist/node/esm/runtime/ciphers.js +++ /dev/null @@ -1,6 +0,0 @@ -import { getCiphers } from 'node:crypto'; -let ciphers; -export default (algorithm) => { - ciphers ||= new Set(getCiphers()); - return ciphers.has(algorithm); -}; diff --git a/dist/node/esm/runtime/decrypt.js b/dist/node/esm/runtime/decrypt.js deleted file mode 100644 index cff3376026..0000000000 --- a/dist/node/esm/runtime/decrypt.js +++ /dev/null @@ -1,101 +0,0 @@ -import { createDecipheriv, KeyObject } from 'node:crypto'; -import checkIvLength from '../lib/check_iv_length.js'; -import checkCekLength from './check_cek_length.js'; -import { concat } from '../lib/buffer_utils.js'; -import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js'; -import timingSafeEqual from './timing_safe_equal.js'; -import cbcTag from './cbc_tag.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import supported from './ciphers.js'; -import { types } from './is_key_like.js'; -function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if (isKeyObject(cek)) { - cek = cek.export(); - } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const macSize = parseInt(enc.slice(-3), 10); - const algorithm = `aes-${keySize}-cbc`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); - let macCheckPassed; - try { - macCheckPassed = timingSafeEqual(tag, expectedTag); - } - catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - const decipher = createDecipheriv(algorithm, encKey, iv); - plaintext = concat(decipher.update(ciphertext), decipher.final()); - } - catch { - } - if (!plaintext) { - throw new JWEDecryptionFailed(); - } - return plaintext; -} -function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - try { - const decipher = createDecipheriv(algorithm, cek, iv, { authTagLength: 16 }); - decipher.setAuthTag(tag); - if (aad.byteLength) { - decipher.setAAD(aad, { plaintextLength: ciphertext.length }); - } - const plaintext = decipher.update(ciphertext); - decipher.final(); - return plaintext; - } - catch { - throw new JWEDecryptionFailed(); - } -} -const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { - let key; - if (isCryptoKey(cek)) { - checkEncCryptoKey(cek, enc, 'decrypt'); - key = KeyObject.from(cek); - } - else if (cek instanceof Uint8Array || isKeyObject(cek)) { - key = cek; - } - else { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); - } - if (!iv) { - throw new JWEInvalid('JWE Initialization Vector missing'); - } - if (!tag) { - throw new JWEInvalid('JWE Authentication Tag missing'); - } - checkCekLength(enc, key); - checkIvLength(enc, iv); - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -export default decrypt; diff --git a/dist/node/esm/runtime/digest.js b/dist/node/esm/runtime/digest.js deleted file mode 100644 index e329024cc0..0000000000 --- a/dist/node/esm/runtime/digest.js +++ /dev/null @@ -1,3 +0,0 @@ -import { createHash } from 'node:crypto'; -const digest = (algorithm, data) => createHash(algorithm).update(data).digest(); -export default digest; diff --git a/dist/node/esm/runtime/dsa_digest.js b/dist/node/esm/runtime/dsa_digest.js deleted file mode 100644 index ce7215bd67..0000000000 --- a/dist/node/esm/runtime/dsa_digest.js +++ /dev/null @@ -1,22 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -export default function dsaDigest(alg) { - switch (alg) { - case 'PS256': - case 'RS256': - case 'ES256': - case 'ES256K': - return 'sha256'; - case 'PS384': - case 'RS384': - case 'ES384': - return 'sha384'; - case 'PS512': - case 'RS512': - case 'ES512': - return 'sha512'; - case 'EdDSA': - return undefined; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} diff --git a/dist/node/esm/runtime/ecdhes.js b/dist/node/esm/runtime/ecdhes.js deleted file mode 100644 index 8ebe873b7f..0000000000 --- a/dist/node/esm/runtime/ecdhes.js +++ /dev/null @@ -1,64 +0,0 @@ -import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'node:crypto'; -import { promisify } from 'node:util'; -import getNamedCurve from './get_named_curve.js'; -import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -const generateKeyPair = promisify(generateKeyPairCb); -export async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - let publicKey; - if (isCryptoKey(publicKee)) { - checkEncCryptoKey(publicKee, 'ECDH'); - publicKey = KeyObject.from(publicKee); - } - else if (isKeyObject(publicKee)) { - publicKey = publicKee; - } - else { - throw new TypeError(invalidKeyInput(publicKee, ...types)); - } - let privateKey; - if (isCryptoKey(privateKee)) { - checkEncCryptoKey(privateKee, 'ECDH', 'deriveBits'); - privateKey = KeyObject.from(privateKee); - } - else if (isKeyObject(privateKee)) { - privateKey = privateKee; - } - else { - throw new TypeError(invalidKeyInput(privateKee, ...types)); - } - const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); - const sharedSecret = diffieHellman({ privateKey, publicKey }); - return concatKdf(sharedSecret, keyLength, value); -} -export async function generateEpk(kee) { - let key; - if (isCryptoKey(kee)) { - key = KeyObject.from(kee); - } - else if (isKeyObject(kee)) { - key = kee; - } - else { - throw new TypeError(invalidKeyInput(kee, ...types)); - } - switch (key.asymmetricKeyType) { - case 'x25519': - return generateKeyPair('x25519'); - case 'x448': { - return generateKeyPair('x448'); - } - case 'ec': { - const namedCurve = getNamedCurve(key); - return generateKeyPair('ec', { namedCurve }); - } - default: - throw new JOSENotSupported('Invalid or unsupported EPK'); - } -} -export const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes(getNamedCurve(key)); diff --git a/dist/node/esm/runtime/encrypt.js b/dist/node/esm/runtime/encrypt.js deleted file mode 100644 index 1e91bacb2e..0000000000 --- a/dist/node/esm/runtime/encrypt.js +++ /dev/null @@ -1,78 +0,0 @@ -import { createCipheriv, KeyObject } from 'node:crypto'; -import checkIvLength from '../lib/check_iv_length.js'; -import checkCekLength from './check_cek_length.js'; -import { concat } from '../lib/buffer_utils.js'; -import cbcTag from './cbc_tag.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import generateIv from '../lib/iv.js'; -import { JOSENotSupported } from '../util/errors.js'; -import supported from './ciphers.js'; -import { types } from './is_key_like.js'; -function cbcEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if (isKeyObject(cek)) { - cek = cek.export(); - } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const algorithm = `aes-${keySize}-cbc`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const cipher = createCipheriv(algorithm, encKey, iv); - const ciphertext = concat(cipher.update(plaintext), cipher.final()); - const macSize = parseInt(enc.slice(-3), 10); - const tag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); - return { ciphertext, tag, iv }; -} -function gcmEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!supported(algorithm)) { - throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const cipher = createCipheriv(algorithm, cek, iv, { authTagLength: 16 }); - if (aad.byteLength) { - cipher.setAAD(aad, { plaintextLength: plaintext.length }); - } - const ciphertext = cipher.update(plaintext); - cipher.final(); - const tag = cipher.getAuthTag(); - return { ciphertext, tag, iv }; -} -const encrypt = (enc, plaintext, cek, iv, aad) => { - let key; - if (isCryptoKey(cek)) { - checkEncCryptoKey(cek, enc, 'encrypt'); - key = KeyObject.from(cek); - } - else if (cek instanceof Uint8Array || isKeyObject(cek)) { - key = cek; - } - else { - throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); - } - checkCekLength(enc, key); - if (iv) { - checkIvLength(enc, iv); - } - else { - iv = generateIv(enc); - } - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcEncrypt(enc, plaintext, key, iv, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmEncrypt(enc, plaintext, key, iv, aad); - default: - throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -export default encrypt; diff --git a/dist/node/esm/runtime/fetch_jwks.js b/dist/node/esm/runtime/fetch_jwks.js deleted file mode 100644 index de1d54556d..0000000000 --- a/dist/node/esm/runtime/fetch_jwks.js +++ /dev/null @@ -1,43 +0,0 @@ -import * as http from 'node:http'; -import * as https from 'node:https'; -import { once } from 'node:events'; -import { JOSEError, JWKSTimeout } from '../util/errors.js'; -import { concat, decoder } from '../lib/buffer_utils.js'; -const fetchJwks = async (url, timeout, options) => { - let get; - switch (url.protocol) { - case 'https:': - get = https.get; - break; - case 'http:': - get = http.get; - break; - default: - throw new TypeError('Unsupported URL protocol.'); - } - const { agent, headers } = options; - const req = get(url.href, { - agent, - timeout, - headers, - }); - const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')])); - if (!response) { - req.destroy(); - throw new JWKSTimeout(); - } - if (response.statusCode !== 200) { - throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); - } - const parts = []; - for await (const part of response) { - parts.push(part); - } - try { - return JSON.parse(decoder.decode(concat(...parts))); - } - catch { - throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); - } -}; -export default fetchJwks; diff --git a/dist/node/esm/runtime/generate.js b/dist/node/esm/runtime/generate.js deleted file mode 100644 index 022fc916d6..0000000000 --- a/dist/node/esm/runtime/generate.js +++ /dev/null @@ -1,97 +0,0 @@ -import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'node:crypto'; -import { promisify } from 'node:util'; -import random from './random.js'; -import { JOSENotSupported } from '../util/errors.js'; -const generate = promisify(generateKeyPairCb); -export async function generateSecret(alg, options) { - let length; - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - length = parseInt(alg.slice(-3), 10); - break; - case 'A128KW': - case 'A192KW': - case 'A256KW': - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - length = parseInt(alg.slice(1, 4), 10); - break; - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return createSecretKey(random(new Uint8Array(length >> 3))); -} -export async function generateKeyPair(alg, options) { - switch (alg) { - case 'RS256': - case 'RS384': - case 'RS512': - case 'PS256': - case 'PS384': - case 'PS512': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - case 'RSA1_5': { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); - } - const keypair = await generate('rsa', { - modulusLength, - publicExponent: 0x10001, - }); - return keypair; - } - case 'ES256': - return generate('ec', { namedCurve: 'P-256' }); - case 'ES256K': - return generate('ec', { namedCurve: 'secp256k1' }); - case 'ES384': - return generate('ec', { namedCurve: 'P-384' }); - case 'ES512': - return generate('ec', { namedCurve: 'P-521' }); - case 'EdDSA': { - switch (options?.crv) { - case undefined: - case 'Ed25519': - return generate('ed25519'); - case 'Ed448': - return generate('ed448'); - default: - throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); - } - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - const crv = options?.crv ?? 'P-256'; - switch (crv) { - case undefined: - case 'P-256': - case 'P-384': - case 'P-521': - return generate('ec', { namedCurve: crv }); - case 'X25519': - return generate('x25519'); - case 'X448': - return generate('x448'); - default: - throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); - } - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } -} diff --git a/dist/node/esm/runtime/get_named_curve.js b/dist/node/esm/runtime/get_named_curve.js deleted file mode 100644 index 45c20a091c..0000000000 --- a/dist/node/esm/runtime/get_named_curve.js +++ /dev/null @@ -1,58 +0,0 @@ -import { KeyObject } from 'node:crypto'; -import { JOSENotSupported } from '../util/errors.js'; -import { isCryptoKey } from './webcrypto.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -import { isJWK } from '../lib/is_jwk.js'; -export const weakMap = new WeakMap(); -const namedCurveToJOSE = (namedCurve) => { - switch (namedCurve) { - case 'prime256v1': - return 'P-256'; - case 'secp384r1': - return 'P-384'; - case 'secp521r1': - return 'P-521'; - case 'secp256k1': - return 'secp256k1'; - default: - throw new JOSENotSupported('Unsupported key curve for this operation'); - } -}; -const getNamedCurve = (kee, raw) => { - let key; - if (isCryptoKey(kee)) { - key = KeyObject.from(kee); - } - else if (isKeyObject(kee)) { - key = kee; - } - else if (isJWK(kee)) { - return kee.crv; - } - else { - throw new TypeError(invalidKeyInput(kee, ...types)); - } - if (key.type === 'secret') { - throw new TypeError('only "private" or "public" type keys can be used for this operation'); - } - switch (key.asymmetricKeyType) { - case 'ed25519': - case 'ed448': - return `Ed${key.asymmetricKeyType.slice(2)}`; - case 'x25519': - case 'x448': - return `X${key.asymmetricKeyType.slice(1)}`; - case 'ec': { - const namedCurve = key.asymmetricKeyDetails.namedCurve; - if (raw) { - return namedCurve; - } - return namedCurveToJOSE(namedCurve); - } - default: - throw new TypeError('Invalid asymmetric key type for this operation'); - } -}; -export default getNamedCurve; diff --git a/dist/node/esm/runtime/get_sign_verify_key.js b/dist/node/esm/runtime/get_sign_verify_key.js deleted file mode 100644 index 4e8770b199..0000000000 --- a/dist/node/esm/runtime/get_sign_verify_key.js +++ /dev/null @@ -1,28 +0,0 @@ -import { KeyObject, createSecretKey } from 'node:crypto'; -import { isCryptoKey } from './webcrypto.js'; -import { checkSigCryptoKey } from '../lib/crypto_key.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -import * as jwk from '../lib/is_jwk.js'; -export default function getSignVerifyKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith('HS')) { - throw new TypeError(invalidKeyInput(key, ...types)); - } - return createSecretKey(key); - } - if (key instanceof KeyObject) { - return key; - } - if (isCryptoKey(key)) { - checkSigCryptoKey(key, alg, usage); - return KeyObject.from(key); - } - if (jwk.isJWK(key)) { - if (alg.startsWith('HS')) { - return createSecretKey(Buffer.from(key.k, 'base64url')); - } - return key; - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key')); -} diff --git a/dist/node/esm/runtime/hmac_digest.js b/dist/node/esm/runtime/hmac_digest.js deleted file mode 100644 index 29d55c3e9c..0000000000 --- a/dist/node/esm/runtime/hmac_digest.js +++ /dev/null @@ -1,13 +0,0 @@ -import { JOSENotSupported } from '../util/errors.js'; -export default function hmacDigest(alg) { - switch (alg) { - case 'HS256': - return 'sha256'; - case 'HS384': - return 'sha384'; - case 'HS512': - return 'sha512'; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} diff --git a/dist/node/esm/runtime/is_key_like.js b/dist/node/esm/runtime/is_key_like.js deleted file mode 100644 index eea3909594..0000000000 --- a/dist/node/esm/runtime/is_key_like.js +++ /dev/null @@ -1,8 +0,0 @@ -import webcrypto, { isCryptoKey } from './webcrypto.js'; -import isKeyObject from './is_key_object.js'; -export default (key) => isKeyObject(key) || isCryptoKey(key); -const types = ['KeyObject']; -if (globalThis.CryptoKey || webcrypto?.CryptoKey) { - types.push('CryptoKey'); -} -export { types }; diff --git a/dist/node/esm/runtime/is_key_object.js b/dist/node/esm/runtime/is_key_object.js deleted file mode 100644 index 854d0a25a3..0000000000 --- a/dist/node/esm/runtime/is_key_object.js +++ /dev/null @@ -1,2 +0,0 @@ -import * as util from 'node:util'; -export default (obj) => util.types.isKeyObject(obj); diff --git a/dist/node/esm/runtime/jwk_to_key.js b/dist/node/esm/runtime/jwk_to_key.js deleted file mode 100644 index 11dd37b04c..0000000000 --- a/dist/node/esm/runtime/jwk_to_key.js +++ /dev/null @@ -1,5 +0,0 @@ -import { createPrivateKey, createPublicKey } from 'node:crypto'; -const parse = (jwk) => { - return (jwk.d ? createPrivateKey : createPublicKey)({ format: 'jwk', key: jwk }); -}; -export default parse; diff --git a/dist/node/esm/runtime/key_to_jwk.js b/dist/node/esm/runtime/key_to_jwk.js deleted file mode 100644 index 2ac129a955..0000000000 --- a/dist/node/esm/runtime/key_to_jwk.js +++ /dev/null @@ -1,34 +0,0 @@ -import { KeyObject } from 'node:crypto'; -import { encode as base64url } from './base64url.js'; -import { JOSENotSupported } from '../util/errors.js'; -import { isCryptoKey } from './webcrypto.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -const keyToJWK = (key) => { - let keyObject; - if (isCryptoKey(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - keyObject = KeyObject.from(key); - } - else if (isKeyObject(key)) { - keyObject = key; - } - else if (key instanceof Uint8Array) { - return { - kty: 'oct', - k: base64url(key), - }; - } - else { - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); - } - if (keyObject.type !== 'secret' && - !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { - throw new JOSENotSupported('Unsupported key asymmetricKeyType'); - } - return keyObject.export({ format: 'jwk' }); -}; -export default keyToJWK; diff --git a/dist/node/esm/runtime/node_key.js b/dist/node/esm/runtime/node_key.js deleted file mode 100644 index d7cecabe50..0000000000 --- a/dist/node/esm/runtime/node_key.js +++ /dev/null @@ -1,103 +0,0 @@ -import { constants, KeyObject } from 'node:crypto'; -import getNamedCurve from './get_named_curve.js'; -import { JOSENotSupported } from '../util/errors.js'; -import checkKeyLength from './check_key_length.js'; -const ecCurveAlgMap = new Map([ - ['ES256', 'P-256'], - ['ES256K', 'secp256k1'], - ['ES384', 'P-384'], - ['ES512', 'P-521'], -]); -export default function keyForCrypto(alg, key) { - let asymmetricKeyType; - let asymmetricKeyDetails; - let isJWK; - if (key instanceof KeyObject) { - asymmetricKeyType = key.asymmetricKeyType; - asymmetricKeyDetails = key.asymmetricKeyDetails; - } - else { - isJWK = true; - switch (key.kty) { - case 'RSA': - asymmetricKeyType = 'rsa'; - break; - case 'EC': - asymmetricKeyType = 'ec'; - break; - case 'OKP': { - if (key.crv === 'Ed25519') { - asymmetricKeyType = 'ed25519'; - break; - } - if (key.crv === 'Ed448') { - asymmetricKeyType = 'ed448'; - break; - } - throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448'); - } - default: - throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC'); - } - } - let options; - switch (alg) { - case 'EdDSA': - if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); - } - break; - case 'RS256': - case 'RS384': - case 'RS512': - if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); - } - checkKeyLength(key, alg); - break; - case 'PS256': - case 'PS384': - case 'PS512': - if (asymmetricKeyType === 'rsa-pss') { - const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails; - const length = parseInt(alg.slice(-3), 10); - if (hashAlgorithm !== undefined && - (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); - } - if (saltLength !== undefined && saltLength > length >> 3) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); - } - } - else if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); - } - checkKeyLength(key, alg); - options = { - padding: constants.RSA_PKCS1_PSS_PADDING, - saltLength: constants.RSA_PSS_SALTLEN_DIGEST, - }; - break; - case 'ES256': - case 'ES256K': - case 'ES384': - case 'ES512': { - if (asymmetricKeyType !== 'ec') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); - } - const actual = getNamedCurve(key); - const expected = ecCurveAlgMap.get(alg); - if (actual !== expected) { - throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); - } - options = { dsaEncoding: 'ieee-p1363' }; - break; - } - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - if (isJWK) { - return { format: 'jwk', key, ...options }; - } - return options ? { ...options, key } : key; -} diff --git a/dist/node/esm/runtime/normalize_key.js b/dist/node/esm/runtime/normalize_key.js deleted file mode 100644 index ff8b4c5632..0000000000 --- a/dist/node/esm/runtime/normalize_key.js +++ /dev/null @@ -1 +0,0 @@ -export default {}; diff --git a/dist/node/esm/runtime/pbes2kw.js b/dist/node/esm/runtime/pbes2kw.js deleted file mode 100644 index 7fde10593d..0000000000 --- a/dist/node/esm/runtime/pbes2kw.js +++ /dev/null @@ -1,43 +0,0 @@ -import { promisify } from 'node:util'; -import { KeyObject, pbkdf2 as pbkdf2cb } from 'node:crypto'; -import random from './random.js'; -import { p2s as concatSalt } from '../lib/buffer_utils.js'; -import { encode as base64url } from './base64url.js'; -import { wrap, unwrap } from './aeskw.js'; -import checkP2s from '../lib/check_p2s.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -const pbkdf2 = promisify(pbkdf2cb); -function getPassword(key, alg) { - if (isKeyObject(key)) { - return key.export(); - } - if (key instanceof Uint8Array) { - return key; - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); - return KeyObject.from(key).export(); - } - throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); -} -export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { - checkP2s(p2s); - const salt = concatSalt(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek); - return { encryptedKey, p2c, p2s: base64url(p2s) }; -}; -export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { - checkP2s(p2s); - const salt = concatSalt(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - return unwrap(alg.slice(-6), derivedKey, encryptedKey); -}; diff --git a/dist/node/esm/runtime/random.js b/dist/node/esm/runtime/random.js deleted file mode 100644 index af6533c8f1..0000000000 --- a/dist/node/esm/runtime/random.js +++ /dev/null @@ -1 +0,0 @@ -export { randomFillSync as default } from 'node:crypto'; diff --git a/dist/node/esm/runtime/rsaes.js b/dist/node/esm/runtime/rsaes.js deleted file mode 100644 index fac0bdfae1..0000000000 --- a/dist/node/esm/runtime/rsaes.js +++ /dev/null @@ -1,66 +0,0 @@ -import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'node:crypto'; -import { deprecate } from 'node:util'; -import checkKeyLength from './check_key_length.js'; -import { isCryptoKey } from './webcrypto.js'; -import { checkEncCryptoKey } from '../lib/crypto_key.js'; -import isKeyObject from './is_key_object.js'; -import invalidKeyInput from '../lib/invalid_key_input.js'; -import { types } from './is_key_like.js'; -const checkKey = (key, alg) => { - if (key.asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); - } - checkKeyLength(key, alg); -}; -const RSA1_5 = deprecate(() => constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'); -const resolvePadding = (alg) => { - switch (alg) { - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - return constants.RSA_PKCS1_OAEP_PADDING; - case 'RSA1_5': - return RSA1_5(); - default: - return undefined; - } -}; -const resolveOaepHash = (alg) => { - switch (alg) { - case 'RSA-OAEP': - return 'sha1'; - case 'RSA-OAEP-256': - return 'sha256'; - case 'RSA-OAEP-384': - return 'sha384'; - case 'RSA-OAEP-512': - return 'sha512'; - default: - return undefined; - } -}; -function ensureKeyObject(key, alg, ...usages) { - if (isKeyObject(key)) { - return key; - } - if (isCryptoKey(key)) { - checkEncCryptoKey(key, alg, ...usages); - return KeyObject.from(key); - } - throw new TypeError(invalidKeyInput(key, ...types)); -} -export const encrypt = (alg, key, cek) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); - checkKey(keyObject, alg); - return publicEncrypt({ key: keyObject, oaepHash, padding }, cek); -}; -export const decrypt = (alg, key, encryptedKey) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); - checkKey(keyObject, alg); - return privateDecrypt({ key: keyObject, oaepHash, padding }, encryptedKey); -}; diff --git a/dist/node/esm/runtime/runtime.js b/dist/node/esm/runtime/runtime.js deleted file mode 100644 index 7bf56f60dc..0000000000 --- a/dist/node/esm/runtime/runtime.js +++ /dev/null @@ -1 +0,0 @@ -export default 'node:crypto'; diff --git a/dist/node/esm/runtime/sign.js b/dist/node/esm/runtime/sign.js deleted file mode 100644 index 409b92a2aa..0000000000 --- a/dist/node/esm/runtime/sign.js +++ /dev/null @@ -1,17 +0,0 @@ -import * as crypto from 'node:crypto'; -import { promisify } from 'node:util'; -import nodeDigest from './dsa_digest.js'; -import hmacDigest from './hmac_digest.js'; -import nodeKey from './node_key.js'; -import getSignKey from './get_sign_verify_key.js'; -const oneShotSign = promisify(crypto.sign); -const sign = async (alg, key, data) => { - const k = getSignKey(alg, key, 'sign'); - if (alg.startsWith('HS')) { - const hmac = crypto.createHmac(hmacDigest(alg), k); - hmac.update(data); - return hmac.digest(); - } - return oneShotSign(nodeDigest(alg), data, nodeKey(alg, k)); -}; -export default sign; diff --git a/dist/node/esm/runtime/timing_safe_equal.js b/dist/node/esm/runtime/timing_safe_equal.js deleted file mode 100644 index d5467eeecc..0000000000 --- a/dist/node/esm/runtime/timing_safe_equal.js +++ /dev/null @@ -1,3 +0,0 @@ -import { timingSafeEqual as impl } from 'node:crypto'; -const timingSafeEqual = impl; -export default timingSafeEqual; diff --git a/dist/node/esm/runtime/verify.js b/dist/node/esm/runtime/verify.js deleted file mode 100644 index 526e210c18..0000000000 --- a/dist/node/esm/runtime/verify.js +++ /dev/null @@ -1,29 +0,0 @@ -import * as crypto from 'node:crypto'; -import { promisify } from 'node:util'; -import nodeDigest from './dsa_digest.js'; -import nodeKey from './node_key.js'; -import sign from './sign.js'; -import getVerifyKey from './get_sign_verify_key.js'; -const oneShotVerify = promisify(crypto.verify); -const verify = async (alg, key, signature, data) => { - const k = getVerifyKey(alg, key, 'verify'); - if (alg.startsWith('HS')) { - const expected = await sign(alg, k, data); - const actual = signature; - try { - return crypto.timingSafeEqual(actual, expected); - } - catch { - return false; - } - } - const algorithm = nodeDigest(alg); - const keyInput = nodeKey(alg, k); - try { - return await oneShotVerify(algorithm, data, keyInput, signature); - } - catch { - return false; - } -}; -export default verify; diff --git a/dist/node/esm/runtime/webcrypto.js b/dist/node/esm/runtime/webcrypto.js deleted file mode 100644 index 7a724729ae..0000000000 --- a/dist/node/esm/runtime/webcrypto.js +++ /dev/null @@ -1,5 +0,0 @@ -import * as crypto from 'node:crypto'; -import * as util from 'node:util'; -const webcrypto = crypto.webcrypto; -export default webcrypto; -export const isCryptoKey = (key) => util.types.isCryptoKey(key); diff --git a/dist/node/esm/util/base64url.js b/dist/node/esm/util/base64url.js deleted file mode 100644 index 88ce7556d6..0000000000 --- a/dist/node/esm/util/base64url.js +++ /dev/null @@ -1,3 +0,0 @@ -import * as base64url from '../runtime/base64url.js'; -export const encode = base64url.encode; -export const decode = base64url.decode; diff --git a/dist/node/esm/util/decode_jwt.js b/dist/node/esm/util/decode_jwt.js deleted file mode 100644 index b6f2602f95..0000000000 --- a/dist/node/esm/util/decode_jwt.js +++ /dev/null @@ -1,32 +0,0 @@ -import { decode as base64url } from './base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -import { JWTInvalid } from './errors.js'; -export function decodeJwt(jwt) { - if (typeof jwt !== 'string') - throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); - const { 1: payload, length } = jwt.split('.'); - if (length === 5) - throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); - if (length !== 3) - throw new JWTInvalid('Invalid JWT'); - if (!payload) - throw new JWTInvalid('JWTs must contain a payload'); - let decoded; - try { - decoded = base64url(payload); - } - catch { - throw new JWTInvalid('Failed to base64url decode the payload'); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } - catch { - throw new JWTInvalid('Failed to parse the decoded payload as JSON'); - } - if (!isObject(result)) - throw new JWTInvalid('Invalid JWT Claims Set'); - return result; -} diff --git a/dist/node/esm/util/decode_protected_header.js b/dist/node/esm/util/decode_protected_header.js deleted file mode 100644 index 04be31d8f2..0000000000 --- a/dist/node/esm/util/decode_protected_header.js +++ /dev/null @@ -1,34 +0,0 @@ -import { decode as base64url } from './base64url.js'; -import { decoder } from '../lib/buffer_utils.js'; -import isObject from '../lib/is_object.js'; -export function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === 'string') { - const parts = token.split('.'); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } - else if (typeof token === 'object' && token) { - if ('protected' in token) { - protectedB64u = token.protected; - } - else { - throw new TypeError('Token does not contain a Protected Header'); - } - } - try { - if (typeof protectedB64u !== 'string' || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(base64url(protectedB64u))); - if (!isObject(result)) { - throw new Error(); - } - return result; - } - catch { - throw new TypeError('Invalid Token or Protected Header formatting'); - } -} diff --git a/dist/node/esm/util/errors.js b/dist/node/esm/util/errors.js deleted file mode 100644 index 50c5aa02da..0000000000 --- a/dist/node/esm/util/errors.js +++ /dev/null @@ -1,119 +0,0 @@ -export class JOSEError extends Error { - static get code() { - return 'ERR_JOSE_GENERIC'; - } - code = 'ERR_JOSE_GENERIC'; - constructor(message) { - super(message); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -} -export class JWTClaimValidationFailed extends JOSEError { - static get code() { - return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - } - code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -export class JWTExpired extends JOSEError { - static get code() { - return 'ERR_JWT_EXPIRED'; - } - code = 'ERR_JWT_EXPIRED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -} -export class JOSEAlgNotAllowed extends JOSEError { - static get code() { - return 'ERR_JOSE_ALG_NOT_ALLOWED'; - } - code = 'ERR_JOSE_ALG_NOT_ALLOWED'; -} -export class JOSENotSupported extends JOSEError { - static get code() { - return 'ERR_JOSE_NOT_SUPPORTED'; - } - code = 'ERR_JOSE_NOT_SUPPORTED'; -} -export class JWEDecryptionFailed extends JOSEError { - static get code() { - return 'ERR_JWE_DECRYPTION_FAILED'; - } - code = 'ERR_JWE_DECRYPTION_FAILED'; - message = 'decryption operation failed'; -} -export class JWEInvalid extends JOSEError { - static get code() { - return 'ERR_JWE_INVALID'; - } - code = 'ERR_JWE_INVALID'; -} -export class JWSInvalid extends JOSEError { - static get code() { - return 'ERR_JWS_INVALID'; - } - code = 'ERR_JWS_INVALID'; -} -export class JWTInvalid extends JOSEError { - static get code() { - return 'ERR_JWT_INVALID'; - } - code = 'ERR_JWT_INVALID'; -} -export class JWKInvalid extends JOSEError { - static get code() { - return 'ERR_JWK_INVALID'; - } - code = 'ERR_JWK_INVALID'; -} -export class JWKSInvalid extends JOSEError { - static get code() { - return 'ERR_JWKS_INVALID'; - } - code = 'ERR_JWKS_INVALID'; -} -export class JWKSNoMatchingKey extends JOSEError { - static get code() { - return 'ERR_JWKS_NO_MATCHING_KEY'; - } - code = 'ERR_JWKS_NO_MATCHING_KEY'; - message = 'no applicable key found in the JSON Web Key Set'; -} -export class JWKSMultipleMatchingKeys extends JOSEError { - [Symbol.asyncIterator]; - static get code() { - return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - } - code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - message = 'multiple matching keys found in the JSON Web Key Set'; -} -export class JWKSTimeout extends JOSEError { - static get code() { - return 'ERR_JWKS_TIMEOUT'; - } - code = 'ERR_JWKS_TIMEOUT'; - message = 'request timed out'; -} -export class JWSSignatureVerificationFailed extends JOSEError { - static get code() { - return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - } - code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - message = 'signature verification failed'; -} diff --git a/dist/node/esm/util/runtime.js b/dist/node/esm/util/runtime.js deleted file mode 100644 index 2a4718b909..0000000000 --- a/dist/node/esm/util/runtime.js +++ /dev/null @@ -1,2 +0,0 @@ -import value from '../runtime/runtime.js'; -export default value; diff --git a/dist/types/index.d.ts b/dist/types/index.d.ts deleted file mode 100644 index 9ea30a9b2d..0000000000 --- a/dist/types/index.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -export { compactDecrypt } from './jwe/compact/decrypt'; -export type { CompactDecryptGetKey } from './jwe/compact/decrypt'; -export { flattenedDecrypt } from './jwe/flattened/decrypt'; -export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt'; -export { generalDecrypt } from './jwe/general/decrypt'; -export type { GeneralDecryptGetKey } from './jwe/general/decrypt'; -export { GeneralEncrypt } from './jwe/general/encrypt'; -export type { Recipient } from './jwe/general/encrypt'; -export { compactVerify } from './jws/compact/verify'; -export type { CompactVerifyGetKey } from './jws/compact/verify'; -export { flattenedVerify } from './jws/flattened/verify'; -export type { FlattenedVerifyGetKey } from './jws/flattened/verify'; -export { generalVerify } from './jws/general/verify'; -export type { GeneralVerifyGetKey } from './jws/general/verify'; -export { jwtVerify } from './jwt/verify'; -export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify'; -export { jwtDecrypt } from './jwt/decrypt'; -export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt'; -export type { ProduceJWT } from './jwt/produce'; -export { CompactEncrypt } from './jwe/compact/encrypt'; -export { FlattenedEncrypt } from './jwe/flattened/encrypt'; -export { CompactSign } from './jws/compact/sign'; -export { FlattenedSign } from './jws/flattened/sign'; -export { GeneralSign } from './jws/general/sign'; -export type { Signature } from './jws/general/sign'; -export { SignJWT } from './jwt/sign'; -export { EncryptJWT } from './jwt/encrypt'; -export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint'; -export { EmbeddedJWK } from './jwk/embedded'; -export { createLocalJWKSet } from './jwks/local'; -export { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote'; -export type { RemoteJWKSetOptions, JWKSCacheInput, ExportedJWKSCache } from './jwks/remote'; -export { UnsecuredJWT } from './jwt/unsecured'; -export type { UnsecuredResult } from './jwt/unsecured'; -export { exportPKCS8, exportSPKI, exportJWK } from './key/export'; -export { importSPKI, importPKCS8, importX509, importJWK } from './key/import'; -export type { PEMImportOptions } from './key/import'; -export { decodeProtectedHeader } from './util/decode_protected_header'; -export { decodeJwt } from './util/decode_jwt'; -export type { ProtectedHeaderParameters } from './util/decode_protected_header'; -export * as errors from './util/errors'; -export { generateKeyPair } from './key/generate_key_pair'; -export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair'; -export { generateSecret } from './key/generate_secret'; -export type { GenerateSecretOptions } from './key/generate_secret'; -export * as base64url from './util/base64url'; -export type { KeyLike, JWK, JWKParameters, JWK_OKP_Public, JWK_OKP_Private, JWK_EC_Public, JWK_EC_Private, JWK_RSA_Public, JWK_RSA_Private, JWK_oct, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, CryptoRuntime, GetKeyFunction, } from './types'; -export { default as cryptoRuntime } from './util/runtime'; diff --git a/dist/types/jwe/compact/decrypt.d.ts b/dist/types/jwe/compact/decrypt.d.ts deleted file mode 100644 index ee900731cc..0000000000 --- a/dist/types/jwe/compact/decrypt.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey } from '../../types'; -/** - * Interface for Compact JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface CompactDecryptGetKey extends GetKeyFunction { -} -/** - * Decrypts a Compact JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/compact/decrypt'`. - * - * @param jwe Compact JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function compactDecrypt(jwe: string | Uint8Array, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; -/** - * @param jwe Compact JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function compactDecrypt(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/dist/types/jwe/compact/encrypt.d.ts b/dist/types/jwe/compact/encrypt.d.ts deleted file mode 100644 index b9b63c2395..0000000000 --- a/dist/types/jwe/compact/encrypt.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { KeyLike, JWEKeyManagementHeaderParameters, CompactJWEHeaderParameters, EncryptOptions } from '../../types'; -/** - * The CompactEncrypt class is used to build and encrypt Compact JWE strings. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/compact/encrypt'`. - * - */ -export declare class CompactEncrypt { - private _flattened; - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array); - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this; - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this; - /** - * Sets the JWE Protected Header on the CompactEncrypt object. - * - * @param protectedHeader JWE Protected Header object. - */ - setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; - /** - * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. - * You do not need to invoke this method, it is only really intended for test and vector - * validation purposes. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; - /** - * Encrypts and resolves the value of the Compact JWE string. - * - * @param key Public Key or Secret to encrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; -} diff --git a/dist/types/jwe/flattened/decrypt.d.ts b/dist/types/jwe/flattened/decrypt.d.ts deleted file mode 100644 index eb31c459b7..0000000000 --- a/dist/types/jwe/flattened/decrypt.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey } from '../../types'; -/** - * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface FlattenedDecryptGetKey extends GetKeyFunction { -} -/** - * Decrypts a Flattened JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/flattened/decrypt'`. - * - * @param jwe Flattened JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function flattenedDecrypt(jwe: FlattenedJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; -/** - * @param jwe Flattened JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function flattenedDecrypt(jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/dist/types/jwe/flattened/encrypt.d.ts b/dist/types/jwe/flattened/encrypt.d.ts deleted file mode 100644 index 291f5ed4c0..0000000000 --- a/dist/types/jwe/flattened/encrypt.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type { KeyLike, FlattenedJWE, JWEHeaderParameters, JWEKeyManagementHeaderParameters, EncryptOptions } from '../../types'; -/** - * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/flattened/encrypt'`. - * - */ -export declare class FlattenedEncrypt { - private _plaintext; - private _protectedHeader; - private _sharedUnprotectedHeader; - private _unprotectedHeader; - private _aad; - private _cek; - private _iv; - private _keyManagementParameters; - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array); - /** - * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is - * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or - * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed - * and missing. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; - /** - * Sets the JWE Protected Header on the FlattenedEncrypt object. - * - * @param protectedHeader JWE Protected Header. - */ - setProtectedHeader(protectedHeader: JWEHeaderParameters): this; - /** - * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. - * - * @param sharedUnprotectedHeader JWE Shared Unprotected Header. - */ - setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; - /** - * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. - * - * @param unprotectedHeader JWE Per-Recipient Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): this; - /** - * Sets the Additional Authenticated Data on the FlattenedEncrypt object. - * - * @param aad Additional Authenticated Data. - */ - setAdditionalAuthenticatedData(aad: Uint8Array): this; - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this; - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this; - /** - * Encrypts and resolves the value of the Flattened JWE object. - * - * @param key Public Key or Secret to encrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; -} diff --git a/dist/types/jwe/general/decrypt.d.ts b/dist/types/jwe/general/decrypt.d.ts deleted file mode 100644 index d184141ca6..0000000000 --- a/dist/types/jwe/general/decrypt.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey } from '../../types'; -/** - * Interface for General JWE Decryption dynamic key resolution. No token components have been - * verified at the time of this function call. - */ -export interface GeneralDecryptGetKey extends GetKeyFunction { -} -/** - * Decrypts a General JWE. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwe/general/decrypt'`. - * - * @param jwe General JWE. - * @param key Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function generalDecrypt(jwe: GeneralJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; -/** - * @param jwe General JWE. - * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Decryption options. - */ -export declare function generalDecrypt(jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions): Promise>; diff --git a/dist/types/jwe/general/encrypt.d.ts b/dist/types/jwe/general/encrypt.d.ts deleted file mode 100644 index 9324bbefcb..0000000000 --- a/dist/types/jwe/general/encrypt.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption } from '../../types'; -export interface Recipient { - /** - * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. - * - * @param unprotectedHeader JWE Per-Recipient Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient; - /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ - addRecipient(...args: Parameters): Recipient; - /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ - encrypt(...args: Parameters): Promise; - /** Returns the enclosing GeneralEncrypt */ - done(): GeneralEncrypt; -} -/** - * The GeneralEncrypt class is used to build and encrypt General JWE objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwe/general/encrypt'`. - * - */ -export declare class GeneralEncrypt { - private _plaintext; - private _recipients; - private _protectedHeader; - private _unprotectedHeader; - private _aad; - /** @param plaintext Binary representation of the plaintext to encrypt. */ - constructor(plaintext: Uint8Array); - /** - * Adds an additional recipient for the General JWE object. - * - * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. - * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient; - /** - * Sets the JWE Protected Header on the GeneralEncrypt object. - * - * @param protectedHeader JWE Protected Header object. - */ - setProtectedHeader(protectedHeader: JWEHeaderParameters): this; - /** - * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. - * - * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. - */ - setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; - /** - * Sets the Additional Authenticated Data on the GeneralEncrypt object. - * - * @param aad Additional Authenticated Data. - */ - setAdditionalAuthenticatedData(aad: Uint8Array): this; - /** Encrypts and resolves the value of the General JWE object. */ - encrypt(): Promise; -} diff --git a/dist/types/jwk/embedded.d.ts b/dist/types/jwk/embedded.d.ts deleted file mode 100644 index b5c686b304..0000000000 --- a/dist/types/jwk/embedded.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { KeyLike, FlattenedJWSInput, JWSHeaderParameters } from '../types'; -/** - * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify - * operations whenever you need to opt-in to verify signatures with a public key embedded in the - * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify - * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/embedded'`. - * - */ -export declare function EmbeddedJWK(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise; diff --git a/dist/types/jwk/thumbprint.d.ts b/dist/types/jwk/thumbprint.d.ts deleted file mode 100644 index c094cbdf66..0000000000 --- a/dist/types/jwk/thumbprint.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { JWK } from '../types'; -/** - * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/thumbprint'`. - * - * @param jwk JSON Web Key. - * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is - * "sha256". - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638} - */ -export declare function calculateJwkThumbprint(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; -/** - * Calculates a JSON Web Key (JWK) Thumbprint URI - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwk/thumbprint'`. - * - * @param jwk JSON Web Key. - * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is - * "sha256". - * - * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278} - */ -export declare function calculateJwkThumbprintUri(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; diff --git a/dist/types/jwks/local.d.ts b/dist/types/jwks/local.d.ts deleted file mode 100644 index 7786871faf..0000000000 --- a/dist/types/jwks/local.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { KeyLike, JWSHeaderParameters, JSONWebKeySet, FlattenedJWSInput } from '../types'; -/** - * Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored, - * or otherwise available, JSON Web Key Set. - * - * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), - * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if - * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key - * Operations) Parameters (if they are present on the JWK). - * - * Only a single public key must match the selection process. As shown in the example below when - * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt - * verification in an iterative manner. - * - * Note: The function's purpose is to resolve public keys used for verifying signatures and will not - * work for public encryption keys. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwks/local'`. - * - * @param jwks JSON Web Key Set formatted object. - */ -export declare function createLocalJWKSet(jwks: JSONWebKeySet): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise; diff --git a/dist/types/jwks/remote.d.ts b/dist/types/jwks/remote.d.ts deleted file mode 100644 index 155666f2b1..0000000000 --- a/dist/types/jwks/remote.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput, JSONWebKeySet } from '../types'; -/** - * DANGER ZONE - This option has security implications that must be understood, assessed for - * applicability, and accepted before use. It is critical that the JSON Web Key Set cache only be - * writable by your own code. - * - * This option is intended for cloud computing runtimes that cannot keep an in memory cache between - * their code's invocations. Use in runtimes where an in memory cache between requests is available - * is not desirable. - * - * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the passed in - * object to: - * - * - Serve as an initial value for the JSON Web Key Set that the module would otherwise need to - * trigger an HTTP request for - * - Have the JSON Web Key Set the function optionally ended up triggering an HTTP request for - * assigned to it as properties - * - * The intended use pattern is: - * - * - Before verifying with {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} you pull the - * previously cached object from a low-latency key-value store offered by the cloud computing - * runtime it is executed on; - * - Default to an empty object `{}` instead when there's no previously cached value; - * - Pass it in as {@link RemoteJWKSetOptions[jwksCache]}; - * - Afterwards, update the key-value storage if the {@link ExportedJWKSCache.uat `uat`} property of - * the object has changed. - * - * import * as jose from 'jose' - * - * // Prerequisites - * let url!: URL - * let jwt!: string - * - * // Load JSON Web Key Set cache - * const jwksCache: jose.JWKSCacheInput = (await getPreviouslyCachedJWKS()) || {} - * const { uat } = jwksCache - * - * const JWKS = jose.createRemoteJWKSet(url, { - * [jose.jwksCache]: jwksCache, - * }) - * - * // Use JSON Web Key Set cache - * await jose.jwtVerify(jwt, JWKS) - * - * if (uat !== jwksCache.uat) { - * // Update JSON Web Key Set cache - * await storeNewJWKScache(jwksCache) - * } - * ``` - */ -export declare const jwksCache: unique symbol; -/** Options for the remote JSON Web Key Set. */ -export interface RemoteJWKSetOptions { - /** - * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and - * the verification will fail. Default is 5000 (5 seconds). - */ - timeoutDuration?: number; - /** - * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous - * successful fetch. Default is 30000 (30 seconds). - */ - cooldownDuration?: number; - /** - * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 - * minutes). - */ - cacheMaxAge?: number | typeof Infinity; - /** - * An instance of {@link https://nodejs.org/api/http.html#class-httpagent http.Agent} or - * {@link https://nodejs.org/api/https.html#class-httpsagent https.Agent} to pass to the - * {@link https://nodejs.org/api/http.html#httpgetoptions-callback http.get} or - * {@link https://nodejs.org/api/https.html#httpsgetoptions-callback https.get} method's options. - * Use when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when - * used outside of Node.js runtime. - */ - agent?: any; - /** - * Headers to be sent with the HTTP request. Default is that `User-Agent: jose/v${version}` header - * is added unless the runtime is a browser in which adding an explicit headers fetch - * configuration would cause an unnecessary CORS preflight request. - */ - headers?: Record; - /** See {@link jwksCache}. */ - [jwksCache]?: JWKSCacheInput; -} -export interface ExportedJWKSCache { - jwks: JSONWebKeySet; - uat: number; -} -export type JWKSCacheInput = ExportedJWKSCache | Record; -/** - * Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a - * remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC - * jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as - * frequently as the `cooldownDuration` option allows to prevent abuse. - * - * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type), - * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if - * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key - * Operations) Parameters (if they are present on the JWK). - * - * Only a single public key must match the selection process. As shown in the example below when - * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt - * verification in an iterative manner. - * - * Note: The function's purpose is to resolve public keys used for verifying signatures and will not - * work for public encryption keys. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwks/remote'`. - * - * @param url URL to fetch the JSON Web Key Set from. - * @param options Options for the remote JSON Web Key Set. - */ -export declare function createRemoteJWKSet(url: URL, options?: RemoteJWKSetOptions): { - (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise; - /** @ignore */ - coolingDown: boolean; - /** @ignore */ - fresh: boolean; - /** @ignore */ - reloading: boolean; - /** @ignore */ - reload: () => Promise; - /** @ignore */ - jwks: () => JSONWebKeySet | undefined; -}; -/** - * @ignore - * - * @deprecated Use {@link jwksCache}. - */ -export declare const experimental_jwksCache: symbol; diff --git a/dist/types/jws/compact/sign.d.ts b/dist/types/jws/compact/sign.d.ts deleted file mode 100644 index 48f2bbeb8b..0000000000 --- a/dist/types/jws/compact/sign.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { JWK, CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types'; -/** - * The CompactSign class is used to build and sign Compact JWS strings. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/compact/sign'`. - * - */ -export declare class CompactSign { - private _flattened; - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array); - /** - * Sets the JWS Protected Header on the Sign object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: CompactJWSHeaderParameters): this; - /** - * Signs and resolves the value of the Compact JWS string. - * - * @param key Private Key or Secret to sign the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise; -} diff --git a/dist/types/jws/compact/verify.d.ts b/dist/types/jws/compact/verify.d.ts deleted file mode 100644 index d9593fba6f..0000000000 --- a/dist/types/jws/compact/verify.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { JWK, CompactVerifyResult, FlattenedJWSInput, GenericGetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; -/** - * Interface for Compact JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface CompactVerifyGetKey extends GenericGetKeyFunction { -} -/** - * Verifies the signature and format of and afterwards decodes the Compact JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/compact/verify'`. - * - * @param jws Compact JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function compactVerify(jws: string | Uint8Array, key: KeyLike | Uint8Array | JWK, options?: VerifyOptions): Promise; -/** - * @param jws Compact JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function compactVerify(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/dist/types/jws/flattened/sign.d.ts b/dist/types/jws/flattened/sign.d.ts deleted file mode 100644 index 7c1a434a64..0000000000 --- a/dist/types/jws/flattened/sign.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { JWK, KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types'; -/** - * The FlattenedSign class is used to build and sign Flattened JWS objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/flattened/sign'`. - * - */ -export declare class FlattenedSign { - private _payload; - private _protectedHeader; - private _unprotectedHeader; - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array); - /** - * Sets the JWS Protected Header on the FlattenedSign object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: JWSHeaderParameters): this; - /** - * Sets the JWS Unprotected Header on the FlattenedSign object. - * - * @param unprotectedHeader JWS Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): this; - /** - * Signs and resolves the value of the Flattened JWS object. - * - * @param key Private Key or Secret to sign the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise; -} diff --git a/dist/types/jws/flattened/verify.d.ts b/dist/types/jws/flattened/verify.d.ts deleted file mode 100644 index 2f9cfdb649..0000000000 --- a/dist/types/jws/flattened/verify.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { JWK, FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GenericGetKeyFunction, ResolvedKey } from '../../types'; -/** - * Interface for Flattened JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface FlattenedVerifyGetKey extends GenericGetKeyFunction { -} -/** - * Verifies the signature and format of and afterwards decodes the Flattened JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/flattened/verify'`. - * - * @param jws Flattened JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function flattenedVerify(jws: FlattenedJWSInput, key: KeyLike | Uint8Array | JWK, options?: VerifyOptions): Promise; -/** - * @param jws Flattened JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function flattenedVerify(jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/dist/types/jws/general/sign.d.ts b/dist/types/jws/general/sign.d.ts deleted file mode 100644 index 672d9a0a9e..0000000000 --- a/dist/types/jws/general/sign.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { JWK, KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types'; -export interface Signature { - /** - * Sets the JWS Protected Header on the Signature object. - * - * @param protectedHeader JWS Protected Header. - */ - setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature; - /** - * Sets the JWS Unprotected Header on the Signature object. - * - * @param unprotectedHeader JWS Unprotected Header. - */ - setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature; - /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ - addSignature(...args: Parameters): Signature; - /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ - sign(...args: Parameters): Promise; - /** Returns the enclosing GeneralSign */ - done(): GeneralSign; -} -/** - * The GeneralSign class is used to build and sign General JWS objects. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jws/general/sign'`. - * - */ -export declare class GeneralSign { - private _payload; - private _signatures; - /** @param payload Binary representation of the payload to sign. */ - constructor(payload: Uint8Array); - /** - * Adds an additional signature for the General JWS object. - * - * @param key Private Key or Secret to sign the individual JWS signature with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Sign options. - */ - addSignature(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Signature; - /** Signs and resolves the value of the General JWS object. */ - sign(): Promise; -} diff --git a/dist/types/jws/general/verify.d.ts b/dist/types/jws/general/verify.d.ts deleted file mode 100644 index fa635312c8..0000000000 --- a/dist/types/jws/general/verify.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { JWK, GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GenericGetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; -/** - * Interface for General JWS Verification dynamic key resolution. No token components have been - * verified at the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface GeneralVerifyGetKey extends GenericGetKeyFunction { -} -/** - * Verifies the signature and format of and afterwards decodes the General JWS. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jws/general/verify'`. - * - * @param jws General JWS. - * @param key Key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function generalVerify(jws: GeneralJWSInput, key: KeyLike | Uint8Array | JWK, options?: VerifyOptions): Promise; -/** - * @param jws General JWS. - * @param getKey Function resolving a key to verify the JWS with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWS Verify options. - */ -export declare function generalVerify(jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions): Promise>; diff --git a/dist/types/jwt/decrypt.d.ts b/dist/types/jwt/decrypt.d.ts deleted file mode 100644 index 30c3390846..0000000000 --- a/dist/types/jwt/decrypt.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { JWTPayload, KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey } from '../types'; -/** Combination of JWE Decryption options and JWT Claims Set verification options. */ -export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions { -} -/** - * Interface for JWT Decryption dynamic key resolution. No token components have been verified at - * the time of this function call. - */ -export interface JWTDecryptGetKey extends GetKeyFunction { -} -/** - * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT - * Claims Set. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/decrypt'`. - * - * @param jwt JSON Web Token value (encoded as JWE). - * @param key Private Key or Secret to decrypt and verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export declare function jwtDecrypt(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions): Promise>; -/** - * @param jwt JSON Web Token value (encoded as JWE). - * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise & ResolvedKey>; diff --git a/dist/types/jwt/encrypt.d.ts b/dist/types/jwt/encrypt.d.ts deleted file mode 100644 index 345d11c6b6..0000000000 --- a/dist/types/jwt/encrypt.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { EncryptOptions, CompactJWEHeaderParameters, JWEKeyManagementHeaderParameters, KeyLike } from '../types'; -import { ProduceJWT } from './produce'; -/** - * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/encrypt'`. - * - */ -export declare class EncryptJWT extends ProduceJWT { - private _cek; - private _iv; - private _keyManagementParameters; - private _protectedHeader; - private _replicateIssuerAsHeader; - private _replicateSubjectAsHeader; - private _replicateAudienceAsHeader; - /** - * Sets the JWE Protected Header on the EncryptJWT object. - * - * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" - * (JWE Encryption Algorithm) properties. - */ - setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; - /** - * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is - * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or - * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed - * and missing. - * - * @param parameters JWE Key Management parameters. - */ - setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; - /** - * Sets a content encryption key to use, by default a random suitable one is generated for the JWE - * enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param cek JWE Content Encryption Key. - */ - setContentEncryptionKey(cek: Uint8Array): this; - /** - * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable - * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. - * - * @deprecated You should not use this method. It is only really intended for test and vector - * validation purposes. - * - * @param iv JWE Initialization Vector. - */ - setInitializationVector(iv: Uint8Array): this; - /** - * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateIssuerAsHeader(): this; - /** - * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateSubjectAsHeader(): this; - /** - * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3} - */ - replicateAudienceAsHeader(): this; - /** - * Encrypts and returns the JWT. - * - * @param key Public Key or Secret to encrypt the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. - * @param options JWE Encryption options. - */ - encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; -} diff --git a/dist/types/jwt/produce.d.ts b/dist/types/jwt/produce.d.ts deleted file mode 100644 index 16c2b1bd8a..0000000000 --- a/dist/types/jwt/produce.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { JWTPayload } from '../types'; -/** Generic class for JWT producing. */ -export declare class ProduceJWT { - protected _payload: JWTPayload; - /** @param payload The JWT Claims Set object. Defaults to an empty object. */ - constructor(payload?: JWTPayload); - /** - * Set the "iss" (Issuer) Claim. - * - * @param issuer "Issuer" Claim value to set on the JWT Claims Set. - */ - setIssuer(issuer: string): this; - /** - * Set the "sub" (Subject) Claim. - * - * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. - */ - setSubject(subject: string): this; - /** - * Set the "aud" (Audience) Claim. - * - * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. - */ - setAudience(audience: string | string[]): this; - /** - * Set the "jti" (JWT ID) Claim. - * - * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. - */ - setJti(jwtId: string): this; - /** - * Set the "nbf" (Not Before) Claim. - * - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. - */ - setNotBefore(input: number | string | Date): this; - /** - * Set the "exp" (Expiration Time) Claim. - * - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. - */ - setExpirationTime(input: number | string | Date): this; - /** - * Set the "iat" (Issued At) Claim. - * - * - If no argument is used the current unix timestamp is used as the claim. - * - If a `number` is passed as an argument it is used as the claim directly. - * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the - * claim. - * - If a `string` is passed as an argument it is resolved to a time span, and then added to the - * current unix timestamp and used as the claim. - * - * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1 - * day". - * - * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", - * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", - * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an - * alias for a year. - * - * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets - * subtracted from the current unix timestamp. A "from now" suffix can also be used for - * readability when adding to the current unix timestamp. - * - * @param input "iat" (Expiration Time) Claim value to set on the JWT Claims Set. - */ - setIssuedAt(input?: number | string | Date): this; -} diff --git a/dist/types/jwt/sign.d.ts b/dist/types/jwt/sign.d.ts deleted file mode 100644 index 3096b0ff4e..0000000000 --- a/dist/types/jwt/sign.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { JWK, JWTHeaderParameters, KeyLike, SignOptions } from '../types'; -import { ProduceJWT } from './produce'; -/** - * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/sign'`. - * - */ -export declare class SignJWT extends ProduceJWT { - private _protectedHeader; - /** - * Sets the JWS Protected Header on the SignJWT object. - * - * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. - */ - setProtectedHeader(protectedHeader: JWTHeaderParameters): this; - /** - * Signs and returns the JWT. - * - * @param key Private Key or Secret to sign the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Sign options. - */ - sign(key: KeyLike | Uint8Array | JWK, options?: SignOptions): Promise; -} diff --git a/dist/types/jwt/unsecured.d.ts b/dist/types/jwt/unsecured.d.ts deleted file mode 100644 index 06730ab03d..0000000000 --- a/dist/types/jwt/unsecured.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types'; -import { ProduceJWT } from './produce'; -export interface UnsecuredResult { - payload: PayloadType & JWTPayload; - header: JWSHeaderParameters; -} -/** - * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. - * - * This class is exported (as a named export) from the main `'jose'` module entry point as well as - * from its subpath export `'jose/jwt/unsecured'`. - * - */ -export declare class UnsecuredJWT extends ProduceJWT { - /** Encodes the Unsecured JWT. */ - encode(): string; - /** - * Decodes an unsecured JWT. - * - * @param jwt Unsecured JWT to decode the payload of. - * @param options JWT Claims Set validation options. - */ - static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult; -} diff --git a/dist/types/jwt/verify.d.ts b/dist/types/jwt/verify.d.ts deleted file mode 100644 index 858e340bc2..0000000000 --- a/dist/types/jwt/verify.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { JWK, JWTPayload, KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GenericGetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey } from '../types'; -/** Combination of JWS Verification options and JWT Claims Set verification options. */ -export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions { -} -/** - * Interface for JWT Verification dynamic key resolution. No token components have been verified at - * the time of this function call. - * - * @see [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. - */ -export interface JWTVerifyGetKey extends GenericGetKeyFunction { -} -/** - * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the - * JWT Claims Set. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/verify'`. - * - * @param jwt JSON Web Token value (encoded as JWS). - * @param key Key to verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export declare function jwtVerify(jwt: string | Uint8Array, key: KeyLike | Uint8Array | JWK, options?: JWTVerifyOptions): Promise>; -/** - * @param jwt JSON Web Token value (encoded as JWS). - * @param getKey Function resolving a key to verify the JWT with. See - * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}. - * @param options JWT Decryption and JWT Claims Set validation options. - */ -export declare function jwtVerify(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise & ResolvedKey>; diff --git a/dist/types/key/export.d.ts b/dist/types/key/export.d.ts deleted file mode 100644 index 50f0f70c65..0000000000 --- a/dist/types/key/export.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { JWK, KeyLike } from '../types'; -/** - * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded - * SPKI string format. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to transform to a PEM-encoded SPKI string format. - */ -export declare function exportSPKI(key: KeyLike): Promise; -/** - * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded - * PKCS8 string format. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to transform to a PEM-encoded PKCS8 string format. - */ -export declare function exportPKCS8(key: KeyLike): Promise; -/** - * Exports a runtime-specific key representation (KeyLike) to a JWK. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/export'`. - * - * @param key Key representation to export as JWK. - */ -export declare function exportJWK(key: KeyLike | Uint8Array): Promise; diff --git a/dist/types/key/generate_key_pair.d.ts b/dist/types/key/generate_key_pair.d.ts deleted file mode 100644 index b07e6d0701..0000000000 --- a/dist/types/key/generate_key_pair.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { KeyLike } from '../types'; -export interface GenerateKeyPairResult { - /** The generated Private Key. */ - privateKey: KeyLikeType; - /** Public Key corresponding to the generated Private Key. */ - publicKey: KeyLikeType; -} -export interface GenerateKeyPairOptions { - /** - * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be - * both supported on the runtime as well as applicable for the given JWA algorithm identifier. - */ - crv?: string; - /** - * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). - * JOSE requires 2048 bits or larger. Default is 2048. - */ - modulusLength?: number; - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} - * `extractable` argument. Default is false. - * - */ - extractable?: boolean; -} -/** - * Generates a private and a public key for a given JWA algorithm identifier. This can only generate - * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. - * - * Note: Under Web Crypto API runtime the `privateKey` is generated with `extractable` set to - * `false` by default. See {@link GenerateKeyPairOptions.extractable} to generate an extractable - * `privateKey`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/generate/keypair'`. - * - * @param alg JWA Algorithm Identifier to be used with the generated key pair. - * @param options Additional options passed down to the key pair generation. - */ -export declare function generateKeyPair(alg: string, options?: GenerateKeyPairOptions): Promise>; diff --git a/dist/types/key/generate_secret.d.ts b/dist/types/key/generate_secret.d.ts deleted file mode 100644 index 8e88159028..0000000000 --- a/dist/types/key/generate_secret.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { KeyLike } from '../types'; -export interface GenerateSecretOptions { - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey SubtleCrypto.generateKey()} - * `extractable` argument. Default is false. - */ - extractable?: boolean; -} -/** - * Generates a symmetric secret key for a given JWA algorithm identifier. - * - * Note: Under Web Crypto API runtime the secret key is generated with `extractable` set to `false` - * by default. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/generate/secret'`. - * - * @param alg JWA Algorithm Identifier to be used with the generated secret. - * @param options Additional options passed down to the secret generation. - */ -export declare function generateSecret(alg: string, options?: GenerateSecretOptions): Promise; diff --git a/dist/types/key/import.d.ts b/dist/types/key/import.d.ts deleted file mode 100644 index e2a06b8f98..0000000000 --- a/dist/types/key/import.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { JWK, KeyLike } from '../types'; -export interface PEMImportOptions { - /** - * (Only effective in Web Crypto API runtimes) The value to use as - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey()} - * `extractable` argument. Default is false. - */ - extractable?: boolean; -} -/** - * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or - * CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param spki PEM-encoded SPKI string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export declare function importSPKI(spki: string, alg: string, options?: PEMImportOptions): Promise; -/** - * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation - * (KeyObject or CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param x509 X.509 certificate string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export declare function importX509(x509: string, alg: string, options?: PEMImportOptions): Promise; -/** - * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject - * or CryptoKey). - * - * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in - * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption - * (1.2.840.113549.1.1.1) instead for all RSA algorithms. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param pkcs8 PEM-encoded PKCS#8 string - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key, its presence is only enforced in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export declare function importPKCS8(pkcs8: string, alg: string, options?: PEMImportOptions): Promise; -/** - * Imports a JWK to a runtime-specific key representation (KeyLike). Either the JWK "alg" - * (Algorithm) Parameter, or the optional "alg" argument, must be present. - * - * Note: When the runtime is using {@link https://w3c.github.io/webcrypto/ Web Cryptography API} the - * jwk parameters "use", "key_ops", and "ext" are also used in the resulting `CryptoKey`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/key/import'`. - * - * @param jwk JSON Web Key. - * @param alg (Only effective in Web Crypto API runtimes) JSON Web Algorithm identifier to be used - * with the imported key. Default is the "alg" property on the JWK, its presence is only enforced - * in Web Crypto API runtimes. See - * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}. - */ -export declare function importJWK(jwk: JWK, alg?: string): Promise; diff --git a/dist/types/types.d.ts b/dist/types/types.d.ts deleted file mode 100644 index 7c85b17481..0000000000 --- a/dist/types/types.d.ts +++ /dev/null @@ -1,716 +0,0 @@ -/** - * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are - * instances of {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} and - * additionally {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} in Node.js - * runtime. - * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array Uint8Array} - * instances are also accepted as symmetric secret representation only. - * - * [Key Import Functions](../modules/key_import.md) can be used to import PEM, or JWK formatted - * asymmetric keys and certificates to these runtime-specific representations. - * - * In Node.js the {@link https://nodejs.org/api/buffer.html#buffer Buffer} class is a subclass of - * Uint8Array and so Buffer can be provided for symmetric secrets as well. - * - * {@link https://nodejs.org/api/crypto.html#class-keyobject KeyObject} is a representation of a - * key/secret available in the Node.js runtime. In addition to the import functions of this library - * you may use the runtime APIs - * {@link https://nodejs.org/api/crypto.html#cryptocreatepublickeykey crypto.createPublicKey}, - * {@link https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey crypto.createPrivateKey}, and - * {@link https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding crypto.createSecretKey} - * to obtain a `KeyObject` from your existing key material. - * - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey CryptoKey} is a representation - * of a key/secret available in the Browser and Web-interoperable runtimes. In addition to the - * import functions of this library you may use the - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey SubtleCrypto.importKey} - * API to obtain a CryptoKey from your existing key material. - * - */ -export type KeyLike = { type: string } - -/** Generic JSON Web Key Parameters. */ -export interface JWKParameters { - /** JWK "kty" (Key Type) Parameter. */ - kty: string - /** JWK "alg" (Algorithm) Parameter. */ - alg?: string - /** JWK "key_ops" (Key Operations) Parameter. */ - key_ops?: string[] - /** JWK "ext" (Extractable) Parameter. */ - ext?: boolean - /** JWK "use" (Public Key Use) Parameter. */ - use?: string - /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ - x5c?: string[] - /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ - x5t?: string - /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ - 'x5t#S256'?: string - /** JWK "x5u" (X.509 URL) Parameter. */ - x5u?: string - /** JWK "kid" (Key ID) Parameter. */ - kid?: string - - [propName: string]: unknown -} - -/** Convenience interface for Public OKP JSON Web Keys */ -export interface JWK_OKP_Public extends JWKParameters { - /** The Subtype of Key Pair */ - crv: string - /** The public key */ - x: string - - [propName: string]: unknown -} - -/** Convenience interface for Private OKP JSON Web Keys */ -export interface JWK_OKP_Private extends JWK_OKP_Public, JWKParameters { - /** The Private Key */ - d: string - - [propName: string]: unknown -} - -/** Convenience interface for Public EC JSON Web Keys */ -export interface JWK_EC_Public extends JWKParameters { - /** Curve */ - crv: string - /** X Coordinate */ - x: string - /** Y Coordinate */ - y: string - - [propName: string]: unknown -} - -/** Convenience interface for Private EC JSON Web Keys */ -export interface JWK_EC_Private extends JWK_EC_Public, JWKParameters { - /** ECC Private Key */ - d: string - - [propName: string]: unknown -} - -/** Convenience interface for Public RSA JSON Web Keys */ -export interface JWK_RSA_Public extends JWKParameters { - /** Exponent */ - e: string - /** Modulus */ - n: string - - [propName: string]: unknown -} - -/** Convenience interface for Private RSA JSON Web Keys */ -export interface JWK_RSA_Private extends JWK_RSA_Public, JWKParameters { - /** Private Exponent */ - d: string - /** First Factor CRT Exponent */ - dp: string - /** Second Factor CRT Exponent */ - dq: string - /** Other Primes Info. This parameter is not supported. */ - oth?: Array<{ - d?: string - r?: string - t?: string - }> - /** First Prime Factor */ - p: string - /** Second Prime Factor */ - q: string - /** First CRT Coefficient */ - qi: string - - [propName: string]: unknown -} - -/** Convenience interface for oct JSON Web Keys */ -export interface JWK_oct extends JWKParameters { - /** Key Value */ - k: string - - [propName: string]: unknown -} - -/** - * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct" - * key types are supported. - * - * @see {@link JWK_OKP_Public} - * @see {@link JWK_OKP_Private} - * @see {@link JWK_EC_Public} - * @see {@link JWK_EC_Private} - * @see {@link JWK_RSA_Public} - * @see {@link JWK_RSA_Private} - * @see {@link JWK_oct} - */ -export interface JWK extends JWKParameters { - /** - * - (EC) Curve - * - (OKP) The Subtype of Key Pair - */ - crv?: string - /** - * - (Private RSA) Private Exponent - * - (Private EC) ECC Private Key - * - (Private OKP) The Private Key - */ - d?: string - /** (Private RSA) First Factor CRT Exponent */ - dp?: string - /** (Private RSA) Second Factor CRT Exponent */ - dq?: string - /** (RSA) Exponent */ - e?: string - /** (oct) Key Value */ - k?: string - /** (RSA) Modulus */ - n?: string - /** (Private RSA) Other Primes Info. This parameter is not supported. */ - oth?: Array<{ - d?: string - r?: string - t?: string - }> - /** (Private RSA) First Prime Factor */ - p?: string - /** (Private RSA) Second Prime Factor */ - q?: string - /** (Private RSA) First CRT Coefficient */ - qi?: string - /** - * - (EC) X Coordinate - * - (OKP) The public key - */ - x?: string - /** (EC) Y Coordinate */ - y?: string - - [propName: string]: unknown -} - -/** - * @private - * - * @internal - */ -export interface GenericGetKeyFunction { - /** - * Dynamic key resolution function. No token components have been verified at the time of this - * function call. - * - * If you cannot match a key suitable for the token, throw an error instead. - * - * @param protectedHeader JWE or JWS Protected Header. - * @param token The consumed JWE or JWS token. - */ - (protectedHeader: IProtectedHeader, token: IToken): Promise | ReturnKeyTypes -} - -/** - * Generic Interface for consuming operations dynamic key resolution. - * - * @param IProtectedHeader Type definition of the JWE or JWS Protected Header. - * @param IToken Type definition of the consumed JWE or JWS token. - */ -export interface GetKeyFunction - extends GenericGetKeyFunction {} - -/** - * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached - * signature validation. - */ -export interface FlattenedJWSInput { - /** - * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS - * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented - * as an unencoded JSON object, rather than as a string. These Header Parameter values are not - * integrity protected. - */ - header?: JWSHeaderParameters - - /** - * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 - * "b64": false is used the value passed may also be a Uint8Array. - */ - payload: string | Uint8Array - - /** - * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected - * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These - * Header Parameter values are integrity protected. - */ - protected?: string - - /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ - signature: string -} - -/** - * General JWS definition for verify function inputs, allows payload as Uint8Array for detached - * signature validation. - */ -export interface GeneralJWSInput { - /** - * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when - * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is - * used the value passed may also be a Uint8Array. - */ - payload: string | Uint8Array - - /** - * The "signatures" member value MUST be an array of JSON objects. Each object represents a - * signature or MAC over the JWS Payload and the JWS Protected Header. - */ - signatures: Omit[] -} - -/** - * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload - * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. - */ -export interface FlattenedJWS extends Partial { - payload: string - signature: string -} - -/** - * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload - * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used. - */ -export interface GeneralJWS { - payload: string - signatures: Omit[] -} - -export interface JoseHeaderParameters { - /** "kid" (Key ID) Header Parameter. */ - kid?: string - - /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ - x5t?: string - - /** "x5c" (X.509 Certificate Chain) Header Parameter. */ - x5c?: string[] - - /** "x5u" (X.509 URL) Header Parameter. */ - x5u?: string - - /** "jku" (JWK Set URL) Header Parameter. */ - jku?: string - - /** "jwk" (JSON Web Key) Header Parameter. */ - jwk?: Pick - - /** "typ" (Type) Header Parameter. */ - typ?: string - - /** "cty" (Content Type) Header Parameter. */ - cty?: string -} - -/** Recognized JWS Header Parameters, any other Header Members may also be present. */ -export interface JWSHeaderParameters extends JoseHeaderParameters { - /** JWS "alg" (Algorithm) Header Parameter. */ - alg?: string - - /** - * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing - * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}. - */ - b64?: boolean - - /** JWS "crit" (Critical) Header Parameter. */ - crit?: string[] - - /** Any other JWS Header member. */ - [propName: string]: unknown -} - -/** Recognized JWE Key Management-related Header Parameters. */ -export interface JWEKeyManagementHeaderParameters { - apu?: Uint8Array - apv?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - p2c?: number - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - p2s?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - iv?: Uint8Array - /** - * @deprecated You should not use this parameter. It is only really intended for test and vector - * validation purposes. - */ - epk?: KeyLike -} - -/** Flattened JWE definition. */ -export interface FlattenedJWE { - /** - * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD - * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a - * base64url-encoded value to be integrity protected but not encrypted. - */ - aad?: string - - /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ - ciphertext: string - - /** - * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) - * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. - */ - encrypted_key?: string - - /** - * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header - * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. - * This value is represented as an unencoded JSON object, rather than as a string. These Header - * Parameter values are not integrity protected. - */ - header?: JWEHeaderParameters - - /** - * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when - * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. - */ - iv?: string - - /** - * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected - * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These - * Header Parameter values are integrity protected. - */ - protected?: string - - /** - * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when - * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. - */ - tag?: string - - /** - * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header - * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This - * value is represented as an unencoded JSON object, rather than as a string. These Header - * Parameter values are not integrity protected. - */ - unprotected?: JWEHeaderParameters -} - -export interface GeneralJWE extends Omit { - recipients: Pick[] -} - -/** Recognized JWE Header Parameters, any other Header members may also be present. */ -export interface JWEHeaderParameters extends JoseHeaderParameters { - /** JWE "alg" (Algorithm) Header Parameter. */ - alg?: string - - /** JWE "enc" (Encryption Algorithm) Header Parameter. */ - enc?: string - - /** JWE "crit" (Critical) Header Parameter. */ - crit?: string[] - - /** - * JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore. - * - * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed - * data often reveals information about the plaintext. - * - * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs} - */ - zip?: string - - /** Any other JWE Header member. */ - [propName: string]: unknown -} - -/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ -export interface CritOption { - /** - * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value - * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity - * protected, `false` when it's irrelevant. - * - * This makes the "Extension Header Parameter "..." is not recognized" error go away. - * - * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" - * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically - * correct when provided and that it is optionally integrity protected. It will not process the - * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the - * Header Parameter was present and process it according to the profile's validation steps after - * the operation succeeds. - * - * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other - * registered Header Parameters that need this kind of default built-in treatment are currently - * available. - */ - crit?: { - [propName: string]: boolean - } -} - -/** JWE Decryption options. */ -export interface DecryptOptions extends CritOption { - /** - * A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg" - * (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for - * all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option. - */ - keyManagementAlgorithms?: string[] - - /** - * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all - * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. - */ - contentEncryptionAlgorithms?: string[] - - /** - * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter - * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default - * this value is set to 10000. - */ - maxPBES2Count?: number -} - -/** JWE Encryption options. */ -export interface EncryptOptions extends CritOption {} - -/** JWT Claims Set verification options. */ -export interface JWTClaimVerificationOptions { - /** - * Expected JWT "aud" (Audience) Claim value(s). - * - * This option makes the JWT "aud" (Audience) Claim presence required. - */ - audience?: string | string[] - - /** - * Expected clock tolerance - * - * - In seconds when number (e.g. 5) - * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). - */ - clockTolerance?: string | number - - /** - * Expected JWT "iss" (Issuer) Claim value(s). - * - * This option makes the JWT "iss" (Issuer) Claim presence required. - */ - issuer?: string | string[] - - /** - * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. - * - * - In seconds when number (e.g. 5) - * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). - * - * This option makes the JWT "iat" (Issued At) Claim presence required. - */ - maxTokenAge?: string | number - - /** - * Expected JWT "sub" (Subject) Claim value. - * - * This option makes the JWT "sub" (Subject) Claim presence required. - */ - subject?: string - - /** - * Expected JWT "typ" (Type) Header Parameter value. - * - * This option makes the JWT "typ" (Type) Header Parameter presence required. - */ - typ?: string - - /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ - currentDate?: Date - - /** - * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if - * the {@link JWTClaimVerificationOptions.issuer `issuer` option} is set, then JWT "iss" (Issuer) - * Claim must be present; if the {@link JWTClaimVerificationOptions.audience `audience` option} is - * set, then JWT "aud" (Audience) Claim must be present; if the - * {@link JWTClaimVerificationOptions.subject `subject` option} is set, then JWT "sub" (Subject) - * Claim must be present; if the - * {@link JWTClaimVerificationOptions.maxTokenAge `maxTokenAge` option} is set, then JWT "iat" - * (Issued At) Claim must be present. - */ - requiredClaims?: string[] -} - -/** JWS Verification options. */ -export interface VerifyOptions extends CritOption { - /** - * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" - * (Algorithm) values applicable for the used key/secret are allowed. - * - * Note: Unsecured JWTs (`{ "alg": "none" }`) are never accepted by this API. - */ - algorithms?: string[] -} - -/** JWS Signing options. */ -export interface SignOptions extends CritOption {} - -/** Recognized JWT Claims Set members, any other members may also be present. */ -export interface JWTPayload { - /** - * JWT Issuer - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1} - */ - iss?: string - - /** - * JWT Subject - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2} - */ - sub?: string - - /** - * JWT Audience - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3} - */ - aud?: string | string[] - - /** - * JWT ID - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7} - */ - jti?: string - - /** - * JWT Not Before - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5} - */ - nbf?: number - - /** - * JWT Expiration Time - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4} - */ - exp?: number - - /** - * JWT Issued At - * - * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6} - */ - iat?: number - - /** Any other JWT Claim Set member. */ - [propName: string]: unknown -} - -export interface FlattenedDecryptResult { - /** JWE AAD. */ - additionalAuthenticatedData?: Uint8Array - - /** Plaintext. */ - plaintext: Uint8Array - - /** JWE Protected Header. */ - protectedHeader?: JWEHeaderParameters - - /** JWE Shared Unprotected Header. */ - sharedUnprotectedHeader?: JWEHeaderParameters - - /** JWE Per-Recipient Unprotected Header. */ - unprotectedHeader?: JWEHeaderParameters -} - -export interface GeneralDecryptResult extends FlattenedDecryptResult {} - -export interface CompactDecryptResult { - /** Plaintext. */ - plaintext: Uint8Array - - /** JWE Protected Header. */ - protectedHeader: CompactJWEHeaderParameters -} - -export interface FlattenedVerifyResult { - /** JWS Payload. */ - payload: Uint8Array - - /** JWS Protected Header. */ - protectedHeader?: JWSHeaderParameters - - /** JWS Unprotected Header. */ - unprotectedHeader?: JWSHeaderParameters -} - -export interface GeneralVerifyResult extends FlattenedVerifyResult {} - -export interface CompactVerifyResult { - /** JWS Payload. */ - payload: Uint8Array - - /** JWS Protected Header. */ - protectedHeader: CompactJWSHeaderParameters -} - -export interface JWTVerifyResult { - /** JWT Claims Set. */ - payload: PayloadType & JWTPayload - - /** JWS Protected Header. */ - protectedHeader: JWTHeaderParameters -} - -export interface JWTDecryptResult { - /** JWT Claims Set. */ - payload: PayloadType & JWTPayload - - /** JWE Protected Header. */ - protectedHeader: CompactJWEHeaderParameters -} - -export interface ResolvedKey { - /** Key resolved from the key resolver function. */ - key: KeyLikeType | Uint8Array -} - -/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ -export interface CompactJWSHeaderParameters extends JWSHeaderParameters { - alg: string -} - -/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ -export interface JWTHeaderParameters extends CompactJWSHeaderParameters { - b64?: true -} - -/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ -export interface CompactJWEHeaderParameters extends JWEHeaderParameters { - alg: string - enc: string -} - -/** JSON Web Key Set */ -export interface JSONWebKeySet { - keys: JWK[] -} - -export type CryptoRuntime = 'WebCryptoAPI' | 'node:crypto' diff --git a/dist/types/util/base64url.d.ts b/dist/types/util/base64url.d.ts deleted file mode 100644 index ec08361d2c..0000000000 --- a/dist/types/util/base64url.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Utility function to encode a string or Uint8Array as a base64url string. - * - * @param input Value that will be base64url-encoded. - */ -interface Base64UrlEncode { - (input: Uint8Array | string): string; -} -/** - * Utility function to decode a base64url encoded string. - * - * @param input Value that will be base64url-decoded. - */ -interface Base64UrlDecode { - (input: Uint8Array | string): Uint8Array; -} -export declare const encode: Base64UrlEncode; -export declare const decode: Base64UrlDecode; -export {}; diff --git a/dist/types/util/decode_jwt.d.ts b/dist/types/util/decode_jwt.d.ts deleted file mode 100644 index 4ebaad8cef..0000000000 --- a/dist/types/util/decode_jwt.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { JWTPayload } from '../types'; -/** - * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or - * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation - * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation - * and JWE decryption use `jose.jwtDecrypt()`. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/jwt/decode'`. - * - * @param jwt JWT token in compact JWS serialization. - */ -export declare function decodeJwt(jwt: string): PayloadType & JWTPayload; diff --git a/dist/types/util/decode_protected_header.d.ts b/dist/types/util/decode_protected_header.d.ts deleted file mode 100644 index 7c12f0a041..0000000000 --- a/dist/types/util/decode_protected_header.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { JWSHeaderParameters, JWEHeaderParameters } from '../types'; -export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters; -/** - * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. - * - * This function is exported (as a named export) from the main `'jose'` module entry point as well - * as from its subpath export `'jose/decode/protected_header'`. - * - * @param token JWE/JWS/JWT token in any JOSE serialization. - */ -export declare function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters; diff --git a/dist/types/util/errors.d.ts b/dist/types/util/errors.d.ts deleted file mode 100644 index e7202722bb..0000000000 --- a/dist/types/util/errors.d.ts +++ /dev/null @@ -1,176 +0,0 @@ -import type { JWTPayload, KeyLike } from '../types'; -/** - * A generic Error that all other JOSE specific Error subclasses extend. - * - */ -export declare class JOSEError extends Error { - /** - * A unique error code for the particular error subclass. - * - * @ignore - */ - static get code(): string; - /** A unique error code for this particular error subclass. */ - code: string; - /** @ignore */ - constructor(message?: string); -} -/** - * An error subclass thrown when a JWT Claim Set member validation fails. - * - */ -export declare class JWTClaimValidationFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - code: string; - /** The Claim for which the validation failed. */ - claim: string; - /** Reason code for the validation failure. */ - reason: string; - /** - * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at - * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity - * has however been verified. Claims Set verification happens after the JWS Signature or JWE - * Decryption processes. - */ - payload: JWTPayload; - /** @ignore */ - constructor(message: string, payload: JWTPayload, claim?: string, reason?: string); -} -/** - * An error subclass thrown when a JWT is expired. - * - */ -export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailed { - /** @ignore */ - static get code(): 'ERR_JWT_EXPIRED'; - code: string; - /** The Claim for which the validation failed. */ - claim: string; - /** Reason code for the validation failure. */ - reason: string; - /** - * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at - * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity - * has however been verified. Claims Set verification happens after the JWS Signature or JWE - * Decryption processes. - */ - payload: JWTPayload; - /** @ignore */ - constructor(message: string, payload: JWTPayload, claim?: string, reason?: string); -} -/** - * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. - * - */ -export declare class JOSEAlgNotAllowed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED'; - code: string; -} -/** - * An error subclass thrown when a particular feature or algorithm is not supported by this - * implementation or JOSE in general. - * - */ -export declare class JOSENotSupported extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JOSE_NOT_SUPPORTED'; - code: string; -} -/** - * An error subclass thrown when a JWE ciphertext decryption fails. - * - */ -export declare class JWEDecryptionFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWE_DECRYPTION_FAILED'; - code: string; - message: string; -} -/** - * An error subclass thrown when a JWE is invalid. - * - */ -export declare class JWEInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWE_INVALID'; - code: string; -} -/** - * An error subclass thrown when a JWS is invalid. - * - */ -export declare class JWSInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWS_INVALID'; - code: string; -} -/** - * An error subclass thrown when a JWT is invalid. - * - */ -export declare class JWTInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWT_INVALID'; - code: string; -} -/** - * An error subclass thrown when a JWK is invalid. - * - */ -export declare class JWKInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWK_INVALID'; - code: string; -} -/** - * An error subclass thrown when a JWKS is invalid. - * - */ -export declare class JWKSInvalid extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_INVALID'; - code: string; -} -/** - * An error subclass thrown when no keys match from a JWKS. - * - */ -export declare class JWKSNoMatchingKey extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_NO_MATCHING_KEY'; - code: string; - message: string; -} -/** - * An error subclass thrown when multiple keys match from a JWKS. - * - */ -export declare class JWKSMultipleMatchingKeys extends JOSEError { - /** @ignore */ - [Symbol.asyncIterator]: () => AsyncIterableIterator; - static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - code: string; - message: string; -} -/** - * Timeout was reached when retrieving the JWKS response. - * - */ -export declare class JWKSTimeout extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWKS_TIMEOUT'; - code: string; - message: string; -} -/** - * An error subclass thrown when JWS signature verification fails. - * - */ -export declare class JWSSignatureVerificationFailed extends JOSEError { - /** @ignore */ - static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - code: string; - message: string; -} diff --git a/dist/types/util/runtime.d.ts b/dist/types/util/runtime.d.ts deleted file mode 100644 index f8b9f66328..0000000000 --- a/dist/types/util/runtime.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { CryptoRuntime } from '../types'; -declare const _default: CryptoRuntime; -export default _default;