Skip to content

Commit

Permalink
add check for node runtime and import from node buffer for Blob (#225)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Bean authored Oct 3, 2023
1 parent 6edb733 commit 7036eb7
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
19 changes: 19 additions & 0 deletions packages/crypto/polyfills.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// This field will be automatically injected into the ./dist/packages/<package-name>/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
}
14 changes: 13 additions & 1 deletion packages/crypto/src/lib/crypto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
6 changes: 4 additions & 2 deletions packages/crypto/src/lib/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -60,6 +60,8 @@ if (!globalThis.wasmECDSA) {
}
});
}


/** ---------- Exports ---------- */

/**
Expand Down Expand Up @@ -101,7 +103,7 @@ export const encryptWithSymmetricKey = async (
symmKey,
data
);

const encryptedZipBlob = new Blob([iv, new Uint8Array(encryptedZipData)], {
type: 'application/octet-stream',
});
Expand Down

0 comments on commit 7036eb7

Please sign in to comment.