Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Adopt shared ente-wasm loaders

Neeraj Guptae0cff6cef2b2
diff --git a/.github/workflows/web-lint.yml b/.github/workflows/web-lint.yml
index 755cac05f3..89c3788889 100644
--- a/.github/workflows/web-lint.yml
+++ b/.github/workflows/web-lint.yml
@@ -46,7 +46,7 @@ jobs:
- run: yarn lint
- - run: yarn test:run
+ - run: yarn test
- name: Audit dependencies
run: |
diff --git a/web/apps/ensu/src/services/wasm.ts b/web/apps/ensu/src/services/wasm.ts
index 7267d8b305..a915bb0b02 100644
--- a/web/apps/ensu/src/services/wasm.ts
+++ b/web/apps/ensu/src/services/wasm.ts
@@ -5,6 +5,8 @@
* when needed (login/crypto flows), while Tauri uses native Rust bindings.
*/
+import { loadEnteWasm } from "ente-wasm/load";
+
export type EnteWasmModule = typeof import("ente-wasm");
export interface EncryptedBox {
@@ -304,7 +306,7 @@ export const enteWasm = async (): Promise<EnteCryptoAdapter> => {
if (isTauriRuntime()) {
return createTauriAdapter();
}
- const wasm = await import("ente-wasm");
+ const wasm = await loadEnteWasm();
return createWasmAdapter(wasm);
})();
_wasmPromise = load.catch((error: unknown) => {
@@ -321,7 +323,6 @@ export const enteWasm = async (): Promise<EnteCryptoAdapter> => {
export const ensureCryptoInit = async () => {
if (_cryptoInitDone) return;
const wasm = await enteWasm();
- // No-op for the pure Rust backend, but keeps the API symmetric.
await wasm.crypto_init();
_cryptoInitDone = true;
};
diff --git a/web/apps/locker/src/services/crypto.ts b/web/apps/locker/src/services/crypto.ts
index 4739c4d547..a6f5e76879 100644
--- a/web/apps/locker/src/services/crypto.ts
+++ b/web/apps/locker/src/services/crypto.ts
@@ -15,7 +15,7 @@ import type {
EncryptedFile,
KeyPair,
} from "ente-base/crypto/types";
-import { ensureCryptoInit, enteWasm } from "./wasm";
+import { loadCryptoReadyEnteWasm } from "ente-wasm/load";
const shouldFallbackToLegacyBlobDecrypt = (error: unknown): boolean => {
if (!error || typeof error !== "object") {
@@ -70,8 +70,7 @@ export const decryptBox = async (
box: EncryptedBox,
key: Uint8Array | string,
): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_decrypt_box(
toB64String(box.encryptedData),
toB64String(box.nonce),
@@ -98,8 +97,7 @@ export const decryptMetadataJSON = async (
blob: EncryptedBlob,
key: Uint8Array | string,
): Promise<unknown> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const encryptedData = toB64String(blob.encryptedData);
const decryptionHeader = toB64String(blob.decryptionHeader);
const keyB64 = toB64String(key);
@@ -131,8 +129,7 @@ export const boxSealOpen = async (
encryptedData: string,
keyPair: KeyPair,
): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_box_seal_open(
encryptedData,
keyPair.publicKey,
@@ -144,8 +141,7 @@ export const boxSeal = async (
dataB64: string,
publicKeyB64: string,
): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_box_seal(dataB64, publicKeyB64);
};
@@ -163,14 +159,12 @@ export const boxSeal = async (
* Generate a random 32-byte key (base64).
*/
export const generateKey = async (): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_generate_key();
};
export const md5Base64 = async (data: Uint8Array): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_md5_base64(data);
};
@@ -182,8 +176,7 @@ export const encryptBox = async (
dataB64: string,
keyB64: string,
): Promise<{ encryptedData: string; nonce: string }> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const result = wasm.crypto_encrypt_box(dataB64, keyB64);
return { encryptedData: result.encrypted_data, nonce: result.nonce };
};
@@ -196,8 +189,7 @@ export const encryptBlob = async (
dataB64: string,
keyB64: string,
): Promise<{ encryptedData: string; decryptionHeader: string }> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const result = wasm.crypto_encrypt_blob(dataB64, keyB64);
return {
encryptedData: result.encrypted_data,
@@ -236,8 +228,7 @@ export interface StreamDecryptorHandle {
export const createStreamEncryptor =
async (): Promise<StreamEncryptorHandle> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const encryptor = new wasm.CryptoStreamEncryptor();
return {
@@ -253,8 +244,7 @@ export const createStreamDecryptor = async (
decryptionHeader: string,
keyB64: string,
): Promise<StreamDecryptorHandle> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const decryptor = new wasm.CryptoStreamDecryptor(decryptionHeader, keyB64);
return {
@@ -290,8 +280,7 @@ export interface EncryptedFileResult {
export const encryptFileStream = async (
dataB64: string,
): Promise<EncryptedFileResult> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const result = wasm.crypto_encrypt_stream(dataB64);
return {
encryptedData: result.encrypted_data,
@@ -311,8 +300,7 @@ export const encryptFileStreamWithKey = async (
dataB64: string,
keyB64: string,
): Promise<EncryptedFileResult> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const result = wasm.crypto_encrypt_stream_with_key(dataB64, keyB64);
return {
encryptedData: result.encrypted_data,
@@ -336,8 +324,7 @@ export const decryptStreamBytes = async (
file: EncryptedFile,
key: Uint8Array | string,
): Promise<Uint8Array> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const plaintextB64 = wasm.crypto_decrypt_stream(
toB64String(file.encryptedData),
toB64String(file.decryptionHeader),
diff --git a/web/apps/locker/src/services/wasm.ts b/web/apps/locker/src/services/wasm.ts
deleted file mode 100644
index 5cfd13bbb9..0000000000
--- a/web/apps/locker/src/services/wasm.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Lazy loader for the `ente-wasm` package.
- *
- * We keep this behind a dynamic import so that the WASM bundle is only loaded
- * when needed (when crypto operations are first invoked).
- *
- * This follows the same pattern as `apps/ensu/src/services/wasm.ts` but
- * without the Tauri adapter since Locker is web-only.
- */
-
-type EnteWasmModule = typeof import("ente-wasm");
-
-let _wasmPromise: Promise<EnteWasmModule> | undefined;
-let _cryptoInitDone = false;
-
-/**
- * Return the lazily loaded `ente-wasm` module.
- *
- * The module is loaded once on first call and the same promise is reused for
- * subsequent calls.
- */
-export const enteWasm = async (): Promise<EnteWasmModule> => {
- if (!_wasmPromise) {
- const load = import("ente-wasm");
- _wasmPromise = load.catch((error: unknown) => {
- if (_wasmPromise === load) {
- _wasmPromise = undefined;
- }
- throw error;
- });
- }
- return _wasmPromise;
-};
-
-/**
- * Ensure the WASM crypto backend has been initialised.
- *
- * This is a no-op for the pure-Rust backend but keeps the API symmetric with
- * other implementations.
- */
-export const ensureCryptoInit = async () => {
- if (_cryptoInitDone) return;
- const wasm = await enteWasm();
- wasm.crypto_init();
- _cryptoInitDone = true;
-};
diff --git a/web/package.json b/web/package.json
index b73b6b2eca..8cef02186b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -38,8 +38,7 @@
"dev:twoof3": "yarn workspace twoof3 next dev -p 3009",
"lint": "concurrently --names 'prettier,eslint,tsc' \"yarn prettier --check --log-level warn .\" \"yarn workspaces run eslint\" \"yarn workspaces run tsc\"",
"lint-fix": "concurrently --names 'prettier,eslint,tsc' \"yarn prettier --write --log-level warn .\" \"yarn workspaces run eslint --fix\" \"yarn workspaces run tsc\"",
- "test": "yarn workspace ente-wasm test",
- "test:run": "yarn workspace ente-wasm test run"
+ "test": "yarn workspace ente-wasm test && yarn workspace ente-contacts-web test"
},
"resolutions": {
"@types/react": "^19.2.2",
diff --git a/web/packages/accounts-rs/services/crypto.ts b/web/packages/accounts-rs/services/crypto.ts
index 26c2efdc4b..bea25a11f8 100644
--- a/web/packages/accounts-rs/services/crypto.ts
+++ b/web/packages/accounts-rs/services/crypto.ts
@@ -1,4 +1,4 @@
-import { ensureCryptoInit, enteWasm } from "./wasm";
+import { loadCryptoReadyEnteWasm } from "ente-wasm/load";
export const deriveKeyInsufficientMemoryErrorMessage =
"Failed to derive key (insufficient memory)";
@@ -84,8 +84,7 @@ export const deriveKey = async (
opsLimit: number,
memLimit: number,
) => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.auth_derive_kek(password, saltB64, memLimit, opsLimit);
};
@@ -99,9 +98,8 @@ const normalizeDerivedKey = (result: WasmDerivedKey): DerivedKey => ({
export const deriveSensitiveKey = async (
password: string,
): Promise<DerivedKey> => {
- await ensureCryptoInit();
+ const wasm = await loadCryptoReadyEnteWasm();
try {
- const wasm = await enteWasm();
return normalizeDerivedKey(
wasm.auth_generate_sensitive_kek(password) as WasmDerivedKey,
);
@@ -113,9 +111,8 @@ export const deriveSensitiveKey = async (
export const deriveInteractiveKey = async (
password: string,
): Promise<DerivedKey> => {
- await ensureCryptoInit();
+ const wasm = await loadCryptoReadyEnteWasm();
try {
- const wasm = await enteWasm();
return normalizeDerivedKey(
wasm.auth_generate_interactive_kek(password) as WasmDerivedKey,
);
@@ -125,14 +122,12 @@ export const deriveInteractiveKey = async (
};
export const generateKey = async (): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_generate_key();
};
export const generateKeyPair = async (): Promise<KeyPair> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const keyPair = wasm.crypto_generate_keypair();
return { publicKey: keyPair.public_key, privateKey: keyPair.secret_key };
};
@@ -141,8 +136,7 @@ export const encryptBox = async (
dataB64: string,
keyB64: string,
): Promise<EncryptedBox> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const box = wasm.crypto_encrypt_box(dataB64, keyB64);
return { encryptedData: box.encrypted_data, nonce: box.nonce };
};
@@ -151,8 +145,7 @@ export const decryptBox = async (
box: EncryptedBox,
keyB64: string,
): Promise<string> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.crypto_decrypt_box(box.encryptedData, box.nonce, keyB64);
};
@@ -160,8 +153,7 @@ export const boxSealOpenBytes = async (
encryptedData: string,
keyPair: KeyPair,
): Promise<Uint8Array> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return fromB64(
wasm.crypto_box_seal_open(
encryptedData,
@@ -177,8 +169,7 @@ export const deriveSubKeyBytes = async (
subKeyID: number,
context: string,
) => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return fromB64(
wasm.crypto_derive_subkey(
keyB64,
@@ -193,8 +184,7 @@ export const generateSRPSetupAttributesRust = async (
kekB64: string,
srpUserID: string,
) => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
const setup = wasm.auth_generate_srp_setup(
kekB64,
srpUserID,
@@ -207,13 +197,11 @@ export const generateSRPSetupAttributesRust = async (
};
export const recoveryKeyFromMnemonicOrHex = async (value: string) => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.auth_recovery_key_from_mnemonic_or_hex(value);
};
export const recoveryKeyToMnemonicRust = async (recoveryKey: string) => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
+ const wasm = await loadCryptoReadyEnteWasm();
return wasm.auth_recovery_key_to_mnemonic(recoveryKey);
};
diff --git a/web/packages/accounts-rs/services/srp.ts b/web/packages/accounts-rs/services/srp.ts
index 123804ffd7..12929ae76f 100644
--- a/web/packages/accounts-rs/services/srp.ts
+++ b/web/packages/accounts-rs/services/srp.ts
@@ -10,6 +10,7 @@ import {
} from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { ensure } from "ente-utils/ensure";
+import { loadEnteWasm } from "ente-wasm/load";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { saveSRPAttributes } from "./accounts-db";
@@ -17,7 +18,6 @@ import {
RemoteSRPVerificationResponse,
type EmailOrSRPVerificationResponse,
} from "./user";
-import { enteWasm } from "./wasm";
export interface SRPAttributes {
srpUserID: string;
@@ -105,7 +105,7 @@ const createSRPSession = async (
srpUserID: string,
loginSubKey: string,
) => {
- const wasm = await enteWasm();
+ const wasm = await loadEnteWasm();
return new wasm.SrpSession(srpUserID, srpSalt, loginSubKey);
};
diff --git a/web/packages/accounts-rs/services/wasm.ts b/web/packages/accounts-rs/services/wasm.ts
deleted file mode 100644
index 2a4b296773..0000000000
--- a/web/packages/accounts-rs/services/wasm.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-type EnteWasmModule = typeof import("ente-wasm");
-
-let wasmPromise: Promise<EnteWasmModule> | undefined;
-let initDone = false;
-
-export const enteWasm = async (): Promise<EnteWasmModule> => {
- if (!wasmPromise) {
- const load = import("ente-wasm");
- wasmPromise = load.catch((error: unknown) => {
- if (wasmPromise === load) {
- wasmPromise = undefined;
- }
- throw error;
- });
- }
- return wasmPromise;
-};
-
-export const ensureCryptoInit = async () => {
- if (initDone) return;
- const wasm = await enteWasm();
- wasm.crypto_init();
- initDone = true;
-};
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index ad2a6d3876..620e7dbfa9 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -7,6 +7,7 @@ import log from "ente-base/log";
import { apiOrigin } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
import type { ContactsCtxHandle } from "ente-wasm";
+import { loadEnteWasm } from "ente-wasm/load";
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import {
saveContactDisplayRecords,
@@ -53,23 +54,6 @@ const AVATAR_FAILURE_TTL_MS = 60_000;
const READY_RETRY_COOLDOWN_MS = 5_000;
const CONTACTS_CACHE_SCHEMA_VERSION = 2;
-type EnteWasmModule = typeof import("ente-wasm");
-
-let _wasmPromise: Promise<EnteWasmModule> | undefined;
-
-const enteWasm = async () => {
- if (!_wasmPromise) {
- const load = import("ente-wasm");
- _wasmPromise = load.catch((error: unknown) => {
- if (_wasmPromise === load) {
- _wasmPromise = undefined;
- }
- throw error;
- });
- }
- return _wasmPromise;
-};
-
interface RemoteContactRecord {
id: string;
contactUserId: number | bigint;
@@ -345,7 +329,7 @@ const ensureContactsCtxOpen = async ({
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- const { contacts_open_ctx } = await enteWasm();
+ const { contacts_open_ctx } = await loadEnteWasm();
const openedCtx = await contacts_open_ctx({
baseUrl: baseURL,
authToken,
diff --git a/web/packages/contacts/package.json b/web/packages/contacts/package.json
index 1ab06ef687..a7192ef223 100644
--- a/web/packages/contacts/package.json
+++ b/web/packages/contacts/package.json
@@ -5,7 +5,7 @@
"main": "./index.ts",
"types": "./index.ts",
"scripts": {
- "test": "vitest"
+ "test": "vitest --run"
},
"dependencies": {
"@mui/icons-material": "^7.3.4",
diff --git a/web/packages/wasm/load.test.ts b/web/packages/wasm/load.test.ts
new file mode 100644
index 0000000000..413b35c39c
--- /dev/null
+++ b/web/packages/wasm/load.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, expect, test, vi } from "vitest";
+
+afterEach(() => {
+ vi.resetModules();
+ vi.restoreAllMocks();
+});
+
+test("loadEnteWasm shares the same import promise", async () => {
+ const wasmModule = { crypto_init: vi.fn() };
+ const importFactory = vi.fn(() => Promise.resolve(wasmModule));
+ vi.doMock("ente-wasm", importFactory);
+
+ const { loadEnteWasm } = await import("./load");
+
+ const first = loadEnteWasm();
+ const second = loadEnteWasm();
+
+ expect(first).toBe(second);
+ await expect(first).resolves.toMatchObject({
+ crypto_init: wasmModule.crypto_init,
+ });
+ await expect(second).resolves.toMatchObject({
+ crypto_init: wasmModule.crypto_init,
+ });
+ expect(importFactory).toHaveBeenCalledTimes(1);
+});
+
+test("loadCryptoReadyEnteWasm initializes crypto once", async () => {
+ const crypto_init = vi.fn();
+ const wasmModule = { crypto_init };
+ const importFactory = vi.fn(() => Promise.resolve(wasmModule));
+ vi.doMock("ente-wasm", importFactory);
+
+ const { loadCryptoReadyEnteWasm } = await import("./load");
+
+ const first = loadCryptoReadyEnteWasm();
+ const second = loadCryptoReadyEnteWasm();
+
+ expect(first).toBe(second);
+
+ const [firstModule, secondModule] = await Promise.all([first, second]);
+ expect(firstModule.crypto_init).toBe(crypto_init);
+ expect(secondModule.crypto_init).toBe(crypto_init);
+ expect(importFactory).toHaveBeenCalledTimes(1);
+ expect(crypto_init).toHaveBeenCalledTimes(1);
+});
+
+test("loadCryptoReadyEnteWasm retries after crypto init failure", async () => {
+ let attempts = 0;
+ const crypto_init = vi.fn(() => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw new Error("init failed");
+ }
+ });
+ const wasmModule = { crypto_init };
+ vi.doMock("ente-wasm", () => wasmModule);
+
+ const { loadCryptoReadyEnteWasm } = await import("./load");
+
+ await expect(loadCryptoReadyEnteWasm()).rejects.toThrow("init failed");
+ await expect(loadCryptoReadyEnteWasm()).resolves.toMatchObject({
+ crypto_init,
+ });
+ expect(crypto_init).toHaveBeenCalledTimes(2);
+});
+
+test("loadEnteWasm retries after a failed load attempt", async () => {
+ const wasmModule = { crypto_init: vi.fn() };
+ let attempts = 0;
+ vi.doMock("ente-wasm", () => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw new Error("import failed");
+ }
+ return Promise.resolve(wasmModule);
+ });
+
+ const { loadEnteWasm } = await import("./load");
+
+ await expect(loadEnteWasm()).rejects.toBeTruthy();
+ await expect(loadEnteWasm()).resolves.toMatchObject({
+ crypto_init: wasmModule.crypto_init,
+ });
+ expect(attempts).toBe(2);
+});
diff --git a/web/packages/wasm/load.ts b/web/packages/wasm/load.ts
new file mode 100644
index 0000000000..06f0136826
--- /dev/null
+++ b/web/packages/wasm/load.ts
@@ -0,0 +1,33 @@
+type EnteWasmModule = typeof import("ente-wasm");
+
+let wasmPromise: Promise<EnteWasmModule> | undefined;
+let cryptoReadyPromise: Promise<EnteWasmModule> | undefined;
+
+/**
+ * Load `ente-wasm` once and return the shared module instance.
+ *
+ * The first call performs the dynamic import. Later calls reuse the same
+ * promise, so all consumers share one loader path.
+ */
+export const loadEnteWasm = (): Promise<EnteWasmModule> =>
+ (wasmPromise ??= import("ente-wasm").catch((error: unknown) => {
+ wasmPromise = undefined;
+ throw error;
+ }));
+
+/**
+ * Load `ente-wasm`, initialize the crypto backend, and return the ready
+ * module.
+ *
+ * The first call runs `crypto_init()`. Later calls reuse the same promise.
+ */
+export const loadCryptoReadyEnteWasm = (): Promise<EnteWasmModule> =>
+ (cryptoReadyPromise ??= loadEnteWasm()
+ .then((wasm) => {
+ wasm.crypto_init();
+ return wasm;
+ })
+ .catch((error: unknown) => {
+ cryptoReadyPromise = undefined;
+ throw error;
+ }));
diff --git a/web/packages/wasm/package.json b/web/packages/wasm/package.json
index 99879089f8..37839fbd7f 100644
--- a/web/packages/wasm/package.json
+++ b/web/packages/wasm/package.json
@@ -6,16 +6,17 @@
".": {
"types": "./pkg/ente_wasm.d.ts",
"import": "./pkg/ente_wasm.js"
+ },
+ "./load": {
+ "types": "./load.ts",
+ "import": "./load.ts"
}
},
"module": "./pkg/ente_wasm.js",
"types": "./pkg/ente_wasm.d.ts",
- "files": [
- "pkg"
- ],
"scripts": {
"build": "wasm-pack build --target bundler",
- "test": "vitest"
+ "test": "vitest --run"
},
"devDependencies": {
"ente-build-config": "*",