Skip to content

armgit / ente

Public Imported from GitHub
0

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

Isolate Ensu storage compatibility code

Manav Rathi60adbdde7086
diff --git a/rust/apps/ensu/changes/simplify-local-chat-storage.md b/rust/apps/ensu/changes/simplify-local-chat-storage.md
new file mode 100644
index 0000000000..32694bd141
--- /dev/null
+++ b/rust/apps/ensu/changes/simplify-local-chat-storage.md
@@ -0,0 +1 @@
+- Simplified local chat storage while preserving existing chats and attachments.
diff --git a/rust/crates/ensu/src/db/chat/mod.rs b/rust/crates/ensu/src/db/chat/mod.rs
index e6fc697f0d..3df9ddee27 100644
--- a/rust/crates/ensu/src/db/chat/mod.rs
+++ b/rust/crates/ensu/src/db/chat/mod.rs
@@ -1,4 +1,6 @@
mod migrations;
+#[cfg(feature = "sqlite")]
+mod retired_storage;
mod schema;
use std::collections::BTreeSet;
@@ -388,7 +390,7 @@ impl ChatDb<crate::db::backend::sqlite::SqliteBackend> {
let path = path.as_ref();
let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;
let db = Self::new(backend, key, clock, uuid_gen)?;
- cleanup_obsolete_sync_storage(path);
+ retired_storage::cleanup(path);
Ok(db)
}
@@ -396,11 +398,7 @@ impl ChatDb<crate::db::backend::sqlite::SqliteBackend> {
path: impl AsRef<std::path::Path>,
key: Vec<u8>,
) -> Result<Self> {
- let path = path.as_ref();
- let backend = crate::db::backend::sqlite::SqliteBackend::open(path)?;
- let db = Self::new_with_defaults(backend, key)?;
- cleanup_obsolete_sync_storage(path);
- Ok(db)
+ Self::open_sqlite(path, key, Arc::new(SystemClock), Arc::new(RandomUuidGen))
}
pub fn open_in_memory(key: Vec<u8>) -> Result<Self> {
@@ -409,21 +407,6 @@ impl ChatDb<crate::db::backend::sqlite::SqliteBackend> {
}
}
-#[cfg(feature = "sqlite")]
-fn cleanup_obsolete_sync_storage(db_path: &std::path::Path) {
- let Some(root) = db_path.parent() else {
- return;
- };
- for name in ["llmchat_sync.db", "llmchat_sync_v2.db", "llmchat_online.db"] {
- for suffix in ["", "-wal", "-shm"] {
- let _ = std::fs::remove_file(root.join(format!("{name}{suffix}")));
- }
- }
- for name in ["llmchat", "sync_meta"] {
- let _ = std::fs::remove_dir_all(root.join(name));
- }
-}
-
fn validate_key(key: Vec<u8>) -> Result<Zeroizing<Vec<u8>>> {
if key.len() != crypto::KEY_BYTES {
return Err(Error::InvalidKeyLength {
@@ -606,31 +589,6 @@ mod tests {
assert!(db.get_message(message_id).unwrap().is_none());
}
- #[test]
- fn sqlite_open_removes_obsolete_sync_storage() {
- let root = std::env::temp_dir().join(format!("ensu-db-{}", Uuid::new_v4()));
- std::fs::create_dir_all(root.join("sync_meta")).unwrap();
- std::fs::create_dir_all(root.join("llmchat")).unwrap();
- for name in [
- "llmchat_sync.db",
- "llmchat_sync.db-wal",
- "llmchat_sync_v2.db",
- "llmchat_online.db",
- ] {
- std::fs::write(root.join(name), b"obsolete").unwrap();
- }
-
- ChatDb::open_sqlite_with_defaults(root.join("llmchat.db"), vec![1u8; KEY_BYTES]).unwrap();
-
- assert!(!root.join("llmchat_sync.db").exists());
- assert!(!root.join("llmchat_sync.db-wal").exists());
- assert!(!root.join("llmchat_sync_v2.db").exists());
- assert!(!root.join("llmchat_online.db").exists());
- assert!(!root.join("sync_meta").exists());
- assert!(!root.join("llmchat").exists());
- std::fs::remove_dir_all(root).unwrap();
- }
-
#[test]
fn on_disk_v4_migration_survives_reopen() {
let root = std::env::temp_dir().join(format!("ensu-v4-{}", Uuid::new_v4()));
diff --git a/rust/crates/ensu/src/db/chat/retired_storage.rs b/rust/crates/ensu/src/db/chat/retired_storage.rs
new file mode 100644
index 0000000000..16b236abbd
--- /dev/null
+++ b/rust/crates/ensu/src/db/chat/retired_storage.rs
@@ -0,0 +1,47 @@
+use std::path::Path;
+
+pub(super) fn cleanup(db_path: &Path) {
+ let Some(root) = db_path.parent() else {
+ return;
+ };
+ for name in ["llmchat_sync.db", "llmchat_sync_v2.db", "llmchat_online.db"] {
+ for suffix in ["", "-wal", "-shm"] {
+ let _ = std::fs::remove_file(root.join(format!("{name}{suffix}")));
+ }
+ }
+ for name in ["llmchat", "sync_meta", "chat_attachments_encrypted"] {
+ let _ = std::fs::remove_dir_all(root.join(name));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::db::chat::ChatDb;
+ use crate::db::crypto::KEY_BYTES;
+ use uuid::Uuid;
+
+ #[test]
+ fn sqlite_open_removes_retired_storage() {
+ let root = std::env::temp_dir().join(format!("ensu-db-{}", Uuid::new_v4()));
+ std::fs::create_dir_all(root.join("sync_meta")).unwrap();
+ std::fs::create_dir_all(root.join("llmchat")).unwrap();
+ for name in [
+ "llmchat_sync.db",
+ "llmchat_sync.db-wal",
+ "llmchat_sync_v2.db",
+ "llmchat_online.db",
+ ] {
+ std::fs::write(root.join(name), b"obsolete").unwrap();
+ }
+
+ ChatDb::open_sqlite_with_defaults(root.join("llmchat.db"), vec![1u8; KEY_BYTES]).unwrap();
+
+ assert!(!root.join("llmchat_sync.db").exists());
+ assert!(!root.join("llmchat_sync.db-wal").exists());
+ assert!(!root.join("llmchat_sync_v2.db").exists());
+ assert!(!root.join("llmchat_online.db").exists());
+ assert!(!root.join("sync_meta").exists());
+ assert!(!root.join("llmchat").exists());
+ std::fs::remove_dir_all(root).unwrap();
+ }
+}
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index e1907cd3a0..2c408d2df4 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -15,7 +15,7 @@ import {
getOrCreateLocalChatKey,
initChatKeyStore,
} from "@/services/chat/chatKey";
-import { initializeChatStorePersistence } from "@/services/chat/migration";
+import { initializeChatStorePersistence } from "@/services/chat/persistence";
import {
addMessage,
createSession,
diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.ts
index 6fc6a426bf..74d9945155 100644
--- a/web/apps/ensu/src/services/chat/chatKey.ts
+++ b/web/apps/ensu/src/services/chat/chatKey.ts
@@ -1,13 +1,12 @@
import { isTauriRuntime } from "@/services/tauri-runtime";
import { secureStorageGet, secureStorageSet } from "../secure-storage";
import { ensureCryptoInit, enteWasm } from "../wasm";
-import { hasRetiredLocalChatStore, promoteLocalChatKey } from "./keyMigration";
+import { hasRetiredLocalChatStore, promoteLocalChatKey } from "./compatibility";
const LOCAL_KEY = "ensu.chatKey.local";
const CURRENT_SECURE_KEY = "localChatKey.v2";
let _localKey: string | undefined;
-let _migrationSourceKeys: string[] = [];
let _initPromise: Promise<void> | undefined;
const localGet = (key: string) =>
@@ -21,13 +20,11 @@ export const initChatKeyStore = async () => {
_initPromise = (async () => {
const current = await secureStorageGet(CURRENT_SECURE_KEY);
- const promotion = await promoteLocalChatKey(
+ _localKey = await promoteLocalChatKey(
current,
CURRENT_SECURE_KEY,
LOCAL_KEY,
);
- _localKey = promotion.key;
- _migrationSourceKeys = promotion.sourceKeys;
})().catch((error: unknown) => {
_initPromise = undefined;
throw error;
@@ -38,8 +35,6 @@ export const initChatKeyStore = async () => {
export const cachedLocalChatKey = () =>
isTauriRuntime() ? _localKey : localGet(LOCAL_KEY);
-export const localChatMigrationSourceKeys = () => _migrationSourceKeys;
-
const persistLocalKey = async (key: string) => {
if (isTauriRuntime()) {
await secureStorageSet(CURRENT_SECURE_KEY, key);
diff --git a/web/apps/ensu/src/services/chat/migration.ts b/web/apps/ensu/src/services/chat/compatibility.ts
similarity index 75%
rename from web/apps/ensu/src/services/chat/migration.ts
rename to web/apps/ensu/src/services/chat/compatibility.ts
index faf2928aa5..5d974fb494 100644
--- a/web/apps/ensu/src/services/chat/migration.ts
+++ b/web/apps/ensu/src/services/chat/compatibility.ts
@@ -1,15 +1,14 @@
import { base64ToBytes } from "@/services/base64";
-import { secureStorageGet } from "@/services/secure-storage";
import { isTauriRuntime } from "@/services/tauri-runtime";
+import { removeKV } from "ente-base/kv";
import log from "ente-base/log";
import { deleteDB, openDB, type DBSchema } from "idb";
-import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";
-import { localChatMigrationSourceKeys } from "./chatKey";
import {
- finalizeLocalChatMigration,
- isLocalChatMigrationDone,
- LEGACY_ATTACHMENT_SECURE_KEY,
-} from "./keyMigration";
+ secureStorageDelete,
+ secureStorageGet,
+ secureStorageSet,
+} from "../secure-storage";
+import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";
import {
attachmentBytesExists,
chatDb,
@@ -28,6 +27,11 @@ import {
const LOCAL_STORAGE_STORE = "ensu.chat.store.v1";
const TOMBSTONE_MIGRATION = "ensu.chat.localMigration.v2";
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 KEY_FILE = "chat-keys.json";
+const LEGACY_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";
type OldSession = StoredSession & {
deletedAt?: number | null;
@@ -51,7 +55,118 @@ interface OldIndexedDb extends DBSchema {
attachmentBytes: { key: string; value: AttachmentBytes };
}
-let _initPromise: Promise<void> | undefined;
+let _migrationSourceKeys: string[] = [];
+
+const localGet = (key: string) => localStorage.getItem(key) ?? undefined;
+
+const keyFilePath = async () => {
+ const { appDataDir, join } = await import("@tauri-apps/api/path");
+ return join(await appDataDir(), KEY_FILE);
+};
+
+const readKeyFile = async () => {
+ const [{ exists, readFile }, path] = await Promise.all([
+ import("@tauri-apps/plugin-fs"),
+ keyFilePath(),
+ ]);
+ if (!(await exists(path))) return undefined;
+ try {
+ const value = JSON.parse(
+ new TextDecoder().decode(await readFile(path)),
+ ) as { localChatKey?: unknown };
+ return typeof value.localChatKey === "string"
+ ? value.localChatKey
+ : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";
+
+export const promoteLocalChatKey = async (
+ current: string | undefined,
+ currentSecureKey: string,
+ browserKey: string,
+) => {
+ if (isLocalChatMigrationDone()) {
+ _migrationSourceKeys = current ? [current] : [];
+ return current;
+ }
+ const [oldSecure, file] = await Promise.all([
+ secureStorageGet(OLD_LOCAL_SECURE_KEY),
+ readKeyFile(),
+ ]);
+ _migrationSourceKeys = [
+ current,
+ localGet(browserKey),
+ oldSecure,
+ file,
+ ].filter(
+ (key, index, keys): key is string =>
+ !!key && keys.indexOf(key) === index,
+ );
+ const key = _migrationSourceKeys[0];
+ if (key && key !== current) await secureStorageSet(currentSecureKey, key);
+ return key;
+};
+
+export const hasRetiredLocalChatStore = () => !!localGet(LOCAL_STORAGE_STORE);
+
+const retiredUserID = () => {
+ try {
+ const user = JSON.parse(localStorage.getItem("user") ?? "null") as {
+ id?: unknown;
+ } | null;
+ return typeof user?.id === "number" ? user.id : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const finalizeLocalChatMigration = async (deleteOldLocalKeys: boolean) => {
+ const userID = retiredUserID();
+ localStorage.removeItem(LOCAL_STORAGE_STORE);
+ const secureKeys = [
+ "masterKey",
+ "remoteChatKey",
+ ...(userID
+ ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]
+ : []),
+ ];
+ if (deleteOldLocalKeys) {
+ secureKeys.push(OLD_LOCAL_SECURE_KEY, LEGACY_ATTACHMENT_SECURE_KEY);
+ }
+ await Promise.all(secureKeys.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);
+ }
+ }
+ [
+ "user",
+ "srpAttributes",
+ "keyAttributes",
+ "originalKeyAttributes",
+ "isFirstLogin",
+ "ensu.chat.nativeMigration.v2",
+ ].forEach((key) => localStorage.removeItem(key));
+ await removeKV("token");
+ localStorage.setItem(MIGRATION_DONE, "1");
+};
const liveStore = (
sessions: OldSession[],
@@ -356,12 +471,12 @@ const reencryptAttachments = async (chatKey: string, sourceKeys: string[]) => {
return allCurrent;
};
-const migrate = async (chatKey: string) => {
+export const openChatStoreWithCompatibility = async (chatKey: string) => {
if (isTauriRuntime()) {
const migrationPending = !isLocalChatMigrationDone();
const sourceKeys = distinctKeys([
chatKey,
- ...(migrationPending ? localChatMigrationSourceKeys() : []),
+ ...(migrationPending ? _migrationSourceKeys : []),
]);
await invokeChat("chat_db_open", {
input: { keyB64: chatKey, recoveryKeysB64: sourceKeys },
@@ -379,16 +494,3 @@ const migrate = async (chatKey: string) => {
await importOldBrowserStores();
}
};
-
-export const initializeChatStorePersistence = async (chatKey: string) => {
- if (_initPromise) return _initPromise;
- const promise = migrate(chatKey).catch((error: unknown) => {
- if (_initPromise === promise) {
- _initPromise = undefined;
- }
- log.error("Failed to initialize chat persistence", error);
- throw error;
- });
- _initPromise = promise;
- return promise;
-};
diff --git a/web/apps/ensu/src/services/chat/keyMigration.ts b/web/apps/ensu/src/services/chat/keyMigration.ts
deleted file mode 100644
index 621f0fb69f..0000000000
--- a/web/apps/ensu/src/services/chat/keyMigration.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { removeKV } from "ente-base/kv";
-import {
- secureStorageDelete,
- secureStorageGet,
- secureStorageSet,
-} from "../secure-storage";
-
-const LOCAL_STORE = "ensu.chat.store.v1";
-const MIGRATION_DONE = "ensu.chat.localMigration.v3";
-const OLD_LOCAL_SECURE_KEY = "localChatKey";
-const OLD_LOCAL_BROWSER_KEY = "ensu.chatKey.local";
-const KEY_FILE = "chat-keys.json";
-export const LEGACY_ATTACHMENT_SECURE_KEY = "legacyAttachmentKey.v2";
-
-const localGet = (key: string) => localStorage.getItem(key) ?? undefined;
-
-const keyFilePath = async () => {
- const { appDataDir, join } = await import("@tauri-apps/api/path");
- return join(await appDataDir(), KEY_FILE);
-};
-
-const readKeyFile = async () => {
- const [{ exists, readFile }, path] = await Promise.all([
- import("@tauri-apps/plugin-fs"),
- keyFilePath(),
- ]);
- if (!(await exists(path))) return undefined;
- try {
- const value = JSON.parse(
- new TextDecoder().decode(await readFile(path)),
- ) as { localChatKey?: unknown };
- return typeof value.localChatKey === "string"
- ? value.localChatKey
- : undefined;
- } catch {
- return undefined;
- }
-};
-
-export const isLocalChatMigrationDone = () => localGet(MIGRATION_DONE) === "1";
-
-export interface LocalChatKeyPromotion {
- key?: string;
- sourceKeys: string[];
-}
-
-export const promoteLocalChatKey = async (
- current: string | undefined,
- currentSecureKey: string,
- browserKey: string,
-): Promise<LocalChatKeyPromotion> => {
- if (isLocalChatMigrationDone()) {
- return { key: current, sourceKeys: current ? [current] : [] };
- }
- const [oldSecure, file] = await Promise.all([
- secureStorageGet(OLD_LOCAL_SECURE_KEY),
- readKeyFile(),
- ]);
- const sourceKeys = [current, localGet(browserKey), oldSecure, file].filter(
- (key, index, keys): key is string =>
- !!key && keys.indexOf(key) === index,
- );
- const key = sourceKeys[0];
- if (key && key !== current) await secureStorageSet(currentSecureKey, key);
- return { key, sourceKeys };
-};
-
-export const hasRetiredLocalChatStore = () => !!localGet(LOCAL_STORE);
-
-const retiredUserID = () => {
- try {
- const user = JSON.parse(localStorage.getItem("user") ?? "null") as {
- id?: unknown;
- } | null;
- return typeof user?.id === "number" ? user.id : undefined;
- } catch {
- return undefined;
- }
-};
-
-export const finalizeLocalChatMigration = async (
- deleteOldLocalKeys: boolean,
-) => {
- const userID = retiredUserID();
- localStorage.removeItem(LOCAL_STORE);
- const secureKeys = [
- "masterKey",
- "remoteChatKey",
- ...(userID
- ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]
- : []),
- ];
- if (deleteOldLocalKeys) {
- secureKeys.push(OLD_LOCAL_SECURE_KEY, LEGACY_ATTACHMENT_SECURE_KEY);
- }
- await Promise.all(secureKeys.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);
- }
- }
- [
- "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/persistence.ts b/web/apps/ensu/src/services/chat/persistence.ts
new file mode 100644
index 0000000000..7eeacc8a67
--- /dev/null
+++ b/web/apps/ensu/src/services/chat/persistence.ts
@@ -0,0 +1,17 @@
+import log from "ente-base/log";
+import { openChatStoreWithCompatibility } from "./compatibility";
+
+let _initPromise: Promise<void> | undefined;
+
+export const initializeChatStorePersistence = async (chatKey: string) => {
+ if (_initPromise) return _initPromise;
+ const promise = openChatStoreWithCompatibility(chatKey).catch(
+ (error: unknown) => {
+ if (_initPromise === promise) _initPromise = undefined;
+ log.error("Failed to initialize chat persistence", error);
+ throw error;
+ },
+ );
+ _initPromise = promise;
+ return promise;
+};