π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add in-memory storage and iframe-friendly security headers
Manav Rathia74eb5012a0d
diff --git a/web/apps/embed/public/_headers b/web/apps/embed/public/_headersnew file mode 100644index 0000000000..c7515bd65f--- /dev/null+++ b/web/apps/embed/public/_headers@@ -0,0 +1,8 @@+/*+ Cache-Control: no-store, must-revalidate+ Strict-Transport-Security: max-age=63072000+ X-Content-Type-Options: nosniff+ X-Download-Options: noopen+ X-XSS-Protection: 1; mode=block+ Reporting-Endpoints: csp-endpoint="https://csp-reporter.ente.io"+ Content-Security-Policy-Report-Only: default-src 'self'; img-src 'self' blob: data: https://*.openstreetmap.org; media-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self'; script-src 'self' https://assets.ente.io 'unsafe-eval' blob:; manifest-src 'self'; child-src 'self' blob:; object-src 'none'; connect-src 'self' https://*.ente.io data: blob: https://*.s3.eu-central-003.backblazeb2.com https://*.s3.eu-central-2.wasabisys.com; base-uri 'self'; form-action 'none'; report-uri https://csp-reporter.ente.io; report-to csp-endpoint;\ No newline at end of filediff --git a/web/apps/embed/src/pages/index.tsx b/web/apps/embed/src/pages/index.tsxindex 39560403c9..751f55dd17 100644--- a/web/apps/embed/src/pages/index.tsx+++ b/web/apps/embed/src/pages/index.tsx@@ -23,13 +23,13 @@ import {savedPublicCollectionByKey,savedPublicCollectionFiles,savePublicCollectionAccessTokenJWT,-} from "ente-new/albums/services/public-albums-fdb";+} from "../services/public-albums-storage";import {pullCollection,pullPublicCollectionFiles,removePublicCollectionFileData,verifyPublicAlbumPassword,-} from "ente-new/albums/services/public-collection";+} from "../services/public-collection";import { usePhotosAppContext } from "ente-new/photos/types/context";import { t } from "i18next";import { useCallback, useEffect, useRef, useState } from "react";diff --git a/web/apps/embed/src/services/in-memory-storage.ts b/web/apps/embed/src/services/in-memory-storage.tsnew file mode 100644index 0000000000..49556a5ef4--- /dev/null+++ b/web/apps/embed/src/services/in-memory-storage.ts@@ -0,0 +1,59 @@+/**+ * @file In-memory storage adapter for embed app+ *+ * This provides an in-memory storage implementation that mirrors the localForage+ * interface used by public-albums-fdb. It ensures complete isolation between+ * different iframe embeds by avoiding any persistent storage.+ */++/**+ * In-memory storage adapter that mimics the localForage interface.+ * Uses Maps to store data in memory, providing isolation between embeds.+ */+export class InMemoryStorage {+ private storage = new Map<string, unknown>();++ async getItem<T>(key: string): Promise<T | null> {+ const value = this.storage.get(key);+ return value !== undefined ? (value as T) : null;+ }++ async setItem<T>(key: string, value: T): Promise<T> {+ this.storage.set(key, value);+ return value;+ }++ async removeItem(key: string): Promise<void> {+ this.storage.delete(key);+ }++ async clear(): Promise<void> {+ this.storage.clear();+ }++ async ready(): Promise<void> {+ // Always ready since it's in-memory+ return Promise.resolve();+ }++ async keys(): Promise<string[]> {+ return Array.from(this.storage.keys());+ }++ async length(): Promise<number> {+ return this.storage.size;+ }++ async key(index: number): Promise<string | null> {+ const keys = await this.keys();+ return keys[index] || null;+ }++ // Config method to match localForage interface (no-op for in-memory)+ config(_options: Record<string, unknown>): void {+ // No configuration needed for in-memory storage+ }+}++// Create a singleton instance to be used as the storage backend+export const inMemoryStorage = new InMemoryStorage();\ No newline at end of filediff --git a/web/apps/embed/src/services/public-albums-storage.ts b/web/apps/embed/src/services/public-albums-storage.tsnew file mode 100644index 0000000000..b3609b5faa--- /dev/null+++ b/web/apps/embed/src/services/public-albums-storage.ts@@ -0,0 +1,310 @@+/**+ * @file Public albums storage facade for embed app+ *+ * This provides the same interface as public-albums-fdb but uses in-memory storage+ * instead of IndexedDB/localStorage. This ensures isolation between different+ * iframe embeds while maintaining API compatibility.+ */++import {+ LocalCollections,+ LocalEnteFiles,+ LocalTimestamp,+ transformFilesIfNeeded,+} from "ente-gallery/services/files-db";+import { type Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod/v4";+import { inMemoryStorage } from "./in-memory-storage";++/**+ * Return all public collections present in our local storage.+ *+ * Use {@link savePublicCollections} to update the storage.+ */+const savedPublicCollections = async (): Promise<Collection[]> =>+ LocalCollections.parse(+ (await inMemoryStorage.getItem("public-collections")) ?? [],+ );++/**+ * Replace the list of public collections stored in our local storage.+ *+ * This is the setter corresponding to {@link savedPublicCollections}.+ */+const savePublicCollections = (collections: Collection[]) =>+ inMemoryStorage.setItem("public-collections", collections);++/**+ * Return the saved public collection with the given {@link key} if present in+ * our local storage.+ *+ * Use {@link savePublicCollection} to save collections in our local storage.+ *+ * @param key The collection key that can be used to identify the public album+ * we want from amongst all the locally saved public albums.+ */+export const savedPublicCollectionByKey = async (+ collectionKey: string,+): Promise<Collection | undefined> =>+ savedPublicCollections().then((cs) =>+ cs.find((c) => c.key == collectionKey),+ );++/**+ * Save a public collection to our local storage.+ *+ * The collection can later be retrieved using {@link savedPublicCollection}.+ * The collection can be removed using {@link removePublicCollection}.+ */+export const savePublicCollection = async (collection: Collection) => {+ const collections = await savedPublicCollections();+ await savePublicCollections([+ collection,+ ...collections.filter((c) => c.id != collection.id),+ ]);+};++/**+ * Remove a public collection, identified using its collection key, from our+ * local storage.+ *+ * @param key The collection key that can be used to identify the public album+ * we want to remove.+ */+export const removePublicCollectionByKey = async (collectionKey: string) => {+ const collections = await savedPublicCollections();+ await savePublicCollections([+ ...collections.filter((c) => c.key != collectionKey),+ ]);+};++/**+ * Zod schema for a nullish string, with `null` transformed to `undefined`.+ */+const LocalString = z.string().nullish().transform(nullToUndefined);++/**+ * Return the last saved referral code present in our local storage.+ *+ * See: [Note: Public albums referral code]. A few more details specific to the+ * persistence of the referral code:+ *+ * 1. The public albums app persists only the referral code for the latest+ * public album that was fetched.+ *+ * 2. This saved value can be read by+ * {@link savedLastPublicCollectionReferralCode}.+ *+ * 3. It gets updated as part of {@link publicAlbumsRemotePull}, which writes+ * out a new value using {@link saveLastPublicCollectionReferralCode}.+ */+export const savedLastPublicCollectionReferralCode = async () =>+ LocalString.parse(await inMemoryStorage.getItem("public-referral-code"));++/**+ * Update the referral code present in our local storage.+ *+ * This is the setter corresponding to+ * {@link savedLastPublicCollectionReferralCode}.+ */+export const saveLastPublicCollectionReferralCode = async (+ referralCode: string,+) => {+ await inMemoryStorage.setItem("public-referral-code", referralCode);+};++const LocalSavedPublicCollectionFilesEntry = z.object({+ /**+ * The collection, identified by its access token.+ *+ * See: [Note: Public album access token]+ */+ collectionUID: z.string(),+ files: LocalEnteFiles,+});++type LocalSavedPublicCollectionFilesEntry = z.infer<+ typeof LocalSavedPublicCollectionFilesEntry+>;++/**+ * Return all files for a public collection present in our local storage.+ *+ * Use {@link savePublicCollectionFiles} to update the list of files in the+ * storage, and {@link removePublicCollectionFiles} to remove them.+ *+ * @param accessToken The access token that identifies the public album whose+ * files we want.+ */+export const savedPublicCollectionFiles = async (+ accessToken: string,+): Promise<EnteFile[]> => {+ const entry = (await pcfEntries()).find(+ (e) => e.collectionUID == accessToken,+ );+ return transformFilesIfNeeded(entry ? entry.files : []);+};++/**+ * A convenience routine to read the storage entries for "public-collection-files".+ */+const pcfEntries = async () => {+ // A local alias to avoid the code from looking scary.+ type ES = LocalSavedPublicCollectionFilesEntry[];++ // See: [Note: Avoiding Zod parsing for large DB arrays] for why we use an+ // (implied) cast here instead of parsing using the Zod schema.+ const entries = await inMemoryStorage.getItem<ES>("public-collection-files");+ return entries ?? [];+};++/**+ * Replace the list of files for a public collection in our local storage.+ *+ * This is the setter corresponding to {@link savedPublicCollectionFiles}.+ *+ * @param accessToken The access token that identifies the public album whose+ * files we want to update.+ *+ * @param files The files to save.+ */+export const savePublicCollectionFiles = async (+ accessToken: string,+ files: EnteFile[],+): Promise<void> => {+ await inMemoryStorage.setItem("public-collection-files", [+ { collectionUID: accessToken, files },+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * Remove the list of files, in any, in our local storage for the given+ * collection (identified by its {@link accessToken}).+ */+export const removePublicCollectionFiles = async (+ accessToken: string,+): Promise<void> => {+ await inMemoryStorage.setItem("public-collection-files", [+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * Return the locally persisted "last sync time" for a public collection that we+ * have pulled from remote. This can be used to perform a paginated delta pull+ * from the saved time onwards.+ *+ * Use {@link savePublic CollectionLastSyncTime} to update the value saved in+ * the storage, and {@link removePublicCollectionLastSyncTime} to remove the+ * saved value from the storage.+ *+ * @param accessToken The access token that identifies the public album whose+ * last sync time we want.+ */+export const savedPublicCollectionLastSyncTime = async (accessToken: string) =>+ LocalTimestamp.parse(+ await inMemoryStorage.getItem(`public-${accessToken}-time`),+ );++/**+ * Update the locally persisted timestamp that will be returned by subsequent+ * calls to {@link savedPublicCollectionLastSyncTime}.+ */+export const savePublicCollectionLastSyncTime = async (+ accessToken: string,+ time: number,+) => {+ await inMemoryStorage.setItem(`public-${accessToken}-time`, time);+};++/**+ * Remove the locally persisted timestamp, if any, previously saved for a+ * collection using {@link savedPublicCollectionLastSyncTime}.+ */+export const removePublicCollectionLastSyncTime = async (+ accessToken: string,+) => {+ await inMemoryStorage.removeItem(`public-${accessToken}-time`);+};++/**+ * Return the access token JWT, if any, present in our local storage for the+ * given public collection (as identified by its {@link accessToken}).+ *+ * Use {@link savePublicCollectionAccessTokenJWT} to save the value, and+ * {@link removePublicCollectionAccessTokenJWT} to remove it.+ */+export const savedPublicCollectionAccessTokenJWT = async (+ accessToken: string,+) =>+ LocalString.parse(+ await inMemoryStorage.getItem(`public-${accessToken}-passkey`),+ );++/**+ * Update the access token JWT in our local storage for the given public+ * collection (as identified by its {@link accessToken}).+ *+ * This is the setter corresponding to+ * {@link savedPublicCollectionAccessTokenJWT}.+ */+export const savePublicCollectionAccessTokenJWT = async (+ accessToken: string,+ passwordJWT: string,+) => {+ await inMemoryStorage.setItem(`public-${accessToken}-passkey`, passwordJWT);+};++/**+ * Remove the access token JWT in our local storage for the given public+ * collection (as identified by its {@link accessToken}).+ */+export const removePublicCollectionAccessTokenJWT = async (+ accessToken: string,+) => {+ await inMemoryStorage.removeItem(`public-${accessToken}-passkey`);+};++/**+ * Return the previously saved uploader name, if any, present in our local+ * storage corresponding to a public collection.+ *+ * Use {@link savePublicCollectionUploaderName} to update the persisted value.+ *+ * [Note: Public albums uploader name]+ *+ * Whenever there is an upload to a public album, we ask the person doing the+ * upload for their name. This uploader name is attached as part of the public+ * magic metadata of the file so that other people know who uploaded the file.+ *+ * The public albums app also saves this value, keyed by an identifier for the+ * public collection, in the local storage so that it can prefill it the next+ * time there is an upload from the same client.+ *+ * @param accessToken The access token that identifies the public album whose+ * saved uploader name we want.+ */+export const savedPublicCollectionUploaderName = async (accessToken: string) =>+ LocalString.parse(+ await inMemoryStorage.getItem(`public-${accessToken}-uploaderName`),+ );++/**+ * Update the uploader name present in our local storage corresponding to a+ * public collection.+ *+ * This is the setter corresponding to+ * {@link savedPublicCollectionUploaderName}.+ */+export const savePublicCollectionUploaderName = async (+ accessToken: string,+ uploaderName: string,+) => {+ await inMemoryStorage.setItem(+ `public-${accessToken}-uploaderName`,+ uploaderName,+ );+};\ No newline at end of filediff --git a/web/apps/embed/src/services/public-collection.ts b/web/apps/embed/src/services/public-collection.tsnew file mode 100644index 0000000000..c69c17f57d--- /dev/null+++ b/web/apps/embed/src/services/public-collection.ts@@ -0,0 +1,201 @@+/**+ * @file Public collection service for embed app+ *+ * This is a copy of the public-collection service that uses the embed app's+ * in-memory storage instead of the original public-albums-fdb storage.+ */++import { deriveKey } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import {+ decryptRemoteCollection,+ RemoteCollection,+ type Collection,+ type PublicURL,+} from "ente-media/collection";+import {+ decryptRemoteFile,+ FileDiffResponse,+ type EnteFile,+} from "ente-media/file";+import { z } from "zod/v4";+import {+ removePublicCollectionAccessTokenJWT,+ removePublicCollectionFiles,+ removePublicCollectionLastSyncTime,+ savedPublicCollectionFiles,+ savedPublicCollectionLastSyncTime,+ savePublicCollection,+ savePublicCollectionFiles,+ savePublicCollectionLastSyncTime,+} from "./public-albums-storage";++/**+ * Verify with remote that the password entered by the user is the same as the+ * password that was set by the person who shared the public album.+ *+ * The verification is done on a password hash that we check with remote. If+ * they match, remote will provide us with another token that can be used to+ * make API calls for this password protected public album.+ *+ * If they don't match, or if {@link accessToken} itself has expired, then+ * remote will return a HTTP 401.+ *+ * @param publicURL Data about the public album.+ *+ * @param password The password entered by the user.+ *+ * @param token The access token to make API requests for a particular public+ * album.+ *+ * @returns A accessTokenJWT.+ *+ * See [Note: Password token for public albums requests]+ */+export const verifyPublicAlbumPassword = async (+ publicURL: PublicURL,+ password: string,+ accessToken: string,+) => {+ const passwordHash = await deriveKey(+ password,+ // TODO: Fix the types to not require the bang.+ publicURL.nonce!,+ publicURL.opsLimit!,+ publicURL.memLimit!,+ );++ const res = await fetch(+ await apiURL("/public-collection/verify-password"),+ {+ method: "POST",+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ body: JSON.stringify({ passHash: passwordHash }),+ },+ );+ ensureOk(res);+ return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;+};++/**+ * Fetch a public collection from remote using its access key, decrypt it using+ * the provided key, save the collection in our local storage for subsequent+ * use, and return it.+ *+ * This function modifies local state.+ *+ * @param accessToken A public collection access key obtained from the "t="+ * query parameter of the public URL.+ *+ * The access key serves to both identify the public collection, and also+ * authenticate the request. See: [Note: Public album access token].+ *+ * @param collectionKey The base64 encoded key that can be used to decrypt the+ * collection obtained from remote.+ *+ * The collection key is obtained from the fragment portion of the public URL+ * (the fragment is a client side only portion that can be used to have local+ * secrets that are not sent by the browser to the server).+ */+export const pullCollection = async (+ accessToken: string,+ collectionKey: string,+) => {+ const res = await fetch(await apiURL("/public-collection"), {+ method: "GET",+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ });+ ensureOk(res);++ const remoteCollection = RemoteCollection.parse(await res.json());+ const collection = await decryptRemoteCollection(+ remoteCollection,+ collectionKey,+ );++ await savePublicCollection(collection);++ return { collection };+};++/**+ * Fetch files that are part of a public collection. Save them to our local+ * storage, invoking {@link onUpdate} with the files when they become available.+ *+ * This function is a stateful loop that incrementally fetches all files that+ * are part of the public collection.+ *+ * @param credentials Credentials that can be used to make API requests for the+ * public collection.+ *+ * @param collection The collection whose files we want to fetch.+ *+ * @param onUpdate A callback that will be invoked with the files when they+ * become available.+ */+export const pullPublicCollectionFiles = async (+ credentials: PublicAlbumsCredentials,+ collection: Collection,+ onUpdate: (files: EnteFile[]) => void,+) => {+ let time = await savedPublicCollectionLastSyncTime(+ credentials.accessToken,+ );+ let hasMore = true;++ while (hasMore) {+ const res = await fetch(await apiURL("/public-collection/diff"), {+ method: "POST",+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),+ body: JSON.stringify({+ collectionID: collection.id,+ sinceTime: time,+ }),+ });+ ensureOk(res);++ const { diff, hasMore: hasMoreRemote } = FileDiffResponse.parse(+ await res.json(),+ );++ const files = await Promise.all(+ diff.map((f) => decryptRemoteFile(f, collection.key)),+ );++ let existingFiles = await savedPublicCollectionFiles(+ credentials.accessToken,+ );++ // The files are returned in insertion order, not in the ascending+ // order of their creation time.+ const newFiles = [...existingFiles, ...files];++ await savePublicCollectionFiles(credentials.accessToken, newFiles);++ if (files.length > 0) {+ time = Math.max(...files.map((f) => f.updationTime));+ await savePublicCollectionLastSyncTime(+ credentials.accessToken,+ time,+ );+ }++ hasMore = hasMoreRemote;+ onUpdate(newFiles);+ }+};++/**+ * Remove all data associated with the public collection (identified by the+ * given {@link accessToken}) from our local storage.+ */+export const removePublicCollectionFileData = async (accessToken: string) => {+ await removePublicCollectionFiles(accessToken);+ await removePublicCollectionLastSyncTime(accessToken);+ await removePublicCollectionAccessTokenJWT(accessToken);+};\ No newline at end of file