π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify Ensu local storage migration
Manav Rathicb04f187ca8b
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.ktindex c08b8dcb91..604449d6a2 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt@@ -24,7 +24,7 @@ class ChatRepository(private val filePaths = FilePathManager(context)private val attachmentsDir = filePaths.attachmentsDirprivate val dbFile = filePaths.mainDbFile- private val dbKey = credentialStore.getOrCreateChatDbKey()+ private val dbKey = credentialStore.getOrCreateChatDbKey(filePaths.hasChatData)private var db: EnsuDb = openDb(dbFile, dbKey)fun listSessions(): List<ChatSession> = withDbRecovery {diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.ktindex b72960d32c..98ad1f4d95 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt@@ -18,15 +18,17 @@ class CredentialStore(context: Context) {EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM)- fun getOrCreateChatDbKey(): ByteArray {- prefs.getString(KEY_CHAT_DB_KEY, null)?.let { existing ->- val decoded = runCatching { decode(existing) }.getOrNull()- if (decoded != null && decoded.size == 32) return decoded+ fun getOrCreateChatDbKey(hasChatData: Boolean): ByteArray {+ prefs.getString(KEY_CHAT_DB_KEY, null)?.let { encoded ->+ val decoded = decode(encoded)+ check(decoded.size == 32) { "Stored chat DB key has invalid length" }+ return decoded}+ check(!hasChatData) { "Existing chat data has no encryption key" }val generated = ByteArray(32)java.security.SecureRandom().nextBytes(generated)- prefs.edit().putString(KEY_CHAT_DB_KEY, encode(generated)).apply()+ check(prefs.edit().putString(KEY_CHAT_DB_KEY, encode(generated)).commit())return generated}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.ktindex 3334e9e72b..72b49ba994 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt@@ -7,6 +7,8 @@ class FilePathManager(context: Context) {private val appDataDir: File = ensureDir(context.filesDir)val attachmentsDir: File = ensureDir(File(appDataDir, "attachments"))val mainDbFile: File = File(appDataDir, "llmchat.db")+ val hasChatData: Boolean+ get() = mainDbFile.exists() || (attachmentsDir.list()?.isNotEmpty() ?: true)private fun ensureDir(dir: File): File {if (!dir.exists()) {diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex 6a1191b975..e8bf035a52 100644--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -133,8 +133,15 @@ final class ChatViewModel: ObservableObject {let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)try? FileManager.default.createDirectory(at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)- let chatDbKey = CredentialStore.shared.getOrCreateChatDbKey()let chatDbPath = dbDir.appendingPathComponent("llmchat.db").path+ let hasChatData = FileManager.default.fileExists(atPath: chatDbPath) ||+ (try? FileManager.default.contentsOfDirectory(atPath: attachmentsDir.path).isEmpty) != true+ let chatDbKey: Data+ do {+ chatDbKey = try CredentialStore.shared.getOrCreateChatDbKey(hasChatData: hasChatData)+ } catch {+ fatalError("Failed to load chat DB key: \(error)")+ }let chatDb: EnsuDbdo {diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swiftindex d56e65211d..7e14708e00 100644--- a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift@@ -12,18 +12,18 @@ final class CredentialStore {static let chatDbKey = "ensu.chatDbKey"}- func getOrCreateChatDbKey() -> Data {- if let existing = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), existing.count == 32 {+ func getOrCreateChatDbKey(hasChatData: Bool) throws -> Data {+ if let existing = try KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey) {+ guard existing.count == 32 else { throw KeychainStoreError.invalidItemFormat }return existing}+ guard !hasChatData else { throw KeychainStoreError.invalidItemFormat }var bytes = [UInt8](repeating: 0, count: 32)let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)- if status != errSecSuccess {- bytes = (0..<32).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }- }+ guard status == errSecSuccess else { throw KeychainStoreError.unexpectedStatus(status) }let data = Data(bytes)- try? KeychainStore.set(data, service: keychainService, account: KeychainAccount.chatDbKey)+ try KeychainStore.set(data, service: keychainService, account: KeychainAccount.chatDbKey)return data}}diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rsindex 00a27fc167..31e4d9ec18 100644--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs@@ -1,5 +1,4 @@-use std::collections::{HashMap, HashSet};-use std::fs;+use std::fs::{self, File};use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};@@ -231,16 +230,6 @@ pub struct ChatMessageUpsertInput {#[serde(rename_all = "camelCase")]pub struct ChatDbImportV1Input {key_b64: String,- v1_key_b64: String,-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ChatDbImportV1Result {- did_migrate: bool,- migrated_sessions: i64,- migrated_messages: i64,- migrated_attachments: i64,}#[tauri::command]@@ -430,15 +419,47 @@ pub async fn chat_db_insert_message_with_uuid(}#[tauri::command]-pub async fn chat_db_import_v1(- app: AppHandle,- input: ChatDbImportV1Input,-) -> Result<ChatDbImportV1Result, ApiError> {+pub async fn chat_db_import_v1(app: AppHandle, input: ChatDbImportV1Input) -> Result<(), ApiError> {async_runtime::spawn_blocking(move || import_v1_chat_db(&app, &input)).await.map_err(|_| chat_db_thread_error())?}+#[tauri::command]+pub fn chat_db_cleanup_v1(app: AppHandle) -> Result<(), ApiError> {+ cleanup_v1_chat_artifacts(&app)+}++#[tauri::command]+pub fn chat_db_has_existing_store(app: AppHandle) -> Result<bool, ApiError> {+ let root = app_data_dir(&app)?;+ for name in [CHAT_DB_FILE_NAME, V1_CHAT_DB_FILE_NAME] {+ if root+ .join(name)+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {+ return Ok(true);+ }+ }+ for name in [ATTACHMENTS_DIR_NAME, V1_ATTACHMENTS_DIR_NAME] {+ let path = root.join(name);+ if path+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ && fs::read_dir(path)+ .map_err(|error| ApiError::new("io", error.to_string()))?+ .next()+ .transpose()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ .is_some()+ {+ return Ok(true);+ }+ }+ Ok(false)+}+#[tauri::command]pub async fn chat_db_compress_attachment_image_file(path: String) -> Result<Vec<u8>, ApiError> {async_runtime::spawn_blocking(move || {@@ -509,7 +530,10 @@ fn remove_sqlite_files(path: &Path) -> Result<(), ApiError> {PathBuf::from(format!("{}-wal", path.display())),PathBuf::from(format!("{}-shm", path.display())),] {- if candidate.exists() {+ if candidate+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {fs::remove_file(candidate).map_err(|error| ApiError::new("io", error.to_string()))?;}}@@ -520,94 +544,61 @@ fn cleanup_v1_chat_artifacts(app: &AppHandle) -> Result<(), ApiError> {remove_sqlite_files(&v1_chat_db_path(app)?)?;remove_sqlite_files(&v1_attachments_db_path(app)?)?;let attachments_dir = v1_attachments_dir_path(app)?;- if attachments_dir.exists() {+ if attachments_dir+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {fs::remove_dir_all(attachments_dir).map_err(|error| ApiError::new("io", error.to_string()))?;}Ok(())}-fn verify_migrated_chat_db(- target: &ChatDb<SqliteBackend>,- session_ids: &[Uuid],- message_ids: &HashMap<Uuid, Vec<Uuid>>,- attachments_dir: &Path,- attachment_ids: &[String],-) -> Result<(), ApiError> {- let target_sessions = target- .list_sessions()- .map_err(ApiError::from)?- .into_iter()- .map(|session| session.uuid)- .collect::<HashSet<_>>();- for uuid in session_ids {- if !target_sessions.contains(uuid) {- return Err(ApiError::new(- "db_migration_verification",- format!("Missing migrated session {uuid}"),- ));- }+fn copy_v1_attachment(source: &Path, destination: &Path) -> Result<(), ApiError> {+ if destination+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {+ return Ok(());}+ let temporary = destination.with_extension("migrating");+ fs::copy(source, &temporary).map_err(|error| ApiError::new("io", error.to_string()))?;+ File::open(&temporary)+ .and_then(|file| file.sync_all())+ .map_err(|error| ApiError::new("io", error.to_string()))?;+ fs::rename(temporary, destination).map_err(|error| ApiError::new("io", error.to_string()))+}- for (session_uuid, expected) in message_ids {- let actual = target- .get_messages(*session_uuid)- .map_err(ApiError::from)?- .into_iter()- .map(|message| message.uuid)- .collect::<HashSet<_>>();- for uuid in expected {- if !actual.contains(uuid) {- return Err(ApiError::new(- "db_migration_verification",- format!("Missing migrated message {uuid}"),- ));- }- }- }+#[cfg(unix)]+fn sync_dir(path: &Path) -> Result<(), ApiError> {+ File::open(path)+ .and_then(|file| file.sync_all())+ .map_err(|error| ApiError::new("io", error.to_string()))+}- for id in attachment_ids {- if !attachments_dir.join(id).exists() {- return Err(ApiError::new(- "db_migration_verification",- format!("Missing migrated attachment {id}"),- ));- }- }+#[cfg(not(unix))]+fn sync_dir(_path: &Path) -> Result<(), ApiError> {Ok(())}-fn import_v1_chat_db(- app: &AppHandle,- input: &ChatDbImportV1Input,-) -> Result<ChatDbImportV1Result, ApiError> {+fn import_v1_chat_db(app: &AppHandle, input: &ChatDbImportV1Input) -> Result<(), ApiError> {let v1_db_path = v1_chat_db_path(app)?;- if !v1_db_path.exists() {- return Ok(ChatDbImportV1Result {- did_migrate: false,- migrated_sessions: 0,- migrated_messages: 0,- migrated_attachments: 0,- });+ if !v1_db_path+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {+ return Ok(());}let v1_attachments_dir = v1_attachments_dir_path(app)?;let target_attachments_dir = attachments_dir_path(app)?;- let v1_key = crypto::decode_b64(&input.v1_key_b64).map_err(ApiError::from)?;let key = crypto::decode_b64(&input.key_b64).map_err(ApiError::from)?;- let v1_db = ChatDb::open_sqlite_with_defaults(&v1_db_path, v1_key).map_err(ApiError::from)?;+ let v1_db =+ ChatDb::open_sqlite_with_defaults(&v1_db_path, key.clone()).map_err(ApiError::from)?;let target =ChatDb::open_sqlite_with_defaults(chat_db_path(app)?, key).map_err(ApiError::from)?;- let mut migrated_sessions = 0;- let mut migrated_messages = 0;- let mut migrated_attachments = 0;- let mut session_ids = Vec::new();- let mut message_ids = HashMap::new();- let mut attachment_ids = Vec::new();-for session in v1_db.list_sessions().map_err(ApiError::from)? {- session_ids.push(session.uuid);target.upsert_session(session.uuid,@@ -616,13 +607,8 @@ fn import_v1_chat_db(session.updated_at,).map_err(ApiError::from)?;- migrated_sessions += 1;for message in v1_db.get_messages(session.uuid).map_err(ApiError::from)? {- message_ids- .entry(session.uuid)- .or_insert_with(Vec::new)- .push(message.uuid);target.insert_message_with_uuid(message.uuid,@@ -638,35 +624,17 @@ fn import_v1_chat_db(for attachment in message.attachments {let source = v1_attachments_dir.join(&attachment.id);let destination = target_attachments_dir.join(&attachment.id);- if source.exists() && !destination.exists() {- fs::copy(&source, &destination)- .map_err(|error| ApiError::new("io", error.to_string()))?;- migrated_attachments += 1;- }- if source.exists() {- attachment_ids.push(attachment.id);+ if source+ .try_exists()+ .map_err(|error| ApiError::new("io", error.to_string()))?+ {+ copy_v1_attachment(&source, &destination)?;}}- migrated_messages += 1;}}-- verify_migrated_chat_db(- &target,- &session_ids,- &message_ids,- &target_attachments_dir,- &attachment_ids,- )?;- drop(v1_db);- cleanup_v1_chat_artifacts(app)?;-- Ok(ChatDbImportV1Result {- did_migrate: true,- migrated_sessions,- migrated_messages,- migrated_attachments,- })+ sync_dir(&target_attachments_dir)?;+ Ok(())}fn with_chat_db<T, F>(diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rsindex d97566c0f6..f1f6999321 100644--- a/rust/apps/ensu/src-tauri/src/main.rs+++ b/rust/apps/ensu/src-tauri/src/main.rs@@ -53,6 +53,8 @@ fn main() {commands::chat_db::chat_db_insert_message_with_uuid,commands::chat_db::chat_db_compress_attachment_image_file,commands::chat_db::chat_db_import_v1,+ commands::chat_db::chat_db_cleanup_v1,+ commands::chat_db::chat_db_has_existing_store,commands::llm::llm_init_backend,commands::llm::llm_load_model,commands::llm::llm_create_context,diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex b025839097..7a7699dab4 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -808,12 +808,15 @@ const Page: React.FC = () => {const run = async () => {try {await initializeChatStorePersistence(chatKey);+ if (!cancelled) setIsChatStoreBridgeReady(true);} catch (error) {log.error("Failed to initialize chat persistence", error);- } finally {- if (!cancelled) {- setIsChatStoreBridgeReady(true);- }+ if (!cancelled)+ showMiniDialog({+ title: "Chat data unavailable",+ message:+ "Ensu could not safely open your local chats. Your existing data has not been removed.",+ });}};void run();@@ -822,7 +825,7 @@ const Page: React.FC = () => {cancelled = true;setIsChatStoreBridgeReady(false);};- }, [chatKey]);+ }, [chatKey, showMiniDialog]);useEffect(() => {isDraftSessionRef.current = isDraftSession;diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex 351fc03eaa..4317be3370 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -1,5 +1,5 @@import { isTauriRuntime } from "@/services/tauri-runtime";-import log from "ente-base/log";+import { removeKV } from "ente-base/kv";import {secureStorageDelete,secureStorageGet,@@ -7,253 +7,160 @@ import {} from "../secure-storage";import { ensureCryptoInit, enteWasm } from "../wasm";-const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";-const CHAT_KEY_FILE_NAME = "chat-keys.json";-const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey.v2";-const V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY = "legacyAttachmentKey.v2";-const V1_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";+const LOCAL_KEY = "ensu.chatKey.local";+const LOCAL_STORE = "ensu.chat.store.v1";+const MIGRATION_DONE = "ensu.chat.localMigration.v3";+const CURRENT_SECURE_KEY = "localChatKey.v2";+const V1_LOCAL_SECURE_KEY = "localChatKey";+const V1_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";+const KEY_FILE = "chat-keys.json";type NativeChatKeys = { localChatKey?: string };-let _localChatKey: string | undefined;-let _v1LocalChatKey: string | undefined;-let _v1AttachmentChatKey: string | undefined;-let _v1ChatKeyCandidates: string[] = [];-let _chatKeyStoreInitPromise: Promise<void> | undefined;+let _localKey: string | undefined;+let _initPromise: Promise<void> | undefined;-const readLocalStorageKey = (key: string) => {- if (typeof localStorage === "undefined") return undefined;- return localStorage.getItem(key) ?? undefined;-};--const writeLocalStorageKey = (key: string, value: string) => {- if (typeof localStorage === "undefined") return;- localStorage.setItem(key, value);-};--const removeLocalStorageKey = (key: string) => {- if (typeof localStorage === "undefined") return;- localStorage.removeItem(key);-};+const localGet = (key: string) =>+ typeof localStorage === "undefined"+ ? undefined+ : (localStorage.getItem(key) ?? undefined);-const nativeChatKeyPath = async () => {+const keyFilePath = async () => {const { appDataDir, join } = await import("@tauri-apps/api/path");- const root = await appDataDir();- return join(root, CHAT_KEY_FILE_NAME);+ return join(await appDataDir(), KEY_FILE);};-const readNativeChatKeys = async (): Promise<NativeChatKeys> => {- if (!isTauriRuntime()) return {};-+const readKeyFile = async (): Promise<NativeChatKeys> => {const [{ exists, readFile }, path] = await Promise.all([import("@tauri-apps/plugin-fs"),- nativeChatKeyPath(),+ keyFilePath(),]);-if (!(await exists(path))) return {};-try {- const raw = new TextDecoder().decode(await readFile(path));- const parsed = JSON.parse(raw) as NativeChatKeys;- return {- localChatKey:- typeof parsed.localChatKey === "string"- ? parsed.localChatKey- : undefined,- };+ const parsed = JSON.parse(+ new TextDecoder().decode(await readFile(path)),+ ) as NativeChatKeys;+ return typeof parsed.localChatKey === "string" ? parsed : {};} catch {return {};}};-const persistNativeChatKeys = async () => {- if (!isTauriRuntime()) return;-- const operations: Promise<void>[] = [];- if (_localChatKey) {- operations.push(- secureStorageSet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY, _localChatKey),- );- } else {- operations.push(secureStorageDelete(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY));- }-- await Promise.all(operations);-};--const persistNativeChatKeysSoon = () => {- persistNativeChatKeys().catch(() => {- // Best effort cache persistence.- });-};--const cleanupV1ChatKeyCopies = async () => {- removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);-- try {- const { remove } = await import("@tauri-apps/plugin-fs");- const path = await nativeChatKeyPath();- await remove(path);- } catch {- // The v1 key file may not exist.- }-};+export const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";export const initChatKeyStore = async () => {if (!isTauriRuntime()) return;+ if (_initPromise) return _initPromise;- if (_chatKeyStoreInitPromise) return _chatKeyStoreInitPromise;-- _chatKeyStoreInitPromise = (async () => {- const [- secureLocalChatKey,- secureV1AttachmentKey,- secureV1LocalChatKey,- nativeKeys,- ] = await Promise.all([- secureStorageGet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(- () => undefined,- ),- secureStorageGet(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY).catch(- () => undefined,- ),- secureStorageGet(V1_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(- () => undefined,- ),- readNativeChatKeys(),- ]);- // Prefer localStorage over v1 secure storage for the local key.- // Pre-v0.1.12 builds only used localStorage, so when both exist the- // localStorage value is the key that actually encrypted the v1 DB.- // Stale OS keyring entries from a previous v0.1.12 install can shadow- // the correct localStorage key if secure storage is checked first.- const v1LocalChatKey =- readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??- secureV1LocalChatKey ??- nativeKeys.localChatKey;- const localChatKey = secureLocalChatKey ?? v1LocalChatKey;-- _localChatKey = localChatKey;- _v1LocalChatKey = v1LocalChatKey;- _v1AttachmentChatKey = secureV1AttachmentKey;-- // Capture v1 candidates before cleanup removes their old copies.- {- const rawLocalStorage = readLocalStorageKey(- LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY,- );- const seen = new Set<string>();- const all: string[] = [];- for (const k of [- secureLocalChatKey,- secureV1LocalChatKey,- nativeKeys.localChatKey,- rawLocalStorage,- ]) {- if (k && !seen.has(k)) {- seen.add(k);- all.push(k);- }- }- _v1ChatKeyCandidates = all;+ _initPromise = (async () => {+ const current = await secureStorageGet(CURRENT_SECURE_KEY);+ if (isLocalChatMigrationDone()) {+ _localKey = current;+ return;}- if (secureLocalChatKey !== localChatKey) {- try {- await persistNativeChatKeys();- } catch (error) {- log.warn(- "Failed to persist chat keys to secure storage; continuing with in-memory keys",- error,- );- return;- }- }-- try {- await cleanupV1ChatKeyCopies();- } catch (error) {- log.warn("Failed to clean up v1 chat key copies", error);+ const [v1Local, file] = await Promise.all([+ secureStorageGet(V1_LOCAL_SECURE_KEY),+ readKeyFile(),+ ]);+ _localKey =+ current ?? localGet(LOCAL_KEY) ?? v1Local ?? file.localChatKey;+ if (_localKey && current !== _localKey) {+ await secureStorageSet(CURRENT_SECURE_KEY, _localKey);}})().catch((error: unknown) => {- _chatKeyStoreInitPromise = undefined;+ _initPromise = undefined;throw error;});-- return _chatKeyStoreInitPromise;+ return _initPromise;};-const setCachedChatKey = (chatKey: string) => {- if (isTauriRuntime()) {- _localChatKey = chatKey;- persistNativeChatKeysSoon();- return;- }-- writeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);-};--/**- * Return the cached local-only chat key (base64), if present.- */-export const cachedLocalChatKey = (): string | undefined => {- if (isTauriRuntime()) {- return _localChatKey;- }-- return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);-};+export const cachedLocalChatKey = () =>+ isTauriRuntime() ? _localKey : localGet(LOCAL_KEY);-export const v1LocalChatKey = (): string | undefined => {+const persistLocalKey = async (key: string) => {if (isTauriRuntime()) {- return _v1LocalChatKey;+ await secureStorageSet(CURRENT_SECURE_KEY, key);+ _localKey = key;+ } else {+ localStorage.setItem(LOCAL_KEY, key);}-- return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);-};--/**- * Return every key candidate that might decrypt the v1 DB.- */-export const v1ChatKeyCandidates = (): string[] => {- const seen = new Set<string>();- const keys: string[] = [];- const add = (k: string | undefined) => {- if (k && !seen.has(k)) {- seen.add(k);- keys.push(k);- }- };- add(_v1LocalChatKey);- add(_localChatKey);- for (const k of _v1ChatKeyCandidates) add(k);- return keys;};-export const v1AttachmentChatKey = (): string | undefined =>- _v1AttachmentChatKey;--export const setV1AttachmentChatKey = async (chatKey?: string) => {- _v1AttachmentChatKey = chatKey;- if (!isTauriRuntime()) return;- if (chatKey) {- await secureStorageSet(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY, chatKey);- } else {- await secureStorageDelete(V1_ATTACHMENT_KEY_SECURE_STORAGE_KEY);- }+const hasNativeChatStore = async () => {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean>("chat_db_has_existing_store");};-/**- * Get or create the local-only chat encryption key.- */export const getOrCreateLocalChatKey = async () => {await initChatKeyStore();const cached = cachedLocalChatKey();if (cached) return cached;+ if (+ localGet(LOCAL_STORE) ||+ (isTauriRuntime() && (await hasNativeChatStore()))+ ) {+ throw new Error("Existing chat data has no encryption key");+ }await ensureCryptoInit();- const wasm = await enteWasm();- const chatKey = await wasm.crypto_generate_key();- setCachedChatKey(chatKey);+ const chatKey = await (await enteWasm()).crypto_generate_key();+ await persistLocalKey(chatKey);return chatKey;};++const retiredUserID = () => {+ try {+ const user = JSON.parse(localStorage.getItem("user") ?? "null") as {+ id?: unknown;+ } | null;+ const id = user?.id;+ return typeof id === "number" ? id : undefined;+ } catch {+ return undefined;+ }+};++export const finalizeLocalChatMigration = async () => {+ if (!isTauriRuntime()) return;+ const userID = retiredUserID();++ // The target DB and attachments have already been verified at this point.+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("chat_db_cleanup_v1");+ localStorage.removeItem(LOCAL_STORE);+ const secureKeys = [+ V1_LOCAL_SECURE_KEY,+ V1_ATTACHMENT_SECURE_KEY,+ "masterKey",+ "remoteChatKey",+ ...(userID+ ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]+ : []),+ ];+ await Promise.all(secureKeys.map(secureStorageDelete));++ const [{ exists, remove }, { appDataDir, join }] = await Promise.all([+ import("@tauri-apps/plugin-fs"),+ import("@tauri-apps/api/path"),+ ]);+ const root = await appDataDir();+ const keyFile = await join(root, KEY_FILE);+ const syncMeta = await join(root, "sync_meta");+ if (await exists(keyFile)) await remove(keyFile);+ if (await exists(syncMeta)) await remove(syncMeta, { recursive: true });++ 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");+ localStorage.setItem(MIGRATION_DONE, "1");+};diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 017a1f4eb8..9ab197233b 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -5,11 +5,8 @@ import log from "ente-base/log";import { deleteDB, openDB, type DBSchema, type IDBPDatabase } from "idb";import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";import {- cachedLocalChatKey,- setV1AttachmentChatKey,- v1AttachmentChatKey,- v1ChatKeyCandidates,- v1LocalChatKey,+ finalizeLocalChatMigration,+ isLocalChatMigrationDone,} from "./chatKey";import {decryptChatField,@@ -19,7 +16,6 @@ import {} from "./crypto";const STORAGE_KEY = "ensu.chat.store.v1";-const NATIVE_V1_IMPORT_KEY = "ensu.chat.nativeMigration.v2";const LOCAL_SCHEMA_MIGRATION_KEY = "ensu.chat.localMigration.v2";const CHAT_DB_NAME = "ensu-chat";const V1_WEB_CHAT_DB_NAME = "ensu.chat.db";@@ -178,13 +174,6 @@ interface NativeMessage {attachments?: NativeAttachment[];}-interface NativeV1ImportResult {- didMigrate: boolean;- migratedSessions: number;- migratedMessages: number;- migratedAttachments: number;-}-const nowMicros = () => Date.now() * 1000;const formatLogError = (error: unknown) => {@@ -200,12 +189,6 @@ const formatLogError = (error: unknown) => {}};-const getErrorCode = (error: unknown) => {- if (!error || typeof error !== "object") return undefined;- const code = (error as { code?: unknown }).code;- return typeof code === "string" ? code : undefined;-};-const loadChatStoreState = (): ChatStoreState => {if (typeof localStorage === "undefined") {return { sessions: [], messages: [], attachmentBytes: [] };@@ -241,7 +224,7 @@ const loadChatStoreState = (): ChatStoreState => {};} catch (error) {log.error("Failed to parse chat store", error);- return { sessions: [], messages: [], attachmentBytes: [] };+ throw error;}};@@ -431,31 +414,39 @@ const safeTitle = (value: unknown) =>? sessionTitleFromText(value, "New chat"): "New chat";-const decryptSessionTitle = async (session: StoredSession, chatKey: string) => {- try {- const payload = (await decryptChatPayload(- { encryptedData: session.encryptedData, header: session.header },- chatKey,- )) as { title?: string };- return safeTitle(payload.title);- } catch (error) {+const decryptSessionTitleStrict = async (+ session: StoredSession,+ chatKey: string,+) => {+ const payload = (await decryptChatPayload(+ { encryptedData: session.encryptedData, header: session.header },+ chatKey,+ )) as { title?: string };+ return safeTitle(payload.title);+};++const decryptSessionTitle = (session: StoredSession, chatKey: string) =>+ decryptSessionTitleStrict(session, chatKey).catch((error: unknown) => {log.error("Failed to decrypt session payload", error);return "New chat";- }+ });++const decryptMessageTextStrict = async (+ message: StoredMessage,+ chatKey: string,+) => {+ const payload = (await decryptChatPayload(+ { encryptedData: message.encryptedData, header: message.header },+ chatKey,+ )) as { text?: string };+ return typeof payload.text === "string" ? payload.text : "";};-const decryptMessageText = async (message: StoredMessage, chatKey: string) => {- try {- const payload = (await decryptChatPayload(- { encryptedData: message.encryptedData, header: message.header },- chatKey,- )) as { text?: string };- return typeof payload.text === "string" ? payload.text : "";- } catch (error) {+const decryptMessageText = (message: StoredMessage, chatKey: string) =>+ decryptMessageTextStrict(message, chatKey).catch((error: unknown) => {log.error("Failed to decrypt message payload", error);return "";- }-};+ });const serializeAttachments = async (attachments: ChatAttachment[] = [],@@ -486,8 +477,6 @@ const deserializeAttachments = async (): Promise<ChatAttachment[]> => {if (!attachments?.length || !isTauriRuntime()) return [];- const localKey = cachedLocalChatKey() ?? v1LocalChatKey();-return Promise.all(attachments.map(async (attachment) => {try {@@ -503,27 +492,6 @@ const deserializeAttachments = async (encryptedName: attachment.encryptedName,} satisfies ChatAttachment;} catch (error) {- if (localKey && localKey !== chatKey) {- try {- const name = await decryptChatField(- attachment.encryptedName,- localKey,- );- return {- id: attachment.id,- kind: attachment.kind,- size: attachment.size,- name,- encryptedName: undefined,- } satisfies ChatAttachment;- } catch (innerError) {- log.error(- "Failed to decrypt attachment name with local key",- innerError,- );- }- }-log.error("Failed to decrypt attachment name", error);return {id: attachment.id,@@ -537,6 +505,19 @@ const deserializeAttachments = async ();};+const deserializeAttachmentsStrict = async (+ attachments: StoredAttachment[] | undefined,+ chatKey: string,+): Promise<ChatAttachment[]> =>+ Promise.all(+ (attachments ?? []).map(async (attachment) => ({+ id: attachment.id,+ kind: attachment.kind,+ size: attachment.size,+ name: await decryptChatField(attachment.encryptedName, chatKey),+ })),+ );+const hasLocalStorageChatStore = () =>typeof localStorage !== "undefined" && !!localStorage.getItem(STORAGE_KEY);@@ -575,15 +556,6 @@ const hasIndexedDbDatabase = async (name: string) => {});};-const isNativeV1ImportDone = () =>- typeof localStorage !== "undefined" &&- localStorage.getItem(NATIVE_V1_IMPORT_KEY) === "1";--const markNativeV1ImportDone = () => {- if (typeof localStorage === "undefined") return;- localStorage.setItem(NATIVE_V1_IMPORT_KEY, "1");-};-const importLocalStorageChatStoreToIndexedDb = async () => {if (typeof localStorage === "undefined") return;@@ -715,7 +687,6 @@ const importLocalStorageChatStoreToNative = async (chatKey: string) => {!localStorageStore.messages.length &&!localStorageStore.attachmentBytes.length) {- localStorage.removeItem(STORAGE_KEY);return;}@@ -729,12 +700,11 @@ const importLocalStorageChatStoreToNative = async (chatKey: string) => {(left, right) => left.createdAt - right.createdAt,);for (const session of sessions) {- const title = await decryptSessionTitle(session, chatKey);await invokeChat("chat_db_upsert_session", {keyB64: chatKey,input: {sessionUuid: session.sessionUuid,- title,+ title: await decryptSessionTitleStrict(session, chatKey),createdAt: session.createdAt,updatedAt: session.updatedAt,},@@ -745,11 +715,10 @@ const importLocalStorageChatStoreToNative = async (chatKey: string) => {(left, right) => left.createdAt - right.createdAt,);for (const message of messages) {- const attachments = await deserializeAttachments(+ const attachments = await deserializeAttachmentsStrict(message.attachments,chatKey,);-await invokeChat("chat_db_insert_message_with_uuid", {keyB64: chatKey,input: {@@ -757,7 +726,7 @@ const importLocalStorageChatStoreToNative = async (chatKey: string) => {sessionUuid: message.sessionUuid,parentMessageUuid: message.parentMessageUuid ?? null,sender: message.sender,- text: await decryptMessageText(message, chatKey),+ text: await decryptMessageTextStrict(message, chatKey),createdAt: message.createdAt,attachments: attachments.map((attachment) => ({id: attachment.id,@@ -773,53 +742,33 @@ const importLocalStorageChatStoreToNative = async (chatKey: string) => {await writeAttachmentBytes(attachment.id, attachment.data);}- localStorage.removeItem(STORAGE_KEY);log.info("Finished migrating localStorage chat store to native DB");};-const importNativeV1ChatStore = async (chatKey: string): Promise<boolean> => {- if (!isTauriRuntime()) return true;-- const candidateKeys = v1ChatKeyCandidates();- const previousAttachmentKey = v1AttachmentChatKey();- const seen = new Set<string>(candidateKeys);- if (chatKey && !seen.has(chatKey)) {- candidateKeys.push(chatKey);- }-- for (const candidateKey of candidateKeys) {- await setV1AttachmentChatKey(- candidateKey === chatKey ? undefined : candidateKey,+const verifyNativeAttachments = async (chatKey: string) => {+ const sessions = await invokeChat<NativeSession[]>(+ "chat_db_list_sessions",+ { keyB64: chatKey },+ );+ const seen = new Set<string>();+ for (const session of sessions) {+ const messages = await invokeChat<NativeMessage[]>(+ "chat_db_get_messages",+ { keyB64: chatKey, sessionUuid: session.sessionUuid },);- try {- const result = await invokeChat<NativeV1ImportResult>(- "chat_db_import_v1",- { input: { keyB64: chatKey, v1KeyB64: candidateKey } },+ for (const attachment of messages.flatMap(+ ({ attachments }) => attachments ?? [],+ )) {+ if (seen.has(attachment.id)) continue;+ seen.add(attachment.id);+ if (!(await attachmentBytesExists(attachment.id))) continue;+ await decryptAttachmentBytes(+ await readAttachmentBytes(attachment.id),+ chatKey,+ session.sessionUuid,);- if (result.didMigrate) {- log.info("Migrated v1 native chat store", result);- } else {- await setV1AttachmentChatKey(previousAttachmentKey);- }- return true;- } catch (error) {- const code = getErrorCode(error);- if (- code === "db_crypto" ||- code === "db_invalid_blob_length" ||- code === "db_invalid_encrypted_field"- ) {- await setV1AttachmentChatKey(previousAttachmentKey);- continue;- }- throw error;}}-- log.warn(- "Skipping v1 native chat migration because no v1 key could decrypt the DB",- );- return false;};export const initializeChatStorePersistence = async (chatKey: string) => {@@ -830,15 +779,15 @@ export const initializeChatStorePersistence = async (chatKey: string) => {_chatPersistenceInitKey = chatKey;const initPromise = (async () => {if (isTauriRuntime()) {- if (!isNativeV1ImportDone()) {- const didResolveNativeV1Import =- await importNativeV1ChatStore(chatKey);+ if (!isLocalChatMigrationDone()) {+ await invokeChat("chat_db_import_v1", {+ input: { keyB64: chatKey },+ });if (hasLocalStorageChatStore()) {await importLocalStorageChatStoreToNative(chatKey);}- if (didResolveNativeV1Import) {- markNativeV1ImportDone();- }+ await verifyNativeAttachments(chatKey);+ await finalizeLocalChatMigration();}} else if (hasLocalStorageChatStore()) {await importLocalStorageChatStoreToIndexedDb();@@ -1383,27 +1332,7 @@ export const readDecryptedAttachmentBytes = async (sessionUuid: string,): Promise<Uint8Array<ArrayBuffer>> => {const encrypted = await readAttachmentBytes(id);- try {- return await decryptAttachmentBytes(encrypted, chatKey, sessionUuid);- } catch (error) {- for (const fallbackKey of [- v1AttachmentChatKey(),- cachedLocalChatKey(),- v1LocalChatKey(),- ]) {- if (!fallbackKey || fallbackKey === chatKey) continue;- try {- return await decryptAttachmentBytes(- encrypted,- fallbackKey,- sessionUuid,- );- } catch {- // Try the next v1 key.- }- }- throw error;- }+ return decryptAttachmentBytes(encrypted, chatKey, sessionUuid);};export const attachmentBytesExists = async (id: string): Promise<boolean> => {