π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remove obsolete Ensu account storage cleanup
Manav Rathi0370282d0f54
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.ktindex a7dfd05842..d7d7c0e927 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt@@ -15,10 +15,8 @@ import io.ente.ensu.config.loadConfigDefaultsimport io.ente.ensu.llm.LlmProviderimport io.ente.ensu.logging.FileLogRepositoryimport io.ente.ensu.storage.CredentialStore-import io.ente.ensu.storage.LegacyDataCleanupimport io.ente.ensu.logging.LogLevelimport io.ente.ensu.AppStore-import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.dropimport kotlinx.coroutines.flow.first@@ -57,10 +55,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"logRepository.log(LogLevel.Info, launchMessage, tag = "App")- viewModelScope.launch(Dispatchers.IO) {- runCatching { LegacyDataCleanup.run(getApplication(), credentialStore) }- }-viewModelScope.launch {val initialSettings = runCatching {advancedSettingsDataStore.settingsFlow.first()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 f84c67aea6..b72960d32c 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@@ -24,32 +24,12 @@ class CredentialStore(context: Context) {if (decoded != null && decoded.size == 32) return decoded}- val fromMaster = prefs.getString(KEY_MASTER_KEY, null)- ?.let { runCatching { decode(it) }.getOrNull() }- if (fromMaster != null && fromMaster.size == 32) {- prefs.edit().putString(KEY_CHAT_DB_KEY, encode(fromMaster)).apply()- return fromMaster- }-val generated = ByteArray(32)java.security.SecureRandom().nextBytes(generated)prefs.edit().putString(KEY_CHAT_DB_KEY, encode(generated)).apply()return generated}- fun removeLegacyCredentials() {- // Ensures the chat DB key no longer needs the master key fallback.- getOrCreateChatDbKey()- prefs.edit()- .remove("email")- .remove("user_id")- .remove("last_user_id")- .remove("secret_key")- .remove("token")- .remove(KEY_MASTER_KEY)- .apply()- }-private fun encode(bytes: ByteArray): String {return Base64.encodeToString(bytes, Base64.NO_WRAP or Base64.URL_SAFE)}@@ -59,7 +39,6 @@ class CredentialStore(context: Context) {}companion object {- private const val KEY_MASTER_KEY = "master_key"private const val KEY_CHAT_DB_KEY = "chat_db_key"}}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.ktdeleted file mode 100644index bee391d98e..0000000000--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.kt+++ /dev/null@@ -1,21 +0,0 @@-package io.ente.ensu.storage--import android.content.Context-import java.io.File--/**- * One-shot removal of data written by the retired login and sync builds, so- * that credentials and chat copies the user can no longer see or delete do not- * linger on disk.- *- * Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).- */-object LegacyDataCleanup {- fun run(context: Context, credentialStore: CredentialStore) {- credentialStore.removeLegacyCredentials()-- File(context.filesDir, "llmchat_online.db").delete()- File(context.filesDir, "llmchat").deleteRecursively()- File(context.filesDir, "datastore/ensu_developer_settings.preferences_pb").delete()- }-}diff --git a/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift b/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swiftindex d11d61c2e7..690a6f4505 100644--- a/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift+++ b/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift@@ -6,7 +6,6 @@ struct EnsuApp: App {init() {EnsuLogging.shared.start()- LegacyDataCleanup.run()}var body: some Scene {diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swiftindex 90064015ea..d56e65211d 100644--- a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift@@ -9,30 +9,14 @@ final class CredentialStore {private let keychainService = "io.ente.ensu"private enum KeychainAccount {- static let masterKey = "ensu.masterKey"static let chatDbKey = "ensu.chatDbKey"}- func removeLegacyCredentials() {- let chatDbKey = getOrCreateChatDbKey()- guard let persisted = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), persisted == chatDbKey else {- return- }- for account in ["ensu.token", "ensu.secretKey", KeychainAccount.masterKey] {- try? KeychainStore.delete(service: keychainService, account: account)- }- }-func getOrCreateChatDbKey() -> Data {if let existing = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), existing.count == 32 {return existing}- if let master = try? KeychainStore.get(service: keychainService, account: KeychainAccount.masterKey), master.count == 32 {- try? KeychainStore.set(master, service: keychainService, account: KeychainAccount.chatDbKey)- return master- }-var bytes = [UInt8](repeating: 0, count: 32)let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)if status != errSecSuccess {diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swift b/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swiftdeleted file mode 100644index 83aca0e42b..0000000000--- a/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swift+++ /dev/null@@ -1,27 +0,0 @@-import Foundation--/// One-shot removal of data written by the retired login and sync builds, so-/// that credentials and chat copies the user can no longer see or delete do-/// not linger.-///-/// Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).-enum LegacyDataCleanup {- static func run() {- CredentialStore.shared.removeLegacyCredentials()-- let defaults = UserDefaults.standard- for key in ["ensu.email", "ensu.userId", "ensu.lastUserId", "ensu.customEndpoint"] {- defaults.removeObject(forKey: key)- }-- Task.detached(priority: .utility) {- guard let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {- return- }- let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)- for item in ["llmchat_online.db", "chat_attachments_encrypted", "sync_meta"] {- try? FileManager.default.removeItem(at: dbDir.appendingPathComponent(item))- }- }- }-}diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.tsindex bcc39f8c8b..b3c8d81492 100644--- a/web/apps/ensu/src/services/chat/chatKey.ts+++ b/web/apps/ensu/src/services/chat/chatKey.ts@@ -7,36 +7,20 @@ import {} from "../secure-storage";import { ensureCryptoInit, enteWasm } from "../wasm";-const CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey";const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";const CHAT_KEY_FILE_NAME = "chat-keys.json";-const REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey.v2";const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey.v2";const LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY = "legacyAttachmentKey.v2";-const LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey";const LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";-type PersistedChatKeys = { localChatKey?: string };-type LegacyChatKeys = { remoteChatKey?: string; localChatKey?: string };+type NativeChatKeys = { localChatKey?: string };-let _persistedChatKeys: PersistedChatKeys = {};-let _legacyPersistedChatKeys: LegacyChatKeys = {};+let _localChatKey: string | undefined;+let _legacyLocalChatKey: string | undefined;let _legacyAttachmentChatKey: string | undefined;/** All distinct keys discovered during init, before any cleanup. */let _allDiscoveredLocalChatKeys: string[] = [];let _chatKeyStoreInitPromise: Promise<void> | undefined;-let _chatKeyStoreInitUserID: number | undefined;--const legacyUserID = () => {- try {- const raw = readLocalStorageKey("user");- if (!raw) return undefined;- const id = (JSON.parse(raw) as { id?: unknown }).id;- return typeof id === "number" ? id : undefined;- } catch {- return undefined;- }-};const readLocalStorageKey = (key: string) => {if (typeof localStorage === "undefined") return undefined;@@ -53,47 +37,13 @@ const removeLocalStorageKey = (key: string) => {localStorage.removeItem(key);};-const legacyRemoteChatKeyLocalStorageKeys = () => {- const keys = [CHAT_KEY_LOCAL_STORAGE_KEY];- const userID = legacyUserID();- if (userID) keys.push(`${CHAT_KEY_LOCAL_STORAGE_KEY}.${userID}`);-- if (typeof localStorage !== "undefined") {- for (let i = 0; i < localStorage.length; i += 1) {- const key = localStorage.key(i);- if (- key?.startsWith(`${CHAT_KEY_LOCAL_STORAGE_KEY}.`) &&- key !== LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY &&- !keys.includes(key)- ) {- keys.push(key);- }- }- }-- return keys;-};--const legacyRemoteChatKeySecureStorageKeys = () => {- const userID = legacyUserID();- return userID- ? [- `${REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`,- `${LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`,- ]- : [];-};--const clearLegacyRemoteChatKeyLocalStorage = () =>- legacyRemoteChatKeyLocalStorageKeys().forEach(removeLocalStorageKey);-const nativeChatKeyPath = async () => {const { appDataDir, join } = await import("@tauri-apps/api/path");const root = await appDataDir();return join(root, CHAT_KEY_FILE_NAME);};-const readNativeChatKeys = async (): Promise<PersistedChatKeys> => {+const readNativeChatKeys = async (): Promise<NativeChatKeys> => {if (!isTauriRuntime()) return {};const [{ exists, readFile }, path] = await Promise.all([@@ -105,7 +55,7 @@ const readNativeChatKeys = async (): Promise<PersistedChatKeys> => {try {const raw = new TextDecoder().decode(await readFile(path));- const parsed = JSON.parse(raw) as PersistedChatKeys;+ const parsed = JSON.parse(raw) as NativeChatKeys;return {localChatKey:typeof parsed.localChatKey === "string"@@ -121,12 +71,9 @@ const persistNativeChatKeys = async () => {if (!isTauriRuntime()) return;const operations: Promise<void>[] = [];- if (_persistedChatKeys.localChatKey) {+ if (_localChatKey) {operations.push(- secureStorageSet(- LOCAL_CHAT_KEY_SECURE_STORAGE_KEY,- _persistedChatKeys.localChatKey,- ),+ secureStorageSet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY, _localChatKey),);} else {operations.push(secureStorageDelete(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY));@@ -142,7 +89,6 @@ const persistNativeChatKeysSoon = () => {};const cleanupLegacyChatKeyCopies = async () => {- clearLegacyRemoteChatKeyLocalStorage();removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);try {@@ -157,20 +103,13 @@ const cleanupLegacyChatKeyCopies = async () => {export const initChatKeyStore = async () => {if (!isTauriRuntime()) return;- const userID = legacyUserID();- if (_chatKeyStoreInitPromise && _chatKeyStoreInitUserID === userID) {- return _chatKeyStoreInitPromise;- }+ if (_chatKeyStoreInitPromise) return _chatKeyStoreInitPromise;- _chatKeyStoreInitUserID = userID;_chatKeyStoreInitPromise = (async () => {- const remoteStorageKeys = legacyRemoteChatKeySecureStorageKeys();- const remoteLocalStorageKeys = legacyRemoteChatKeyLocalStorageKeys();const [secureLocalChatKey,secureLegacyAttachmentKey,legacySecureLocalChatKey,- secureRemoteChatKeys,nativeKeys,] = await Promise.all([secureStorageGet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(@@ -182,18 +121,8 @@ export const initChatKeyStore = async () => {secureStorageGet(LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(() => undefined,),- Promise.all(- remoteStorageKeys.map((key) =>- secureStorageGet(key).catch(() => undefined),- ),- ),readNativeChatKeys(),]);- const legacyRemoteChatKey =- secureRemoteChatKeys.find(Boolean) ??- remoteLocalStorageKeys- .map((key) => readLocalStorageKey(key))- .find(Boolean);// Prefer localStorage over legacy 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 legacy DB.@@ -203,14 +132,10 @@ export const initChatKeyStore = async () => {readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??legacySecureLocalChatKey ??nativeKeys.localChatKey;- const localChatKey =- secureLocalChatKey ?? legacyLocalChatKey ?? legacyRemoteChatKey;+ const localChatKey = secureLocalChatKey ?? legacyLocalChatKey;- _persistedChatKeys = { localChatKey };- _legacyPersistedChatKeys = {- remoteChatKey: legacyRemoteChatKey,- localChatKey: legacyLocalChatKey,- };+ _localChatKey = localChatKey;+ _legacyLocalChatKey = legacyLocalChatKey;_legacyAttachmentChatKey = secureLegacyAttachmentKey;// Capture every distinct local chat key found across all sources@@ -228,7 +153,6 @@ export const initChatKeyStore = async () => {legacySecureLocalChatKey,nativeKeys.localChatKey,rawLocalStorage,- legacyRemoteChatKey,]) {if (k && !seen.has(k)) {seen.add(k);@@ -265,12 +189,11 @@ export const initChatKeyStore = async () => {const setCachedChatKey = (chatKey: string) => {if (isTauriRuntime()) {- _persistedChatKeys.localChatKey = chatKey;+ _localChatKey = chatKey;persistNativeChatKeysSoon();return;}- clearLegacyRemoteChatKeyLocalStorage();writeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);};@@ -279,20 +202,15 @@ const setCachedChatKey = (chatKey: string) => {*/export const cachedLocalChatKey = (): string | undefined => {if (isTauriRuntime()) {- return _persistedChatKeys.localChatKey;+ return _localChatKey;}- return (- readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??- legacyRemoteChatKeyLocalStorageKeys()- .map((key) => readLocalStorageKey(key))- .find(Boolean)- );+ return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);};export const legacyLocalChatKey = (): string | undefined => {if (isTauriRuntime()) {- return _legacyPersistedChatKeys.localChatKey;+ return _legacyLocalChatKey;}return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);@@ -315,9 +233,8 @@ export const allLegacyKeyCandidates = (): string[] => {keys.push(k);}};- add(_legacyPersistedChatKeys.remoteChatKey);- add(_legacyPersistedChatKeys.localChatKey);- add(_persistedChatKeys.localChatKey);+ add(_legacyLocalChatKey);+ add(_localChatKey);// Include every local chat key discovered during init (before cleanup// deleted legacy copies). This ensures we try the raw localStorage key// even when stale OS keyring entries shadowed it in the ?? chains.diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex 22cc72738c..96c03f0c20 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -1,8 +1,4 @@import { base64ToBytes } from "@/services/base64";-import {- secureStorageDelete,- secureStorageGet,-} from "@/services/secure-storage";import { isTauriRuntime } from "@/services/tauri-runtime";import { getKV, removeKV, setKV } from "ente-base/kv";import log from "ente-base/log";@@ -811,64 +807,6 @@ const migrateLegacyNativeChatStoreToV2 = async (return false;};-/**- * One-shot removal of data written by the retired login and sync builds, so- * that credentials and chat copies the user can no longer see or delete do not- * linger.- *- * Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).- */-const cleanupLegacyData = async () => {- if (isTauriRuntime()) {- // The legacy keyring entries are potential decryption keys for a- // not-yet-migrated legacy DB, and potential sources of the v2 chat- // key. Only delete them once the legacy DB migration has completed- // and the v2 key is durably in the OS keyring.- if (!isNativeMigrationDone()) return;- if (!(await secureStorageGet("localChatKey.v2"))) return;-- const entries = ["masterKey", "localChatKey", "remoteChatKey"];- const userID = legacyUserID();- if (userID) {- entries.push(- `remoteChatKey.v2.${userID}`,- `remoteChatKey.${userID}`,- );- }- for (const entry of entries) await secureStorageDelete(entry);-- const [{ exists, remove }, { appDataDir, join }] = await Promise.all([- import("@tauri-apps/plugin-fs"),- import("@tauri-apps/api/path"),- ]);- const syncMetaDir = await join(await appDataDir(), "sync_meta");- if (await exists(syncMetaDir)) {- await remove(syncMetaDir, { recursive: true });- }- }-- [- "user",- "srpAttributes",- "keyAttributes",- "originalKeyAttributes",- "isFirstLogin",- ].forEach((key) => localStorage.removeItem(key));-- await removeKV("token");-};--const legacyUserID = () => {- try {- const raw = localStorage.getItem("user");- if (!raw) return undefined;- const id = (JSON.parse(raw) as { id?: unknown }).id;- return typeof id === "number" ? id : undefined;- } catch {- return undefined;- }-};-export const initializeChatStorePersistence = async (chatKey: string) => {if (_chatPersistenceInitKey === chatKey && _chatPersistenceInitPromise) {return _chatPersistenceInitPromise;@@ -892,10 +830,6 @@ export const initializeChatStorePersistence = async (chatKey: string) => {} else {await migrateLegacyIndexedDbChatStore();}-- void cleanupLegacyData().catch((error: unknown) =>- log.error("Failed to clean up legacy data", error),- );})().catch((error: unknown) => {if (_chatPersistenceInitPromise === initPromise) {_chatPersistenceInitPromise = undefined;