Skip to content

armgit / ente

Public Imported from GitHub
0

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

Migrate legacy Ensu attachment encryption

Manav Rathi7557acf362f7
diff --git a/web/apps/ensu/src/services/chat/keyMigration.ts b/web/apps/ensu/src/services/chat/keyMigration.ts
index eb576afba9..621f0fb69f 100644
--- a/web/apps/ensu/src/services/chat/keyMigration.ts
+++ b/web/apps/ensu/src/services/chat/keyMigration.ts
@@ -8,7 +8,9 @@ import {
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;
@@ -76,30 +78,39 @@ const retiredUserID = () => {
}
};
-export const finalizeLocalChatMigration = async () => {
+export const finalizeLocalChatMigration = async (
+ deleteOldLocalKeys: boolean,
+) => {
const userID = retiredUserID();
localStorage.removeItem(LOCAL_STORE);
- await Promise.all(
- [
- OLD_LOCAL_SECURE_KEY,
- "masterKey",
- "remoteChatKey",
- ...(userID
- ? [`remoteChatKey.${userID}`, `remoteChatKey.v2.${userID}`]
- : []),
- ].map(secureStorageDelete),
- );
+ 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));
- 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);
- if (await exists(keyFile)) await remove(keyFile);
+ 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")) localStorage.removeItem(key);
+ if (
+ key.startsWith("ensu.chatKey") &&
+ (deleteOldLocalKeys || key !== OLD_LOCAL_BROWSER_KEY)
+ ) {
+ localStorage.removeItem(key);
+ }
}
[
"user",
diff --git a/web/apps/ensu/src/services/chat/migration.ts b/web/apps/ensu/src/services/chat/migration.ts
index fd6079014a..faf2928aa5 100644
--- a/web/apps/ensu/src/services/chat/migration.ts
+++ b/web/apps/ensu/src/services/chat/migration.ts
@@ -1,19 +1,24 @@
import { base64ToBytes } from "@/services/base64";
+import { secureStorageGet } from "@/services/secure-storage";
import { isTauriRuntime } from "@/services/tauri-runtime";
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";
import {
+ attachmentBytesExists,
chatDb,
decryptMessageTextStrict,
decryptSessionTitleStrict,
+ deleteAttachmentBytes,
deserializeAttachmentsStrict,
invokeChat,
- pruneOrphanedAttachmentBytes,
+ readAttachmentBytes,
writeAttachmentBytes,
type StoredAttachment,
type StoredMessage,
@@ -267,6 +272,90 @@ const distinctKeys = (keys: (string | undefined)[]) =>
!!key && values.indexOf(key) === index,
);
+const decryptAttachmentWith = async (
+ encrypted: Uint8Array,
+ keys: string[],
+ sessionUuid: string,
+) => {
+ for (const key of keys) {
+ try {
+ return [
+ await decryptAttachmentBytes(encrypted, key, sessionUuid),
+ key,
+ ] as const;
+ } catch {
+ // Try the next migration-only key.
+ }
+ }
+ return undefined;
+};
+
+const reencryptAttachments = async (chatKey: string, sourceKeys: string[]) => {
+ const candidates = distinctKeys([
+ ...sourceKeys,
+ await secureStorageGet(LEGACY_ATTACHMENT_SECURE_KEY),
+ ]);
+ let allCurrent = true;
+
+ for (const { sessionUuid } of await invokeChat<{ sessionUuid: string }[]>(
+ "chat_db_list_sessions",
+ )) {
+ for (const { id } of (
+ await invokeChat<{ attachments?: { id: string }[] }[]>(
+ "chat_db_get_messages",
+ { 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,
+ 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,
+ );
+ await deleteAttachmentBytes(stagingID);
+ }
+ }
+ return allCurrent;
+};
+
const migrate = async (chatKey: string) => {
if (isTauriRuntime()) {
const migrationPending = !isLocalChatMigrationDone();
@@ -281,17 +370,14 @@ const migrate = async (chatKey: string) => {
if (hasLocalStorageStore()) {
await importLocalStorageToNative(sourceKeys);
}
- await finalizeLocalChatMigration();
+ await finalizeLocalChatMigration(
+ await reencryptAttachments(chatKey, sourceKeys),
+ );
}
} else {
await removeCurrentBrowserTombstones();
await importOldBrowserStores();
}
- try {
- await pruneOrphanedAttachmentBytes();
- } catch (error) {
- log.warn("Failed to prune orphaned attachment payloads", error);
- }
};
export const initializeChatStorePersistence = async (chatKey: string) => {
diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.ts
index 099c25e2fd..e9c1f57672 100644
--- a/web/apps/ensu/src/services/chat/store.ts
+++ b/web/apps/ensu/src/services/chat/store.ts
@@ -367,57 +367,6 @@ export const deserializeAttachmentsStrict = async (
})),
);
-export const pruneOrphanedAttachmentBytes = async () => {
- if (isTauriRuntime()) {
- const sessions = await invokeChat<NativeSession[]>(
- "chat_db_list_sessions",
- );
- const referenced = new Set<string>();
- for (const session of sessions) {
- const messages = await invokeChat<NativeMessage[]>(
- "chat_db_get_messages",
- { sessionUuid: session.sessionUuid },
- );
- for (const attachment of messages.flatMap(
- ({ attachments }) => attachments ?? [],
- )) {
- referenced.add(attachment.id);
- }
- }
-
- const { readDir } = await import("@tauri-apps/plugin-fs");
- for (const entry of await readDir(await attachmentDir())) {
- if (entry.isFile && !referenced.has(entry.name)) {
- await deleteAttachmentBytes(entry.name);
- }
- }
- return;
- }
-
- const db = await chatDb();
- const [messages, attachments] = await Promise.all([
- db.getAll("messages"),
- db.getAll("attachmentBytes"),
- ]);
- const referenced = new Set(
- messages.flatMap((message) =>
- (message.attachments ?? []).map((attachment) => attachment.id),
- ),
- );
- const orphaned = attachments.filter(
- (attachment) => !referenced.has(attachment.id),
- );
- if (!orphaned.length) return;
-
- const tx = db.transaction(["attachmentBytes"], "readwrite");
- await Promise.all(
- orphaned.map((attachment) =>
- tx.objectStore("attachmentBytes").delete(attachment.id),
- ),
- );
- await tx.done;
-};
-
const fetchStore = async () => {
const db = await chatDb();
const [sessions, messages] = await Promise.all([