From 7b32660d0832fce3bc3fb0789504ef66153810b5 Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Wed, 7 Dec 2022 18:48:55 +0100 Subject: [PATCH] Don't call getCryptoModule in getSubtle --- CHANGELOG.md | 9 +++++++++ packages/crypto/src/pbkdf2.ts | 20 ++++++++++++-------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52b2632f41..65836ce454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,15 @@ and this project adheres to [#1326]: https://github.com/cosmos/cosmjs/pull/1326 +### Changed + +- @cosmjs/crypto: `getSubtle()` does not use `getCryptoModule()` anymore to find + a subtle implementation. Turns out all environments we support have subtle in + `globalThis` or do not have it at all ([#1307], [#1340]). + +[#1307]: https://github.com/cosmos/cosmjs/pull/1307 +[#1340]: https://github.com/cosmos/cosmjs/pull/1340 + ### Deprecated - @cosmjs/stargate: Deprecate `QueryClient.queryUnverified` in favour of newly diff --git a/packages/crypto/src/pbkdf2.ts b/packages/crypto/src/pbkdf2.ts index 110b16e265..38ad1ab38a 100644 --- a/packages/crypto/src/pbkdf2.ts +++ b/packages/crypto/src/pbkdf2.ts @@ -24,14 +24,18 @@ export async function getCryptoModule(): Promise { } export async function getSubtle(): Promise { - const g: any = globalThis; - let subtle = g.crypto && g.crypto.subtle; - if (!subtle) { - const crypto = await getCryptoModule(); - if (crypto && crypto.webcrypto && crypto.webcrypto.subtle) { - subtle = crypto.webcrypto.subtle; - } - } + // From Node.js 15 onwards, webcrypto is available in globalThis. + // In version 15 and 16 this was stored under the webcrypto key. + // With Node.js 17 it was moved to the same locations where browsers + // make it available. + // Loading `require("crypto")` here seems unnecessary since it only + // causes issues with bundlers and does not increase compatibility. + + // Browsers and Node.js 17+ + let subtle: any | undefined = (globalThis as any)?.crypto?.subtle; + // Node.js 15+ + if (!subtle) subtle = (globalThis as any)?.crypto?.webcrypto?.subtle; + return subtle; }