π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Share authenticated WASM session lifecycle
Manav Rathi5fc1c7cb6dc6
diff --git a/web/apps/auth/src/services/authenticated-session.ts b/web/apps/auth/src/services/authenticated-session.tsindex 830da8efad..80453c2ae6 100644--- a/web/apps/auth/src/services/authenticated-session.ts+++ b/web/apps/auth/src/services/authenticated-session.ts@@ -1,65 +1,11 @@-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 { createAuthenticatedSessionCache } from "ente-accounts/services/authenticated-session";+import { openSession } from "ente-auth-wasm";import { masterKeyFromSession } from "./account-keys";-let current: { key: string; opening: Promise<Session> } | undefined;-let generation = 0;+const sessions = createAuthenticatedSessionCache(+ openSession,+ masterKeyFromSession,+);-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;-};+export const ensureAuthenticatedSession = sessions.ensure;+export const clearAuthenticatedSession = sessions.clear;diff --git a/web/apps/locker/src/services/authenticated-session.ts b/web/apps/locker/src/services/authenticated-session.tsindex 3073eeb034..801d6c7994 100644--- a/web/apps/locker/src/services/authenticated-session.ts+++ b/web/apps/locker/src/services/authenticated-session.ts@@ -1,110 +1,23 @@-import {- ensureLocalUser,- ensureSavedKeyAttributes,-} from "ente-accounts/services/user";-import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";-import { apiOrigin } from "ente-base/origins";-import { savedAuthToken } from "ente-base/token";+import { createAuthenticatedSessionCache } from "ente-accounts/services/authenticated-session";import { openSession as openLegacySession } from "ente-legacy-wasm/authenticated";-import { openSession, type Session } from "ente-locker-wasm";+import { openSession } from "ente-locker-wasm";import { masterKeyFromSession } from "./account-keys";-const lockerSessions = sessionCache(openSession);-const legacySessions = sessionCache(openLegacySession);-let generation = 0;+const lockerSessions = createAuthenticatedSessionCache(+ openSession,+ masterKeyFromSession,+);+const legacySessions = createAuthenticatedSessionCache(+ openLegacySession,+ masterKeyFromSession,+);export const openAuthenticatedSession = lockerSessions.open;--const savedSessionCredentials = async () => {- const startedGeneration = generation;- const userID = ensureLocalUser().id;- const [authToken, masterKeyB64] = await Promise.all([- 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");- return { userID, authToken, masterKeyB64 };-};--export const ensureAuthenticatedSession = async () => {- const current = lockerSessions.current();- if (current) return current;-- const { userID, authToken, masterKeyB64 } = await savedSessionCredentials();- return lockerSessions.open(userID, authToken, masterKeyB64);-};--export const authenticatedLegacySession = async () => {- const { userID, authToken, masterKeyB64 } = await savedSessionCredentials();- return legacySessions.open(userID, authToken, masterKeyB64);-};+export const ensureAuthenticatedSession = () =>+ lockerSessions.current() ?? lockerSessions.ensure();+export const authenticatedLegacySession = legacySessions.ensure;export const clearAuthenticatedSession = () => {- generation++;lockerSessions.clear();legacySessions.clear();};--function sessionCache<T extends Pick<Session, "free" | "updateAuthToken">>(- open: (config: Parameters<typeof openSession>[0]) => Promise<T>,-) {- let current: { key: string; opening: Promise<T> } | undefined;-- return {- current: () => current?.opening,- open: async (- userID: number,- authToken: string,- masterKeyB64: string,- ) => {- const startedGeneration = generation;- const baseUrl = await apiOrigin();- if (startedGeneration !== generation) {- throw new Error("Authenticated session was cleared");- }- const key = `${baseUrl}:${userID}`;- if (current?.key !== key) {- const keyAttributes = ensureSavedKeyAttributes();- const opening = open({- baseUrl,- authToken,- userID,- masterKeyB64,- keyAttributes,- clientPackage: clientPackageName,- clientVersion: isDesktop ? desktopAppVersion : undefined,- })- .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;- },- clear: () => {- // In-flight calls may still borrow the handle; wasm-bindgen finalizes it.- current = undefined;- },- };-}diff --git a/web/apps/photos/src/services/authenticated-session.ts b/web/apps/photos/src/services/authenticated-session.tsindex 62efcf9753..a40ee985e8 100644--- a/web/apps/photos/src/services/authenticated-session.ts+++ b/web/apps/photos/src/services/authenticated-session.ts@@ -1,10 +1,4 @@-import {- ensureLocalUser,- ensureSavedKeyAttributes,-} from "ente-accounts/services/user";-import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";-import { apiOrigin } from "ente-base/origins";-import { savedAuthToken } from "ente-base/token";+import { createAuthenticatedSessionCache } from "ente-accounts/services/authenticated-session";import { masterKeyFromSession } from "ente-new/photos/services/account-keys";import {bindCollectionKeyOpener,@@ -12,80 +6,23 @@ import {} from "ente-new/photos/services/collection";import { openCollectionKey, openSession, type Session } from "ente-photos-wasm";-let current: { key: string; opening: Promise<Session> } | undefined;-let generation = 0;--export const openAuthenticatedSession = async (- userID: number,- authToken: string,- masterKeyB64: string,-) => {- const startedGeneration = generation;- const baseUrl = await apiOrigin();- if (startedGeneration !== generation) {- throw new Error("Authenticated session was cleared");- }- const key = `${baseUrl}:${userID}`;- if (current?.key !== key) {- const keyAttributes = ensureSavedKeyAttributes();- const opening = openSession({- baseUrl,- authToken,- userID,- masterKeyB64,- keyAttributes,- clientPackage: clientPackageName,- clientVersion: isDesktop ? desktopAppVersion : undefined,- })- .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 };- bindCollectionKeyOpener(async (input) =>- openCollectionKey(- await (current?.opening ?? ensureAuthenticatedSession()),- input.ownerID,- input.encryptedKey,- input.keyDecryptionNonce,- ),- );- }+const sessions = createAuthenticatedSessionCache((input): Promise<Session> => {+ const opening = openSession(input);+ bindCollectionKeyOpener(async (input) =>+ openCollectionKey(+ await (sessions.current() ?? sessions.ensure()),+ input.ownerID,+ input.encryptedKey,+ input.keyDecryptionNonce,+ ),+ );+ return opening;+}, masterKeyFromSession);- 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 ensureAuthenticatedSession = async () => {- const startedGeneration = generation;- const userID = ensureLocalUser().id;- const [authToken, masterKeyB64] = await Promise.all([- 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");- return openAuthenticatedSession(userID, authToken, masterKeyB64);-};+export const openAuthenticatedSession = sessions.open;+export const ensureAuthenticatedSession = sessions.ensure;export const clearAuthenticatedSession = () => {- generation++;+ sessions.clear();unbindCollectionKeyOpener();- // In-flight calls may still borrow the handle; wasm-bindgen finalizes it.- current = undefined;};diff --git a/web/packages/accounts/services/authenticated-session.ts b/web/packages/accounts/services/authenticated-session.tsnew file mode 100644index 0000000000..e02590f06c--- /dev/null+++ b/web/packages/accounts/services/authenticated-session.ts@@ -0,0 +1,97 @@+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";+import { apiOrigin } from "ente-base/origins";+import { savedAuthToken } from "ente-base/token";+import { ensureLocalUser, ensureSavedKeyAttributes } from "./user";++interface Session {+ free(): void;+ updateAuthToken(authToken: string): void;+}++interface SessionInput {+ baseUrl: string;+ authToken: string;+ userID: number;+ masterKeyB64: string;+ keyAttributes: ReturnType<typeof ensureSavedKeyAttributes>;+ clientPackage: string;+ clientVersion: string | undefined;+}++export const createAuthenticatedSessionCache = <T extends Session>(+ openSession: (input: SessionInput) => Promise<T>,+ masterKeyFromSession: () => Promise<string | undefined>,+) => {+ let current: { key: string; opening: Promise<T> } | undefined;+ let generation = 0;++ const open = async (+ userID: number,+ authToken: string,+ masterKeyB64: string,+ ) => {+ const startedGeneration = generation;+ const baseUrl = await apiOrigin();+ if (startedGeneration !== generation) {+ throw new Error("Authenticated session was cleared");+ }+ const key = `${baseUrl}:${userID}`;+ if (current?.key !== key) {+ const opening = openSession({+ baseUrl,+ authToken,+ userID,+ masterKeyB64,+ keyAttributes: ensureSavedKeyAttributes(),+ clientPackage: clientPackageName,+ clientVersion: isDesktop ? desktopAppVersion : undefined,+ })+ .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;+ };++ const ensure = async () => {+ const startedGeneration = generation;+ const userID = ensureLocalUser().id;+ const [authToken, masterKeyB64] = await Promise.all([+ 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");+ return open(userID, authToken, masterKeyB64);+ };++ return {+ current: () => current?.opening,+ open,+ ensure,+ clear: () => {+ generation++;+ // In-flight calls may still borrow the handle; wasm-bindgen finalizes it.+ current = undefined;+ },+ };+};