@gaonengwww/jose
Version:
JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes
326 lines (317 loc) • 9.44 kB
JavaScript
// src/lib/buffer_utils.ts
var encoder = new TextEncoder();
var decoder = new TextDecoder();
var MAX_INT32 = 2 ** 32;
function concat(...buffers) {
const size = buffers.reduce((acc, { length }) => acc + length, 0);
const buf = new Uint8Array(size);
let i = 0;
for (const buffer of buffers) {
buf.set(buffer, i);
i += buffer.length;
}
return buf;
}
function writeUInt32BE(buf, value, offset) {
if (value < 0 || value >= MAX_INT32) {
throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
}
buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
}
function uint64be(value) {
const high = Math.floor(value / MAX_INT32);
const low = value % MAX_INT32;
const buf = new Uint8Array(8);
writeUInt32BE(buf, high, 0);
writeUInt32BE(buf, low, 4);
return buf;
}
// src/util/errors.ts
var JOSEError = class extends Error {
/**
* A unique error code for the particular error subclass.
*
* @ignore
*/
static code = "ERR_JOSE_GENERIC";
/** A unique error code for {@link JOSEError}. */
code = "ERR_JOSE_GENERIC";
/** @ignore */
constructor(message2, options) {
super(message2, options);
this.name = this.constructor.name;
Error.captureStackTrace?.(this, this.constructor);
}
};
var JOSENotSupported = class extends JOSEError {
/** @ignore */
static code = "ERR_JOSE_NOT_SUPPORTED";
/** A unique error code for {@link JOSENotSupported}. */
code = "ERR_JOSE_NOT_SUPPORTED";
};
var JWEDecryptionFailed = class extends JOSEError {
/** @ignore */
static code = "ERR_JWE_DECRYPTION_FAILED";
/** A unique error code for {@link JWEDecryptionFailed}. */
code = "ERR_JWE_DECRYPTION_FAILED";
/** @ignore */
constructor(message2 = "decryption operation failed", options) {
super(message2, options);
}
};
var JWEInvalid = class extends JOSEError {
/** @ignore */
static code = "ERR_JWE_INVALID";
/** A unique error code for {@link JWEInvalid}. */
code = "ERR_JWE_INVALID";
};
// src/lib/iv.ts
function bitLength(alg) {
switch (alg) {
case "A128GCM":
case "A128GCMKW":
case "A192GCM":
case "A192GCMKW":
case "A256GCM":
case "A256GCMKW":
return 96;
case "A128CBC-HS256":
case "A192CBC-HS384":
case "A256CBC-HS512":
return 128;
default:
throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
}
}
// src/lib/check_iv_length.ts
var check_iv_length_default = (enc, iv) => {
if (iv.length << 3 !== bitLength(enc)) {
throw new JWEInvalid("Invalid Initialization Vector length");
}
};
// src/lib/check_cek_length.ts
var check_cek_length_default = (cek, expected) => {
const actual = cek.byteLength << 3;
if (actual !== expected) {
throw new JWEInvalid(
`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`
);
}
};
// src/lib/crypto_key.ts
function unusable(name, prop = "algorithm.name") {
return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
}
function isAlgorithm(algorithm, name) {
return algorithm.name === name;
}
function getHashLength(hash) {
return parseInt(hash.name.slice(4), 10);
}
function checkUsage(key, usage) {
if (usage && !key.usages.includes(usage)) {
throw new TypeError(
`CryptoKey does not support this operation, its usages must include ${usage}.`
);
}
}
function checkEncCryptoKey(key, alg, usage) {
switch (alg) {
case "A128GCM":
case "A192GCM":
case "A256GCM": {
if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM");
const expected = parseInt(alg.slice(1, 4), 10);
const actual = key.algorithm.length;
if (actual !== expected) throw unusable(expected, "algorithm.length");
break;
}
case "A128KW":
case "A192KW":
case "A256KW": {
if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW");
const expected = parseInt(alg.slice(1, 4), 10);
const actual = key.algorithm.length;
if (actual !== expected) throw unusable(expected, "algorithm.length");
break;
}
case "ECDH": {
switch (key.algorithm.name) {
case "ECDH":
case "X25519":
break;
default:
throw unusable("ECDH or X25519");
}
break;
}
case "PBES2-HS256+A128KW":
case "PBES2-HS384+A192KW":
case "PBES2-HS512+A256KW":
if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2");
break;
case "RSA-OAEP":
case "RSA-OAEP-256":
case "RSA-OAEP-384":
case "RSA-OAEP-512": {
if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP");
const expected = parseInt(alg.slice(9), 10) || 1;
const actual = getHashLength(key.algorithm.hash);
if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
break;
}
default:
throw new TypeError("CryptoKey does not support this operation");
}
checkUsage(key, usage);
}
// src/lib/invalid_key_input.ts
function message(msg, actual, ...types) {
types = types.filter(Boolean);
if (types.length > 2) {
const last = types.pop();
msg += `one of type ${types.join(", ")}, or ${last}.`;
} else if (types.length === 2) {
msg += `one of type ${types[0]} or ${types[1]}.`;
} else {
msg += `of type ${types[0]}.`;
}
if (actual == null) {
msg += ` Received ${actual}`;
} else if (typeof actual === "function" && actual.name) {
msg += ` Received function ${actual.name}`;
} else if (typeof actual === "object" && actual != null) {
if (actual.constructor?.name) {
msg += ` Received an instance of ${actual.constructor.name}`;
}
}
return msg;
}
var invalid_key_input_default = (actual, ...types) => {
return message("Key must be ", actual, ...types);
};
// src/lib/is_key_like.ts
function isCryptoKey(key) {
return key?.[Symbol.toStringTag] === "CryptoKey";
}
// src/lib/decrypt.ts
async function timingSafeEqual(a, b) {
if (!(a instanceof Uint8Array)) {
throw new TypeError("First argument must be a buffer");
}
if (!(b instanceof Uint8Array)) {
throw new TypeError("Second argument must be a buffer");
}
const algorithm = { name: "HMAC", hash: "SHA-256" };
const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
let out = 0;
let i = -1;
while (++i < 32) {
out |= aHmac[i] ^ bHmac[i];
}
return out === 0;
}
async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
if (!(cek instanceof Uint8Array)) {
throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
}
const keySize = parseInt(enc.slice(1, 4), 10);
const encKey = await crypto.subtle.importKey(
"raw",
cek.subarray(keySize >> 3),
"AES-CBC",
false,
["decrypt"]
);
const macKey = await crypto.subtle.importKey(
"raw",
cek.subarray(0, keySize >> 3),
{
hash: `SHA-${keySize << 1}`,
name: "HMAC"
},
false,
["sign"]
);
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const expectedTag = new Uint8Array(
(await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)
);
let macCheckPassed;
try {
macCheckPassed = await timingSafeEqual(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();
}
}
var decrypt_default = async (enc, cek, ciphertext, iv, tag, aad) => {
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
throw new TypeError(
invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")
);
}
if (!iv) {
throw new JWEInvalid("JWE Initialization Vector missing");
}
if (!tag) {
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, tag, 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, tag, aad);
default:
throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
}
};
export {
decrypt_default as default
};