Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use app WASM for session crypto and check unused exports

Manav Rathi19df576e784c
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 20b7cc6510..db1b06b300 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2395,6 +2395,13 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "ente-auth-wasm"
+version = "0.0.0"
+dependencies = [
+ "ente-wasm-lib",
+]
+
[[package]]
name = "ente-cast"
version = "0.0.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index fc9c2b55ed..91550b912c 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -12,6 +12,7 @@ members = [
"bindings/uniffi/cast",
"bindings/uniffi/ensu",
"bindings/uniffi/log",
+ "bindings/wasm/auth",
"bindings/wasm/cast",
"bindings/wasm/ensu",
"bindings/wasm/legacy",
diff --git a/rust/bindings/wasm/auth/Cargo.toml b/rust/bindings/wasm/auth/Cargo.toml
new file mode 100644
index 0000000000..c46aecc89a
--- /dev/null
+++ b/rust/bindings/wasm/auth/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "ente-auth-wasm"
+edition.workspace = true
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-wasm-lib = { workspace = true, features = ["crypto-blob", "session"] }
+
+[lints]
+workspace = true
diff --git a/rust/bindings/wasm/auth/src/lib.rs b/rust/bindings/wasm/auth/src/lib.rs
new file mode 100644
index 0000000000..786e389426
--- /dev/null
+++ b/rust/bindings/wasm/auth/src/lib.rs
@@ -0,0 +1 @@
+use ente_wasm_lib as _;
diff --git a/rust/bindings/wasm/lib/Cargo.toml b/rust/bindings/wasm/lib/Cargo.toml
index bc4ce184d7..b58bfbb3da 100644
--- a/rust/bindings/wasm/lib/Cargo.toml
+++ b/rust/bindings/wasm/lib/Cargo.toml
@@ -11,7 +11,8 @@ contacts = [
"dep:wasm-bindgen-futures",
]
crypto = ["dep:serde", "dep:serde-wasm-bindgen", "dep:tsify"]
-crypto-file = ["crypto", "dep:md-5"]
+crypto-blob = ["crypto"]
+crypto-file = ["crypto-blob", "dep:md-5"]
crypto-seal = ["crypto"]
locker = ["session", "dep:ente-locker"]
prelogin = ["accounts", "crypto"]
diff --git a/rust/bindings/wasm/lib/src/crypto.rs b/rust/bindings/wasm/lib/src/crypto.rs
index a41bf84ccd..1164b5eedd 100644
--- a/rust/bindings/wasm/lib/src/crypto.rs
+++ b/rust/bindings/wasm/lib/src/crypto.rs
@@ -5,6 +5,8 @@ use wasm_bindgen::prelude::*;
use crate::EncryptedBox;
+#[cfg(feature = "crypto-blob")]
+mod blob;
#[cfg(feature = "crypto-file")]
mod file;
diff --git a/rust/bindings/wasm/lib/src/crypto/blob.rs b/rust/bindings/wasm/lib/src/crypto/blob.rs
new file mode 100644
index 0000000000..5e146d46a6
--- /dev/null
+++ b/rust/bindings/wasm/lib/src/crypto/blob.rs
@@ -0,0 +1,55 @@
+use ente_core::{b64, crypto};
+use serde::Serialize;
+use tsify::Tsify;
+use wasm_bindgen::prelude::*;
+
+use super::Error;
+
+#[derive(Serialize, Tsify)]
+#[serde(rename_all = "camelCase")]
+pub struct EncryptedBlob {
+ pub encrypted_data: String,
+ pub decryption_header: String,
+}
+
+#[wasm_bindgen(js_name = cryptoEncryptBlob)]
+pub fn crypto_encrypt_blob(
+ data: &[u8],
+ key_b64: &str,
+) -> Result<<EncryptedBlob as Tsify>::JsType, Error> {
+ let key = b64::decode(key_b64)?;
+
+ let out = crypto::blob::encrypt(data, &crypto::Key::try_from_slice(&key)?)?;
+ EncryptedBlob {
+ encrypted_data: b64::encode(&out.encrypted_data),
+ decryption_header: b64::encode(out.decryption_header.as_bytes()),
+ }
+ .into_js()
+ .map_err(Into::into)
+}
+
+#[wasm_bindgen(js_name = cryptoDecryptBlobLegacy)]
+pub fn crypto_decrypt_blob_legacy(
+ encrypted_data_b64: &str,
+ decryption_header_b64: &str,
+ key_b64: &str,
+) -> Result<Vec<u8>, Error> {
+ crypto_decrypt_blob_legacy_bytes(
+ &b64::decode(encrypted_data_b64)?,
+ &b64::decode(decryption_header_b64)?,
+ &b64::decode(key_b64)?,
+ )
+}
+
+#[wasm_bindgen(js_name = cryptoDecryptBlobLegacyBytes)]
+pub fn crypto_decrypt_blob_legacy_bytes(
+ encrypted_data: &[u8],
+ decryption_header: &[u8],
+ key: &[u8],
+) -> Result<Vec<u8>, Error> {
+ Ok(crypto::blob::decrypt_legacy(
+ encrypted_data,
+ &crypto::Header::try_from_slice(decryption_header)?,
+ &crypto::Key::try_from_slice(key)?,
+ )?)
+}
diff --git a/rust/bindings/wasm/lib/src/crypto/file.rs b/rust/bindings/wasm/lib/src/crypto/file.rs
index de2c835d7d..e817b5177a 100644
--- a/rust/bindings/wasm/lib/src/crypto/file.rs
+++ b/rust/bindings/wasm/lib/src/crypto/file.rs
@@ -93,63 +93,6 @@ pub fn crypto_md5_base64(data: Vec<u8>) -> String {
b64::encode(&digest)
}
-#[derive(Serialize, Tsify)]
-#[serde(rename_all = "camelCase")]
-pub struct EncryptedBlob {
- pub encrypted_data: String,
- pub decryption_header: String,
-}
-
-#[wasm_bindgen(js_name = cryptoEncryptBlob)]
-pub fn crypto_encrypt_blob(
- data: &[u8],
- key_b64: &str,
-) -> Result<<EncryptedBlob as Tsify>::JsType, Error> {
- let key = b64::decode(key_b64)?;
-
- let out = crypto::blob::encrypt(data, &crypto::Key::try_from_slice(&key)?)?;
- EncryptedBlob {
- encrypted_data: b64::encode(&out.encrypted_data),
- decryption_header: b64::encode(out.decryption_header.as_bytes()),
- }
- .into_js()
- .map_err(Into::into)
-}
-
-#[wasm_bindgen(js_name = cryptoDecryptBlob)]
-pub fn crypto_decrypt_blob(
- encrypted_data_b64: &str,
- decryption_header_b64: &str,
- key_b64: &str,
-) -> Result<Vec<u8>, Error> {
- let ciphertext = b64::decode(encrypted_data_b64)?;
- let header = b64::decode(decryption_header_b64)?;
- let key = b64::decode(key_b64)?;
-
- Ok(crypto::blob::decrypt(
- &ciphertext,
- &crypto::Header::try_from_slice(&header)?,
- &crypto::Key::try_from_slice(&key)?,
- )?)
-}
-
-#[wasm_bindgen(js_name = cryptoDecryptBlobLegacy)]
-pub fn crypto_decrypt_blob_legacy(
- encrypted_data_b64: &str,
- decryption_header_b64: &str,
- key_b64: &str,
-) -> Result<Vec<u8>, Error> {
- let ciphertext = b64::decode(encrypted_data_b64)?;
- let header = b64::decode(decryption_header_b64)?;
- let key = b64::decode(key_b64)?;
-
- Ok(crypto::blob::decrypt_legacy(
- &ciphertext,
- &crypto::Header::try_from_slice(&header)?,
- &crypto::Key::try_from_slice(&key)?,
- )?)
-}
-
#[derive(Serialize, Tsify)]
#[serde(rename_all = "camelCase")]
pub struct EncryptedStreamResult {
diff --git a/web/apps/auth/package.json b/web/apps/auth/package.json
index 6f386b2efa..3005925a58 100644
--- a/web/apps/auth/package.json
+++ b/web/apps/auth/package.json
@@ -8,6 +8,7 @@
"@hugeicons/react": "1.1.6",
"@noble/hashes": "2.2.0",
"ente-accounts": "*",
+ "ente-auth-wasm": "*",
"ente-base": "*",
"otpauth": "9.5.1"
},
diff --git a/web/apps/auth/src/pages/_app.tsx b/web/apps/auth/src/pages/_app.tsx
index 6c76c26a62..5a24f08743 100644
--- a/web/apps/auth/src/pages/_app.tsx
+++ b/web/apps/auth/src/pages/_app.tsx
@@ -1,9 +1,9 @@
+import { authLogout } from "@/services/logout";
import "@fontsource-variable/inter";
import "@fontsource-variable/outfit";
import { CssBaseline } from "@mui/material";
import { ThemeProvider } from "@mui/material/styles";
import { savedLocalUser } from "ente-accounts/services/accounts-db";
-import { accountLogout } from "ente-accounts/services/logout";
import { staticAppTitle } from "ente-base/app";
import { CustomHead } from "ente-base/components/Head";
import {
@@ -35,9 +35,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
logStartupBanner(savedLocalUser()?.id);
}, []);
- const logout = useCallback(() => {
- void accountLogout().then(() => window.location.replace("/"));
- }, []);
+ const logout = useCallback(() => void authLogout(), []);
const baseContext = useMemo(
() => deriveBaseContext({ logout, showMiniDialog }),
diff --git a/web/apps/auth/src/pages/auth.tsx b/web/apps/auth/src/pages/auth.tsx
index b8a09e0268..0ff64695c1 100644
--- a/web/apps/auth/src/pages/auth.tsx
+++ b/web/apps/auth/src/pages/auth.tsx
@@ -1,3 +1,4 @@
+import { masterKeyFromSession } from "@/services/account-keys";
import { generateOTPs, type Code } from "@/services/code";
import { getAuthCodesAndTimeOffset } from "@/services/remote";
import { prettyFormatCode } from "@/utils/format";
@@ -15,7 +16,6 @@ import {
} from "@mui/material";
import { useColorScheme } from "@mui/material/styles";
import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
-import { masterKeyFromSession } from "ente-accounts/services/prelogin-session";
import { stashRedirect } from "ente-accounts/services/redirect";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { LoadingIndicator } from "ente-base/components/loaders";
diff --git a/web/apps/auth/src/pages/share.tsx b/web/apps/auth/src/pages/share.tsx
index f4e1dfa185..caeaa3a7e7 100644
--- a/web/apps/auth/src/pages/share.tsx
+++ b/web/apps/auth/src/pages/share.tsx
@@ -1,7 +1,7 @@
import { prettyFormatCode } from "@/utils/format";
import { Box, Button, Stack, Typography, useTheme } from "@mui/material";
+import { decryptMetadataJSONBytes } from "ente-auth-wasm";
import { EnteLogo } from "ente-base/components/EnteLogo";
-import { decryptMetadataJSON } from "ente-base/crypto";
import React, { useEffect, useMemo, useState } from "react";
interface SharedCode {
@@ -47,7 +47,7 @@ const Page: React.FC = () => {
}
try {
- const decryptedCode = (await decryptMetadataJSON(
+ const decryptedCode = (await decryptMetadataJSONBytes(
{
encryptedData: base64URLToBytes(data),
decryptionHeader: base64URLToBytes(header),
diff --git a/web/apps/auth/src/pages/two-factor/setup.tsx b/web/apps/auth/src/pages/two-factor/setup.tsx
index be83cb097c..0bab7dbdaa 100644
--- a/web/apps/auth/src/pages/two-factor/setup.tsx
+++ b/web/apps/auth/src/pages/two-factor/setup.tsx
@@ -1,10 +1,8 @@
+import { encryptWithRecoveryKey } from "@/services/recovery-key";
import TwoFactorSetupPage from "ente-accounts/pages/two-factor/setup";
-import { encryptWithPreloginRecoveryKey } from "ente-accounts/services/recovery-key";
export default function Page() {
return (
- <TwoFactorSetupPage
- encryptWithRecoveryKey={encryptWithPreloginRecoveryKey}
- />
+ <TwoFactorSetupPage encryptWithRecoveryKey={encryptWithRecoveryKey} />
);
}
diff --git a/web/apps/auth/src/services/account-keys.ts b/web/apps/auth/src/services/account-keys.ts
new file mode 100644
index 0000000000..048aebd4e4
--- /dev/null
+++ b/web/apps/auth/src/services/account-keys.ts
@@ -0,0 +1,4 @@
+import { decryptBox } from "ente-auth-wasm";
+import { readMasterKeyFromSession } from "ente-base/session-storage";
+
+export const masterKeyFromSession = () => readMasterKeyFromSession(decryptBox);
diff --git a/web/apps/auth/src/services/authenticated-session.ts b/web/apps/auth/src/services/authenticated-session.ts
new file mode 100644
index 0000000000..830da8efad
--- /dev/null
+++ b/web/apps/auth/src/services/authenticated-session.ts
@@ -0,0 +1,65 @@
+import {
+ ensureLocalUser,
+ ensureSavedKeyAttributes,
+} from "ente-accounts/services/user";
+import { openSession, type Session } from "ente-auth-wasm";
+import { clientPackageName } from "ente-base/app";
+import { apiOrigin } from "ente-base/origins";
+import { savedAuthToken } from "ente-base/token";
+import { masterKeyFromSession } from "./account-keys";
+
+let current: { key: string; opening: Promise<Session> } | undefined;
+let generation = 0;
+
+export const ensureAuthenticatedSession = async () => {
+ const startedGeneration = generation;
+ const userID = ensureLocalUser().id;
+ const [baseUrl, authToken, masterKeyB64] = await Promise.all([
+ apiOrigin(),
+ savedAuthToken(),
+ masterKeyFromSession(),
+ ]);
+ if (startedGeneration !== generation) {
+ throw new Error("Authenticated session was cleared");
+ }
+ if (!masterKeyB64) throw new Error("Missing current master key");
+ if (!authToken) throw new Error("Missing auth token");
+
+ const key = `${baseUrl}:${userID}`;
+ if (current?.key !== key) {
+ const opening = openSession({
+ baseUrl,
+ authToken,
+ userID,
+ masterKeyB64,
+ keyAttributes: ensureSavedKeyAttributes(),
+ clientPackage: clientPackageName,
+ })
+ .then((session) => {
+ if (current?.opening !== opening) {
+ session.free();
+ throw new Error("Authenticated session was cleared");
+ }
+ return session;
+ })
+ .catch((error: unknown) => {
+ if (current?.opening === opening) current = undefined;
+ throw error;
+ });
+ current = { key, opening };
+ }
+
+ const entry = current;
+ const session = await entry.opening;
+ if (current !== entry) {
+ throw new Error("Authenticated session was cleared");
+ }
+ session.updateAuthToken(authToken);
+ return session;
+};
+
+export const clearAuthenticatedSession = () => {
+ generation++;
+ // In-flight calls may still borrow the handle; wasm-bindgen finalizes it.
+ current = undefined;
+};
diff --git a/web/apps/auth/src/services/logout.ts b/web/apps/auth/src/services/logout.ts
new file mode 100644
index 0000000000..2790fd47af
--- /dev/null
+++ b/web/apps/auth/src/services/logout.ts
@@ -0,0 +1,8 @@
+import { accountLogout } from "ente-accounts/services/logout";
+import { clearAuthenticatedSession } from "./authenticated-session";
+
+export const authLogout = async () => {
+ clearAuthenticatedSession();
+ await accountLogout();
+ window.location.replace("/");
+};
diff --git a/web/apps/auth/src/services/recovery-key.ts b/web/apps/auth/src/services/recovery-key.ts
new file mode 100644
index 0000000000..bc35bfe266
--- /dev/null
+++ b/web/apps/auth/src/services/recovery-key.ts
@@ -0,0 +1,5 @@
+import { encryptBoxWithRecoveryKey } from "ente-auth-wasm";
+import { ensureAuthenticatedSession } from "./authenticated-session";
+
+export const encryptWithRecoveryKey = async (data: string) =>
+ encryptBoxWithRecoveryKey(await ensureAuthenticatedSession(), data);
diff --git a/web/apps/auth/src/services/remote.ts b/web/apps/auth/src/services/remote.ts
index 7dd15967d7..d329c48750 100644
--- a/web/apps/auth/src/services/remote.ts
+++ b/web/apps/auth/src/services/remote.ts
@@ -1,5 +1,5 @@
import { codeFromURIString, type Code } from "@/services/code";
-import { decryptBox, decryptMetadataJSON } from "ente-base/crypto";
+import { decryptBox, decryptMetadataJSON } from "ente-auth-wasm";
import {
authenticatedRequestHeaders,
ensureOk,
diff --git a/web/apps/locker/src/components/sidebar/LockerRecoveryKeyDrawer.tsx b/web/apps/locker/src/components/sidebar/LockerRecoveryKeyDrawer.tsx
index c18bdebef2..b66cd482ab 100644
--- a/web/apps/locker/src/components/sidebar/LockerRecoveryKeyDrawer.tsx
+++ b/web/apps/locker/src/components/sidebar/LockerRecoveryKeyDrawer.tsx
@@ -1,4 +1,4 @@
-import { recoveryKeyMnemonic } from "@/services/authenticated-session";
+import { recoveryKeyMnemonic } from "@/services/recovery-key";
import {
Box,
Button,
diff --git a/web/apps/locker/src/components/sidebar/LockerSecurityDrawer.tsx b/web/apps/locker/src/components/sidebar/LockerSecurityDrawer.tsx
index 3cac3db9d0..04603a5e97 100644
--- a/web/apps/locker/src/components/sidebar/LockerSecurityDrawer.tsx
+++ b/web/apps/locker/src/components/sidebar/LockerSecurityDrawer.tsx
@@ -1,4 +1,4 @@
-import { generatePasskeyRecovery } from "@/services/authenticated-session";
+import { generatePasskeyRecovery } from "@/services/recovery-key";
import {
ComputerPhoneSyncIcon,
Key01Icon,
diff --git a/web/apps/locker/src/pages/_app.tsx b/web/apps/locker/src/pages/_app.tsx
index 4f98662dc6..d590810624 100644
--- a/web/apps/locker/src/pages/_app.tsx
+++ b/web/apps/locker/src/pages/_app.tsx
@@ -37,9 +37,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
logStartupBanner(savedLocalUser()?.id);
}, []);
- const logout = useCallback(() => {
- void lockerLogout().then(() => window.location.replace("/login"));
- }, []);
+ const logout = useCallback(() => void lockerLogout(), []);
useEffect(() => {
void isSavedUserTokenMismatch()
diff --git a/web/apps/locker/src/pages/two-factor/setup.tsx b/web/apps/locker/src/pages/two-factor/setup.tsx
index aad48bf538..0bab7dbdaa 100644
--- a/web/apps/locker/src/pages/two-factor/setup.tsx
+++ b/web/apps/locker/src/pages/two-factor/setup.tsx
@@ -1,4 +1,4 @@
-import { encryptWithRecoveryKey } from "@/services/authenticated-session";
+import { encryptWithRecoveryKey } from "@/services/recovery-key";
import TwoFactorSetupPage from "ente-accounts/pages/two-factor/setup";
export default function Page() {
diff --git a/web/apps/locker/src/services/account-keys.ts b/web/apps/locker/src/services/account-keys.ts
index 628c275d4e..7930a9593a 100644
--- a/web/apps/locker/src/services/account-keys.ts
+++ b/web/apps/locker/src/services/account-keys.ts
@@ -1,8 +1,4 @@
-import { createSessionStorage } from "ente-base/session-storage";
-import { decryptBox, encryptBox, generateKey } from "ente-locker-wasm";
+import { readMasterKeyFromSession } from "ente-base/session-storage";
+import { decryptBox } from "ente-locker-wasm";
-export const { masterKeyFromSession } = createSessionStorage({
- decryptBox,
- encryptBox,
- generateKey,
-});
+export const masterKeyFromSession = () => readMasterKeyFromSession(decryptBox);
diff --git a/web/apps/locker/src/services/authenticated-session.ts b/web/apps/locker/src/services/authenticated-session.ts
index ff49bef707..3073eeb034 100644
--- a/web/apps/locker/src/services/authenticated-session.ts
+++ b/web/apps/locker/src/services/authenticated-session.ts
@@ -1,4 +1,3 @@
-import { createAuthenticatedRecoveryKeyOps } from "ente-accounts/services/authenticated-recovery-key";
import {
ensureLocalUser,
ensureSavedKeyAttributes,
@@ -7,12 +6,7 @@ import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { apiOrigin } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
import { openSession as openLegacySession } from "ente-legacy-wasm/authenticated";
-import {
- encryptBoxWithRecoveryKey,
- generateKey,
- openSession,
- type Session,
-} from "ente-locker-wasm";
+import { openSession, type Session } from "ente-locker-wasm";
import { masterKeyFromSession } from "./account-keys";
const lockerSessions = sessionCache(openSession);
@@ -55,16 +49,6 @@ export const clearAuthenticatedSession = () => {
legacySessions.clear();
};
-export const {
- encryptWithRecoveryKey,
- generatePasskeyRecovery,
- recoveryKeyMnemonic,
-} = createAuthenticatedRecoveryKeyOps({
- ensureSession: ensureAuthenticatedSession,
- encryptBox: encryptBoxWithRecoveryKey,
- generateKey,
-});
-
function sessionCache<T extends Pick<Session, "free" | "updateAuthToken">>(
open: (config: Parameters<typeof openSession>[0]) => Promise<T>,
) {
diff --git a/web/apps/locker/src/services/logout.ts b/web/apps/locker/src/services/logout.ts
index 0fca2e437b..d0ff2bb7d9 100644
--- a/web/apps/locker/src/services/logout.ts
+++ b/web/apps/locker/src/services/logout.ts
@@ -51,7 +51,8 @@ export const lockerLogout = async () => {
ignoreError("Contacts", error);
}
- // Final sweep before the caller reloads
+ // Final sweep and reload
await logoutClearStateAgain();
+ window.location.replace("/login");
};
diff --git a/web/apps/locker/src/services/recovery-key.ts b/web/apps/locker/src/services/recovery-key.ts
new file mode 100644
index 0000000000..2c7987c8ec
--- /dev/null
+++ b/web/apps/locker/src/services/recovery-key.ts
@@ -0,0 +1,13 @@
+import { createAuthenticatedRecoveryKeyOps } from "ente-accounts/services/authenticated-recovery-key";
+import { encryptBoxWithRecoveryKey, generateKey } from "ente-locker-wasm";
+import { ensureAuthenticatedSession } from "./authenticated-session";
+
+export const {
+ encryptWithRecoveryKey,
+ generatePasskeyRecovery,
+ recoveryKeyMnemonic,
+} = createAuthenticatedRecoveryKeyOps({
+ ensureSession: ensureAuthenticatedSession,
+ encryptBox: encryptBoxWithRecoveryKey,
+ generateKey,
+});
diff --git a/web/apps/locker/tests/logout.test.ts b/web/apps/locker/tests/logout.test.ts
index a21060763a..318e3d9158 100644
--- a/web/apps/locker/tests/logout.test.ts
+++ b/web/apps/locker/tests/logout.test.ts
@@ -1,19 +1,11 @@
import { logoutClearStateAgain } from "ente-accounts/services/logout";
import { logoutContacts } from "ente-contacts";
-import { expect, test, vi } from "vitest";
+import { afterEach, expect, test, vi } from "vitest";
import { openAuthenticatedSession } from "../src/services/authenticated-session";
import { lockerLogout } from "../src/services/logout";
-const {
- apiOrigin,
- encryptBoxWithRecoveryKey,
- generateKey,
- openSession,
- accountLogout,
-} = vi.hoisted(() => ({
+const { apiOrigin, openSession, accountLogout } = vi.hoisted(() => ({
apiOrigin: vi.fn<() => Promise<string>>(),
- encryptBoxWithRecoveryKey: vi.fn(),
- generateKey: vi.fn(),
openSession: vi.fn(() =>
Promise.resolve({ free: vi.fn(), updateAuthToken: vi.fn() }),
),
@@ -52,19 +44,19 @@ vi.mock("ente-accounts/services/logout", () => ({
accountLogout,
logoutClearStateAgain: vi.fn(),
}));
-vi.mock("ente-locker-wasm", () => ({
- encryptBoxWithRecoveryKey,
- generateKey,
- openSession,
-}));
+vi.mock("ente-locker-wasm", () => ({ openSession }));
vi.mock("ente-legacy-wasm/authenticated", () => ({ openSession }));
vi.mock("../src/services/locker-db", () => ({ clearLockerDB: vi.fn() }));
+afterEach(() => vi.unstubAllGlobals());
+
test("logout rejects pending sessions while account cleanup is pending", async () => {
const origin = Promise.withResolvers<string>();
const accountCleanup = Promise.withResolvers<undefined>();
apiOrigin.mockReturnValue(origin.promise);
accountLogout.mockReturnValue(accountCleanup.promise);
+ const replace = vi.fn();
+ vi.stubGlobal("window", { location: { replace } });
const opening = openAuthenticatedSession(1, "token", "key");
const loggingOut = lockerLogout();
@@ -75,10 +67,12 @@ test("logout rejects pending sessions while account cleanup is pending", async (
"Authenticated session was cleared",
);
expect(openSession).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
} finally {
accountCleanup.resolve(undefined);
await loggingOut;
}
expect(logoutContacts).toHaveBeenCalledOnce();
expect(logoutClearStateAgain).toHaveBeenCalledOnce();
+ expect(replace).toHaveBeenCalledExactlyOnceWith("/login");
});
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 4b9390c965..dcd9fdc587 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -8,11 +8,11 @@ import { ReferralSettings } from "@/components/sidebar/ReferralSettings";
import { SessionsSettings } from "@/components/sidebar/SessionsSettings";
import { TwoFactorSettings } from "@/components/sidebar/TwoFactorSettings";
import { downloadAppDialogAttributes } from "@/components/utils/download";
+import exportService from "@/services/export";
import {
generatePasskeyRecovery,
recoveryKeyMnemonic,
-} from "@/services/authenticated-session";
-import exportService from "@/services/export";
+} from "@/services/recovery-key";
import { performSidebarAction as performSidebarRegistryAction } from "@/services/search/sidebar-search-registry";
import {
Delete02Icon,
diff --git a/web/apps/photos/src/components/utils/use-app-lock.ts b/web/apps/photos/src/components/utils/use-app-lock.ts
index 8c18a85aa5..91908acce1 100644
--- a/web/apps/photos/src/components/utils/use-app-lock.ts
+++ b/web/apps/photos/src/components/utils/use-app-lock.ts
@@ -3,7 +3,7 @@ import {
subscribeMainWindowFocus,
} from "ente-base/electron";
import log from "ente-base/log";
-import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-base/session";
+import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-new/photos/services/account-keys";
import {
appLockSnapshot,
clearAutoLockBlurSuppression,
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 17a1be86fa..5fa02d0d32 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -82,7 +82,6 @@ import { subscribeMainWindowFocus } from "ente-base/electron";
import { isNamedError } from "ente-base/error";
import { hasPendingAlbumToJoin } from "ente-base/join-album";
import log from "ente-base/log";
-import { masterKeyFromSession } from "ente-base/session";
import {
clearSessionStorage,
haveMasterKeyInSession,
@@ -105,6 +104,7 @@ import {
useSettingsSnapshot,
useUserDetailsSnapshot,
} from "ente-new/photos/components/utils/use-snapshot";
+import { masterKeyFromSession } from "ente-new/photos/services/account-keys";
import { reauthenticateWithAppLock } from "ente-new/photos/services/app-lock";
import {
addToCollection,
diff --git a/web/apps/photos/src/pages/index.tsx b/web/apps/photos/src/pages/index.tsx
index e2535e7def..d6ccb8803d 100644
--- a/web/apps/photos/src/pages/index.tsx
+++ b/web/apps/photos/src/pages/index.tsx
@@ -14,13 +14,11 @@ import {
} from "ente-base/join-album";
import log from "ente-base/log";
import { customAPIHost } from "ente-base/origins";
-import {
- masterKeyFromSession,
- updateSessionFromElectronSafeStorageIfNeeded,
-} from "ente-base/session";
+import { haveMasterKeyInSession } from "ente-base/session-storage";
import { savedAuthToken } from "ente-base/token";
import { canAccessIndexedDB } from "ente-gallery/services/files-db";
import { DevSettings } from "ente-new/photos/components/DevSettings";
+import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-new/photos/services/account-keys";
import { t } from "i18next";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
@@ -95,7 +93,7 @@ const Page: React.FC = () => {
}
await updateSessionFromElectronSafeStorageIfNeeded();
- if ((await masterKeyFromSession()) && (await savedAuthToken())) {
+ if (haveMasterKeyInSession() && (await savedAuthToken())) {
await router.push("/gallery");
} else if (savedPartialLocalUser()?.email) {
await router.push("/verify");
diff --git a/web/apps/photos/src/pages/two-factor/setup.tsx b/web/apps/photos/src/pages/two-factor/setup.tsx
index aad48bf538..0bab7dbdaa 100644
--- a/web/apps/photos/src/pages/two-factor/setup.tsx
+++ b/web/apps/photos/src/pages/two-factor/setup.tsx
@@ -1,4 +1,4 @@
-import { encryptWithRecoveryKey } from "@/services/authenticated-session";
+import { encryptWithRecoveryKey } from "@/services/recovery-key";
import TwoFactorSetupPage from "ente-accounts/pages/two-factor/setup";
export default function Page() {
diff --git a/web/apps/photos/src/services/authenticated-session.ts b/web/apps/photos/src/services/authenticated-session.ts
index a6d47122bb..62efcf9753 100644
--- a/web/apps/photos/src/services/authenticated-session.ts
+++ b/web/apps/photos/src/services/authenticated-session.ts
@@ -1,23 +1,16 @@
-import { createAuthenticatedRecoveryKeyOps } from "ente-accounts/services/authenticated-recovery-key";
import {
ensureLocalUser,
ensureSavedKeyAttributes,
} from "ente-accounts/services/user";
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { apiOrigin } from "ente-base/origins";
-import { masterKeyFromSession } from "ente-base/session";
import { savedAuthToken } from "ente-base/token";
+import { masterKeyFromSession } from "ente-new/photos/services/account-keys";
import {
bindCollectionKeyOpener,
unbindCollectionKeyOpener,
} from "ente-new/photos/services/collection";
-import {
- encryptBoxWithRecoveryKey,
- generateKey,
- openCollectionKey,
- openSession,
- type Session,
-} from "ente-photos-wasm";
+import { openCollectionKey, openSession, type Session } from "ente-photos-wasm";
let current: { key: string; opening: Promise<Session> } | undefined;
let generation = 0;
@@ -96,13 +89,3 @@ export const clearAuthenticatedSession = () => {
// In-flight calls may still borrow the handle; wasm-bindgen finalizes it.
current = undefined;
};
-
-export const {
- encryptWithRecoveryKey,
- generatePasskeyRecovery,
- recoveryKeyMnemonic,
-} = createAuthenticatedRecoveryKeyOps({
- ensureSession: ensureAuthenticatedSession,
- encryptBox: encryptBoxWithRecoveryKey,
- generateKey,
-});
diff --git a/web/apps/photos/src/services/recovery-key.ts b/web/apps/photos/src/services/recovery-key.ts
new file mode 100644
index 0000000000..59fbc24d8c
--- /dev/null
+++ b/web/apps/photos/src/services/recovery-key.ts
@@ -0,0 +1,13 @@
+import { createAuthenticatedRecoveryKeyOps } from "ente-accounts/services/authenticated-recovery-key";
+import { encryptBoxWithRecoveryKey, generateKey } from "ente-photos-wasm";
+import { ensureAuthenticatedSession } from "./authenticated-session";
+
+export const {
+ encryptWithRecoveryKey,
+ generatePasskeyRecovery,
+ recoveryKeyMnemonic,
+} = createAuthenticatedRecoveryKeyOps({
+ ensureSession: ensureAuthenticatedSession,
+ encryptBox: encryptBoxWithRecoveryKey,
+ generateKey,
+});
diff --git a/web/apps/photos/tests/authenticated-session.test.ts b/web/apps/photos/tests/authenticated-session.test.ts
index 0b770a235b..5f1bdfaa47 100644
--- a/web/apps/photos/tests/authenticated-session.test.ts
+++ b/web/apps/photos/tests/authenticated-session.test.ts
@@ -46,7 +46,9 @@ vi.mock("ente-accounts/services/user", () => ({
ensureLocalUser: () => ({ id: 1 }),
ensureSavedKeyAttributes: () => keyAttributes,
}));
-vi.mock("ente-base/session", () => ({ masterKeyFromSession }));
+vi.mock("ente-new/photos/services/account-keys", () => ({
+ masterKeyFromSession,
+}));
vi.mock("ente-base/token", () => ({ savedAuthToken }));
vi.mock("ente-new/photos/services/collection", () => ({
bindCollectionKeyOpener,
diff --git a/web/apps/photos/tests/logout.test.ts b/web/apps/photos/tests/logout.test.ts
index c4d6bd5fa1..ba75f8bf5e 100644
--- a/web/apps/photos/tests/logout.test.ts
+++ b/web/apps/photos/tests/logout.test.ts
@@ -27,7 +27,9 @@ vi.mock("ente-base/app", () => ({
isDesktop: false,
}));
vi.mock("ente-base/origins", () => ({ apiOrigin }));
-vi.mock("ente-base/session", () => ({ masterKeyFromSession: vi.fn() }));
+vi.mock("ente-new/photos/services/account-keys", () => ({
+ masterKeyFromSession: vi.fn(),
+}));
vi.mock("ente-base/token", () => ({ savedAuthToken: vi.fn() }));
vi.mock("ente-base/log", () => ({
default: { info: vi.fn(), error: vi.fn() },
diff --git a/web/checks/wasm-exports/check.mjs b/web/checks/wasm-exports/check.mjs
new file mode 100644
index 0000000000..3eddc0e66e
--- /dev/null
+++ b/web/checks/wasm-exports/check.mjs
@@ -0,0 +1,94 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, globSync, readFileSync } from "node:fs";
+import { basename, dirname, relative, resolve } from "node:path";
+import ts from "typescript";
+import { rustFunctionExports, unusedExports } from "./exports.mjs";
+
+const cwd = resolve(import.meta.dirname, "../..");
+const rustDirectory = resolve(cwd, "../rust/bindings/wasm");
+const rustExports = (crate) =>
+ rustFunctionExports(
+ globSync(`${crate}/src/**/*.rs`, { cwd: rustDirectory }).map((file) =>
+ resolve(rustDirectory, file),
+ ),
+ );
+const sharedExports = rustExports("lib");
+const rustOrigins = new Map();
+const files = [];
+for (const manifestPath of globSync("packages/wasm/*/package.json", { cwd })) {
+ const manifest = JSON.parse(
+ readFileSync(resolve(cwd, manifestPath), "utf8"),
+ );
+ if (!manifest.scripts?.build) continue;
+ const directory = resolve(cwd, dirname(manifestPath));
+ const bindings = resolve(
+ directory,
+ "pkg",
+ `${manifest.name.replaceAll("-", "_")}.d.ts`,
+ );
+ if (!existsSync(bindings))
+ throw new Error(`Build WASM before checking exports: ${bindings}`);
+ rustOrigins.set(
+ bindings,
+ new Map([...sharedExports, ...rustExports(basename(directory))]),
+ );
+ files.push(
+ bindings,
+ ...globSync("**/*.ts", {
+ cwd: directory,
+ exclude: [
+ "pkg/**",
+ "tests/**",
+ "**/*.test.ts",
+ "**/*.config.ts",
+ "**/*.d.ts",
+ ],
+ }).map((file) => resolve(directory, file)),
+ );
+}
+
+const projects = globSync("apps/*/tsconfig.json", { cwd }).map((file) => {
+ const parsed = ts.getParsedCommandLineOfConfigFile(
+ resolve(cwd, file),
+ {},
+ {
+ ...ts.sys,
+ onUnRecoverableConfigFileDiagnostic: (error) => {
+ throw new Error(
+ ts.flattenDiagnosticMessageText(error.messageText, "\n"),
+ );
+ },
+ },
+ );
+ if (parsed.errors.length)
+ throw new Error(
+ ts.formatDiagnostics(parsed.errors, {
+ getCanonicalFileName: (file) => file,
+ getCurrentDirectory: () => cwd,
+ getNewLine: () => "\n",
+ }),
+ );
+ const entryFiles = parsed.fileNames.filter(
+ (file) =>
+ /\/src\/pages\/.*\.tsx?$|\/src\/main\.tsx?$/.test(file) &&
+ !/\.test\./.test(file),
+ );
+ if (!entryFiles.length)
+ throw new Error(`No production entrypoints found for ${file}`);
+ return { entryFiles, options: parsed.options };
+});
+
+for (const { file, line, name } of unusedExports(
+ files,
+ projects,
+ rustOrigins,
+)) {
+ console.error(
+ `${relative(cwd, file)}:${line}: ${name} has no production reference`,
+ );
+ process.exitCode = 1;
+}
+execFileSync(process.execPath, ["--test", "checks/wasm-exports/test.mjs"], {
+ cwd,
+ stdio: "inherit",
+});
diff --git a/web/checks/wasm-exports/exports.mjs b/web/checks/wasm-exports/exports.mjs
new file mode 100644
index 0000000000..8b32d19e14
--- /dev/null
+++ b/web/checks/wasm-exports/exports.mjs
@@ -0,0 +1,186 @@
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import ts from "typescript";
+
+const isProductionSource = (source) =>
+ !source.isDeclarationFile &&
+ !/\/(node_modules|tests|__tests__)\/|\.(test|spec)\.[^/]+$/.test(
+ source.fileName,
+ );
+
+const declarationKey = (node) => `${node.getSourceFile().fileName}:${node.pos}`;
+
+export function rustFunctionExports(files) {
+ const exports = new Map();
+ for (const file of files) {
+ const source = readFileSync(file, "utf8");
+ const declaration =
+ /^#\[wasm_bindgen(?:\(([^)]*)\))?\]\s*pub (?:async )?fn (\w+)/gm;
+ for (const match of source.matchAll(declaration)) {
+ const name =
+ /js_name\s*=\s*"?(\w+)/.exec(match[1] ?? "")?.[1] ?? match[2];
+ if (exports.has(name))
+ throw new Error(`Duplicate Rust WASM export: ${name}`);
+ exports.set(name, {
+ file,
+ name,
+ line: source.slice(0, match.index).split("\n").length,
+ });
+ }
+ }
+ return exports;
+}
+
+export function unusedExports(files, projects, rustOrigins = new Map()) {
+ const candidates = new Map();
+ for (const file of files) {
+ const source = ts.createSourceFile(
+ file,
+ readFileSync(file, "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ );
+ const add = (node) => {
+ if (
+ !node.name ||
+ (source.isDeclarationFile && node.name.getText() === "start")
+ )
+ return;
+ if (
+ ts.isObjectBindingPattern(node.name) ||
+ ts.isArrayBindingPattern(node.name)
+ ) {
+ for (const element of node.name.elements) add(element);
+ return;
+ }
+ const name = node.name.getText();
+ const origin = rustOrigins.get(file)?.get(name);
+ if (source.isDeclarationFile && rustOrigins.has(file) && !origin) {
+ throw new Error(`${file}: cannot locate Rust export ${name}`);
+ }
+ candidates.set(declarationKey(node), {
+ key: origin ? `${origin.file}:${name}` : declarationKey(node),
+ file: origin?.file ?? file,
+ name,
+ line:
+ origin?.line ??
+ source.getLineAndCharacterOfPosition(node.getStart()).line +
+ 1,
+ });
+ };
+ for (const node of source.statements) {
+ if (
+ !node.modifiers?.some(
+ (m) => m.kind === ts.SyntaxKind.ExportKeyword,
+ )
+ )
+ continue;
+ if (ts.isFunctionDeclaration(node)) add(node);
+ if (ts.isClassDeclaration(node) && !source.isDeclarationFile)
+ add(node);
+ if (ts.isVariableStatement(node)) {
+ for (const declaration of node.declarationList.declarations)
+ add(declaration);
+ }
+ }
+ }
+
+ const used = new Set();
+ for (const { entryFiles, options } of projects) {
+ const program = withWorkers(entryFiles, options);
+ const checker = program.getTypeChecker();
+ const reference = (symbol) => {
+ if (!symbol) return;
+ if (symbol.flags & ts.SymbolFlags.Alias)
+ symbol = checker.getAliasedSymbol(symbol);
+ for (const root of checker.getRootSymbols(symbol)) {
+ for (const declaration of root.declarations ?? []) {
+ const candidate = candidates.get(
+ declarationKey(declaration),
+ );
+ if (candidate) used.add(candidate.key);
+ }
+ }
+ };
+ for (const source of program.getSourceFiles()) {
+ if (!isProductionSource(source)) continue;
+ const visit = (node) => {
+ if (
+ ts.isImportDeclaration(node) ||
+ ts.isExportDeclaration(node) ||
+ ts.isTypeNode(node)
+ )
+ return;
+ if (
+ ts.isBindingElement(node) &&
+ ts.isObjectBindingPattern(node.parent)
+ ) {
+ const name = node.propertyName ?? node.name;
+ reference(
+ checker.getPropertyOfType(
+ checker.getTypeAtLocation(node.parent),
+ name.getText(),
+ ),
+ );
+ } else if (ts.isShorthandPropertyAssignment(node)) {
+ reference(checker.getShorthandAssignmentValueSymbol(node));
+ } else if (
+ ts.isIdentifier(node) &&
+ (node.parent.name !== node ||
+ ts.isPropertyAccessExpression(node.parent))
+ ) {
+ reference(checker.getSymbolAtLocation(node));
+ } else if (
+ ts.isElementAccessExpression(node) &&
+ ts.isStringLiteral(node.argumentExpression)
+ ) {
+ reference(
+ checker.getPropertyOfType(
+ checker.getTypeAtLocation(node.expression),
+ node.argumentExpression.text,
+ ),
+ );
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ }
+ return [
+ ...new Map(
+ [...candidates.values()]
+ .filter(({ key }) => !used.has(key))
+ .map(({ key, ...candidate }) => [key, candidate]),
+ ).values(),
+ ];
+}
+
+function withWorkers(entryFiles, options) {
+ const roots = new Set(entryFiles);
+ let program;
+ for (;;) {
+ program = ts.createProgram([...roots], options, undefined, program);
+ const previousSize = roots.size;
+ for (const source of program.getSourceFiles()) {
+ if (!isProductionSource(source)) continue;
+ const visit = (node) => {
+ if (
+ ts.isNewExpression(node) &&
+ node.expression.getText(source) === "URL" &&
+ node.arguments?.[0] &&
+ ts.isStringLiteral(node.arguments[0])
+ ) {
+ const file = resolve(
+ dirname(source.fileName),
+ node.arguments[0].text,
+ );
+ if (/\.[jt]sx?$/.test(file) && existsSync(file))
+ roots.add(file);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ if (roots.size === previousSize) return program;
+ }
+}
diff --git a/web/checks/wasm-exports/test.mjs b/web/checks/wasm-exports/test.mjs
new file mode 100644
index 0000000000..501a3c6148
--- /dev/null
+++ b/web/checks/wasm-exports/test.mjs
@@ -0,0 +1,186 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import ts from "typescript";
+import { rustFunctionExports, unusedExports } from "./exports.mjs";
+
+test("production references cross lazy loaders, aliases, destructuring and workers", () => {
+ const directory = mkdtempSync(join(tmpdir(), "wasm-exports-"));
+ const file = (name, contents) => {
+ const path = join(directory, name);
+ writeFileSync(path, contents);
+ return path;
+ };
+ try {
+ const bindings = file(
+ "raw.d.ts",
+ `
+ export function used(): void;
+ export function destructured(): void;
+ export function aliased(): void;
+ export function indexed(): void;
+ export function workerOnly(): void;
+ export function orphan(): void;
+ export function testOnly(): void;
+ export function typeOnly(): void;
+ export function wrapperOnly(): void;
+ export function start(): void;
+ `,
+ );
+ const wrapper = file(
+ "wrapper.ts",
+ `
+ const wasm = () => import("./raw");
+ export const run = async () => {
+ (await wasm()).used();
+ const { destructured: read } = await wasm();
+ read();
+ (await wasm())["indexed"]();
+ };
+ export const unusedForwarder = async () => (await wasm()).wrapperOnly();
+ `,
+ );
+ const entry = file(
+ "entry.ts",
+ `
+ import { run as execute } from "./wrapper";
+ import { aliased as action } from "./raw";
+ execute();
+ action();
+ type Signature = typeof import("./raw").typeOnly;
+ new Worker(new URL("./worker.ts", import.meta.url));
+ `,
+ );
+ file("worker.ts", `import { workerOnly } from "./raw"; workerOnly();`);
+ file("unused.ts", `import { orphan } from "./raw"; orphan();`);
+ file(
+ "binding.test.ts",
+ `import { testOnly } from "./raw"; testOnly();`,
+ );
+ const projects = [
+ {
+ entryFiles: [entry],
+ options: {
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ },
+ },
+ ];
+ const check = () =>
+ unusedExports([bindings, wrapper], projects)
+ .map(({ name }) => name)
+ .sort();
+ assert.deepEqual(check(), [
+ "orphan",
+ "testOnly",
+ "typeOnly",
+ "unusedForwarder",
+ ]);
+
+ file(
+ "wrapper.ts",
+ `export const run = async () => {
+ const wasm = await import("./raw");
+ wasm.used(); wasm.destructured(); wasm.indexed();
+ };`,
+ );
+ assert.deepEqual(check(), [
+ "orphan",
+ "testOnly",
+ "typeOnly",
+ "wrapperOnly",
+ ]);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("copies of a Rust export need one caller across artifacts", () => {
+ const directory = mkdtempSync(join(tmpdir(), "wasm-export-origins-"));
+ const file = (name, contents) => {
+ const path = join(directory, name);
+ writeFileSync(path, contents);
+ return path;
+ };
+ try {
+ const shared = file(
+ "shared.rs",
+ `
+#[wasm_bindgen(js_name = sharedOperation)]
+pub fn shared_operation() {}
+
+pub fn internal_helper() {}
+`,
+ );
+ const appSource = (app) =>
+ file(
+ `${app}.rs`,
+ `
+#[wasm_bindgen(js_name = localOperation)]
+pub fn local_operation() {}
+`,
+ );
+ const leftSource = appSource("left");
+ const rightSource = appSource("right");
+ const declarations = `
+ export function sharedOperation(): void;
+ export function localOperation(): void;
+ `;
+ const left = file("left.d.ts", declarations);
+ const right = file("right.d.ts", declarations);
+ const origins = new Map([
+ [left, rustFunctionExports([shared, leftSource])],
+ [right, rustFunctionExports([shared, rightSource])],
+ ]);
+ const entry = file(
+ "entry.ts",
+ `
+ import { sharedOperation, localOperation } from "./left";
+ sharedOperation();
+ localOperation();
+ `,
+ );
+ file(
+ "right.test.ts",
+ `import { localOperation } from "./right"; localOperation();`,
+ );
+ const check = () =>
+ unusedExports(
+ [left, right],
+ [
+ {
+ entryFiles: [entry],
+ options: {
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ },
+ },
+ ],
+ origins,
+ ).map(({ file, name }) => ({ file, name }));
+
+ assert.deepEqual(check(), [
+ { file: rightSource, name: "localOperation" },
+ ]);
+
+ file(
+ "entry.ts",
+ `import { localOperation } from "./left"; localOperation();`,
+ );
+ file(
+ "shared.test.ts",
+ `import { sharedOperation } from "./right"; sharedOperation();`,
+ );
+ assert.deepEqual(check(), [
+ { file: shared, name: "sharedOperation" },
+ { file: rightSource, name: "localOperation" },
+ ]);
+
+ file("right.d.ts", declarations + "export function unmapped(): void;");
+ assert.throws(check, /cannot locate Rust export unmapped/);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/web/package-lock.json b/web/package-lock.json
index 6f60e2a41c..5ac2f8c4a5 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -113,6 +113,7 @@
"@hugeicons/react": "1.1.6",
"@noble/hashes": "2.2.0",
"ente-accounts": "*",
+ "ente-auth-wasm": "*",
"ente-base": "*",
"otpauth": "9.5.1"
},
@@ -4721,6 +4722,10 @@
"resolved": "packages/accounts",
"link": true
},
+ "node_modules/ente-auth-wasm": {
+ "resolved": "packages/wasm/auth",
+ "link": true
+ },
"node_modules/ente-base": {
"resolved": "packages/base",
"link": true
@@ -11313,6 +11318,7 @@
"ente-accounts": "*",
"ente-base": "*",
"ente-gallery": "*",
+ "ente-photos-wasm": "*",
"ente-utils": "*",
"i18next": "26.3.1",
"react": "19.2.7"
@@ -11329,6 +11335,14 @@
"ente-build-config": "*"
}
},
+ "packages/wasm/auth": {
+ "name": "ente-auth-wasm",
+ "version": "0.0.0",
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+ },
"packages/wasm/cast": {
"name": "ente-cast-wasm",
"version": "0.0.0",
diff --git a/web/package.json b/web/package.json
index 72f4d36e2b..a4fd0f446b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -11,7 +11,8 @@
"build": "npm run build:photos",
"build:accounts": "npm run build:prelogin-wasm && npm exec --workspace accounts -- next build --webpack",
"build:albums": "npm run build:prelogin-wasm && npm exec --workspace albums -- next build --webpack",
- "build:auth": "npm run build:prelogin-wasm && npm exec --workspace auth -- next build --webpack",
+ "build:auth": "npm run build:prelogin-wasm && npm run build:auth-wasm && npm exec --workspace auth -- next build --webpack",
+ "build:auth-wasm": "npm run build --workspace ente-auth-wasm",
"build:cast": "npm run build:prelogin-wasm && npm run build:cast-wasm && npm exec --workspace cast -- next build --webpack",
"build:cast-wasm": "npm run build --workspace ente-cast-wasm",
"build:embed": "npm run build:prelogin-wasm && npm exec --workspace embed -- next build --webpack",
@@ -32,11 +33,11 @@
"build:space": "npm run build:prelogin-wasm && npm run build:space-wasm && npm exec --workspace space -- next build --webpack && npm run build:post --workspace space",
"build:space-wasm": "npm run build --workspace ente-space-wasm",
"build:twoof3": "npm exec --workspace twoof3 -- next build --webpack",
- "build:wasm": "npm run build:prelogin-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm run build:paste-wasm && npm run build:photos-wasm && npm run build:space-wasm",
+ "build:wasm": "npm run build:prelogin-wasm && npm run build:auth-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm run build:paste-wasm && npm run build:photos-wasm && npm run build:space-wasm",
"dev": "npm run dev:photos",
"dev:accounts": "npm run build:prelogin-wasm && npm exec --workspace accounts -- next dev --webpack -p 3001",
"dev:albums": "npm run build:prelogin-wasm && npm exec --workspace albums -- next dev --webpack -p 3002",
- "dev:auth": "npm run build:prelogin-wasm && npm exec --workspace auth -- next dev --webpack -p 3003",
+ "dev:auth": "npm run build:prelogin-wasm && npm run build:auth-wasm && npm exec --workspace auth -- next dev --webpack -p 3003",
"dev:cast": "npm run build:prelogin-wasm && npm run build:cast-wasm && npm exec --workspace cast -- next dev --webpack -p 3004",
"dev:embed": "npm run build:prelogin-wasm && npm exec --workspace embed -- next dev --webpack -p 3006",
"dev:ensu": "npm run build:ensu-wasm && npm exec --workspace ensu -- next dev --webpack -p 3007",
diff --git a/web/packages/accounts/services/recovery-key.ts b/web/packages/accounts/services/recovery-key.ts
index 6f9b75fc7a..eaa5035d14 100644
--- a/web/packages/accounts/services/recovery-key.ts
+++ b/web/packages/accounts/services/recovery-key.ts
@@ -1,7 +1,6 @@
import { savedKeyAttributes } from "ente-accounts/services/accounts-db";
import {
decryptBox,
- encryptBox,
recoveryKeyFromMnemonicOrHex,
} from "ente-accounts/services/crypto";
import { ensureMasterKeyFromSession } from "ente-accounts/services/prelogin-session";
@@ -33,6 +32,3 @@ const preloginRecoveryKey = async () => {
export const getPreloginRecoveryKeyMnemonic = async () =>
recoveryKeyToMnemonic(await preloginRecoveryKey());
-
-export const encryptWithPreloginRecoveryKey = async (data: string) =>
- encryptBox(data, await preloginRecoveryKey());
diff --git a/web/packages/base/session-storage.ts b/web/packages/base/session-storage.ts
index 84c4fa5883..c288873572 100644
--- a/web/packages/base/session-storage.ts
+++ b/web/packages/base/session-storage.ts
@@ -29,11 +29,31 @@ interface SessionStorageCrypto {
generateKey: () => Promise<string>;
}
+export const readMasterKeyFromSession = async (
+ decryptBox: SessionStorageCrypto["decryptBox"],
+) => {
+ const value = sessionStorage.getItem("encryptionKey");
+ if (!value) return undefined;
+
+ const { encryptedData, key, nonce } = SessionKeyData.parse(
+ JSON.parse(value),
+ );
+ return decryptBox({ encryptedData, nonce }, key);
+};
+
export const createSessionStorage = ({
decryptBox,
encryptBox,
generateKey,
}: SessionStorageCrypto) => {
+ const masterKeyFromSession = () => readMasterKeyFromSession(decryptBox);
+
+ const ensureMasterKeyFromSession = async () => {
+ const key = await masterKeyFromSession();
+ if (!key) throw new Error("Master key not found in session");
+ return key;
+ };
+
const sessionKeyData = async (keyData: string): Promise<SessionKeyData> => {
const key = await generateKey();
const box = await encryptBox(keyData, key);
@@ -47,22 +67,6 @@ export const createSessionStorage = ({
);
};
- const masterKeyFromSession = async () => {
- const value = sessionStorage.getItem("encryptionKey");
- if (!value) return undefined;
-
- const { encryptedData, key, nonce } = SessionKeyData.parse(
- JSON.parse(value),
- );
- return decryptBox({ encryptedData, nonce }, key);
- };
-
- const ensureMasterKeyFromSession = async () => {
- const key = await masterKeyFromSession();
- if (!key) throw new Error("Master key not found in session");
- return key;
- };
-
const saveMasterKeyInSessionAndSafeStore = async (masterKey: string) => {
await saveKeyInSessionStore("encryptionKey", masterKey);
try {
diff --git a/web/packages/new/package.json b/web/packages/new/package.json
index bc434fe906..2681657dc9 100644
--- a/web/packages/new/package.json
+++ b/web/packages/new/package.json
@@ -9,6 +9,7 @@
"ente-accounts": "*",
"ente-base": "*",
"ente-gallery": "*",
+ "ente-photos-wasm": "*",
"ente-utils": "*",
"i18next": "26.3.1",
"react": "19.2.7"
diff --git a/web/packages/base/session.ts b/web/packages/new/photos/services/account-keys.ts
similarity index 58%
rename from web/packages/base/session.ts
rename to web/packages/new/photos/services/account-keys.ts
index f95a193f7e..6a1ebd86d1 100644
--- a/web/packages/base/session.ts
+++ b/web/packages/new/photos/services/account-keys.ts
@@ -1,5 +1,5 @@
-import { decryptBox, encryptBox, generateKey } from "./crypto";
-import { createSessionStorage } from "./session-storage";
+import { createSessionStorage } from "ente-base/session-storage";
+import { decryptBox, encryptBox, generateKey } from "ente-photos-wasm";
export const {
ensureMasterKeyFromSession,
diff --git a/web/packages/new/photos/services/collection.ts b/web/packages/new/photos/services/collection.ts
index edf36f3e08..3002df9b72 100644
--- a/web/packages/new/photos/services/collection.ts
+++ b/web/packages/new/photos/services/collection.ts
@@ -4,7 +4,6 @@ import { boxSeal, encryptBox, generateKey } from "ente-base/crypto";
import { haveWindow } from "ente-base/env";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
-import { ensureMasterKeyFromSession } from "ente-base/session";
import { groupFilesByCollectionID } from "ente-gallery/utils/file";
import {
CollectionSubType,
@@ -32,6 +31,7 @@ import {
createMagicMetadata,
encryptMagicMetadata,
} from "ente-media/magic-metadata";
+import { ensureMasterKeyFromSession } from "ente-new/photos/services/account-keys";
import { batch, splitByPredicate } from "ente-utils/array";
import { z } from "zod";
import { batched, type UpdateMagicMetadataRequest } from "./file";
diff --git a/web/packages/new/photos/services/ml/index.ts b/web/packages/new/photos/services/ml/index.ts
index 6ed3a323c1..6bd9505a79 100644
--- a/web/packages/new/photos/services/ml/index.ts
+++ b/web/packages/new/photos/services/ml/index.ts
@@ -4,12 +4,12 @@ import { isDesktop } from "ente-base/app";
import { blobCache } from "ente-base/blob-cache";
import { ensureElectron } from "ente-base/electron";
import log from "ente-base/log";
-import { ensureMasterKeyFromSession } from "ente-base/session";
import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import type { ProcessableUploadItem } from "ente-gallery/services/upload";
import { createUtilityProcess } from "ente-gallery/utils/native-worker";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
+import { ensureMasterKeyFromSession } from "ente-new/photos/services/account-keys";
import { throttled } from "ente-utils/promise";
import pDebounce from "p-debounce";
import { getRemoteFlag, updateRemoteFlag } from "../remote-store";
diff --git a/web/packages/new/photos/services/search/index.ts b/web/packages/new/photos/services/search/index.ts
index 49a79c4f3f..3471ba1827 100644
--- a/web/packages/new/photos/services/search/index.ts
+++ b/web/packages/new/photos/services/search/index.ts
@@ -1,11 +1,11 @@
import { ensureLocalUser } from "ente-accounts/services/user";
import log from "ente-base/log";
-import { ensureMasterKeyFromSession } from "ente-base/session";
import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import { uniqueFilesByID } from "ente-gallery/utils/file";
import type { Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
+import { ensureMasterKeyFromSession } from "ente-new/photos/services/account-keys";
import i18n, { t } from "i18next";
import { clipMatches, isMLEnabled, isMLSupported } from "../ml";
import type { NamedPerson } from "../ml/people";
diff --git a/web/packages/new/photos/services/user.ts b/web/packages/new/photos/services/user.ts
index 61d9ef2131..fba704cf00 100644
--- a/web/packages/new/photos/services/user.ts
+++ b/web/packages/new/photos/services/user.ts
@@ -3,7 +3,7 @@ import { boxSealOpenBytes, decryptBox } from "ente-base/crypto";
import type { KeyPair } from "ente-base/crypto/types";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
-import { ensureMasterKeyFromSession } from "ente-base/session";
+import { ensureMasterKeyFromSession } from "ente-new/photos/services/account-keys";
import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
diff --git a/web/packages/wasm/auth/eslint.config.mjs b/web/packages/wasm/auth/eslint.config.mjs
new file mode 100644
index 0000000000..e6c7d4d3b0
--- /dev/null
+++ b/web/packages/wasm/auth/eslint.config.mjs
@@ -0,0 +1,3 @@
+import config from "ente-build-config/eslintrc-base.mjs";
+
+export default [...config, { ignores: ["pkg/"] }];
diff --git a/web/packages/wasm/auth/index.ts b/web/packages/wasm/auth/index.ts
new file mode 100644
index 0000000000..62f6e7e1c7
--- /dev/null
+++ b/web/packages/wasm/auth/index.ts
@@ -0,0 +1,43 @@
+import type {
+ EncryptedBlob,
+ EncryptedBox,
+ OpenSessionInput,
+ Session,
+} from "./pkg/ente_auth_wasm";
+
+const wasm = () => import("./pkg/ente_auth_wasm");
+
+export type { Session } from "./pkg/ente_auth_wasm";
+
+export const openSession = async (input: OpenSessionInput): Promise<Session> =>
+ (await wasm()).openSession(input);
+
+export const encryptBoxWithRecoveryKey = (session: Session, dataB64: string) =>
+ session.encryptWithRecoveryKey(dataB64);
+
+export const decryptBox = async (box: EncryptedBox, keyB64: string) =>
+ (await wasm()).cryptoDecryptBox(box.encryptedData, box.nonce, keyB64);
+
+export const decryptMetadataJSON = async (
+ blob: EncryptedBlob,
+ keyB64: string,
+): Promise<unknown> => {
+ const plaintext = (await wasm()).cryptoDecryptBlobLegacy(
+ blob.encryptedData,
+ blob.decryptionHeader,
+ keyB64,
+ );
+ return JSON.parse(new TextDecoder().decode(plaintext));
+};
+
+export const decryptMetadataJSONBytes = async (
+ blob: { encryptedData: Uint8Array; decryptionHeader: Uint8Array },
+ key: Uint8Array,
+): Promise<unknown> => {
+ const plaintext = (await wasm()).cryptoDecryptBlobLegacyBytes(
+ blob.encryptedData,
+ blob.decryptionHeader,
+ key,
+ );
+ return JSON.parse(new TextDecoder().decode(plaintext));
+};
diff --git a/web/packages/wasm/auth/package.json b/web/packages/wasm/auth/package.json
new file mode 100644
index 0000000000..7d623970a1
--- /dev/null
+++ b/web/packages/wasm/auth/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "ente-auth-wasm",
+ "version": "0.0.0",
+ "private": true,
+ "exports": {
+ ".": {
+ "types": "./index.ts",
+ "import": "./index.ts"
+ }
+ },
+ "module": "./index.ts",
+ "types": "./index.ts",
+ "scripts": {
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/auth --target bundler --out-dir ../../../../web/packages/wasm/auth/pkg --no-pack"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+}
diff --git a/web/packages/wasm/auth/tsconfig.json b/web/packages/wasm/auth/tsconfig.json
new file mode 100644
index 0000000000..3f3b6cd165
--- /dev/null
+++ b/web/packages/wasm/auth/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "ente-build-config/tsconfig-typecheck.json", "include": ["."] }
diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.ts
index 5604fc01e6..eaf2e6a7f1 100644
--- a/web/packages/wasm/locker/index.ts
+++ b/web/packages/wasm/locker/index.ts
@@ -2,6 +2,8 @@ import { wrap } from "comlink";
import { workerReady } from "ente-utils/worker";
import type { FileLinkWorker } from "./file-link.worker";
import type {
+ EncryptedBlob,
+ EncryptedBox,
OpenSessionInput,
Session,
WrappedRootContactKey,
@@ -56,18 +58,6 @@ export const contactsGetProfilePicture = async (
contactID,
);
-type BytesOrB64 = Uint8Array | string;
-
-interface EncryptedBlob {
- encryptedData: BytesOrB64;
- decryptionHeader: BytesOrB64;
-}
-
-interface EncryptedBox {
- encryptedData: BytesOrB64;
- nonce: BytesOrB64;
-}
-
export const prepareFileLink = async (session: Session, fileKeyB64: string) => {
const worker = new Worker(new URL("file-link.worker.ts", import.meta.url));
const RemoteWorker = wrap<typeof FileLinkWorker>(worker);
@@ -109,52 +99,28 @@ export const encryptBoxBytes = async (data: Uint8Array, keyB64: string) =>
export const decryptBox = async (
box: EncryptedBox,
- key: Uint8Array | string,
+ keyB64: string,
): Promise<string> =>
- (await wasm()).cryptoDecryptBox(
- toB64String(box.encryptedData),
- toB64String(box.nonce),
- toB64String(key),
- );
+ (await wasm()).cryptoDecryptBox(box.encryptedData, box.nonce, keyB64);
export const decryptBoxBytes = async (
box: EncryptedBox,
- key: Uint8Array | string,
+ keyB64: string,
): Promise<Uint8Array> =>
- (await wasm()).cryptoDecryptBoxBytes(
- toB64String(box.encryptedData),
- toB64String(box.nonce),
- toB64String(key),
- );
+ (await wasm()).cryptoDecryptBoxBytes(box.encryptedData, box.nonce, keyB64);
export const encryptBlob = async (data: Uint8Array, keyB64: string) =>
(await wasm()).cryptoEncryptBlob(data, keyB64);
export const decryptMetadataJSON = async (
blob: EncryptedBlob,
- key: Uint8Array | string,
+ keyB64: string,
): Promise<unknown> => {
- const wasmModule = await wasm();
- const encryptedData = toB64String(blob.encryptedData);
- const decryptionHeader = toB64String(blob.decryptionHeader);
- const keyB64 = toB64String(key);
- let plaintext: Uint8Array;
- try {
- plaintext = wasmModule.cryptoDecryptBlob(
- encryptedData,
- decryptionHeader,
- keyB64,
- );
- } catch (error) {
- if (!(error instanceof Error && error.name == "stream_truncated")) {
- throw error;
- }
- plaintext = wasmModule.cryptoDecryptBlobLegacy(
- encryptedData,
- decryptionHeader,
- keyB64,
- );
- }
+ const plaintext = (await wasm()).cryptoDecryptBlobLegacy(
+ blob.encryptedData,
+ blob.decryptionHeader,
+ keyB64,
+ );
return JSON.parse(new TextDecoder().decode(plaintext));
};
@@ -178,10 +144,3 @@ export const encryptFileStreamWithKey = async (
dataB64: string,
keyB64: string,
) => (await wasm()).cryptoEncryptStreamWithKey(dataB64, keyB64);
-
-const toB64String = (value: Uint8Array | string): string => {
- if (typeof value == "string") return value;
- let binary = "";
- for (const byte of value) binary += String.fromCharCode(byte);
- return btoa(binary);
-};
diff --git a/web/packages/wasm/locker/tests/crypto.test.ts b/web/packages/wasm/locker/tests/crypto.test.ts
index bb41fcc5ec..86538701d5 100644
--- a/web/packages/wasm/locker/tests/crypto.test.ts
+++ b/web/packages/wasm/locker/tests/crypto.test.ts
@@ -12,7 +12,6 @@ import {
encryptFileStreamWithKey,
generateKey,
} from "../index";
-import { cryptoDecryptBlob } from "../pkg/ente_locker_wasm.js";
test.each([
new Uint8Array(),
@@ -72,7 +71,7 @@ test("encrypted file bytes are uploadable with their MD5 and header", async () =
}
});
-test("metadata wrapper reads legacy JSON after a stream_truncated error", async () => {
+test("metadata accepts legacy records without a final tag", async () => {
const metadata = { title: "ZoΓ« πŸ¦‹" };
const encryptor = await createStreamEncryptor();
@@ -83,18 +82,14 @@ test("metadata wrapper reads legacy JSON after a stream_truncated error", async
);
const { key, decryptionHeader } = encryptor;
- expect(() =>
- cryptoDecryptBlob(
- Buffer.from(encryptedData).toString("base64"),
- decryptionHeader,
- key,
- ),
- ).toThrow(expect.objectContaining({ name: "stream_truncated" }));
-
expect(
await decryptMetadataJSON(
- { encryptedData, decryptionHeader },
- Buffer.from(key, "base64"),
+ {
+ encryptedData:
+ Buffer.from(encryptedData).toString("base64"),
+ decryptionHeader,
+ },
+ key,
),
).toStrictEqual(metadata);
} finally {
diff --git a/web/packages/wasm/paste/index.ts b/web/packages/wasm/paste/index.ts
index b5767c69b7..b8c7e54576 100644
--- a/web/packages/wasm/paste/index.ts
+++ b/web/packages/wasm/paste/index.ts
@@ -3,16 +3,13 @@ import { workerReady } from "ente-utils/worker";
import type { PasteWorker } from "./worker";
export class PasteClient {
- private constructor(
- private worker: Worker,
- private remote: Remote<PasteWorker>,
- ) {}
+ private constructor(private remote: Remote<PasteWorker>) {}
static async init(apiOrigin: string) {
const worker = new Worker(new URL("worker.ts", import.meta.url));
const RemoteWorker = wrap<typeof PasteWorker>(worker);
const remote = await workerReady(worker, new RemoteWorker(apiOrigin));
- return new PasteClient(worker, remote);
+ return new PasteClient(remote);
}
create = (pasteOrigin: string, text: string, password?: string) =>
@@ -21,6 +18,4 @@ export class PasteClient {
open = (url: string) => this.remote.open(url);
submitPassword = (password: string) => this.remote.submitPassword(password);
-
- terminate = () => this.worker.terminate();
}
diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.ts
index a1b793cda1..1018e58382 100644
--- a/web/packages/wasm/photos/index.ts
+++ b/web/packages/wasm/photos/index.ts
@@ -1,4 +1,5 @@
import type {
+ EncryptedBox,
OpenSessionInput,
Session,
WrappedRootContactKey,
@@ -16,6 +17,12 @@ export const encryptBoxWithRecoveryKey = (session: Session, dataB64: string) =>
export const generateKey = async () => (await wasm()).cryptoGenerateKey();
+export const encryptBox = async (dataB64: string, keyB64: string) =>
+ (await wasm()).cryptoEncryptBox(dataB64, keyB64);
+
+export const decryptBox = async (box: EncryptedBox, keyB64: string) =>
+ (await wasm()).cryptoDecryptBox(box.encryptedData, box.nonce, keyB64);
+
export const contactsGetDiff = async (
session: Session,
wrappedRootContactKey: WrappedRootContactKey | undefined,