From 7036eb70a090eba6fe9e28c15e4bf6b09ea64c78 Mon Sep 17 00:00:00 2001 From: Bean Date: Tue, 3 Oct 2023 14:53:46 -0400 Subject: [PATCH] add check for node runtime and import from node buffer for Blob (#225) * add check for node runtime and import from node buffer for Blob * move Blob import to global scope of package * migrate Blob injection to polyfil --- packages/crypto/polyfills.js | 19 +++++++++++++++++++ packages/crypto/src/lib/crypto.spec.ts | 14 +++++++++++++- packages/crypto/src/lib/crypto.ts | 6 ++++-- 3 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 packages/crypto/polyfills.js diff --git a/packages/crypto/polyfills.js b/packages/crypto/polyfills.js new file mode 100644 index 0000000000..8d97ea1728 --- /dev/null +++ b/packages/crypto/polyfills.js @@ -0,0 +1,19 @@ +// This field will be automatically injected into the ./dist/packages//index.js file +// between the autogen:polyfills:start/end comments + +try { + if (isNode()) { + try { + //@ts-ignore + let { Blob } = import('node:buffer').then((module) => { + globalThis.Blob = module.Blob; + }); + } catch (e) { + log( + 'Warn: could not resolve Blob from node api set, perhaps polyfil a Blob implementation of your choice' + ); + } + } +} catch (e) { + // swallow +} diff --git a/packages/crypto/src/lib/crypto.spec.ts b/packages/crypto/src/lib/crypto.spec.ts index 42623f460a..bab2bc93bf 100644 --- a/packages/crypto/src/lib/crypto.spec.ts +++ b/packages/crypto/src/lib/crypto.spec.ts @@ -64,11 +64,23 @@ describe('encryptWithSymmetricKey', () => { let symmetricKey: CryptoKey; beforeAll(async () => { + try { + //@ts-ignore + import('node:buffer').then((module) => { + //@ts-ignore + globalThis.Blob = module.Blob; + }); + } catch (e) { + console.log( + 'Warn: could not resolve Blob from node api set, perhaps polyfil a Blob implementation of your choice' + ); + } symmetricKey = await generateSymmetricKey(); }); - testData.forEach((data, index) => { + testData.forEach(async (data, index) => { it(`should encrypt data (test case ${index + 1})`, async () => { + const { Blob } = await import("node:buffer"); const encryptedBlob = await encryptWithSymmetricKey(symmetricKey, data); expect(encryptedBlob).toBeDefined(); diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index 245c8691c1..74ff4c81cf 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -11,7 +11,7 @@ import { import * as wasmECDSA from '@lit-protocol/ecdsa-sdk'; -import { isBrowser, log, throwError } from '@lit-protocol/misc'; +import { isBrowser, isNode, log, throwError } from '@lit-protocol/misc'; import { uint8arrayFromString, @@ -60,6 +60,8 @@ if (!globalThis.wasmECDSA) { } }); } + + /** ---------- Exports ---------- */ /** @@ -101,7 +103,7 @@ export const encryptWithSymmetricKey = async ( symmKey, data ); - + const encryptedZipBlob = new Blob([iv, new Uint8Array(encryptedZipData)], { type: 'application/octet-stream', });