summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorMatthew Miller <matthew@millerti.me>2023-10-27 20:16:45 -0700
committerMatthew Miller <matthew@millerti.me>2023-10-27 20:16:45 -0700
commitdf2653896acda25c49dd6180d61d3f62e9c5873b (patch)
treea3fbefa03d20c426babcdb7bf7fb77c96f968d78
parent9d000d1108524906188636d7070823e80f9ce2cb (diff)
Make node:crypto import more resilient
-rw-r--r--packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts43
1 files changed, 27 insertions, 16 deletions
diff --git a/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts b/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts
index fe86219..3cf7ab6 100644
--- a/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts
+++ b/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts
@@ -15,25 +15,23 @@ export async function getWebCrypto(): Promise<Crypto> {
* Naively attempt to access Crypto as a global object, which popular alternative run-times
* support.
*/
- const _crypto = _getWebCryptoInternals.stubThisGlobalThisCrypto();
+ const _globalThisCrypto = _getWebCryptoInternals.stubThisGlobalThisCrypto();
- if (_crypto) {
- webCrypto = _crypto;
+ if (_globalThisCrypto) {
+ console.log('globalThis.crypto');
+ webCrypto = _globalThisCrypto;
return webCrypto;
}
- try {
- /**
- * `globalThis.crypto` isn't available, so attempt a Node import...
- */
- const _crypto = await _getWebCryptoInternals.stubThisImportNodeCrypto();
+ /**
+ * `globalThis.crypto` isn't available, so attempt a Node import...
+ */
+ const _nodeCrypto = await _getWebCryptoInternals.stubThisImportNodeCrypto();
- if (_crypto.webcrypto) {
- webCrypto = _crypto.webcrypto as Crypto;
- return webCrypto;
- }
- } catch (_err) {
- // pass
+ if (_nodeCrypto?.webcrypto) {
+ console.log('node:crypto');
+ webCrypto = _nodeCrypto.webcrypto as Crypto;
+ return webCrypto;
}
// We tried to access it both in Node and globally, so bail out
@@ -50,8 +48,21 @@ export class MissingWebCrypto extends Error {
// Make it possible to stub return values during testing
export const _getWebCryptoInternals = {
- // dnt-shim-ignore
- stubThisImportNodeCrypto: () => import('node:crypto'),
+ stubThisImportNodeCrypto: async () => {
+ try {
+ // dnt-shim-ignore
+ const _nodeCrypto = await import('node:crypto');
+ return _nodeCrypto;
+ } catch (_err) {
+ /**
+ * Intentionally declaring webcrypto as undefined because we're assuming the Node import
+ * failed due to either:
+ * - `import()` isn't supported
+ * - `node:crypto` is unavailable.
+ */
+ return { webcrypto: undefined };
+ }
+ },
stubThisGlobalThisCrypto: () => globalThis.crypto,
// Make it possible to reset the `webCrypto` at the top of the file
setCachedCrypto: (newCrypto: Crypto | undefined) => {