π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Move
Manav Rathi746c85bc9ffa
diff --git a/web/apps/photos/src/components/Upload/Uploader.tsx b/web/apps/photos/src/components/Upload/Uploader.tsxindex 1c3c17e108..f0461e76b6 100644--- a/web/apps/photos/src/components/Upload/Uploader.tsx+++ b/web/apps/photos/src/components/Upload/Uploader.tsx@@ -9,6 +9,7 @@ import { UploaderNameInput } from "@/new/albums/components/UploaderNameInput";import { CollectionMappingChoice } from "@/new/photos/components/CollectionMappingChoice";import type { CollectionSelectorAttributes } from "@/new/photos/components/CollectionSelector";import { downloadAppDialogAttributes } from "@/new/photos/components/utils/download";+import { getLatestCollections } from "@/new/photos/services/collections";import { exportMetadataDirectoryName } from "@/new/photos/services/export";import type {FileAndPath,@@ -26,7 +27,6 @@ import { t } from "i18next";import { GalleryContext } from "pages/gallery";import { useContext, useEffect, useRef, useState } from "react";import { Trans } from "react-i18next";-import { getLatestCollections } from "services/collectionService";import {getPublicCollectionUID,getPublicCollectionUploaderName,diff --git a/web/apps/photos/src/pages/deduplicate.tsx b/web/apps/photos/src/pages/deduplicate.tsxindex 4b1d16630a..6defce11f2 100644--- a/web/apps/photos/src/pages/deduplicate.tsx+++ b/web/apps/photos/src/pages/deduplicate.tsx@@ -3,10 +3,14 @@ import { ActivityIndicator } from "@/base/components/mui/ActivityIndicator";import { errorDialogAttributes } from "@/base/components/utils/dialog";import log from "@/base/log";import { ALL_SECTION, moveToTrash } from "@/new/photos/services/collection";-import { getLocalCollections } from "@/new/photos/services/collections";+import {+ getAllLatestCollections,+ getLocalCollections,+} from "@/new/photos/services/collections";import {createFileCollectionIDs,getLocalFiles,+ syncFiles,} from "@/new/photos/services/files";import { useAppContext } from "@/new/photos/types/context";import { VerticallyCentered } from "@ente/shared/components/Container";@@ -22,9 +26,7 @@ import PhotoFrame from "components/PhotoFrame";import { t } from "i18next";import { default as Router, default as router } from "next/router";import { createContext, useEffect, useState } from "react";-import { getAllLatestCollections } from "services/collectionService";import { Duplicate, getDuplicates } from "services/deduplicationService";-import { syncFiles } from "services/fileService";import { syncTrash } from "services/trashService";import { SelectedState } from "types/gallery";import { getSelectedFiles } from "utils/file";diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex 15e229fdb9..1b6f41b299 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -35,7 +35,10 @@ import {isHiddenCollection,} from "@/new/photos/services/collection";import { areOnlySystemCollections } from "@/new/photos/services/collection/ui";-import { getAllLocalCollections } from "@/new/photos/services/collections";+import {+ getAllLatestCollections,+ getAllLocalCollections,+} from "@/new/photos/services/collections";import {getLocalFiles,getLocalTrashedFiles,@@ -114,7 +117,6 @@ import {constructUserIDToEmailMap,createAlbum,createUnCategorizedCollection,- getAllLatestCollections,} from "services/collectionService";import exportService from "services/export";import { preCollectionsAndFilesSync, sync } from "services/sync";diff --git a/web/apps/photos/src/services/collectionService.ts b/web/apps/photos/src/services/collectionService.tsindex 8e36d9903a..a8dc225337 100644--- a/web/apps/photos/src/services/collectionService.ts+++ b/web/apps/photos/src/services/collectionService.ts@@ -6,7 +6,6 @@ import {CollectionMagicMetadata,CollectionMagicMetadataProps,CollectionPublicMagicMetadata,- CollectionShareeMagicMetadata,CollectionType,CreatePublicAccessTokenRequest,EncryptedCollection,@@ -20,7 +19,6 @@ import { ItemVisibility } from "@/media/file-metadata";import {addToCollection,isDefaultHiddenCollection,- isHiddenCollection,moveToCollection,} from "@/new/photos/services/collection";import type { CollectionSummary } from "@/new/photos/services/collection/ui";@@ -29,9 +27,8 @@ import {CollectionsSortBy,} from "@/new/photos/services/collection/ui";import {- getAllLocalCollections,+ getCollectionWithSecrets,getLocalCollections,- removeCollectionLastSyncTime,} from "@/new/photos/services/collections";import {getLocalFiles,@@ -42,7 +39,6 @@ import { updateMagicMetadata } from "@/new/photos/services/magic-metadata";import type { FamilyData } from "@/new/photos/services/user-details";import { batch } from "@/utils/array";import HTTPService from "@ente/shared/network/HTTPService";-import localForage from "@ente/shared/storage/localForage";import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";import { getToken } from "@ente/shared/storage/localStorage/helpers";import { getActualKey } from "@ente/shared/user";@@ -55,252 +51,12 @@ import {import { UpdateMagicMetadataRequest } from "./fileService";import { getPublicKey } from "./userService";-const COLLECTION_TABLE = "collections";--const COLLECTION_UPDATION_TIME = "collection-updation-time";-const HIDDEN_COLLECTION_IDS = "hidden-collection-ids";-const UNCATEGORIZED_COLLECTION_NAME = "Uncategorized";export const HIDDEN_COLLECTION_NAME = ".hidden";const FAVORITE_COLLECTION_NAME = "Favorites";const REQUEST_BATCH_SIZE = 1000;-const getCollectionWithSecrets = async (- collection: EncryptedCollection,- masterKey: string,-): Promise<Collection> => {- const cryptoWorker = await sharedCryptoWorker();- const userID = getData(LS_KEYS.USER).id;- let collectionKey: string;- if (collection.owner.id === userID) {- collectionKey = await cryptoWorker.decryptB64(- collection.encryptedKey,- collection.keyDecryptionNonce,- masterKey,- );- } else {- const keyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);- const secretKey = await cryptoWorker.decryptB64(- keyAttributes.encryptedSecretKey,- keyAttributes.secretKeyDecryptionNonce,- masterKey,- );- collectionKey = await cryptoWorker.boxSealOpen(- collection.encryptedKey,- keyAttributes.publicKey,- secretKey,- );- }- const collectionName =- collection.name ||- (await cryptoWorker.decryptToUTF8(- collection.encryptedName,- collection.nameDecryptionNonce,- collectionKey,- ));-- let collectionMagicMetadata: CollectionMagicMetadata;- if (collection.magicMetadata?.data) {- collectionMagicMetadata = {- ...collection.magicMetadata,- data: await cryptoWorker.decryptMetadataJSON({- encryptedDataB64: collection.magicMetadata.data,- decryptionHeaderB64: collection.magicMetadata.header,- keyB64: collectionKey,- }),- };- }- let collectionPublicMagicMetadata: CollectionPublicMagicMetadata;- if (collection.pubMagicMetadata?.data) {- collectionPublicMagicMetadata = {- ...collection.pubMagicMetadata,- data: await cryptoWorker.decryptMetadataJSON({- encryptedDataB64: collection.pubMagicMetadata.data,- decryptionHeaderB64: collection.pubMagicMetadata.header,- keyB64: collectionKey,- }),- };- }-- let collectionShareeMagicMetadata: CollectionShareeMagicMetadata;- if (collection.sharedMagicMetadata?.data) {- collectionShareeMagicMetadata = {- ...collection.sharedMagicMetadata,- data: await cryptoWorker.decryptMetadataJSON({- encryptedDataB64: collection.sharedMagicMetadata.data,- decryptionHeaderB64: collection.sharedMagicMetadata.header,- keyB64: collectionKey,- }),- };- }-- return {- ...collection,- name: collectionName,- key: collectionKey,- magicMetadata: collectionMagicMetadata,- pubMagicMetadata: collectionPublicMagicMetadata,- sharedMagicMetadata: collectionShareeMagicMetadata,- };-};--const getCollections = async (- token: string,- sinceTime: number,- key: string,-): Promise<Collection[]> => {- try {- const resp = await HTTPService.get(- await apiURL("/collections/v2"),- {- sinceTime,- },- { "X-Auth-Token": token },- );- const decryptedCollections: Collection[] = await Promise.all(- resp.data.collections.map(- async (collection: EncryptedCollection) => {- if (collection.isDeleted) {- return collection;- }- try {- return await getCollectionWithSecrets(collection, key);- } catch (e) {- log.error(- `decryption failed for collection with ID ${collection.id}`,- e,- );- return collection;- }- },- ),- );- // only allow deleted or collection with key, filtering out collection whose decryption failed- const collections = decryptedCollections.filter(- (collection) => collection.isDeleted || collection.key,- );- return collections;- } catch (e) {- log.error("getCollections failed", e);- throw e;- }-};--export const getCollectionUpdationTime = async (): Promise<number> =>- (await localForage.getItem<number>(COLLECTION_UPDATION_TIME)) ?? 0;--export const getHiddenCollectionIDs = async (): Promise<number[]> =>- (await localForage.getItem<number[]>(HIDDEN_COLLECTION_IDS)) ?? [];--export const getLatestCollections = async (- type: "normal" | "hidden" = "normal",-): Promise<Collection[]> => {- const collections = await getAllLatestCollections();- return type == "normal"- ? collections.filter((c) => !isHiddenCollection(c))- : collections.filter((c) => isHiddenCollection(c));-};--export const getAllLatestCollections = async (): Promise<Collection[]> => {- const collections = await syncCollections();- return collections;-};--export const syncCollections = async () => {- const localCollections = await getAllLocalCollections();- let lastCollectionUpdationTime = await getCollectionUpdationTime();- const hiddenCollectionIDs = await getHiddenCollectionIDs();- const token = getToken();- const key = await getActualKey();- const updatedCollections =- (await getCollections(token, lastCollectionUpdationTime, key)) ?? [];- if (updatedCollections.length === 0) {- return localCollections;- }- const allCollectionsInstances = [- ...localCollections,- ...updatedCollections,- ];- const latestCollectionsInstances = new Map<number, Collection>();- allCollectionsInstances.forEach((collection) => {- if (- !latestCollectionsInstances.has(collection.id) ||- latestCollectionsInstances.get(collection.id).updationTime <- collection.updationTime- ) {- latestCollectionsInstances.set(collection.id, collection);- }- });-- const collections: Collection[] = [];- // eslint-disable-next-line @typescript-eslint/no-unused-vars- for (const [_, collection] of latestCollectionsInstances) {- const isDeletedCollection = collection.isDeleted;- const isNewlyHiddenCollection =- isHiddenCollection(collection) &&- !hiddenCollectionIDs.includes(collection.id);- const isNewlyUnHiddenCollection =- !isHiddenCollection(collection) &&- hiddenCollectionIDs.includes(collection.id);- if (- isDeletedCollection ||- isNewlyHiddenCollection ||- isNewlyUnHiddenCollection- ) {- removeCollectionLastSyncTime(collection);- }- if (isDeletedCollection) {- continue;- }- collections.push(collection);- lastCollectionUpdationTime = Math.max(- lastCollectionUpdationTime,- collection.updationTime,- );- }-- const updatedHiddenCollectionIDs = collections- .filter((collection) => isHiddenCollection(collection))- .map((collection) => collection.id);-- await localForage.setItem(COLLECTION_TABLE, collections);- await localForage.setItem(- COLLECTION_UPDATION_TIME,- lastCollectionUpdationTime,- );- await localForage.setItem(- HIDDEN_COLLECTION_IDS,- updatedHiddenCollectionIDs,- );- return collections;-};--export const getCollection = async (- collectionID: number,-): Promise<Collection> => {- try {- const token = getToken();- if (!token) {- return;- }- const resp = await HTTPService.get(- await apiURL(`/collections/${collectionID}`),- null,- { "X-Auth-Token": token },- );- const key = await getActualKey();- const collectionWithSecrets = await getCollectionWithSecrets(- resp.data?.collection,- key,- );- return collectionWithSecrets;- } catch (e) {- log.error("failed to get collection", e);- throw e;- }-};-export const createAlbum = (albumName: string) => {return createCollection(albumName, CollectionType.album);};diff --git a/web/apps/photos/src/services/sync.ts b/web/apps/photos/src/services/sync.tsindex 7101c3ca2d..2bba28055f 100644--- a/web/apps/photos/src/services/sync.ts+++ b/web/apps/photos/src/services/sync.ts@@ -1,10 +1,10 @@import { isHiddenCollection } from "@/new/photos/services/collection";+import { getAllLatestCollections } from "@/new/photos/services/collections";+import { syncFiles } from "@/new/photos/services/files";import { isMLSupported, mlStatusSync, mlSync } from "@/new/photos/services/ml";import { searchDataSync } from "@/new/photos/services/search";import { syncSettings } from "@/new/photos/services/settings";import { splitByPredicate } from "@/utils/array";-import { getAllLatestCollections } from "./collectionService";-import { syncFiles } from "./fileService";import { syncTrash } from "./trashService";/**diff --git a/web/apps/photos/src/services/trashService.ts b/web/apps/photos/src/services/trashService.tsindex 62e93d5664..9d61cea1ed 100644--- a/web/apps/photos/src/services/trashService.ts+++ b/web/apps/photos/src/services/trashService.ts@@ -7,6 +7,7 @@ import {Trash,type EnteFile,} from "@/media/file";+import { getCollection } from "@/new/photos/services/collections";import {getLocalTrash,getTrashedFiles,@@ -15,7 +16,6 @@ import {import HTTPService from "@ente/shared/network/HTTPService";import localForage from "@ente/shared/storage/localForage";import { getToken } from "@ente/shared/storage/localStorage/helpers";-import { getCollection } from "./collectionService";const TRASH_TIME = "trash-time";const DELETED_COLLECTION = "deleted-collection";diff --git a/web/packages/new/photos/services/collections.ts b/web/packages/new/photos/services/collections.tsindex 0d838c993c..3bec9b4d70 100644--- a/web/packages/new/photos/services/collections.ts+++ b/web/packages/new/photos/services/collections.ts@@ -1,8 +1,31 @@-import { type Collection } from "@/media/collection";+/* eslint-disable @typescript-eslint/no-unsafe-call */+// TODO: Audit this file+/* eslint-disable @typescript-eslint/no-unnecessary-condition */+/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */+/* eslint-disable @typescript-eslint/no-unsafe-member-access */+/* eslint-disable @typescript-eslint/no-unsafe-argument */+/* eslint-disable @typescript-eslint/no-unsafe-assignment */++import { sharedCryptoWorker } from "@/base/crypto";+import log from "@/base/log";+import { apiURL } from "@/base/origins";+import {+ type Collection,+ type CollectionMagicMetadata,+ type CollectionPublicMagicMetadata,+ type CollectionShareeMagicMetadata,+ type EncryptedCollection,+} from "@/media/collection";+import HTTPService from "@ente/shared/network/HTTPService";import localForage from "@ente/shared/storage/localForage";+import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";+import { getToken } from "@ente/shared/storage/localStorage/helpers";+import { getActualKey } from "@ente/shared/user";import { isHiddenCollection } from "./collection";const COLLECTION_TABLE = "collections";+const HIDDEN_COLLECTION_IDS = "hidden-collection-ids";+const COLLECTION_UPDATION_TIME = "collection-updation-time";export const getLocalCollections = async (type: "normal" | "hidden" = "normal",@@ -29,3 +52,247 @@ export const setCollectionLastSyncTime = async (export const removeCollectionLastSyncTime = async (collection: Collection) =>await localForage.removeItem(`${collection.id}-time`);++export const getHiddenCollectionIDs = async (): Promise<number[]> =>+ (await localForage.getItem<number[]>(HIDDEN_COLLECTION_IDS)) ?? [];++export const getCollectionUpdationTime = async (): Promise<number> =>+ (await localForage.getItem<number>(COLLECTION_UPDATION_TIME)) ?? 0;++export const getLatestCollections = async (+ type: "normal" | "hidden" = "normal",+): Promise<Collection[]> => {+ const collections = await getAllLatestCollections();+ return type == "normal"+ ? collections.filter((c) => !isHiddenCollection(c))+ : collections.filter((c) => isHiddenCollection(c));+};++export const getAllLatestCollections = async (): Promise<Collection[]> => {+ const collections = await syncCollections();+ return collections;+};++export const syncCollections = async () => {+ const localCollections = await getAllLocalCollections();+ let lastCollectionUpdationTime = await getCollectionUpdationTime();+ const hiddenCollectionIDs = await getHiddenCollectionIDs();+ const token = getToken();+ const key = await getActualKey();+ const updatedCollections =+ (await getCollections(token, lastCollectionUpdationTime, key)) ?? [];+ if (updatedCollections.length === 0) {+ return localCollections;+ }+ const allCollectionsInstances = [+ ...localCollections,+ ...updatedCollections,+ ];+ const latestCollectionsInstances = new Map<number, Collection>();+ allCollectionsInstances.forEach((collection) => {+ if (+ !latestCollectionsInstances.has(collection.id) ||+ // @ts-expect-error TODO fixme+ latestCollectionsInstances.get(collection.id).updationTime <+ collection.updationTime+ ) {+ latestCollectionsInstances.set(collection.id, collection);+ }+ });++ const collections: Collection[] = [];+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ for (const [_, collection] of latestCollectionsInstances) {+ const isDeletedCollection = collection.isDeleted;+ const isNewlyHiddenCollection =+ isHiddenCollection(collection) &&+ !hiddenCollectionIDs.includes(collection.id);+ const isNewlyUnHiddenCollection =+ !isHiddenCollection(collection) &&+ hiddenCollectionIDs.includes(collection.id);+ if (+ isDeletedCollection ||+ isNewlyHiddenCollection ||+ isNewlyUnHiddenCollection+ ) {+ await removeCollectionLastSyncTime(collection);+ }+ if (isDeletedCollection) {+ continue;+ }+ collections.push(collection);+ lastCollectionUpdationTime = Math.max(+ lastCollectionUpdationTime,+ collection.updationTime,+ );+ }++ const updatedHiddenCollectionIDs = collections+ .filter((collection) => isHiddenCollection(collection))+ .map((collection) => collection.id);++ await localForage.setItem(COLLECTION_TABLE, collections);+ await localForage.setItem(+ COLLECTION_UPDATION_TIME,+ lastCollectionUpdationTime,+ );+ await localForage.setItem(+ HIDDEN_COLLECTION_IDS,+ updatedHiddenCollectionIDs,+ );+ return collections;+};++const getCollections = async (+ token: string,+ sinceTime: number,+ key: string,+): Promise<Collection[]> => {+ try {+ const resp = await HTTPService.get(+ await apiURL("/collections/v2"),+ {+ sinceTime,+ },+ { "X-Auth-Token": token },+ );+ const decryptedCollections: Collection[] = await Promise.all(+ resp.data.collections.map(+ async (collection: EncryptedCollection) => {+ if (collection.isDeleted) {+ return collection;+ }+ try {+ return await getCollectionWithSecrets(collection, key);+ } catch (e) {+ log.error(+ `decryption failed for collection with ID ${collection.id}`,+ e,+ );+ return collection;+ }+ },+ ),+ );+ // only allow deleted or collection with key, filtering out collection whose decryption failed+ const collections = decryptedCollections.filter(+ (collection) => collection.isDeleted || collection.key,+ );+ return collections;+ } catch (e) {+ log.error("getCollections failed", e);+ throw e;+ }+};++export const getCollectionWithSecrets = async (+ collection: EncryptedCollection,+ masterKey: string,+): Promise<Collection> => {+ const cryptoWorker = await sharedCryptoWorker();+ const userID = getData(LS_KEYS.USER).id;+ let collectionKey: string;+ if (collection.owner.id === userID) {+ collectionKey = await cryptoWorker.decryptB64(+ collection.encryptedKey,+ collection.keyDecryptionNonce,+ masterKey,+ );+ } else {+ const keyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);+ const secretKey = await cryptoWorker.decryptB64(+ keyAttributes.encryptedSecretKey,+ keyAttributes.secretKeyDecryptionNonce,+ masterKey,+ );+ collectionKey = await cryptoWorker.boxSealOpen(+ collection.encryptedKey,+ keyAttributes.publicKey,+ secretKey,+ );+ }+ const collectionName =+ collection.name ||+ (await cryptoWorker.decryptToUTF8(+ collection.encryptedName,+ collection.nameDecryptionNonce,+ collectionKey,+ ));++ let collectionMagicMetadata: CollectionMagicMetadata;+ if (collection.magicMetadata?.data) {+ collectionMagicMetadata = {+ ...collection.magicMetadata,+ // @ts-expect-error TODO fixme+ data: await cryptoWorker.decryptMetadataJSON({+ encryptedDataB64: collection.magicMetadata.data,+ decryptionHeaderB64: collection.magicMetadata.header,+ keyB64: collectionKey,+ }),+ };+ }+ let collectionPublicMagicMetadata: CollectionPublicMagicMetadata;+ if (collection.pubMagicMetadata?.data) {+ collectionPublicMagicMetadata = {+ ...collection.pubMagicMetadata,+ // @ts-expect-error TODO fixme+ data: await cryptoWorker.decryptMetadataJSON({+ encryptedDataB64: collection.pubMagicMetadata.data,+ decryptionHeaderB64: collection.pubMagicMetadata.header,+ keyB64: collectionKey,+ }),+ };+ }++ let collectionShareeMagicMetadata: CollectionShareeMagicMetadata;+ if (collection.sharedMagicMetadata?.data) {+ collectionShareeMagicMetadata = {+ ...collection.sharedMagicMetadata,+ // @ts-expect-error TODO fixme+ data: await cryptoWorker.decryptMetadataJSON({+ encryptedDataB64: collection.sharedMagicMetadata.data,+ decryptionHeaderB64: collection.sharedMagicMetadata.header,+ keyB64: collectionKey,+ }),+ };+ }++ return {+ ...collection,+ name: collectionName,+ key: collectionKey,+ // @ts-expect-error TODO fixme+ magicMetadata: collectionMagicMetadata,+ // @ts-expect-error TODO fixme+ pubMagicMetadata: collectionPublicMagicMetadata,+ // @ts-expect-error TODO fixme+ sharedMagicMetadata: collectionShareeMagicMetadata,+ };+};++export const getCollection = async (+ collectionID: number,+): Promise<Collection> => {+ try {+ const token = getToken();+ if (!token) {+ // @ts-expect-error TODO fixme+ return;+ }+ const resp = await HTTPService.get(+ await apiURL(`/collections/${collectionID}`),+ // @ts-expect-error TODO fixme+ null,+ { "X-Auth-Token": token },+ );+ const key = await getActualKey();+ const collectionWithSecrets = await getCollectionWithSecrets(+ resp.data?.collection,+ key,+ );+ return collectionWithSecrets;+ } catch (e) {+ log.error("failed to get collection", e);+ throw e;+ }+};