π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refactor remote service
Vishnu Mohandasd931de87d6f4
diff --git a/web/apps/locker/src/services/remote-cache.ts b/web/apps/locker/src/services/remote-cache.tsnew file mode 100644index 0000000000..a229c7d8db--- /dev/null+++ b/web/apps/locker/src/services/remote-cache.ts@@ -0,0 +1,194 @@+import type { LockerCollectionParticipant } from "types";++/**+ * An encrypted collection record stored in-memory. All sensitive fields remain+ * encrypted exactly as received from remote β we never persist decrypted keys+ * or names. Decryption is done on-the-fly when the UI requests the data.+ */+export interface EncryptedCollectionRecord {+ /** Collection ID. */+ id: number;+ /** Owner info (plaintext β structural metadata only). */+ owner: LockerCollectionParticipant;+ /** Owner user ID (plaintext β structural metadata only). */+ ownerID: number;+ /** Participants excluding the owner. */+ sharees: LockerCollectionParticipant[];+ /** Encrypted collection key (base64). */+ encryptedKey: string;+ /** Nonce for key decryption (base64), null for shared collections. */+ keyDecryptionNonce: string | undefined;+ /** Encrypted collection name (base64). */+ encryptedName: string | undefined;+ /** Nonce for name decryption (base64). */+ nameDecryptionNonce: string | undefined;+ /** Unencrypted name (legacy, may be blank). */+ name: string | undefined;+ /** Collection type (structural metadata). */+ type: string;+ /** Whether the collection has sharees. */+ isShared: boolean;+ /** Whether this collection is deleted on remote (key still needed for trash restore). */+ isDeleted: boolean;+ /** Updation time (structural metadata). */+ updationTime: number;+}++/**+ * An encrypted file record stored in-memory. All sensitive payloads remain+ * encrypted until explicitly decrypted for display.+ */+export interface EncryptedFileRecord {+ /** File ID (structural metadata). */+ id: number;+ /** Collection this file belongs to (structural metadata). */+ collectionID: number;+ /** Owner of the file, when provided by remote. */+ ownerID?: number;+ /** Encrypted file key (base64). */+ encryptedKey: string;+ /** Nonce for file key decryption (base64). */+ keyDecryptionNonce: string;+ /** Decryption header for the actual file content blob on S3. */+ fileDecryptionHeader: string;+ /** Whether the file has a downloadable backing object. */+ hasObject: boolean;+ /** File size in bytes, when provided by the API. */+ fileSize?: number;+ /** Encrypted file metadata. */+ metadata: { encryptedData: string; decryptionHeader: string };+ /** Encrypted private magic metadata, if present. */+ magicMetadata?: { version: number; data: string; header: string };+ /** Encrypted public magic metadata, if present. */+ pubMagicMetadata?: { version: number; data: string; header: string };+ /** Updation time (structural metadata). */+ updationTime: number;+}++export interface LockerEncryptedCache {+ collections: Map<number, EncryptedCollectionRecord>;+ files: Map<number, Map<number, EncryptedFileRecord>>;+}++/** In-memory cache: collectionID β EncryptedCollectionRecord */+let encryptedCollections = new Map<number, EncryptedCollectionRecord>();++/** In-memory cache: fileID β (collectionID β EncryptedFileRecord) */+let encryptedFiles = new Map<number, Map<number, EncryptedFileRecord>>();++export const createEmptyLockerCache = (): LockerEncryptedCache => ({+ collections: new Map<number, EncryptedCollectionRecord>(),+ files: new Map<number, Map<number, EncryptedFileRecord>>(),+});++export const setEncryptedFileRecord = (+ target: Map<number, Map<number, EncryptedFileRecord>>,+ record: EncryptedFileRecord,+) => {+ const existing =+ target.get(record.id) ?? new Map<number, EncryptedFileRecord>();+ existing.set(record.collectionID, record);+ target.set(record.id, existing);+};++export const getLockerCacheSnapshot = (): LockerEncryptedCache => ({+ collections: encryptedCollections,+ files: encryptedFiles,+});++export const replaceLockerCache = (cache: LockerEncryptedCache) => {+ encryptedCollections = cache.collections;+ encryptedFiles = cache.files;+};++export const clearLockerCache = () => {+ encryptedCollections = new Map();+ encryptedFiles = new Map();+};++export const getCollectionRecord = (collectionID: number) =>+ encryptedCollections.get(collectionID);++export const getCollectionRecords = () => [...encryptedCollections.values()];++export const findCollectionByType = (type: string) =>+ [...encryptedCollections.values()].find(+ (candidate) => candidate.type === type,+ );++export const updateCollectionShareesInCache = (+ collectionID: number,+ sharees: LockerCollectionParticipant[],+) => {+ const record = encryptedCollections.get(collectionID);+ if (!record) {+ return;+ }++ encryptedCollections.set(collectionID, {+ ...record,+ sharees,+ isShared: sharees.length > 0,+ });+};++export const getEncryptedFileRecord = (+ fileID: number,+ collectionID?: number,+): EncryptedFileRecord | undefined => {+ const records = encryptedFiles.get(fileID);+ if (!records) {+ return undefined;+ }+ if (collectionID !== undefined) {+ return records.get(collectionID);+ }+ return records.values().next().value;+};++export const getAllEncryptedFileRecords = (): EncryptedFileRecord[] =>+ [...encryptedFiles.values()].flatMap((records) => [...records.values()]);++export const getCollectionIDsForFile = (fileID: number): number[] => {+ const records = encryptedFiles.get(fileID);+ return records ? [...records.keys()] : [];+};++export const mergeEncryptedFileRecordsIntoCache = (+ records: EncryptedFileRecord[],+) => {+ if (records.length === 0) {+ return;+ }++ const nextFiles = new Map(encryptedFiles);+ for (const record of records) {+ const existingRecords =+ nextFiles.get(record.id) ?? new Map<number, EncryptedFileRecord>();+ const nextRecords = new Map(existingRecords);+ nextRecords.set(record.collectionID, record);+ nextFiles.set(record.id, nextRecords);+ }+ encryptedFiles = nextFiles;+};++export const updateCachedPubMagicMetadata = (+ fileID: number,+ pubMagicMetadata: { version: number; data: string; header: string },+) => {+ const records = encryptedFiles.get(fileID);+ if (!records) {+ return;+ }++ encryptedFiles = new Map(encryptedFiles);+ encryptedFiles.set(+ fileID,+ new Map(+ [...records.entries()].map(([recordCollectionID, record]) => [+ recordCollectionID,+ { ...record, pubMagicMetadata },+ ]),+ ),+ );+};diff --git a/web/apps/locker/src/services/remote-read.ts b/web/apps/locker/src/services/remote-read.tsnew file mode 100644index 0000000000..87061d0aae--- /dev/null+++ b/web/apps/locker/src/services/remote-read.ts@@ -0,0 +1,816 @@+import {+ ensureLocalUser,+ ensureUserKeyPair,+} from "ente-accounts-rs/services/user";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import log from "ente-base/log";+import { apiURL, customAPIOrigin } from "ente-base/origins";+import { ensureAuthToken } from "ente-base/token";+import type {+ LockerCollection,+ LockerCollectionParticipant,+ LockerCollectionParticipantRole,+ LockerItem,+ LockerItemType,+} from "types";+import { z } from "zod";+import {+ boxSealOpen,+ createStreamDecryptor,+ decryptBox,+ decryptBoxBytes,+ decryptMetadataJSON,+} from "./crypto";+import {+ type EncryptedCollectionRecord,+ type EncryptedFileRecord,+ type LockerEncryptedCache,+ createEmptyLockerCache,+ getEncryptedFileRecord,+ getLockerCacheSnapshot,+ mergeEncryptedFileRecordsIntoCache,+ replaceLockerCache,+ setEncryptedFileRecord,+} from "./remote-cache";++const RemoteCollectionUser = z.object({+ id: z.number(),+ email: z.string().nullish(),+ role: z.string().nullish(),+});++const RemoteMagicMetadata = z.object({+ version: z.number(),+ count: z.number().optional(),+ data: z.string(),+ header: z.string(),+});++const RemoteCollection = z.object({+ id: z.number(),+ owner: RemoteCollectionUser,+ encryptedKey: z.string(),+ keyDecryptionNonce: z.string().nullish(),+ encryptedName: z.string().nullish(),+ nameDecryptionNonce: z.string().nullish(),+ name: z.string().nullish(),+ type: z.string(),+ sharees: z.array(RemoteCollectionUser).nullish(),+ publicURLs: z.array(z.unknown()).nullish(),+ updationTime: z.number(),+ isDeleted: z.boolean().nullish(),+ magicMetadata: RemoteMagicMetadata.nullish(),+ pubMagicMetadata: RemoteMagicMetadata.nullish(),+ sharedMagicMetadata: RemoteMagicMetadata.nullish(),+});++type RemoteCollection = z.infer<typeof RemoteCollection>;++const CollectionsResponse = z.object({+ collections: z.array(RemoteCollection),+});++const RemoteEncryptedMetadata = z.object({+ encryptedData: z.string(),+ decryptionHeader: z.string(),+});++const RemoteFileObjectAttributes = z.object({ decryptionHeader: z.string() });++const RemoteFile = z.object({+ id: z.number(),+ collectionID: z.number(),+ ownerID: z.number().optional(),+ encryptedKey: z.string(),+ keyDecryptionNonce: z.string(),+ file: RemoteFileObjectAttributes,+ thumbnail: RemoteFileObjectAttributes.optional(),+ metadata: RemoteEncryptedMetadata,+ magicMetadata: z+ .object({+ version: z.number(),+ count: z.number().optional(),+ data: z.string(),+ header: z.string(),+ })+ .nullish(),+ pubMagicMetadata: z+ .object({+ version: z.number(),+ count: z.number().optional(),+ data: z.string(),+ header: z.string(),+ })+ .nullish(),+ updationTime: z.number(),+ isDeleted: z.boolean(),+ info: z.object({ fileSize: z.number().optional() }).nullish(),+});++type RemoteFile = z.infer<typeof RemoteFile>;++const FileDiffResponse = z.object({+ diff: z.array(RemoteFile),+ hasMore: z.boolean(),+});++const RemoteTrashItem = z.object({+ file: RemoteFile,+ isDeleted: z.boolean(),+ isRestored: z.boolean(),+ updatedAt: z.number(),+ deleteBy: z.number(),+});++const TrashDiffResponse = z.object({+ diff: z.array(RemoteTrashItem),+ hasMore: z.boolean(),+});++interface DecryptAllDataResult {+ collections: LockerCollection[];+ failedCollectionIDs: number[];+ totalCollectionCount: number;+}++export interface LockerTrashData {+ items: LockerItem[];+ lastUpdatedAt: number;+}++const collectionNameDecoder = new TextDecoder();++const toLockerCollectionParticipant = (+ user: z.infer<typeof RemoteCollectionUser>,+): LockerCollectionParticipant => ({+ id: user.id,+ email: user.email ?? undefined,+ role: user.role+ ? (user.role.toUpperCase() as LockerCollectionParticipantRole)+ : undefined,+});++const describeCryptoError = (error: unknown): string => {+ if (typeof error === "object" && error && "code" in error) {+ const code = typeof error.code === "string" ? error.code : "unknown";+ const message =+ "message" in error && typeof error.message === "string"+ ? error.message+ : "unknown";+ return `code=${code}, msg=${message}`;+ }+ if (error instanceof Error) {+ return error.message;+ }+ return String(error);+};++const toEpochMicroseconds = (timestamp: unknown) => {+ if (typeof timestamp !== "number") {+ return undefined;+ }++ // Locker mobile stores metadata timestamps in epoch milliseconds while+ // server structural timestamps use epoch microseconds.+ return timestamp < 100_000_000_000_000 ? timestamp * 1000 : timestamp;+};++const buildEncryptedFileRecord = (file: RemoteFile): EncryptedFileRecord => ({+ id: file.id,+ collectionID: file.collectionID,+ ownerID: file.ownerID ?? undefined,+ encryptedKey: file.encryptedKey,+ keyDecryptionNonce: file.keyDecryptionNonce,+ fileDecryptionHeader: file.file.decryptionHeader,+ hasObject: file.file.decryptionHeader.length > 0,+ fileSize: file.info?.fileSize,+ metadata: {+ encryptedData: file.metadata.encryptedData,+ decryptionHeader: file.metadata.decryptionHeader,+ },+ magicMetadata: file.magicMetadata+ ? {+ version: file.magicMetadata.version,+ data: file.magicMetadata.data,+ header: file.magicMetadata.header,+ }+ : undefined,+ pubMagicMetadata: file.pubMagicMetadata+ ? {+ version: file.pubMagicMetadata.version,+ data: file.pubMagicMetadata.data,+ header: file.pubMagicMetadata.header,+ }+ : undefined,+ updationTime: file.updationTime,+});++const fetchEncryptedCollections = async () => {+ const response = await fetch(+ await apiURL("/collections/v2", { sinceTime: 0 }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(response);+ const { collections } = CollectionsResponse.parse(await response.json());++ const nextCollections = new Map<number, EncryptedCollectionRecord>();+ for (const collection of collections) {+ nextCollections.set(collection.id, {+ id: collection.id,+ owner: {+ ...toLockerCollectionParticipant(collection.owner),+ role: "OWNER",+ },+ ownerID: collection.owner.id,+ sharees: (collection.sharees ?? []).map(+ toLockerCollectionParticipant,+ ),+ encryptedKey: collection.encryptedKey,+ keyDecryptionNonce: collection.keyDecryptionNonce ?? undefined,+ encryptedName: collection.encryptedName ?? undefined,+ nameDecryptionNonce: collection.nameDecryptionNonce ?? undefined,+ name: collection.name ?? undefined,+ type: collection.type,+ isShared: (collection.sharees?.length ?? 0) > 0,+ isDeleted: !!collection.isDeleted,+ updationTime: collection.updationTime,+ });+ }++ return nextCollections;+};++const fetchEncryptedFilesForCollection = async (+ collectionID: number,+): Promise<EncryptedFileRecord[]> => {+ let sinceTime = 0;+ let hasMore = true;+ const records: EncryptedFileRecord[] = [];++ while (hasMore) {+ const response = await fetch(+ await apiURL("/collections/v2/diff", { collectionID, sinceTime }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(response);+ const parsed = FileDiffResponse.parse(await response.json());++ for (const file of parsed.diff) {+ sinceTime = Math.max(sinceTime, file.updationTime);+ if (!file.isDeleted) {+ records.push(buildEncryptedFileRecord(file));+ }+ }++ hasMore = parsed.hasMore;+ }++ return records;+};++const fetchAllEncryptedFiles = async (+ collections: Map<number, EncryptedCollectionRecord>,+) => {+ const activeCollections = [...collections.values()].filter(+ (collection) => !collection.isDeleted,+ );+ const fileResults = await Promise.all(+ activeCollections.map((collection) =>+ fetchEncryptedFilesForCollection(collection.id),+ ),+ );++ const nextFiles = createEmptyLockerCache().files;+ for (const records of fileResults) {+ for (const record of records) {+ setEncryptedFileRecord(nextFiles, record);+ }+ }++ return nextFiles;+};++export const decryptCollectionKey = async (+ record: EncryptedCollectionRecord,+ masterKey: string,+): Promise<string> => {+ const currentUserID = ensureLocalUser().id;+ if (record.ownerID === currentUserID) {+ return decryptBox(+ {+ encryptedData: record.encryptedKey,+ nonce: record.keyDecryptionNonce!,+ },+ masterKey,+ );+ }++ return boxSealOpen(record.encryptedKey, await ensureUserKeyPair());+};++const decryptCollectionName = async (+ record: EncryptedCollectionRecord,+ collectionKey: string,+): Promise<string> => {+ if (record.name) {+ return record.name;+ }++ if (record.encryptedName && record.nameDecryptionNonce) {+ try {+ const nameBytes = await decryptBoxBytes(+ {+ encryptedData: record.encryptedName,+ nonce: record.nameDecryptionNonce,+ },+ collectionKey,+ );+ return collectionNameDecoder.decode(nameBytes);+ } catch (error) {+ log.error(+ `Failed to decrypt collection name for ${record.id}`,+ error,+ );+ }+ }++ return "Untitled";+};++const decryptFileKeyForRecordFromCollections = async (+ record: EncryptedFileRecord,+ masterKey: string,+ collections: Map<number, EncryptedCollectionRecord>,+): Promise<string> => {+ const collectionRecord = collections.get(record.collectionID);+ if (!collectionRecord) {+ throw new Error(`Collection ${record.collectionID} not found in cache`);+ }++ const collectionKey = await decryptCollectionKey(+ collectionRecord,+ masterKey,+ );+ return decryptBox(+ {+ encryptedData: record.encryptedKey,+ nonce: record.keyDecryptionNonce,+ },+ collectionKey,+ );+};++export const decryptFileKeyForRecord = async (+ record: EncryptedFileRecord,+ masterKey: string,+): Promise<string> => {+ const cacheSnapshot = getLockerCacheSnapshot();+ return decryptFileKeyForRecordFromCollections(+ record,+ masterKey,+ cacheSnapshot.collections,+ );+};++const decryptFileToLockerItem = async (+ record: EncryptedFileRecord,+ collectionKey: string,+ collectionOwnerID: number,+): Promise<LockerItem | undefined> => {+ try {+ const fileKey = await decryptBox(+ {+ encryptedData: record.encryptedKey,+ nonce: record.keyDecryptionNonce,+ },+ collectionKey,+ );++ const metadata = (await decryptMetadataJSON(+ record.metadata,+ fileKey,+ )) as Record<string, unknown> | undefined;++ let pubMagicMetadata: Record<string, unknown> | undefined;+ if (record.pubMagicMetadata) {+ try {+ pubMagicMetadata = (await decryptMetadataJSON(+ {+ encryptedData: record.pubMagicMetadata.data,+ decryptionHeader: record.pubMagicMetadata.header,+ },+ fileKey,+ )) as Record<string, unknown> | undefined;+ } catch {+ // Public metadata can be missing or unreadable for some older+ // files. We still want to surface the file row if basic+ // metadata decrypts successfully.+ }+ }++ const info = pubMagicMetadata?.info as+ | { type?: string; data?: Record<string, unknown> }+ | undefined;++ const validInfoTypes = new Set<string>([+ "note",+ "accountCredential",+ "physicalRecord",+ "emergencyContact",+ ]);++ if (info?.type && info.data && validInfoTypes.has(info.type)) {+ return {+ id: record.id,+ type: info.type as LockerItemType,+ data: info.data as unknown as LockerItem["data"],+ collectionID: record.collectionID,+ collectionIDs: [record.collectionID],+ ownerID: record.ownerID ?? collectionOwnerID,+ createdAt: toEpochMicroseconds(metadata?.creationTime),+ updatedAt: record.updationTime,+ };+ }++ const editedName =+ typeof pubMagicMetadata?.editedName === "string"+ ? pubMagicMetadata.editedName+ : undefined;+ const metadataTitle =+ typeof metadata?.title === "string" ? metadata.title : undefined;+ const displayName = editedName ?? metadataTitle ?? "File";++ return {+ id: record.id,+ type: "file",+ data: {+ name: displayName,+ fileSize: record.fileSize,+ hasObject: record.hasObject,+ },+ collectionID: record.collectionID,+ collectionIDs: [record.collectionID],+ ownerID: record.ownerID ?? collectionOwnerID,+ createdAt: toEpochMicroseconds(metadata?.creationTime),+ updatedAt: record.updationTime,+ };+ } catch (error) {+ log.error(+ `Failed to decrypt file ${record.id}: ${describeCryptoError(error)}`,+ );+ return undefined;+ }+};++const decryptAllData = async (+ masterKey: string,+ cache: LockerEncryptedCache,+): Promise<DecryptAllDataResult> => {+ const activeCollectionRecords = [...cache.collections.values()].filter(+ (collection) => !collection.isDeleted,+ );+ const result: LockerCollection[] = [];+ const failedCollectionIDs: number[] = [];+ const totalCollectionCount = activeCollectionRecords.length;++ const filesByCollection = new Map<number, EncryptedFileRecord[]>();+ for (const records of cache.files.values()) {+ for (const file of records.values()) {+ const existing = filesByCollection.get(file.collectionID) ?? [];+ existing.push(file);+ filesByCollection.set(file.collectionID, existing);+ }+ }++ for (const collectionRecord of activeCollectionRecords) {+ try {+ const collectionKey = await decryptCollectionKey(+ collectionRecord,+ masterKey,+ );+ const name = await decryptCollectionName(+ collectionRecord,+ collectionKey,+ );+ const files = filesByCollection.get(collectionRecord.id) ?? [];+ const decryptedItems = await Promise.all(+ files.map((file) =>+ decryptFileToLockerItem(+ file,+ collectionKey,+ collectionRecord.ownerID,+ ),+ ),+ );+ const items = decryptedItems.filter(+ (item): item is LockerItem => item !== undefined,+ );++ result.push({+ id: collectionRecord.id,+ name,+ owner: collectionRecord.owner,+ sharees: collectionRecord.sharees,+ items,+ type: collectionRecord.type,+ isShared: collectionRecord.isShared,+ });+ } catch (error) {+ failedCollectionIDs.push(collectionRecord.id);+ log.error(+ `Failed to decrypt collection ${collectionRecord.id}: ${describeCryptoError(+ error,+ )}`,+ );+ }+ }++ result.sort((a, b) => a.name.localeCompare(b.name));+ return { collections: result, failedCollectionIDs, totalCollectionCount };+};++const withoutFailedCollections = (+ cache: LockerEncryptedCache,+ failedCollectionIDs: number[],+): LockerEncryptedCache => {+ if (failedCollectionIDs.length === 0) {+ return cache;+ }++ const failedCollectionIDSet = new Set(failedCollectionIDs);+ return {+ collections: new Map(+ [...cache.collections.entries()].filter(+ ([collectionID]) => !failedCollectionIDSet.has(collectionID),+ ),+ ),+ files: new Map(+ [...cache.files.entries()]+ .map(+ ([fileID, records]): [+ number,+ Map<number, EncryptedFileRecord>,+ ] => [+ fileID,+ new Map(+ [...records.entries()].filter(+ ([collectionID]) =>+ !failedCollectionIDSet.has(collectionID),+ ),+ ),+ ],+ )+ .filter(([, records]) => records.size > 0),+ ),+ };+};++export const fetchLockerData = async (+ masterKey: string,+): Promise<LockerCollection[]> => {+ const stagedCollections = await fetchEncryptedCollections();+ const stagedFiles = await fetchAllEncryptedFiles(stagedCollections);+ const stagedCache: LockerEncryptedCache = {+ collections: stagedCollections,+ files: stagedFiles,+ };++ const decrypted = await decryptAllData(masterKey, stagedCache);+ if (+ decrypted.totalCollectionCount > 0 &&+ decrypted.collections.length === 0+ ) {+ throw new Error(+ `Failed to decrypt all ${decrypted.totalCollectionCount} locker collections`,+ );+ }++ replaceLockerCache(+ withoutFailedCollections(stagedCache, decrypted.failedCollectionIDs),+ );++ if (decrypted.failedCollectionIDs.length > 0) {+ log.warn(+ `Decrypted ${decrypted.collections.length}/${decrypted.totalCollectionCount} locker collections`,+ );+ }++ return decrypted.collections;+};++export const fetchLockerTrash = async (+ masterKey: string,+): Promise<LockerTrashData> => {+ const cacheSnapshot = getLockerCacheSnapshot();+ const trashItems: LockerItem[] = [];+ const stagedTrashFileRecords: EncryptedFileRecord[] = [];+ let sinceTime = 0;+ let hasMore = true;++ while (hasMore) {+ const response = await fetch(+ await apiURL("/trash/v2/diff", { sinceTime }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(response);+ const parsed = TrashDiffResponse.parse(await response.json());++ for (const entry of parsed.diff) {+ sinceTime = Math.max(sinceTime, entry.updatedAt);+ if (entry.isDeleted || entry.isRestored) {+ continue;+ }++ const collectionRecord = cacheSnapshot.collections.get(+ entry.file.collectionID,+ );+ if (!collectionRecord) {+ log.warn(+ `Skipping trash file ${entry.file.id}: collection ${entry.file.collectionID} not in cache`,+ );+ continue;+ }++ const fileRecord = buildEncryptedFileRecord(entry.file);+ stagedTrashFileRecords.push(fileRecord);++ try {+ const collectionKey = await decryptCollectionKey(+ collectionRecord,+ masterKey,+ );+ const item = await decryptFileToLockerItem(+ fileRecord,+ collectionKey,+ collectionRecord.ownerID,+ );+ if (item) {+ trashItems.push({ ...item, deleteBy: entry.deleteBy });+ }+ } catch (error) {+ log.error(+ `Failed to decrypt trash file ${entry.file.id}`,+ error,+ );+ }+ }++ hasMore = parsed.hasMore;+ }++ mergeEncryptedFileRecordsIntoCache(stagedTrashFileRecords);+ trashItems.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));+ return { items: trashItems, lastUpdatedAt: sinceTime };+};++export const downloadLockerFile = async (+ fileID: number,+ fileName: string,+ masterKey: string,+ onProgress?: (progress: { loaded: number; total?: number }) => void,+): Promise<void> => {+ const fileRecord = getEncryptedFileRecord(fileID);+ if (!fileRecord) {+ throw new Error(`File ${fileID} not found in cache`);+ }++ const cacheSnapshot = getLockerCacheSnapshot();+ const collectionRecord = cacheSnapshot.collections.get(+ fileRecord.collectionID,+ );+ if (!collectionRecord) {+ throw new Error(+ `Collection ${fileRecord.collectionID} not found in cache`,+ );+ }++ const collectionKey = await decryptCollectionKey(+ collectionRecord,+ masterKey,+ );+ const fileKey = await decryptBox(+ {+ encryptedData: fileRecord.encryptedKey,+ nonce: fileRecord.keyDecryptionNonce,+ },+ collectionKey,+ );++ const customOrigin = await customAPIOrigin();+ let response: Response;+ if (customOrigin) {+ const token = await ensureAuthToken();+ const url = await apiURL(`/files/download/${fileID}`, { token });+ response = await fetch(url);+ } else {+ response = await fetch(`https://files.ente.io/?fileID=${fileID}`, {+ headers: await authenticatedRequestHeaders(),+ });+ }+ ensureOk(response);++ const body = response.body;+ if (!body) {+ throw new Error("Download response body is empty");+ }++ const reader = body.getReader();+ const contentLength =+ parseInt(response.headers.get("Content-Length") ?? "", 10) || 0;+ let downloadedBytes = 0;++ onProgress?.({+ loaded: 0,+ total: contentLength > 0 ? contentLength : undefined,+ });++ const streamDecryptor = await createStreamDecryptor(+ fileRecord.fileDecryptionHeader,+ fileKey,+ );+ let leftoverBytes = new Uint8Array();++ const decryptedStream = new ReadableStream<Uint8Array>({+ pull: async (controller) => {+ let didEnqueue = false;+ try {+ do {+ const { done, value } = await reader.read();+ let data: Uint8Array;+ if (done) {+ data = leftoverBytes;+ } else {+ downloadedBytes += value.length;+ onProgress?.({+ loaded: downloadedBytes,+ total:+ contentLength > 0 ? contentLength : undefined,+ });+ data = new Uint8Array(+ leftoverBytes.length + value.length,+ );+ data.set(leftoverBytes, 0);+ data.set(value, leftoverBytes.length);+ }++ while (data.length >= streamDecryptor.decryptionChunkSize) {+ const decryptedChunk =+ await streamDecryptor.decryptChunk(+ data.slice(+ 0,+ streamDecryptor.decryptionChunkSize,+ ),+ );+ controller.enqueue(decryptedChunk);+ didEnqueue = true;+ data = data.slice(streamDecryptor.decryptionChunkSize);+ }++ if (done) {+ if (data.length > 0) {+ const decryptedChunk =+ await streamDecryptor.decryptChunk(data);+ controller.enqueue(decryptedChunk);+ }+ if (!streamDecryptor.isFinalized()) {+ throw new Error(+ "Download stream truncated before final chunk",+ );+ }+ onProgress?.({+ loaded:+ contentLength > 0+ ? contentLength+ : downloadedBytes,+ total:+ contentLength > 0 ? contentLength : undefined,+ });+ streamDecryptor.free();+ controller.close();+ didEnqueue = true;+ } else {+ leftoverBytes = new Uint8Array(data);+ }+ } while (!didEnqueue);+ } catch (error) {+ streamDecryptor.free();+ controller.error(error);+ }+ },+ cancel: () => {+ streamDecryptor.free();+ void reader.cancel();+ },+ });++ const decryptedData = await new Response(decryptedStream).blob();+ const url = URL.createObjectURL(decryptedData);+ const anchor = document.createElement("a");+ anchor.style.display = "none";+ anchor.href = url;+ anchor.download = fileName;+ document.body.appendChild(anchor);+ anchor.click();+ setTimeout(() => URL.revokeObjectURL(url), 0);+ anchor.remove();+};diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.tsindex a1677f8ea4..ac6f35f522 100644--- a/web/apps/locker/src/services/remote.ts+++ b/web/apps/locker/src/services/remote.ts@@ -17,12 +17,10 @@ import {} from "ente-accounts-rs/services/user";import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";import log from "ente-base/log";-import { apiURL, customAPIOrigin } from "ente-base/origins";-import { ensureAuthToken } from "ente-base/token";+import { apiURL } from "ente-base/origins";import type {LockerCollection,LockerCollectionParticipant,- LockerCollectionParticipantRole,LockerItem,LockerItemType,} from "types";@@ -31,15 +29,22 @@ import {b64ToBytes,boxSeal,boxSealOpen,- createStreamDecryptor,decryptBox,- decryptBoxBytes,decryptMetadataJSON,encryptBlob,encryptBox,generateKey,stringToB64,} from "./crypto";+import {+ clearLockerCache,+ findCollectionByType,+ getCollectionIDsForFile,+ getCollectionRecord,+ getEncryptedFileRecord,+ updateCachedPubMagicMetadata,+ updateCollectionShareesInCache,+} from "./remote-cache";import {deleteCollectionKeepingFilesWithDeps,type EncryptedCollectionFileItem,@@ -56,217 +61,26 @@ import {ensureUncategorizedCollectionWithDeps,renameCollectionWithDeps,} from "./remote-collections";+import {+ decryptCollectionKey,+ decryptFileKeyForRecord,+ downloadLockerFile,+ fetchLockerData,+ fetchLockerTrash,+} from "./remote-read";import {type LockerUploadProgress,uploadLockerFileWithDeps,} from "./remote-uploads";-// ----------------------------------------------------------------------------// Zod schemas for API responses-// -----------------------------------------------------------------------------const RemoteCollectionUser = z.object({- id: z.number(),- email: z.string().nullish(),- role: z.string().nullish(),-});--const RemoteMagicMetadata = z.object({- version: z.number(),- count: z.number().optional(),- data: z.string(),- header: z.string(),-});--const RemoteCollection = z.object({- id: z.number(),- owner: RemoteCollectionUser,- encryptedKey: z.string(),- keyDecryptionNonce: z.string().nullish(),- encryptedName: z.string().nullish(),- nameDecryptionNonce: z.string().nullish(),- name: z.string().nullish(),- type: z.string(),- sharees: z.array(RemoteCollectionUser).nullish(),- publicURLs: z.array(z.unknown()).nullish(),- updationTime: z.number(),- isDeleted: z.boolean().nullish(),- magicMetadata: RemoteMagicMetadata.nullish(),- pubMagicMetadata: RemoteMagicMetadata.nullish(),- sharedMagicMetadata: RemoteMagicMetadata.nullish(),-});--type RemoteCollection = z.infer<typeof RemoteCollection>;--const CollectionsResponse = z.object({- collections: z.array(RemoteCollection),-});--const RemoteEncryptedMetadata = z.object({- encryptedData: z.string(),- decryptionHeader: z.string(),-});--const RemoteFileObjectAttributes = z.object({ decryptionHeader: z.string() });--const RemoteFile = z.object({- id: z.number(),- collectionID: z.number(),- ownerID: z.number().optional(),- encryptedKey: z.string(),- keyDecryptionNonce: z.string(),- file: RemoteFileObjectAttributes,- thumbnail: RemoteFileObjectAttributes.optional(),- metadata: RemoteEncryptedMetadata,- magicMetadata: z- .object({- version: z.number(),- count: z.number().optional(),- data: z.string(),- header: z.string(),- })- .nullish(),- pubMagicMetadata: z- .object({- version: z.number(),- count: z.number().optional(),- data: z.string(),- header: z.string(),- })- .nullish(),- updationTime: z.number(),- isDeleted: z.boolean(),- info: z.object({ fileSize: z.number().optional() }).nullish(),-});--type RemoteFile = z.infer<typeof RemoteFile>;--const FileDiffResponse = z.object({- diff: z.array(RemoteFile),- hasMore: z.boolean(),-});--// ----------------------------------------------------------------------------// In-memory cache of encrypted collection data (never persisted decrypted)-// -----------------------------------------------------------------------------/**- * An encrypted collection record stored in-memory. All sensitive fields remain- * encrypted exactly as received from remote β we never persist decrypted keys- * or names. Decryption is done on-the-fly when the UI requests the data.- */-interface EncryptedCollectionRecord {- /** Collection ID. */- id: number;- /** Owner info (plaintext β structural metadata only). */- owner: LockerCollectionParticipant;- /** Owner user ID (plaintext β structural metadata only). */- ownerID: number;- /** Participants excluding the owner. */- sharees: LockerCollectionParticipant[];- /** Encrypted collection key (base64). */- encryptedKey: string;- /** Nonce for key decryption (base64), null for shared collections. */- keyDecryptionNonce: string | undefined;- /** Encrypted collection name (base64). */- encryptedName: string | undefined;- /** Nonce for name decryption (base64). */- nameDecryptionNonce: string | undefined;- /** Unencrypted name (legacy, may be blank). */- name: string | undefined;- /** Collection type (structural metadata). */- type: string;- /** Whether the collection has sharees. */- isShared: boolean;- /** Whether this collection is deleted on remote (key still needed for trash restore). */- isDeleted: boolean;- /** Updation time (structural metadata). */- updationTime: number;-}--/**- * An encrypted file record stored in-memory. All sensitive payloads remain- * encrypted until explicitly decrypted for display.- */-interface EncryptedFileRecord {- /** File ID (structural metadata). */- id: number;- /** Collection this file belongs to (structural metadata). */- collectionID: number;- /** Owner of the file, when provided by remote. */- ownerID?: number;- /** Encrypted file key (base64). */- encryptedKey: string;- /** Nonce for file key decryption (base64). */- keyDecryptionNonce: string;- /** Decryption header for the actual file content blob on S3. */- fileDecryptionHeader: string;- /** Whether the file has a downloadable backing object. */- hasObject: boolean;- /** File size in bytes, when provided by the API. */- fileSize?: number;- /** Encrypted file metadata. */- metadata: { encryptedData: string; decryptionHeader: string };- /** Encrypted private magic metadata, if present. */- magicMetadata?: { version: number; data: string; header: string };- /** Encrypted public magic metadata, if present. */- pubMagicMetadata?: { version: number; data: string; header: string };- /** Updation time (structural metadata). */- updationTime: number;-}--/** In-memory cache: collectionID β EncryptedCollectionRecord */-let encryptedCollections = new Map<number, EncryptedCollectionRecord>();--/** In-memory cache: fileID β (collectionID β EncryptedFileRecord) */-let encryptedFiles = new Map<number, Map<number, EncryptedFileRecord>>();--const setEncryptedFileRecord = (- target: Map<number, Map<number, EncryptedFileRecord>>,- record: EncryptedFileRecord,-) => {- const existing =- target.get(record.id) ?? new Map<number, EncryptedFileRecord>();- existing.set(record.collectionID, record);- target.set(record.id, existing);-};--const getEncryptedFileRecord = (- fileID: number,- collectionID?: number,-): EncryptedFileRecord | undefined => {- const records = encryptedFiles.get(fileID);- if (!records) {- return undefined;- }- if (collectionID !== undefined) {- return records.get(collectionID);- }- return records.values().next().value;-};--const getAllEncryptedFileRecords = (): EncryptedFileRecord[] =>- [...encryptedFiles.values()].flatMap((records) => [...records.values()]);--const getCollectionIDsForFile = (fileID: number): number[] => {- const records = encryptedFiles.get(fileID);- return records ? [...records.keys()] : [];+export {+ clearLockerCache,+ downloadLockerFile,+ fetchLockerData,+ fetchLockerTrash,};-const describeCryptoError = (e: unknown): string => {- if (typeof e === "object" && e && "code" in e) {- const code = typeof e.code === "string" ? e.code : "unknown";- const message =- "message" in e && typeof e.message === "string"- ? e.message- : "unknown";- return `code=${code}, msg=${message}`;- }- if (e instanceof Error) {- return e.message;- }- return String(e);-};+const utf8Decoder = new TextDecoder();const RemoteFileShareLink = z.object({linkID: z.union([z.string(), z.number().transform(String)]),@@ -307,288 +121,12 @@ export interface LockerFileShareLinkSummary {passwordEnabled: boolean;}-interface DecryptAllDataResult {- collections: LockerCollection[];- failedCollectionIDs: number[];- totalCollectionCount: number;-}--const utf8Decoder = new TextDecoder();--const toLockerCollectionParticipant = (- user: z.infer<typeof RemoteCollectionUser>,-): LockerCollectionParticipant => ({- id: user.id,- email: user.email ?? undefined,- role: user.role- ? (user.role.toUpperCase() as LockerCollectionParticipantRole)- : undefined,-});--const updateCollectionShareesInCache = (- collectionID: number,- sharees: LockerCollectionParticipant[],-) => {- const record = encryptedCollections.get(collectionID);- if (!record) {- return;- }-- encryptedCollections.set(collectionID, {- ...record,- sharees,- isShared: sharees.length > 0,- });-};-// ----------------------------------------------------------------------------// Public API+// File link helpers// ----------------------------------------------------------------------------/**- * Fetch all Locker collections and their info items from remote, decrypt- * them using the user's master key, and return them ready for display.- *- * Encrypted data is cached in-memory (never written to persistent storage- * in decrypted form). Only structural metadata (IDs, timestamps) is- * stored unencrypted β matching the mobile app's SQLite pattern.- */-export const fetchLockerData = async (- masterKey: string,-): Promise<LockerCollection[]> => {- const previousCollections = encryptedCollections;- const previousFiles = encryptedFiles;-- // Step 1: Fetch all encrypted collections from remote- await fetchEncryptedCollections();-- // Step 2: For each collection, fetch encrypted file diffs- await fetchAllEncryptedFiles();-- // Step 3: Decrypt everything in-memory and return- const decrypted = await decryptAllData(masterKey);- if (- decrypted.totalCollectionCount > 0 &&- decrypted.collections.length === 0- ) {- encryptedCollections = previousCollections;- encryptedFiles = previousFiles;- throw new Error(- `Failed to decrypt all ${decrypted.totalCollectionCount} locker collections`,- );- }-- if (decrypted.failedCollectionIDs.length > 0) {- log.warn(- `Decrypted ${decrypted.collections.length}/${decrypted.totalCollectionCount} locker collections`,- );- }-- return decrypted.collections;-};--/**- * Clear all cached data (call on logout).- */-export const clearLockerCache = () => {- encryptedCollections = new Map();- encryptedFiles = new Map();-};--// ----------------------------------------------------------------------------// Step 1: Fetch encrypted collections-// -----------------------------------------------------------------------------const fetchEncryptedCollections = async () => {- const res = await fetch(await apiURL("/collections/v2", { sinceTime: 0 }), {- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- const { collections } = CollectionsResponse.parse(await res.json());-- const nextCollections = new Map<number, EncryptedCollectionRecord>();-- for (const c of collections) {- nextCollections.set(c.id, {- id: c.id,- owner: { ...toLockerCollectionParticipant(c.owner), role: "OWNER" },- ownerID: c.owner.id,- sharees: (c.sharees ?? []).map(toLockerCollectionParticipant),- encryptedKey: c.encryptedKey,- keyDecryptionNonce: c.keyDecryptionNonce ?? undefined,- encryptedName: c.encryptedName ?? undefined,- nameDecryptionNonce: c.nameDecryptionNonce ?? undefined,- name: c.name ?? undefined,- type: c.type,- isShared: (c.sharees?.length ?? 0) > 0,- isDeleted: !!c.isDeleted,- updationTime: c.updationTime,- });- }-- encryptedCollections = nextCollections;-};--// ----------------------------------------------------------------------------// Step 2: Fetch encrypted files for all collections-// -----------------------------------------------------------------------------const fetchAllEncryptedFiles = async () => {- const activeCollections = [...encryptedCollections.values()].filter(- (collection) => !collection.isDeleted,- );- const fileResults = await Promise.all(- activeCollections.map((c) => fetchEncryptedFilesForCollection(c.id)),- );-- const nextFiles = new Map<number, Map<number, EncryptedFileRecord>>();- for (const records of fileResults) {- for (const record of records) {- setEncryptedFileRecord(nextFiles, record);- }- }-- encryptedFiles = nextFiles;-};--const fetchEncryptedFilesForCollection = async (- collectionID: number,-): Promise<EncryptedFileRecord[]> => {- let sinceTime = 0;- let hasMore = true;- const records: EncryptedFileRecord[] = [];-- while (hasMore) {- const res = await fetch(- await apiURL("/collections/v2/diff", { collectionID, sinceTime }),- { headers: await authenticatedRequestHeaders() },- );- ensureOk(res);- const parsed = FileDiffResponse.parse(await res.json());-- for (const f of parsed.diff) {- sinceTime = Math.max(sinceTime, f.updationTime);-- if (f.isDeleted) {- continue;- }-- records.push({- id: f.id,- collectionID: f.collectionID,- ownerID: f.ownerID ?? undefined,- encryptedKey: f.encryptedKey,- keyDecryptionNonce: f.keyDecryptionNonce,- fileDecryptionHeader: f.file.decryptionHeader,- hasObject: f.file.decryptionHeader.length > 0,- fileSize: f.info?.fileSize,- metadata: {- encryptedData: f.metadata.encryptedData,- decryptionHeader: f.metadata.decryptionHeader,- },- magicMetadata: f.magicMetadata- ? {- version: f.magicMetadata.version,- data: f.magicMetadata.data,- header: f.magicMetadata.header,- }- : undefined,- pubMagicMetadata: f.pubMagicMetadata- ? {- version: f.pubMagicMetadata.version,- data: f.pubMagicMetadata.data,- header: f.pubMagicMetadata.header,- }- : undefined,- updationTime: f.updationTime,- });- }-- hasMore = parsed.hasMore;- }-- return records;-};--// ----------------------------------------------------------------------------// Step 3: Decrypt everything in-memory-// -----------------------------------------------------------------------------/**- * Decrypt a collection key. Owned collections use masterKey + nonce (box),- * shared collections use the user's keypair (sealed box).- */-const decryptCollectionKey = async (- record: EncryptedCollectionRecord,- masterKey: string,-): Promise<string> => {- const currentUserID = ensureLocalUser().id;- if (record.ownerID === currentUserID) {- // Owned collection: key encrypted with masterKey + nonce- return decryptBox(- {- encryptedData: record.encryptedKey,- nonce: record.keyDecryptionNonce!,- },- masterKey,- );- } else {- // Shared collection: key encrypted with user's public key (sealed)- return boxSealOpen(record.encryptedKey, await ensureUserKeyPair());- }-};--/**- * Decrypt a collection name from its encrypted fields.- */-const decryptCollectionName = async (- record: EncryptedCollectionRecord,- collectionKey: string,-): Promise<string> => {- // Legacy collections might have unencrypted name- if (record.name) return record.name;-- if (record.encryptedName && record.nameDecryptionNonce) {- try {- const nameBytes = await decryptBoxBytes(- {- encryptedData: record.encryptedName,- nonce: record.nameDecryptionNonce,- },- collectionKey,- );- return new TextDecoder().decode(nameBytes);- } catch (e) {- log.error(`Failed to decrypt collection name for ${record.id}`, e);- }- }- return "Untitled";-};-const decodeUTF8B64 = (b64: string) => utf8Decoder.decode(b64ToBytes(b64));-const decryptFileKeyForRecord = async (- record: EncryptedFileRecord,- masterKey: string,-): Promise<string> => {- const collectionRecord = encryptedCollections.get(record.collectionID);- if (!collectionRecord) {- throw new Error(`Collection ${record.collectionID} not found in cache`);- }-- const collectionKey = await decryptCollectionKey(- collectionRecord,- masterKey,- );- return decryptBox(- {- encryptedData: record.encryptedKey,- nonce: record.keyDecryptionNonce,- },- collectionKey,- );-};-const generateBase62Secret = (length: number) => {const charset ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";@@ -662,495 +200,6 @@ const infoItemTitle = (}};-const toEpochMicroseconds = (timestamp: unknown) => {- if (typeof timestamp !== "number") {- return undefined;- }-- // Locker mobile stores metadata timestamps in epoch milliseconds while- // server structural timestamps use epoch microseconds.- return timestamp < 100_000_000_000_000 ? timestamp * 1000 : timestamp;-};--/**- * Decrypt a file and return a LockerItem.- *- * If the file has pubMagicMetadata.info with a recognised type, we return a- * structured info item. Otherwise we return a generic "file" item with the- * display name extracted from basic metadata.- */-const decryptFileToLockerItem = async (- record: EncryptedFileRecord,- collectionKey: string,- collectionOwnerID: number,-): Promise<LockerItem | undefined> => {- try {- // Decrypt file key using collection key- const fileKey = await decryptBox(- {- encryptedData: record.encryptedKey,- nonce: record.keyDecryptionNonce,- },- collectionKey,- );-- // Decrypt basic metadata (title / filename lives here)- const metadata = (await decryptMetadataJSON(- record.metadata,- fileKey,- )) as Record<string, unknown> | undefined;-- // Try to decrypt pubMagicMetadata for info items- let pubMM: Record<string, unknown> | undefined;- if (record.pubMagicMetadata) {- try {- pubMM = (await decryptMetadataJSON(- {- encryptedData: record.pubMagicMetadata.data,- decryptionHeader: record.pubMagicMetadata.header,- },- fileKey,- )) as Record<string, unknown> | undefined;- } catch {- // pubMM decryption may fail for some files β that's fine- }- }-- // Check for structured info item- const info = pubMM?.info as- | { type?: string; data?: Record<string, unknown> }- | undefined;-- const validInfoTypes = new Set<string>([- "note",- "accountCredential",- "physicalRecord",- "emergencyContact",- ]);-- if (info?.type && info.data && validInfoTypes.has(info.type)) {- return {- id: record.id,- type: info.type as LockerItemType,- data: info.data as unknown as LockerItem["data"],- collectionID: record.collectionID,- collectionIDs: [record.collectionID],- ownerID: record.ownerID ?? collectionOwnerID,- createdAt: toEpochMicroseconds(metadata?.creationTime),- updatedAt: record.updationTime,- };- }-- // Fall back to generic file item- const editedName =- typeof pubMM?.editedName === "string"- ? pubMM.editedName- : undefined;- const metadataTitle =- typeof metadata?.title === "string" ? metadata.title : undefined;- const displayName = editedName ?? metadataTitle ?? "File";-- return {- id: record.id,- type: "file",- data: {- name: displayName,- fileSize: record.fileSize,- hasObject: record.hasObject,- },- collectionID: record.collectionID,- collectionIDs: [record.collectionID],- ownerID: record.ownerID ?? collectionOwnerID,- createdAt: toEpochMicroseconds(metadata?.creationTime),- updatedAt: record.updationTime,- };- } catch (e: unknown) {- const detail = describeCryptoError(e);- log.error(`Failed to decrypt file ${record.id}: ${detail}`);- return undefined;- }-};--/**- * Decrypt all cached encrypted data and assemble into LockerCollections.- * This is the only place where decryption happens β results are never- * persisted back to storage.- */-const decryptAllData = async (- masterKey: string,-): Promise<DecryptAllDataResult> => {- const activeCollectionRecords = [...encryptedCollections.values()].filter(- (collection) => !collection.isDeleted,- );- const result: LockerCollection[] = [];- const failedCollectionIDs: number[] = [];- const totalCollectionCount = activeCollectionRecords.length;-- // Group files by collection- const filesByCollection = new Map<number, EncryptedFileRecord[]>();- for (const file of getAllEncryptedFileRecords()) {- const existing = filesByCollection.get(file.collectionID) ?? [];- existing.push(file);- filesByCollection.set(file.collectionID, existing);- }-- // Decrypt each collection and its files- for (const collectionRecord of activeCollectionRecords) {- try {- const collectionKey = await decryptCollectionKey(- collectionRecord,- masterKey,- );- const name = await decryptCollectionName(- collectionRecord,- collectionKey,- );-- const files = filesByCollection.get(collectionRecord.id) ?? [];- const itemPromises = files.map((f) =>- decryptFileToLockerItem(- f,- collectionKey,- collectionRecord.ownerID,- ),- );- const decryptedItems = await Promise.all(itemPromises);- const items = decryptedItems.filter(- (item): item is LockerItem => item !== undefined,- );-- result.push({- id: collectionRecord.id,- name,- owner: collectionRecord.owner,- sharees: collectionRecord.sharees,- items,- type: collectionRecord.type,- isShared: collectionRecord.isShared,- });- } catch (e: unknown) {- failedCollectionIDs.push(collectionRecord.id);- log.error(- `Failed to decrypt collection ${collectionRecord.id}: ${describeCryptoError(e)}`,- );- }- }-- if (failedCollectionIDs.length > 0) {- const failedCollectionIDSet = new Set(failedCollectionIDs);- encryptedCollections = new Map(- [...encryptedCollections.entries()].filter(- ([collectionID]) => !failedCollectionIDSet.has(collectionID),- ),- );- encryptedFiles = new Map(- [...encryptedFiles.entries()]- .map(- ([fileID, records]): [- number,- Map<number, EncryptedFileRecord>,- ] => [- fileID,- new Map(- [...records.entries()].filter(- ([collectionID]) =>- !failedCollectionIDSet.has(collectionID),- ),- ),- ],- )- .filter(([, records]) => records.size > 0),- );- }-- // Sort collections alphabetically by name- result.sort((a, b) => a.name.localeCompare(b.name));-- return { collections: result, failedCollectionIDs, totalCollectionCount };-};--// ----------------------------------------------------------------------------// Trash support-// -----------------------------------------------------------------------------const RemoteTrashItem = z.object({- file: RemoteFile,- isDeleted: z.boolean(),- isRestored: z.boolean(),- updatedAt: z.number(),- deleteBy: z.number(),-});--const TrashDiffResponse = z.object({- diff: z.array(RemoteTrashItem),- hasMore: z.boolean(),-});--interface LockerTrashData {- items: LockerItem[];- lastUpdatedAt: number;-}--/**- * Fetch trashed Locker items from remote, decrypt them, and return them- * ready for display. Must be called after {@link fetchLockerData} so that- * the encrypted collection cache is populated (needed for key decryption).- */-export const fetchLockerTrash = async (- masterKey: string,-): Promise<LockerTrashData> => {- const trashItems: LockerItem[] = [];- let sinceTime = 0;- let hasMore = true;-- while (hasMore) {- const res = await fetch(await apiURL("/trash/v2/diff", { sinceTime }), {- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- const parsed = TrashDiffResponse.parse(await res.json());-- for (const entry of parsed.diff) {- sinceTime = Math.max(sinceTime, entry.updatedAt);-- // Skip items that have been permanently deleted or restored- if (entry.isDeleted || entry.isRestored) continue;-- const f = entry.file;-- // We need the collection key to decrypt the file. The collection- // may have been deleted by the time trash is fetched, but its- // record should still be in our cache from the collections fetch.- const collectionRecord = encryptedCollections.get(f.collectionID);- if (!collectionRecord) {- log.warn(- `Skipping trash file ${f.id}: collection ${f.collectionID} not in cache`,- );- continue;- }-- // Build an EncryptedFileRecord from the trash entry's file- const fileRecord: EncryptedFileRecord = {- id: f.id,- collectionID: f.collectionID,- ownerID: f.ownerID ?? undefined,- encryptedKey: f.encryptedKey,- keyDecryptionNonce: f.keyDecryptionNonce,- fileDecryptionHeader: f.file.decryptionHeader,- hasObject: f.file.decryptionHeader.length > 0,- fileSize: f.info?.fileSize,- metadata: {- encryptedData: f.metadata.encryptedData,- decryptionHeader: f.metadata.decryptionHeader,- },- magicMetadata: f.magicMetadata- ? {- version: f.magicMetadata.version,- data: f.magicMetadata.data,- header: f.magicMetadata.header,- }- : undefined,- pubMagicMetadata: f.pubMagicMetadata- ? {- version: f.pubMagicMetadata.version,- data: f.pubMagicMetadata.data,- header: f.pubMagicMetadata.header,- }- : undefined,- updationTime: f.updationTime,- };- // Keep trash records in cache so restore can locate key material.- setEncryptedFileRecord(encryptedFiles, fileRecord);-- try {- const collectionKey = await decryptCollectionKey(- collectionRecord,- masterKey,- );- const item = await decryptFileToLockerItem(- fileRecord,- collectionKey,- collectionRecord.ownerID,- );- if (item) {- trashItems.push({ ...item, deleteBy: entry.deleteBy });- }- } catch (e) {- log.error(`Failed to decrypt trash file ${f.id}`, e);- }- }-- hasMore = parsed.hasMore;- }-- // Sort by most recently trashed first- trashItems.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));- return { items: trashItems, lastUpdatedAt: sinceTime };-};--// ----------------------------------------------------------------------------// File download (read-only β decrypt and save to user's device)-// -----------------------------------------------------------------------------/**- * Download a Locker file: fetch the encrypted blob from remote, decrypt it- * in-memory using the file's key, and trigger a browser download.- *- * @param fileID The file's unique ID.- * @param fileName The display name for the downloaded file.- * @param masterKey The user's decrypted master key.- */-export const downloadLockerFile = async (- fileID: number,- fileName: string,- masterKey: string,- onProgress?: (progress: { loaded: number; total?: number }) => void,-): Promise<void> => {- const fileRecord = getEncryptedFileRecord(fileID);- if (!fileRecord) throw new Error(`File ${fileID} not found in cache`);-- const collectionRecord = encryptedCollections.get(fileRecord.collectionID);- if (!collectionRecord)- throw new Error(- `Collection ${fileRecord.collectionID} not found in cache`,- );-- // Decrypt collection key β file key- const collectionKey = await decryptCollectionKey(- collectionRecord,- masterKey,- );- const fileKey = await decryptBox(- {- encryptedData: fileRecord.encryptedKey,- nonce: fileRecord.keyDecryptionNonce,- },- collectionKey,- );-- // Fetch encrypted file blob from remote- const customOrigin = await customAPIOrigin();- let res: Response;- if (customOrigin) {- const token = await ensureAuthToken();- const url = await apiURL(`/files/download/${fileID}`, { token });- res = await fetch(url);- } else {- res = await fetch(`https://files.ente.io/?fileID=${fileID}`, {- headers: await authenticatedRequestHeaders(),- });- }- ensureOk(res);- const body = res.body;- if (!body) {- throw new Error("Download response body is empty");- }-- const reader = body.getReader();- const contentLength =- parseInt(res.headers.get("Content-Length") ?? "", 10) || 0;- let downloadedBytes = 0;-- onProgress?.({- loaded: 0,- total: contentLength > 0 ? contentLength : undefined,- });-- const streamDecryptor = await createStreamDecryptor(- fileRecord.fileDecryptionHeader,- fileKey,- );-- let leftoverBytes = new Uint8Array();-- const decryptedStream = new ReadableStream<Uint8Array>({- pull: async (controller) => {- let didEnqueue = false;- try {- do {- const { done, value } = await reader.read();-- let data: Uint8Array;- if (done) {- data = leftoverBytes;- } else {- downloadedBytes += value.length;- onProgress?.({- loaded: downloadedBytes,- total:- contentLength > 0 ? contentLength : undefined,- });- data = new Uint8Array(- leftoverBytes.length + value.length,- );- data.set(leftoverBytes, 0);- data.set(value, leftoverBytes.length);- }-- while (data.length >= streamDecryptor.decryptionChunkSize) {- const decryptedChunk =- await streamDecryptor.decryptChunk(- data.slice(- 0,- streamDecryptor.decryptionChunkSize,- ),- );- controller.enqueue(decryptedChunk);- didEnqueue = true;- data = data.slice(streamDecryptor.decryptionChunkSize);- }-- if (done) {- if (data.length) {- const decryptedChunk =- await streamDecryptor.decryptChunk(data);- controller.enqueue(decryptedChunk);- }- if (!streamDecryptor.isFinalized()) {- throw new Error(- "Download stream truncated before final chunk",- );- }- onProgress?.({- loaded:- contentLength > 0- ? contentLength- : downloadedBytes,- total:- contentLength > 0 ? contentLength : undefined,- });- streamDecryptor.free();- controller.close();- didEnqueue = true;- } else {- leftoverBytes = new Uint8Array(data);- }- } while (!didEnqueue);- } catch (error) {- streamDecryptor.free();- controller.error(error);- }- },- cancel: () => {- streamDecryptor.free();- void reader.cancel();- },- });-- const decryptedData = await new Response(decryptedStream).blob();-- // Trigger browser download- const url = URL.createObjectURL(decryptedData);- const a = document.createElement("a");- a.style.display = "none";- a.href = url;- a.download = fileName;- document.body.appendChild(a);- a.click();- setTimeout(() => URL.revokeObjectURL(url), 0);- a.remove();-};-/*** Fetch Locker file share links for the current user.*@@ -1259,7 +308,7 @@ export const createInfoItem = async (if (collectionID === undefined) {throw new Error("No collection selected");}- const collectionRecord = encryptedCollections.get(collectionID);+ const collectionRecord = getCollectionRecord(collectionID);if (!collectionRecord)throw new Error(`Collection ${collectionID} not in cache`);@@ -1355,7 +404,7 @@ export const updateInfoItem = async (const fileRecord = getEncryptedFileRecord(fileID);if (!fileRecord) throw new Error(`File ${fileID} not in cache`);- const collectionRecord = encryptedCollections.get(fileRecord.collectionID);+ const collectionRecord = getCollectionRecord(fileRecord.collectionID);if (!collectionRecord)throw new Error(`Collection ${fileRecord.collectionID} not in cache`);@@ -1420,25 +469,11 @@ export const updateInfoItem = async (});ensureOk(res);- const records = encryptedFiles.get(fileID);- if (records) {- encryptedFiles.set(- fileID,- new Map(- [...records.entries()].map(([recordCollectionID, record]) => [- recordCollectionID,- {- ...record,- pubMagicMetadata: {- version: version + 1,- data: encryptedPubMM.encryptedData,- header: encryptedPubMM.decryptionHeader,- },- },- ]),- ),- );- }+ updateCachedPubMagicMetadata(fileID, {+ version: version + 1,+ data: encryptedPubMM.encryptedData,+ header: encryptedPubMM.decryptionHeader,+ });};export const updateFileItem = async (@@ -1449,7 +484,7 @@ export const updateFileItem = async (const fileRecord = getEncryptedFileRecord(fileID);if (!fileRecord) throw new Error(`File ${fileID} not in cache`);- const collectionRecord = encryptedCollections.get(fileRecord.collectionID);+ const collectionRecord = getCollectionRecord(fileRecord.collectionID);if (!collectionRecord)throw new Error(`Collection ${fileRecord.collectionID} not in cache`);@@ -1507,25 +542,11 @@ export const updateFileItem = async (});ensureOk(res);- const records = encryptedFiles.get(fileID);- if (records) {- encryptedFiles.set(- fileID,- new Map(- [...records.entries()].map(([recordCollectionID, record]) => [- recordCollectionID,- {- ...record,- pubMagicMetadata: {- version: version + 1,- data: encryptedPubMM.encryptedData,- header: encryptedPubMM.decryptionHeader,- },- },- ]),- ),- );- }+ updateCachedPubMagicMetadata(fileID, {+ version: version + 1,+ data: encryptedPubMM.encryptedData,+ header: encryptedPubMM.decryptionHeader,+ });};export const updateItemCollections = async (@@ -1608,7 +629,7 @@ const addFileToCollections = async (masterKey: string,): Promise<void> => {for (const targetCollectionID of targetCollectionIDs) {- const collectionRecord = encryptedCollections.get(targetCollectionID);+ const collectionRecord = getCollectionRecord(targetCollectionID);if (!collectionRecord) {throw new Error(`Collection ${targetCollectionID} not in cache`);}@@ -1665,7 +686,7 @@ const decryptFileKeyForCollection = async ();}- const collectionRecord = encryptedCollections.get(collectionID);+ const collectionRecord = getCollectionRecord(collectionID);if (!collectionRecord) {throw new Error(`Collection ${collectionID} not in cache`);}@@ -1694,7 +715,7 @@ const buildEncryptedFileMoveItem = async (fromCollectionID,masterKey,);- const targetCollectionRecord = encryptedCollections.get(toCollectionID);+ const targetCollectionRecord = getCollectionRecord(toCollectionID);if (!targetCollectionRecord) {throw new Error(`Collection ${toCollectionID} not in cache`);}@@ -1760,8 +781,7 @@ const moveFilesBetweenCollections = async (const createCollectionMutationDeps = () => ({getCollectionIDsForFile,- getCollectionRecord: (collectionID: number) =>- encryptedCollections.get(collectionID),+ getCollectionRecord,ensureUncategorizedCollection,decryptFileKeyForCollection,buildEncryptedFileMoveItem,@@ -1782,7 +802,7 @@ export const restoreFromTrash = async (targetCollectionID: number,masterKey: string,): Promise<void> => {- const collectionRecord = encryptedCollections.get(targetCollectionID);+ const collectionRecord = getCollectionRecord(targetCollectionID);if (!collectionRecord)throw new Error(`Collection ${targetCollectionID} not in cache`);@@ -1812,7 +832,7 @@ export const restoreFromTrash = async (}// Decrypt file key using original collection key- const origCollectionRecord = encryptedCollections.get(+ const origCollectionRecord = getCollectionRecord(fileRecord.collectionID,);if (!origCollectionRecord) {@@ -1895,10 +915,7 @@ export const createCollection = async (const ensureUncategorizedCollection = async (masterKey: string) => {return ensureUncategorizedCollectionWithDeps(masterKey, {- findCollectionByType: (type) =>- [...encryptedCollections.values()].find(- (candidate) => candidate.type === type,- ),+ findCollectionByType,refetchCollections: async (masterKey) => {await fetchLockerData(masterKey);},@@ -1918,8 +935,7 @@ export const renameCollection = async (masterKey: string,): Promise<void> => {await renameCollectionWithDeps(collectionID, newName, masterKey, {- getCollectionRecord: (collectionID) =>- encryptedCollections.get(collectionID),+ getCollectionRecord,decryptCollectionKey,});};@@ -1955,8 +971,7 @@ export const fetchCollectionSharees = async (collectionID: number,): Promise<LockerCollectionParticipant[]> => {return fetchCollectionShareesWithDeps(collectionID, {- getCollectionRecord: (collectionID) =>- encryptedCollections.get(collectionID),+ getCollectionRecord,decryptCollectionKey,updateCollectionShareesInCache,});@@ -1971,8 +986,7 @@ export const shareCollection = async (masterKey: string,): Promise<LockerCollectionParticipant[]> => {return shareCollectionWithDeps(collectionID, email, masterKey, {- getCollectionRecord: (collectionID) =>- encryptedCollections.get(collectionID),+ getCollectionRecord,decryptCollectionKey,updateCollectionShareesInCache,});@@ -1986,8 +1000,7 @@ export const unshareCollection = async (email: string,): Promise<LockerCollectionParticipant[]> => {return unshareCollectionWithDeps(collectionID, email, {- getCollectionRecord: (collectionID) =>- encryptedCollections.get(collectionID),+ getCollectionRecord,decryptCollectionKey,updateCollectionShareesInCache,});@@ -2009,12 +1022,7 @@ export const uploadLockerFile = async (file,collectionIDs,masterKey,- {- getCollectionRecord: (collectionID) =>- encryptedCollections.get(collectionID),- decryptCollectionKey,- addFileToCollections,- },+ { getCollectionRecord, decryptCollectionKey, addFileToCollections },onProgress,);};