π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify app WASM operations and session access
Manav Rathid44887440ae1
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 4177327c2c..000ecfa2e1 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2813,13 +2813,7 @@ dependencies = [name = "ente-photos-wasm"version = "0.0.0"dependencies = [- "ente-cast","ente-wasm-lib",- "serde",- "serde-wasm-bindgen",- "thiserror 2.0.18",- "tsify",- "wasm-bindgen",][[package]]@@ -2932,6 +2926,7 @@ name = "ente-wasm-lib"version = "0.0.0"dependencies = ["ente-accounts",+ "ente-cast","ente-collections","ente-contacts","ente-core",diff --git a/rust/bindings/wasm/lib/Cargo.toml b/rust/bindings/wasm/lib/Cargo.tomlindex b8d07e5b86..f74e91cd01 100644--- a/rust/bindings/wasm/lib/Cargo.toml+++ b/rust/bindings/wasm/lib/Cargo.toml@@ -4,6 +4,7 @@ edition.workspace = true[features]accounts = ["dep:ente-accounts", "dep:serde", "dep:serde-wasm-bindgen", "dep:tsify"]+cast = ["dep:ente-cast", "dep:serde", "dep:serde-wasm-bindgen", "dep:tsify"]collections = ["session", "dep:ente-collections"]contacts = ["session",@@ -26,6 +27,7 @@ session = [[dependencies]ente-accounts = { workspace = true, optional = true }+ente-cast = { workspace = true, optional = true }ente-collections = { workspace = true, optional = true }ente-contacts = { workspace = true, optional = true }ente-core.workspace = truediff --git a/rust/bindings/wasm/lib/src/cast.rs b/rust/bindings/wasm/lib/src/cast.rsnew file mode 100644index 0000000000..d61aef90c9--- /dev/null+++ b/rust/bindings/wasm/lib/src/cast.rs@@ -0,0 +1,46 @@+use serde::Serialize;+use serde_wasm_bindgen as swb;+use tsify::Tsify;+use wasm_bindgen::prelude::*;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error(transparent)]+ Cast(#[from] ente_cast::Error),+ #[error(transparent)]+ Serde(#[from] swb::Error),+}++impl From<Error> for JsValue {+ fn from(error: Error) -> Self {+ crate::js_error(&error, None)+ }+}++#[derive(Serialize, Tsify)]+#[serde(rename_all = "camelCase")]+pub struct PreparedCastPayload {+ cast_token: String,+ encrypted_payload: String,+}++#[wasm_bindgen(js_name = castPreparePayload)]+pub fn prepare_payload(+ public_key: &str,+ pq_public_key: Option<String>,+ collection_id: i64,+ collection_key: &str,+) -> Result<<PreparedCastPayload as Tsify>::JsType, Error> {+ let payload = ente_cast::prepare_payload(+ public_key,+ pq_public_key.as_deref(),+ collection_id,+ collection_key,+ )?;+ PreparedCastPayload {+ cast_token: payload.cast_token,+ encrypted_payload: payload.encrypted_payload,+ }+ .into_js()+ .map_err(Into::into)+}diff --git a/rust/bindings/wasm/lib/src/lib.rs b/rust/bindings/wasm/lib/src/lib.rsindex d4bd490f6a..a4dee15ea5 100644--- a/rust/bindings/wasm/lib/src/lib.rs+++ b/rust/bindings/wasm/lib/src/lib.rs@@ -1,5 +1,7 @@#[cfg(feature = "accounts")]pub mod accounts;+#[cfg(feature = "cast")]+pub mod cast;#[cfg(feature = "collections")]pub mod collections;#[cfg(feature = "contacts")]diff --git a/rust/bindings/wasm/photos/Cargo.toml b/rust/bindings/wasm/photos/Cargo.tomlindex 1897ee993b..605fceb362 100644--- a/rust/bindings/wasm/photos/Cargo.toml+++ b/rust/bindings/wasm/photos/Cargo.toml@@ -6,13 +6,7 @@ edition.workspace = truecrate-type = ["cdylib"][dependencies]-ente-cast.workspace = true-ente-wasm-lib = { workspace = true, features = ["collections", "contacts", "crypto"] }-serde.workspace = true-serde-wasm-bindgen.workspace = true-thiserror.workspace = true-tsify.workspace = true-wasm-bindgen.workspace = true+ente-wasm-lib = { workspace = true, features = ["cast", "collections", "contacts", "crypto"] }[lints]workspace = truediff --git a/rust/bindings/wasm/photos/src/lib.rs b/rust/bindings/wasm/photos/src/lib.rsindex 82c61eb8b0..786e389426 100644--- a/rust/bindings/wasm/photos/src/lib.rs+++ b/rust/bindings/wasm/photos/src/lib.rs@@ -1,46 +1 @@-use serde::Serialize;-use serde_wasm_bindgen as swb;-use tsify::Tsify;-use wasm_bindgen::prelude::*;--#[derive(Debug, thiserror::Error)]-pub enum Error {- #[error(transparent)]- Cast(#[from] ente_cast::Error),- #[error(transparent)]- Serde(#[from] swb::Error),-}--impl From<Error> for JsValue {- fn from(error: Error) -> Self {- ente_wasm_lib::js_error(&error, None)- }-}--#[derive(Serialize, Tsify)]-#[serde(rename_all = "camelCase")]-pub struct PreparedCastPayload {- cast_token: String,- encrypted_payload: String,-}--#[wasm_bindgen(js_name = preparePayload)]-pub fn prepare_payload(- public_key: &str,- pq_public_key: Option<String>,- collection_id: i64,- collection_key: &str,-) -> Result<<PreparedCastPayload as Tsify>::JsType, Error> {- let payload = ente_cast::prepare_payload(- public_key,- pq_public_key.as_deref(),- collection_id,- collection_key,- )?;- PreparedCastPayload {- cast_token: payload.cast_token,- encrypted_payload: payload.encrypted_payload,- }- .into_js()- .map_err(Into::into)-}+use ente_wasm_lib as _;diff --git a/web/apps/locker/src/components/sidebar/LockerLegacyDrawer.tsx b/web/apps/locker/src/components/sidebar/LockerLegacyDrawer.tsxindex e2550f3d98..ba216d4dec 100644--- a/web/apps/locker/src/components/sidebar/LockerLegacyDrawer.tsx+++ b/web/apps/locker/src/components/sidebar/LockerLegacyDrawer.tsx@@ -1,11 +1,11 @@-import { authenticatedSession } from "@/services/authenticated-session";+import { ensureAuthenticatedSession } from "@/services/authenticated-session";import { UserAdd01Icon } from "@hugeicons/core-free-icons";import { CircularProgress } from "@mui/material";import {LegacyDrawerContent,type LegacySuggestedUser,} from "ente-contacts/legacy";-import { createLegacyService } from "ente-locker-wasm/legacy";+import * as legacy from "ente-locker-wasm/legacy";import { t } from "i18next";import React from "react";import { LockerSidebarCardButton } from "./LockerSidebarCardButton";@@ -14,8 +14,6 @@ import {type LockerNestedSidebarDrawerVisibilityProps,} from "./LockerSidebarShell";-const legacyService = createLegacyService(authenticatedSession);-export const LockerLegacyDrawer: React.FC<LockerNestedSidebarDrawerVisibilityProps & {suggestedUsers: LegacySuggestedUser[];@@ -29,7 +27,8 @@ export const LockerLegacyDrawer: React.FC<intro={t("legacy_intro")}open={open}suggestedUsers={suggestedUsers}- service={legacyService}+ getSession={ensureAuthenticatedSession}+ operations={legacy}renderAddContactButton={({ onClick, disabled, loading }) => (<LockerSidebarCardButtonicon={UserAdd01Icon}diff --git a/web/apps/locker/src/services/authenticated-session.ts b/web/apps/locker/src/services/authenticated-session.tsindex 17e8275c85..1a68c9682b 100644--- a/web/apps/locker/src/services/authenticated-session.ts+++ b/web/apps/locker/src/services/authenticated-session.ts@@ -8,7 +8,5 @@ const sessions = createAuthenticatedSessionCache();export const openAuthenticatedSession = sessions.open;-export const ensureAuthenticatedSession = () =>- sessions.current() ?? sessions.ensure();-export const authenticatedSession = sessions.ensure;+export const ensureAuthenticatedSession = sessions.ensure;export const clearAuthenticatedSession = sessions.clear;diff --git a/web/apps/locker/tests/authenticated-session.test.ts b/web/apps/locker/tests/authenticated-session.test.tsindex bdd64c2bfb..21dc5bb20b 100644--- a/web/apps/locker/tests/authenticated-session.test.ts+++ b/web/apps/locker/tests/authenticated-session.test.ts@@ -58,7 +58,7 @@ beforeEach(async () => {sessions = await import("../src/services/authenticated-session");});-test("Legacy reuses the Locker session and refreshes its token", async () => {+test("reuses the session without decrypting the master key and refreshes its token", async () => {const locker = mockSession();openLocker.mockResolvedValue(locker);@@ -67,15 +67,14 @@ test("Legacy reuses the Locker session and refreshes its token", async () => {);expect(await sessions.ensureAuthenticatedSession()).toBe(locker);expect(masterKeyFromSession).not.toHaveBeenCalled();- expect(await sessions.authenticatedSession()).toBe(locker);savedAuthToken.mockResolvedValue("rotated-token");- expect(await sessions.authenticatedSession()).toBe(locker);+ expect(await sessions.ensureAuthenticatedSession()).toBe(locker);expect(locker.updateAuthToken).toHaveBeenLastCalledWith("rotated-token");expect(openLocker).toHaveBeenCalledOnce();sessions.clearAuthenticatedSession();expect(locker.free).not.toHaveBeenCalled();- await sessions.authenticatedSession();+ await sessions.ensureAuthenticatedSession();expect(openLocker).toHaveBeenCalledTimes(2);});@@ -94,8 +93,13 @@ test("retries a failed Locker session", async () => {test("logout during credential lookup cannot reopen a session", async () => {const key = Promise.withResolvers<string>();- masterKeyFromSession.mockReturnValue(key.promise);- const opening = sessions.authenticatedSession();+ const started = Promise.withResolvers<undefined>();+ masterKeyFromSession.mockImplementation(() => {+ started.resolve(undefined);+ return key.promise;+ });+ const opening = sessions.ensureAuthenticatedSession();+ await started.promise;sessions.clearAuthenticatedSession();key.resolve("key");@@ -103,6 +107,20 @@ test("logout during credential lookup cannot reopen a session", async () => {expect(openLocker).not.toHaveBeenCalled();});+test("concurrent access decrypts the master key once", async () => {+ const locker = mockSession();+ openLocker.mockResolvedValue(locker);+ expect(+ await Promise.all([+ sessions.ensureAuthenticatedSession(),+ sessions.ensureAuthenticatedSession(),+ ]),+ ).toEqual([locker, locker]);+ expect(await sessions.ensureAuthenticatedSession()).toBe(locker);+ expect(masterKeyFromSession).toHaveBeenCalledOnce();+ expect(openLocker).toHaveBeenCalledOnce();+});+test("logout during WASM initialization frees the unused handle and permits a new session", async () => {const ready = Promise.withResolvers<Session>();const started = Promise.withResolvers<undefined>();@@ -114,15 +132,15 @@ test("logout during WASM initialization frees the unused handle and permits a nereturn ready.promise;}).mockResolvedValueOnce(next);- const opening = sessions.authenticatedSession();+ const opening = sessions.ensureAuthenticatedSession();await started.promise;sessions.clearAuthenticatedSession();- expect(await sessions.authenticatedSession()).toBe(next);+ expect(await sessions.ensureAuthenticatedSession()).toBe(next);ready.resolve(previous);await expect(opening).rejects.toThrow("Authenticated session was cleared");expect(previous.free).toHaveBeenCalledOnce();- expect(await sessions.authenticatedSession()).toBe(next);+ expect(await sessions.ensureAuthenticatedSession()).toBe(next);expect(next.free).not.toHaveBeenCalled();expect(openLocker).toHaveBeenCalledTimes(2);});@@ -134,15 +152,15 @@ test("failed opens can be retried and account changes replace the cached session.mockRejectedValueOnce(new Error("Download failed")).mockResolvedValueOnce(previous).mockResolvedValueOnce(next);- await expect(sessions.authenticatedSession()).rejects.toThrow(+ await expect(sessions.ensureAuthenticatedSession()).rejects.toThrow("Download failed",);- expect(await sessions.authenticatedSession()).toBe(previous);+ expect(await sessions.ensureAuthenticatedSession()).toBe(previous);user.id = 2;savedAuthToken.mockResolvedValue("other-token");masterKeyFromSession.mockResolvedValue("other-key");- expect(await sessions.authenticatedSession()).toBe(next);+ expect(await sessions.ensureAuthenticatedSession()).toBe(next);expect(openLocker).toHaveBeenLastCalledWith({baseUrl: "http://localhost:8080",authToken: "other-token",diff --git a/web/apps/photos/src/services/authenticated-session.ts b/web/apps/photos/src/services/authenticated-session.tsindex a40ee985e8..05df86d44d 100644--- a/web/apps/photos/src/services/authenticated-session.ts+++ b/web/apps/photos/src/services/authenticated-session.ts@@ -10,7 +10,7 @@ const sessions = createAuthenticatedSessionCache((input): Promise<Session> => {const opening = openSession(input);bindCollectionKeyOpener(async (input) =>openCollectionKey(- await (sessions.current() ?? sessions.ensure()),+ await sessions.ensure(),input.ownerID,input.encryptedKey,input.keyDecryptionNonce,diff --git a/web/apps/photos/tests/authenticated-session.test.ts b/web/apps/photos/tests/authenticated-session.test.tsindex 5f1bdfaa47..42fe5a1594 100644--- a/web/apps/photos/tests/authenticated-session.test.ts+++ b/web/apps/photos/tests/authenticated-session.test.ts@@ -100,6 +100,9 @@ test("concurrent opens share a session and retain the latest token", async () =>);expect(openSession).toHaveBeenCalledTimes(1);+ expect(await sessions.ensureAuthenticatedSession()).toBe(session);+ expect(masterKeyFromSession).not.toHaveBeenCalled();+sessions.clearAuthenticatedSession();sessions.clearAuthenticatedSession();expect(session.free).not.toHaveBeenCalled();diff --git a/web/checks/wasm-exports/exports.mjs b/web/checks/wasm-exports/exports.mjsindex 1ff88c9720..93d2f77c3f 100644--- a/web/checks/wasm-exports/exports.mjs+++ b/web/checks/wasm-exports/exports.mjs@@ -205,6 +205,15 @@ export function unusedExports(files, projects, rustOrigins = new Map()) {ts.isPropertyAccessExpression(node.parent))) {reference(checker.getSymbolAtLocation(node));+ const expected = checker.getContextualType(node);+ for (const property of expected?.getProperties() ?? []) {+ reference(+ checker.getPropertyOfType(+ checker.getTypeAtLocation(node),+ property.name,+ ),+ );+ }} else if (ts.isElementAccessExpression(node) &&ts.isStringLiteral(node.argumentExpression)diff --git a/web/checks/wasm-exports/test.mjs b/web/checks/wasm-exports/test.mjsindex 9086960c28..6d7b9f5c64 100644--- a/web/checks/wasm-exports/test.mjs+++ b/web/checks/wasm-exports/test.mjs@@ -121,6 +121,49 @@ test("production references cross lazy loaders, aliases, destructuring and worke}});+test("injected operations count only properties in the receiving interface", () => {+ const directory = mkdtempSync(join(tmpdir(), "wasm-operations-"));+ try {+ const operations = join(directory, "operations.ts");+ const entry = join(directory, "entry.tsx");+ writeFileSync(+ operations,+ `+ export const getInfo = () => "info";+ export const unused = () => "unused";+ `,+ );+ writeFileSync(+ entry,+ `+ import * as operations from "./operations";+ interface Operations { getInfo(): string; }+ const View = (props: { operations: Operations }) => null;+ export const app = <View operations={operations} />;+ `,+ );+ const result = unusedExports(+ [operations],+ [+ {+ entryFiles: [entry],+ options: {+ jsx: ts.JsxEmit.Preserve,+ module: ts.ModuleKind.ESNext,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ },+ },+ ],+ );+ assert.deepEqual(+ result.map(({ name }) => name),+ ["unused"],+ );+ } 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) => {diff --git a/web/packages/accounts/services/authenticated-session.ts b/web/packages/accounts/services/authenticated-session.tsindex e02590f06c..60493c5a12 100644--- a/web/packages/accounts/services/authenticated-session.ts+++ b/web/packages/accounts/services/authenticated-session.ts@@ -28,7 +28,7 @@ export const createAuthenticatedSessionCache = <T extends Session>(const open = async (userID: number,authToken: string,- masterKeyB64: string,+ masterKeyB64?: string,) => {const startedGeneration = generation;const baseUrl = await apiOrigin();@@ -37,15 +37,24 @@ export const createAuthenticatedSessionCache = <T extends Session>(}const key = `${baseUrl}:${userID}`;if (current?.key !== key) {- const opening = openSession({- baseUrl,- authToken,- userID,- masterKeyB64,- keyAttributes: ensureSavedKeyAttributes(),- clientPackage: clientPackageName,- clientVersion: isDesktop ? desktopAppVersion : undefined,- })+ const opening = (async () => {+ const keyAttributes = ensureSavedKeyAttributes();+ const masterKey =+ masterKeyB64 ?? (await masterKeyFromSession());+ if (startedGeneration !== generation) {+ throw new Error("Authenticated session was cleared");+ }+ if (!masterKey) throw new Error("Missing current master key");+ return openSession({+ baseUrl,+ authToken,+ userID,+ masterKeyB64: masterKey,+ keyAttributes,+ clientPackage: clientPackageName,+ clientVersion: isDesktop ? desktopAppVersion : undefined,+ });+ })().then((session) => {if (current?.opening !== opening) {session.free();@@ -72,20 +81,15 @@ export const createAuthenticatedSessionCache = <T extends Session>(const ensure = async () => {const startedGeneration = generation;const userID = ensureLocalUser().id;- const [authToken, masterKeyB64] = await Promise.all([- savedAuthToken(),- masterKeyFromSession(),- ]);+ const authToken = await savedAuthToken();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");- return open(userID, authToken, masterKeyB64);+ return open(userID, authToken);};return {- current: () => current?.opening,open,ensure,clear: () => {diff --git a/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsxindex 6194c86b15..769a396e57 100644--- a/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx+++ b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx@@ -10,8 +10,8 @@ import {import { ensureLocalUser } from "ente-accounts/services/user";import { useBaseContext } from "ente-base/context";import { isNamedError } from "ente-base/error";-import React, { useMemo, useState } from "react";-import type { LegacyService, LegacySuggestedUser } from "..";+import { useMemo, useState } from "react";+import type { LegacyOperations, LegacySuggestedUser } from "..";import { contactsDisplaySnapshot } from "../..";import { resolveContactDisplayFromSnapshot } from "../../resolver";import { ActionButton } from "./ActionButton";@@ -20,8 +20,9 @@ import { LegacyRecoveryDayPicker } from "./LegacyRecoveryDayPicker";const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;-interface LegacyAddContactContentProps {- service: LegacyService;+interface LegacyAddContactContentProps<Session> {+ getSession: () => Promise<Session>;+ operations: LegacyOperations<Session>;existingEmails: string[];onAdded: () => Promise<void>;suggestedUsers: LegacySuggestedUser[];@@ -33,15 +34,14 @@ const nonEnteDialogAttributes = (email: string) => ({message: `${email} is not linked to an Ente account yet, so it cannot be used as a trusted contact.`,});-export const LegacyAddContactContent: React.FC<- LegacyAddContactContentProps-> = ({- service,+export const LegacyAddContactContent = <Session,>({+ getSession,+ operations,existingEmails,onAdded,suggestedUsers,variant = "page",-}) => {+}: LegacyAddContactContentProps<Session>) => {const { showMiniDialog, onGenericError } = useBaseContext();const currentUser = ensureLocalUser();const [email, setEmail] = useState("");@@ -104,8 +104,13 @@ export const LegacyAddContactContent: React.FC<return;}try {- const verificationID =- await service.verificationID(normalizedEmail);+ const key = await operations.publicKey(+ await getSession(),+ normalizedEmail,+ );+ const verificationID = key+ ? await operations.verificationID(key)+ : undefined;if (!verificationID) {showMiniDialog({title: "Verification ID unavailable",@@ -159,7 +164,10 @@ export const LegacyAddContactContent: React.FC<void (async () => {try {- const key = await service.publicKey(normalizedEmail);+ const key = await operations.publicKey(+ await getSession(),+ normalizedEmail,+ );if (!key) {showMiniDialog(nonEnteDialogAttributes(normalizedEmail));return;@@ -190,7 +198,8 @@ export const LegacyAddContactContent: React.FC<text: "Add trusted contact",action: async () => {try {- await service.addContact(+ await operations.addContact(+ await getSession(),normalizedEmail,selectedRecoveryDays,);diff --git a/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsxindex 35165d9d84..c6ae04ee77 100644--- a/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx+++ b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx@@ -10,8 +10,8 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";import type {LegacyContactRecord,LegacyInfo,+ LegacyOperations,LegacyRecoverySession,- LegacyService,LegacySuggestedUser,} from "..";import { mergeLegacySuggestedUsers } from "../suggestions";@@ -146,7 +146,7 @@ const warningBannerSx = {backgroundColor: "rgba(255, 82, 82, 0.14)",};-interface LegacyDrawerContentProps {+interface LegacyDrawerContentProps<Session> {intro?: React.ReactNode;renderAddContactButton?: (props: {onClick: () => void;@@ -154,7 +154,8 @@ interface LegacyDrawerContentProps {loading: boolean;}) => React.ReactNode;open: boolean;- service: LegacyService;+ getSession: () => Promise<Session>;+ operations: LegacyOperations<Session>;suggestedUsers?: LegacySuggestedUser[];}@@ -166,13 +167,14 @@ interface ConfirmActionDialogInput {action: () => Promise<void>;}-export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({+export const LegacyDrawerContent = <Session,>({intro,open,- service,+ getSession,+ operations,suggestedUsers = [],renderAddContactButton,-}) => {+}: LegacyDrawerContentProps<Session>) => {const { showMiniDialog, onGenericError } = useBaseContext();const [info, setInfo] = useState<LegacyInfo | undefined>();const [isLoading, setIsLoading] = useState(false);@@ -185,7 +187,7 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({async (reportErrors: boolean) => {setIsLoading(true);try {- setInfo(await service.getInfo());+ setInfo(await operations.getInfo(await getSession()));return true;} catch (error) {if (reportErrors) {@@ -201,7 +203,7 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({setIsLoading(false);}},- [service, onGenericError],+ [getSession, operations, onGenericError],);const refresh = useCallback(async () => {@@ -336,7 +338,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({}setIsSubmitting(true);try {- await service.updateRecoveryNotice(+ await operations.updateRecoveryNotice(+ await getSession(),selectedOwnerContact.emergencyContact.id,selectedOwnerDays,);@@ -356,7 +359,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({setIsSubmitting(false);}}, [- service,+ getSession,+ operations,onGenericError,refreshAfterMutation,selectedOwnerContact,@@ -386,7 +390,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({continueText: "Start recovery",continueColor: "accent",action: async () => {- await service.startRecovery(+ await operations.startRecovery(+ await getSession(),selectedTrustedContact.user.id,selectedTrustedContact.emergencyContact.id,);@@ -412,7 +417,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({message: `Are you sure you want to cancel recovery of ${selectedTrustedContact.user.email}'s account?`,continueText: "Cancel recovery",action: async () => {- await service.stopRecovery(+ await operations.stopRecovery(+ await getSession(),selectedTrustedRecovery.id,selectedTrustedRecovery.user.id,selectedTrustedRecovery.emergencyContact.id,@@ -426,7 +432,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({message: `If you remove yourself as a trusted contact, you'll lose access to ${selectedTrustedContact.user.email}'s account after their inactivity period.`,continueText: "Remove contact",action: async () => {- await service.updateContact(+ await operations.updateContact(+ await getSession(),selectedTrustedContact.user.id,selectedTrustedContact.emergencyContact.id,"CONTACT_LEFT",@@ -449,7 +456,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({onSubmit={async (password) => {setIsSubmitting(true);try {- await service.changePassword(+ await operations.changePassword(+ await getSession(),resetPasswordPage.session.id,password,);@@ -742,7 +750,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({onClose={() => setActiveSheet(undefined)}><LegacyAddContactContent- service={service}+ getSession={getSession}+ operations={operations}variant="sheet"suggestedUsers={addScreenSuggestedUsers}existingEmails={existingEmails}@@ -804,7 +813,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({? "Revoke invite": "Remove contact",action: async () => {- await service.updateContact(+ await operations.updateContact(+ await getSession(),selectedOwnerContact.user.id,selectedOwnerContact.emergencyContact.id,@@ -843,7 +853,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({onClick={() =>void runAction(async () =>- service.updateContact(+ operations.updateContact(+ await getSession(),selectedTrustedInvite.user.id,selectedTrustedInvite.emergencyContact.id,@@ -860,7 +871,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({onClick={() =>void runAction(async () =>- service.updateContact(+ operations.updateContact(+ await getSession(),selectedTrustedInvite.user.id,selectedTrustedInvite.emergencyContact.id,@@ -899,7 +911,8 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({),continueText: "Reject recovery",action: async () => {- await service.rejectRecovery(+ await operations.rejectRecovery(+ await getSession(),selectedRecoveryAttempt.id,selectedRecoveryAttempt.user.id,selectedRecoveryAttempt.emergencyContactdiff --git a/web/packages/contacts/legacy/index.ts b/web/packages/contacts/legacy/index.tsindex 9e75ffa9ff..e179b397b7 100644--- a/web/packages/contacts/legacy/index.ts+++ b/web/packages/contacts/legacy/index.ts@@ -3,7 +3,7 @@ export { mergeLegacySuggestedUsers } from "./suggestions";export type {LegacyContactRecord,LegacyInfo,+ LegacyOperations,LegacyRecoverySession,- LegacyService,LegacySuggestedUser,} from "./types";diff --git a/web/packages/contacts/legacy/types.ts b/web/packages/contacts/legacy/types.tsindex 638d88e606..d303bb255c 100644--- a/web/packages/contacts/legacy/types.ts+++ b/web/packages/contacts/legacy/types.ts@@ -42,30 +42,46 @@ export interface LegacySuggestedUser {email: string;}-export interface LegacyService {- getInfo(): Promise<LegacyInfo>;- publicKey(email: string): Promise<string | undefined>;- verificationID(email: string): Promise<string | undefined>;- addContact(email: string, recoveryNoticeInDays?: number): Promise<void>;+export interface LegacyOperations<Session> {+ getInfo(session: Session): Promise<LegacyInfo>;+ publicKey(session: Session, email: string): Promise<string | undefined>;+ verificationID(publicKeyB64: string): Promise<string>;+ addContact(+ session: Session,+ email: string,+ recoveryNoticeInDays?: number,+ ): Promise<void>;updateContact(+ session: Session,userID: number,emergencyContactID: number,state: LegacyContactRecord["state"],): Promise<void>;updateRecoveryNotice(+ session: Session,emergencyContactID: number,recoveryNoticeInDays: number,): Promise<void>;- startRecovery(userID: number, emergencyContactID: number): Promise<void>;+ startRecovery(+ session: Session,+ userID: number,+ emergencyContactID: number,+ ): Promise<void>;stopRecovery(+ session: Session,recoveryID: string,userID: number,emergencyContactID: number,): Promise<void>;rejectRecovery(+ session: Session,recoveryID: string,userID: number,emergencyContactID: number,): Promise<void>;- changePassword(recoveryID: string, newPassword: string): Promise<void>;+ changePassword(+ session: Session,+ recoveryID: string,+ newPassword: string,+ ): Promise<void>;}diff --git a/web/packages/wasm/locker/legacy.ts b/web/packages/wasm/locker/legacy.tsindex 716e59370e..15f83b20b8 100644--- a/web/packages/wasm/locker/legacy.ts+++ b/web/packages/wasm/locker/legacy.ts@@ -2,82 +2,84 @@ import type { LegacyContactState, Session } from "./pkg/ente_locker_wasm";const wasm = () => import("./pkg/ente_locker_wasm");-export const createLegacyService = (getSession: () => Promise<Session>) => ({- getInfo: async () => (await wasm()).legacyGetInfo(await getSession()),+export const getInfo = async (session: Session) =>+ (await wasm()).legacyGetInfo(session);- publicKey: async (email: string) =>- (await wasm()).legacyPublicKey(await getSession(), email),+export const publicKey = async (session: Session, email: string) =>+ (await wasm()).legacyPublicKey(session, email);- verificationID: async (email: string) => {- const api = await wasm();- const key = await api.legacyPublicKey(await getSession(), email);- return key ? api.legacyVerificationID(key) : undefined;- },+export const verificationID = async (publicKeyB64: string) =>+ (await wasm()).legacyVerificationID(publicKeyB64);- addContact: async (email: string, recoveryNoticeInDays?: number) =>- (await wasm()).legacyAddContact(- await getSession(),- email,- recoveryNoticeInDays,- ),+export const addContact = async (+ session: Session,+ email: string,+ recoveryNoticeInDays?: number,+) => (await wasm()).legacyAddContact(session, email, recoveryNoticeInDays);- updateContact: async (- userID: number,- emergencyContactID: number,- state: LegacyContactState,- ) =>- (await wasm()).legacyUpdateContact(- await getSession(),- BigInt(userID),- BigInt(emergencyContactID),- state,- ),+export const updateContact = async (+ session: Session,+ userID: number,+ emergencyContactID: number,+ state: LegacyContactState,+) =>+ (await wasm()).legacyUpdateContact(+ session,+ BigInt(userID),+ BigInt(emergencyContactID),+ state,+ );- updateRecoveryNotice: async (- emergencyContactID: number,- recoveryNoticeInDays: number,- ) =>- (await wasm()).legacyUpdateRecoveryNotice(- await getSession(),- BigInt(emergencyContactID),- recoveryNoticeInDays,- ),+export const updateRecoveryNotice = async (+ session: Session,+ emergencyContactID: number,+ recoveryNoticeInDays: number,+) =>+ (await wasm()).legacyUpdateRecoveryNotice(+ session,+ BigInt(emergencyContactID),+ recoveryNoticeInDays,+ );- startRecovery: async (userID: number, emergencyContactID: number) =>- (await wasm()).legacyStartRecovery(- await getSession(),- BigInt(userID),- BigInt(emergencyContactID),- ),+export const startRecovery = async (+ session: Session,+ userID: number,+ emergencyContactID: number,+) =>+ (await wasm()).legacyStartRecovery(+ session,+ BigInt(userID),+ BigInt(emergencyContactID),+ );- stopRecovery: async (- recoveryID: string,- userID: number,- emergencyContactID: number,- ) =>- (await wasm()).legacyStopRecovery(- await getSession(),- recoveryID,- BigInt(userID),- BigInt(emergencyContactID),- ),+export const stopRecovery = async (+ session: Session,+ recoveryID: string,+ userID: number,+ emergencyContactID: number,+) =>+ (await wasm()).legacyStopRecovery(+ session,+ recoveryID,+ BigInt(userID),+ BigInt(emergencyContactID),+ );- rejectRecovery: async (- recoveryID: string,- userID: number,- emergencyContactID: number,- ) =>- (await wasm()).legacyRejectRecovery(- await getSession(),- recoveryID,- BigInt(userID),- BigInt(emergencyContactID),- ),+export const rejectRecovery = async (+ session: Session,+ recoveryID: string,+ userID: number,+ emergencyContactID: number,+) =>+ (await wasm()).legacyRejectRecovery(+ session,+ recoveryID,+ BigInt(userID),+ BigInt(emergencyContactID),+ );- changePassword: async (recoveryID: string, newPassword: string) =>- (await wasm()).legacyChangePassword(- await getSession(),- recoveryID,- newPassword,- ),-});+export const changePassword = async (+ session: Session,+ recoveryID: string,+ newPassword: string,+) => (await wasm()).legacyChangePassword(session, recoveryID, newPassword);diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.tsindex 24b46ca3c9..76bad9a0d6 100644--- a/web/packages/wasm/photos/index.ts+++ b/web/packages/wasm/photos/index.ts@@ -68,7 +68,7 @@ export const prepareCastPayload = async (collectionID: number,collectionKey: string,) =>- (await wasm()).preparePayload(+ (await wasm()).castPreparePayload(publicKey,pqPublicKey,BigInt(collectionID),diff --git a/web/packages/wasm/tests/bindings.test.ts b/web/packages/wasm/tests/bindings.test.tsindex 95ceae23e6..7144d0b906 100644--- a/web/packages/wasm/tests/bindings.test.ts+++ b/web/packages/wasm/tests/bindings.test.ts@@ -1,6 +1,6 @@import * as cast from "ente-cast-wasm";import * as locker from "ente-locker-wasm";-import { createLegacyService } from "ente-locker-wasm/legacy";+import * as legacy from "ente-locker-wasm/legacy";import * as photos from "ente-photos-wasm";import {boxSealOpenBytes,@@ -243,27 +243,26 @@ describe("Locker Legacy", () => {...(await sessionKeyAttributes(masterKey)),});try {- const legacy = createLegacyService(async () => session);- expect(await legacy.getInfo()).toStrictEqual(info);+ expect(await legacy.getInfo(session)).toStrictEqual(info);session.updateAuthToken("rotated-token");- await legacy.updateContact(42, 43, "CONTACT_LEFT");+ await legacy.updateContact(session, 42, 43, "CONTACT_LEFT");expect(updateBody).toStrictEqual({userID: 42,emergencyContactID: 43,state: "CONTACT_LEFT",});await expect(- legacy.updateRecoveryNotice(43, 30),+ legacy.updateRecoveryNotice(session, 43, 30),).rejects.toMatchObject({ name: "active_recovery_session" });recoveryErrorBody = {code: "BAD_REQUEST",message: "Cannot update during an active recovery session",};await expect(- legacy.updateRecoveryNotice(43, 30),+ legacy.updateRecoveryNotice(session, 43, 30),).rejects.not.toMatchObject({ name: "active_recovery_session" });recovery.createdAt = Number.MAX_SAFE_INTEGER + 1;- await expect(legacy.getInfo()).rejects.toBeInstanceOf(Error);+ await expect(legacy.getInfo(session)).rejects.toBeInstanceOf(Error);} finally {session.free();}@@ -303,8 +302,7 @@ describe("Locker Legacy", () => {...(await sessionKeyAttributes(masterKey, recoveryKey)),});try {- const legacy = createLegacyService(async () => session);- await legacy.addContact("[email protected]", 30);+ await legacy.addContact(session, "[email protected]", 30);expect(sharedRecoveryKey).toStrictEqual(new Uint8Array(Buffer.from(recoveryKey, "base64")),);