π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Harden Ensu storage migration
Manav Rathi12c853d82767
diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rsindex 9c295a2102..6ed763f2ad 100644--- a/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rs+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db_migration.rs@@ -32,7 +32,9 @@ pub(super) fn prepare() -> Result<(), ApiError> {let source_db = root.join(SOURCE_DB);if exists(&source_db)? {- let source_key = select_source_key(&source_db, &recovery_keys)?;+ let Ok(source_key) = select_source_key(&source_db, &recovery_keys) else {+ return Ok(());+ };import(&source_db,&root.join(SOURCE_ATTACHMENTS),@@ -42,7 +44,8 @@ pub(super) fn prepare(target_key,)?;}- cleanup(root)+ let _ = cleanup(root);+ Ok(())}fn select_source_key(path: &Path, keys: &[Vec<u8>]) -> Result<Vec<u8>, ApiError> {@@ -106,16 +109,14 @@ fn import(for attachment in message.attachments {let from = source_attachments.join(&attachment.id);let to = target_attachments.join(&attachment.id);- if exists(&from)? && !exists(&to)? {- copy_attachment(&from, &to)?;+ if from.exists() && !to.exists() {+ let _ = copy_attachment(&from, &to);}}}}- for session in target.list_sessions().map_err(ApiError::from)? {- target.get_messages(session.uuid).map_err(ApiError::from)?;- }- sync_dir(target_attachments)+ let _ = sync_dir(target_attachments);+ Ok(())}fn copy_attachment(source: &Path, target: &Path) -> Result<(), ApiError> {@@ -241,21 +242,60 @@ mod tests {}#[test]- fn failed_key_recovery_preserves_the_source() {+ fn attachment_io_failure_does_not_block_chat_import() {+ let source_key = vec![7; 32];+ let target_key = vec![8; 32];+ let (root, session, _) = fixture(&source_key);+ let target_db = root.join("target.db");+ let target_attachments = root.join("not-a-directory");+ fs::write(&target_attachments, b"file").unwrap();++ prepare(+ &root,+ &target_db,+ &target_attachments,+ target_key.clone(),+ vec![source_key],+ )+ .unwrap();++ let target = ChatDb::open_sqlite_with_defaults(target_db, target_key).unwrap();+ assert_eq!(+ target.get_messages(session).unwrap()[0].text,+ "Migrated message"+ );+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn failed_key_recovery_preserves_the_source_without_blocking_target() {let source_key = vec![10; 32];let (root, _, attachment) = fixture(&source_key);+ let target_key = vec![11; 32];+ let target_db = root.join("target.db");let target_attachments = root.join("target-attachments");fs::create_dir(&target_attachments).unwrap();+ let target = ChatDb::open_sqlite_with_defaults(&target_db, target_key.clone()).unwrap();+ let target_session = target.create_session("Current chat").unwrap();+ drop(target);- assert!(- prepare(- &root,- &root.join("target.db"),- &target_attachments,- vec![11; 32],- vec![vec![12; 32]],- )- .is_err()+ prepare(+ &root,+ &target_db,+ &target_attachments,+ target_key.clone(),+ vec![vec![12; 32]],+ )+ .unwrap();++ let target = ChatDb::open_sqlite_with_defaults(target_db, target_key).unwrap();+ assert_eq!(+ target+ .get_session(target_session.uuid)+ .unwrap()+ .unwrap()+ .title,+ "Current chat");assert!(root.join(SOURCE_DB).exists());assert!(root.join(SOURCE_ATTACHMENTS).join(attachment).exists());diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 2c408d2df4..b654f92475 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -756,27 +756,21 @@ const Page: React.FC = () => {);const refreshLocalChatKey = useCallback(async () => {- await initChatKeyStore();-- const cachedLocal = cachedLocalChatKey();- if (cachedLocal) {- log.info("Using cached local chat key");- setChatKey(cachedLocal);- return;- }-try {+ await initChatKeyStore();+ const cachedLocal = cachedLocalChatKey();+ if (cachedLocal) {+ log.info("Using cached local chat key");+ setChatKey(cachedLocal);+ return;+ }log.info("Generating new local chat key");setChatKey(await getOrCreateLocalChatKey());} catch (error) {log.error("Failed to initialize local chat key", error);- showMiniDialog({- title: "Encryption error",- message:- "We could not initialize encryption. Please refresh the page.",- });+ onGenericError(error);}- }, [showMiniDialog]);+ }, [onGenericError]);useEffect(() => {chatKeyInitCancelledRef.current = false;@@ -812,12 +806,7 @@ const Page: React.FC = () => {if (!cancelled) setIsChatStoreBridgeReady(true);} catch (error) {log.error("Failed to initialize chat persistence", error);- if (!cancelled)- showMiniDialog({- title: "Chat data unavailable",- message:- "Ensu could not safely open your local chats. Your existing data has not been removed.",- });+ if (!cancelled) onGenericError(error);}};void run();@@ -826,7 +815,7 @@ const Page: React.FC = () => {cancelled = true;setIsChatStoreBridgeReady(false);};- }, [chatKey, showMiniDialog]);+ }, [chatKey, onGenericError]);useEffect(() => {isDraftSessionRef.current = isDraftSession;diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex 74d9945155..3de0fbad5f 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -1,7 +1,11 @@import { isTauriRuntime } from "@/services/tauri-runtime";import { secureStorageGet, secureStorageSet } from "../secure-storage";import { ensureCryptoInit, enteWasm } from "../wasm";-import { hasRetiredLocalChatStore, promoteLocalChatKey } from "./compatibility";+import {+ hasRetiredLocalChatStore,+ promoteLocalChatKey,+ retiredBrowserChatKey,+} from "./compatibility";const LOCAL_KEY = "ensu.chatKey.local";const CURRENT_SECURE_KEY = "localChatKey.v2";@@ -32,8 +36,12 @@ export const initChatKeyStore = async () => {return _initPromise;};-export const cachedLocalChatKey = () =>- isTauriRuntime() ? _localKey : localGet(LOCAL_KEY);+export const cachedLocalChatKey = () => {+ if (isTauriRuntime()) return _localKey;+ const key = localGet(LOCAL_KEY) ?? retiredBrowserChatKey();+ if (key) localStorage.setItem(LOCAL_KEY, key);+ return key;+};const persistLocalKey = async (key: string) => {if (isTauriRuntime()) {diff --git a/web/apps/ensu/src/services/chat/compatibility.ts b/web/apps/ensu/src/services/chat/compatibility.tsindex 5d974fb494..6aac8faa27 100644--- a/web/apps/ensu/src/services/chat/compatibility.ts+++ b/web/apps/ensu/src/services/chat/compatibility.ts@@ -30,6 +30,7 @@ const OLD_INDEXED_DB = "ensu.chat.db";const MIGRATION_DONE = "ensu.chat.localMigration.v3";const OLD_LOCAL_SECURE_KEY = "localChatKey";const OLD_LOCAL_BROWSER_KEY = "ensu.chatKey.local";+const OLD_REMOTE_BROWSER_KEY = "ensu.chatKey";const KEY_FILE = "chat-keys.json";const LEGACY_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";@@ -124,47 +125,59 @@ const retiredUserID = () => {}};-const finalizeLocalChatMigration = async (deleteOldLocalKeys: boolean) => {+export const retiredBrowserChatKey = () => {+ if (typeof localStorage === "undefined") return undefined;const userID = retiredUserID();- localStorage.removeItem(LOCAL_STORAGE_STORE);- const secureKeys = [- "masterKey",- "remoteChatKey",- ...(userID- ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]- : []),+ const names = [+ OLD_REMOTE_BROWSER_KEY,+ ...(userID ? [`${OLD_REMOTE_BROWSER_KEY}.${userID}`] : []),+ ...Object.keys(localStorage).filter(+ (key) =>+ key.startsWith(`${OLD_REMOTE_BROWSER_KEY}.`) &&+ key !== OLD_LOCAL_BROWSER_KEY,+ ),];- if (deleteOldLocalKeys) {- secureKeys.push(OLD_LOCAL_SECURE_KEY, LEGACY_ATTACHMENT_SECURE_KEY);- }- await Promise.all(secureKeys.map(secureStorageDelete));+ return names.map(localGet).find(Boolean);+};++const finalizeLocalChatMigration = async () => {+ try {+ const userID = retiredUserID();+ localStorage.removeItem(LOCAL_STORAGE_STORE);+ await Promise.all(+ [+ "masterKey",+ "remoteChatKey",+ ...(userID+ ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]+ : []),+ OLD_LOCAL_SECURE_KEY,+ LEGACY_ATTACHMENT_SECURE_KEY,+ ].map(secureStorageDelete),+ );- if (deleteOldLocalKeys) {const [{ exists, remove }, { appDataDir, join }] = await Promise.all([import("@tauri-apps/plugin-fs"),import("@tauri-apps/api/path"),]);const keyFile = await join(await appDataDir(), KEY_FILE);if (await exists(keyFile)) await remove(keyFile);- }- for (const key of Object.keys(localStorage)) {- if (- key.startsWith("ensu.chatKey") &&- (deleteOldLocalKeys || key !== OLD_LOCAL_BROWSER_KEY)- ) {- localStorage.removeItem(key);+ for (const key of Object.keys(localStorage)) {+ if (key.startsWith("ensu.chatKey")) localStorage.removeItem(key);}+ [+ "user",+ "srpAttributes",+ "keyAttributes",+ "originalKeyAttributes",+ "isFirstLogin",+ "ensu.chat.nativeMigration.v2",+ ].forEach((key) => localStorage.removeItem(key));+ await removeKV("token");+ } catch (error) {+ log.warn("Could not finish cleaning up old chat storage", error);}- [- "user",- "srpAttributes",- "keyAttributes",- "originalKeyAttributes",- "isFirstLogin",- "ensu.chat.nativeMigration.v2",- ].forEach((key) => localStorage.removeItem(key));- await removeKV("token");localStorage.setItem(MIGRATION_DONE, "1");};@@ -192,19 +205,24 @@ const liveStore = (const localStorageStore = (): BrowserStore => {const json = localStorage.getItem(LOCAL_STORAGE_STORE);if (!json) return { sessions: [], messages: [], attachmentBytes: [] };- const parsed = JSON.parse(json) as Partial<{- sessions: OldSession[];- messages: OldMessage[];- attachmentBytes: { id: string; data: string }[];- }>;- return liveStore(- parsed.sessions ?? [],- parsed.messages ?? [],- (parsed.attachmentBytes ?? []).map(({ id, data }) => ({- id,- data: base64ToBytes(data),- })),- );+ try {+ const parsed = JSON.parse(json) as Partial<{+ sessions: OldSession[];+ messages: OldMessage[];+ attachmentBytes: { id: string; data: string }[];+ }>;+ return liveStore(+ parsed.sessions ?? [],+ parsed.messages ?? [],+ (parsed.attachmentBytes ?? []).map(({ id, data }) => ({+ id,+ data: base64ToBytes(data),+ })),+ );+ } catch (error) {+ log.warn("Ignoring an unreadable old local chat store", error);+ return { sessions: [], messages: [], attachmentBytes: [] };+ }};const hasLocalStorageStore = () => !!localStorage.getItem(LOCAL_STORAGE_STORE);@@ -247,9 +265,9 @@ const removeCurrentBrowserTombstones = async () => {);const tx = db.transaction(["sessions", "messages"], "readwrite");await Promise.all([- ...deletedSessions- .values()- .map((id) => tx.objectStore("sessions").delete(id)),+ ...[...deletedSessions].map((id) =>+ tx.objectStore("sessions").delete(id),+ ),...deletedMessages.map(({ messageUuid }) =>tx.objectStore("messages").delete(messageUuid),),@@ -258,15 +276,18 @@ const removeCurrentBrowserTombstones = async () => {localStorage.setItem(TOMBSTONE_MIGRATION, "1");};-const hasIndexedDb = async (name: string) => {- return (await indexedDB.databases()).some(- (database) => database.name === name,- );-};-const readOldIndexedDb = async () => {- if (!(await hasIndexedDb(OLD_INDEXED_DB))) return undefined;- const source = await openDB<OldIndexedDb>(OLD_INDEXED_DB);+ let created = false;+ const source = await openDB<OldIndexedDb>(OLD_INDEXED_DB, undefined, {+ upgrade: () => {+ created = true;+ },+ });+ if (created) {+ source.close();+ await deleteDB(OLD_INDEXED_DB);+ return undefined;+ }try {return liveStore(await source.getAll("sessions"),@@ -278,44 +299,22 @@ const readOldIndexedDb = async () => {}};-const hasChatData = ({ sessions, messages }: BrowserStore) =>- sessions.length > 0 || messages.length > 0;--const cleanupOldBrowserStores = () => {- try {- localStorage.removeItem(LOCAL_STORAGE_STORE);- } catch (error) {- log.warn("Failed to remove the old local chat store", error);- }- void deleteDB(OLD_INDEXED_DB, {- blocked: () => log.warn("Waiting for the old chat DB to close"),- }).catch((error: unknown) =>- log.warn("Failed to remove the old chat DB", error),- );-};-const importOldBrowserStores = async () => {- const current = await chatDb();- const [sessions, messages] = await Promise.all([- current.getAll("sessions"),- current.getAll("messages"),- ]);- if (sessions.length || messages.length) {- cleanupOldBrowserStores();+ if (isLocalChatMigrationDone()) return;+ if (hasLocalStorageStore()) {+ await writeBrowserStore(localStorageStore());+ localStorage.removeItem(LOCAL_STORAGE_STORE);return;}- const indexedDbStore = await readOldIndexedDb();- const source =- indexedDbStore && hasChatData(indexedDbStore)- ? indexedDbStore- : hasLocalStorageStore()- ? localStorageStore()- : undefined;- if (source && hasChatData(source)) {+ const source = await readOldIndexedDb();+ if (source) {await writeBrowserStore(source);+ await deleteDB(OLD_INDEXED_DB, {+ blocked: () => log.warn("Waiting for the old chat DB to close"),+ });}- cleanupOldBrowserStores();+ localStorage.setItem(MIGRATION_DONE, "1");};const localStorageSourceKey = async (@@ -405,12 +404,64 @@ const decryptAttachmentWith = async (return undefined;};+const reencryptAttachment = async (+ id: string,+ sessionUuid: string,+ chatKey: string,+ candidates: string[],+) => {+ const stagingID = `${id}.migrating`;+ if (await attachmentBytesExists(stagingID)) {+ const staged = await readAttachmentBytes(stagingID);+ if (await decryptAttachmentWith(staged, [chatKey], sessionUuid)) {+ await writeAttachmentBytes(id, staged);+ await decryptAttachmentBytes(+ await readAttachmentBytes(id),+ chatKey,+ sessionUuid,+ );+ await deleteAttachmentBytes(stagingID);+ return;+ }+ await deleteAttachmentBytes(stagingID);+ }+ if (!(await attachmentBytesExists(id))) return;++ const decrypted = await decryptAttachmentWith(+ await readAttachmentBytes(id),+ candidates,+ sessionUuid,+ );+ if (!decrypted) {+ log.warn(`No stored key can decrypt attachment ${id}`);+ return;+ }+ const [plaintext, key] = decrypted;+ if (key === chatKey) return;++ await writeAttachmentBytes(+ stagingID,+ await encryptAttachmentBytes(plaintext, chatKey, sessionUuid),+ );+ const staged = await readAttachmentBytes(stagingID);+ await decryptAttachmentBytes(staged, chatKey, sessionUuid);+ await writeAttachmentBytes(id, staged);+ await decryptAttachmentBytes(+ await readAttachmentBytes(id),+ chatKey,+ sessionUuid,+ );+ await deleteAttachmentBytes(stagingID);+};+const reencryptAttachments = async (chatKey: string, sourceKeys: string[]) => {- const candidates = distinctKeys([- ...sourceKeys,- await secureStorageGet(LEGACY_ATTACHMENT_SECURE_KEY),- ]);- let allCurrent = true;+ const legacyAttachmentKey = await secureStorageGet(+ LEGACY_ATTACHMENT_SECURE_KEY,+ ).catch((error: unknown) => {+ log.warn("Could not read the old attachment key", error);+ return undefined;+ });+ const candidates = distinctKeys([...sourceKeys, legacyAttachmentKey]);for (const { sessionUuid } of await invokeChat<{ sessionUuid: string }[]>("chat_db_list_sessions",@@ -421,54 +472,16 @@ const reencryptAttachments = async (chatKey: string, sourceKeys: string[]) => {{ sessionUuid },)).flatMap(({ attachments }) => attachments ?? [])) {- const stagingID = `${id}.migrating`;- if (await attachmentBytesExists(stagingID)) {- const staged = await readAttachmentBytes(stagingID);- if (- await decryptAttachmentWith(staged, [chatKey], sessionUuid)- ) {- await writeAttachmentBytes(id, staged);- await decryptAttachmentBytes(- await readAttachmentBytes(id),- chatKey,- sessionUuid,- );- await deleteAttachmentBytes(stagingID);- continue;- }- await deleteAttachmentBytes(stagingID);- }- if (!(await attachmentBytesExists(id))) continue;-- const decrypted = await decryptAttachmentWith(- await readAttachmentBytes(id),- candidates,+ await reencryptAttachment(+ id,sessionUuid,- );- if (!decrypted) {- allCurrent = false;- log.warn(`No stored key can decrypt attachment ${id}`);- continue;- }- const [plaintext, key] = decrypted;- if (key === chatKey) continue;-- await writeAttachmentBytes(- stagingID,- await encryptAttachmentBytes(plaintext, chatKey, sessionUuid),- );- const staged = await readAttachmentBytes(stagingID);- await decryptAttachmentBytes(staged, chatKey, sessionUuid);- await writeAttachmentBytes(id, staged);- await decryptAttachmentBytes(- await readAttachmentBytes(id),chatKey,- sessionUuid,+ candidates,+ ).catch((error: unknown) =>+ log.warn(`Could not migrate attachment ${id}`, error),);- await deleteAttachmentBytes(stagingID);}}- return allCurrent;};export const openChatStoreWithCompatibility = async (chatKey: string) => {@@ -483,11 +496,18 @@ export const openChatStoreWithCompatibility = async (chatKey: string) => {});if (migrationPending) {if (hasLocalStorageStore()) {- await importLocalStorageToNative(sourceKeys);+ try {+ await importLocalStorageToNative(sourceKeys);+ } catch (error) {+ log.warn(+ "Could not import the old local chat store",+ error,+ );+ return;+ }}- await finalizeLocalChatMigration(- await reencryptAttachments(chatKey, sourceKeys),- );+ await reencryptAttachments(chatKey, sourceKeys);+ await finalizeLocalChatMigration();}} else {await removeCurrentBrowserTombstones();