From 280828dae65b0b5aae923510049fe4da8c471333 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Tue, 6 Feb 2024 15:41:40 +0100 Subject: [PATCH] Throw if WebCrypto API is not available It was already required, this simply makes errors more clear. --- src/crypto/hkdf.js | 6 ++---- src/util.js | 13 ++++++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/crypto/hkdf.js b/src/crypto/hkdf.js index 91ff9a2e..361703b1 100644 --- a/src/crypto/hkdf.js +++ b/src/crypto/hkdf.js @@ -7,14 +7,12 @@ import enums from '../enums'; import util from '../util'; const webCrypto = util.getWebCrypto(); -const nodeCrypto = util.getNodeCrypto(); export default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { const hash = enums.read(enums.webHash, hashAlgo); if (!hash) throw new Error('Hash algo not supported with HKDF'); - const crypto = webCrypto || nodeCrypto.webcrypto.subtle; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); return new Uint8Array(bits); } diff --git a/src/util.js b/src/util.js index 188a86fa..47363c97 100644 --- a/src/util.js +++ b/src/util.js @@ -420,11 +420,18 @@ const util = { }, /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available */ getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; }, /**