π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat: add locker collection sharing on web
AmanRajSinghMouryaba5523c601a5
diff --git a/web/apps/share/src/components/file-share/CollectionShareView.tsx b/web/apps/share/src/components/file-share/CollectionShareView.tsxnew file mode 100644index 0000000000..0169ed7c8d--- /dev/null+++ b/web/apps/share/src/components/file-share/CollectionShareView.tsx@@ -0,0 +1,351 @@+import {+ Box,+ ButtonBase,+ CircularProgress,+ Stack,+ Typography,+} from "@mui/material";+import { SingleInputForm } from "ente-base/components/SingleInputForm";+import { Notification } from "ente-new/photos/components/Notification";+import React from "react";+import { useCollectionShare } from "../../hooks/useCollectionShare";+import { type SharedCollectionItemInfo } from "../../services/collection-share";+import { formatFileSize } from "../../services/file-share";+import { getLockerFileIcon } from "../../utils/file-type";+import { PublicShareScaffold } from "./PublicShareScaffold";+import { SharedItemDetails } from "./SharedItemDetails";++const lockerTypeLabel = (lockerType: string) => {+ switch (lockerType) {+ case "note":+ return "Note";+ case "accountCredential":+ return "Secret";+ case "physicalRecord":+ return "Location";+ case "emergencyContact":+ return "Emergency Contact";+ default:+ return lockerType;+ }+};++const itemSubtitle = (item: SharedCollectionItemInfo) => {+ if (item.lockerType) {+ return lockerTypeLabel(item.lockerType);+ }++ if (item.fileSize > 0) {+ return formatFileSize(item.fileSize);+ }++ return "File";+};++const contentMaxWidth = 560;++export const CollectionShareView: React.FC = () => {+ const {+ loading,+ requiresPassword,+ downloadingItemID,+ downloadProgress,+ errorTitle,+ error,+ collectionInfo,+ selectedItem,+ notificationAttributes,+ handleItemClick,+ handleCloseItem,+ handleDownload,+ handleSubmitPassword,+ handleCopyContent,+ setNotificationAttributes,+ } = useCollectionShare();++ return (+ <PublicShareScaffold>+ {loading && (+ <Box+ sx={{+ flex: 1,+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <CircularProgress sx={{ color: "accent.main" }} size={32} />+ </Box>+ )}++ {error && !loading && (+ <Box+ sx={{+ flex: 1,+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ p: 3,+ }}+ >+ <Box sx={{ maxWidth: 420, textAlign: "center" }}>+ <Typography+ variant="h4"+ sx={{+ fontWeight: 700,+ color: "text.base",+ mb: 1.5,+ }}+ >+ {errorTitle ?? "Unable to open this collection"}+ </Typography>+ <Typography variant="body" sx={{ color: "text.muted" }}>+ {error}+ </Typography>+ </Box>+ </Box>+ )}++ {requiresPassword && !loading && !error && (+ <Box+ sx={{+ flex: 1,+ width: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ p: 3,+ }}+ >+ <Box sx={{ width: "100%", maxWidth: 420 }}>+ <Typography+ variant="h4"+ sx={{+ fontWeight: 700,+ color: "text.base",+ mb: 1.5,+ }}+ >+ Password+ </Typography>+ <Typography+ variant="body"+ sx={{ color: "text.muted", mb: 2 }}+ >+ This collection link is password protected.+ </Typography>+ <SingleInputForm+ inputType="password"+ label="Password"+ submitButtonColor="primary"+ submitButtonTitle="Unlock"+ onSubmit={handleSubmitPassword}+ />+ </Box>+ </Box>+ )}++ {/* Item detail view - uses same component as single-file share */}+ {selectedItem && !loading && !requiresPassword && (+ <SharedItemDetails+ itemInfo={selectedItem}+ downloading={downloadingItemID === selectedItem.id}+ onDownload={+ collectionInfo?.allowDownload && selectedItem.hasObject+ ? handleDownload+ : undefined+ }+ onCopyContent={(value) => {+ void handleCopyContent(value);+ }}+ onBack={handleCloseItem}+ />+ )}++ {/* Collection list view */}+ {collectionInfo &&+ !loading &&+ !selectedItem &&+ !requiresPassword && (+ <Box+ sx={{+ width: "100%",+ flex: 1,+ px: { xs: 2, sm: 3 },+ pb: "calc(env(safe-area-inset-bottom) + 120px)",+ pt: { xs: 3, md: 5 },+ }}+ >+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ justifyContent: "space-between",+ gap: 2,+ maxWidth: contentMaxWidth,+ mx: "auto",+ mt: 1,+ mb: 2.25,+ }}+ >+ <Box sx={{ minWidth: 0 }}>+ <Typography+ variant="h3"+ sx={{ fontWeight: "bold", minWidth: 0 }}+ >+ {collectionInfo.name}+ </Typography>+ <Typography+ variant="small"+ sx={{ color: "text.muted", mt: 1 }}+ >+ {collectionInfo.items.length}{" "}+ {collectionInfo.items.length === 1+ ? "item"+ : "items"}+ </Typography>+ </Box>+ </Stack>++ <Stack+ sx={{+ maxWidth: contentMaxWidth,+ mx: "auto",+ gap: 1.1,+ mt: 1.25,+ }}+ >+ {collectionInfo.items.map((item) => {+ const iconInfo = getLockerFileIcon(+ item.fileName,+ { lockerType: item.lockerType, size: 20 },+ );++ return (+ <ButtonBase+ key={`${item.collectionID}-${item.id}`}+ component="div"+ onClick={() => handleItemClick(item)}+ sx={(theme) => ({+ display: "flex",+ width: "100%",+ textAlign: "left",+ borderRadius: "18px",+ overflow: "hidden",+ px: 1.5,+ py: 1.25,+ gap: 1.25,+ alignItems: "center",+ backgroundColor:+ theme.vars.palette.fill.faint,+ transition:+ "background-color 0.15s",+ "&:hover": {+ backgroundColor:+ theme.vars.palette.fill+ .faintHover,+ },+ ...theme.applyStyles("light", {+ backgroundColor: "#FFFFFF",+ "&:hover": {+ backgroundColor: "#FFFFFF",+ },+ }),+ })}+ >+ <Box+ sx={{+ position: "relative",+ width: 52,+ height: 52,+ flexShrink: 0,+ }}+ >+ <Box+ sx={{+ position: "relative",+ zIndex: 1,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ width: 40,+ height: 40,+ m: "6px",+ borderRadius: "12px",+ backgroundColor:+ iconInfo.backgroundColor,+ }}+ >+ {iconInfo.icon}+ </Box>+ </Box>+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <Typography+ variant="body"+ sx={{+ minWidth: 0,+ fontWeight: "regular",+ lineHeight: 1.45,+ }}+ noWrap+ >+ {item.fileName}+ </Typography>+ <Typography+ variant="small"+ sx={{+ color: "text.muted",+ mt: 0.25,+ }}+ noWrap+ >+ {itemSubtitle(item)}+ </Typography>+ </Box>+ {downloadingItemID === item.id && (+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ width: 28,+ height: 28,+ flexShrink: 0,+ }}+ >+ <CircularProgress+ size={20}+ thickness={5}+ variant={+ downloadProgress !==+ null+ ? "determinate"+ : "indeterminate"+ }+ value={+ downloadProgress ??+ undefined+ }+ sx={{+ color: "accent.main",+ }}+ />+ </Box>+ )}+ </ButtonBase>+ );+ })}+ </Stack>+ </Box>+ )}++ <Notification+ open={!!notificationAttributes}+ onClose={() => setNotificationAttributes(undefined)}+ attributes={notificationAttributes}+ />+ </PublicShareScaffold>+ );+};diff --git a/web/apps/share/src/components/file-share/FileShareView.tsx b/web/apps/share/src/components/file-share/FileShareView.tsxindex 0609907300..90baff3b9d 100644--- a/web/apps/share/src/components/file-share/FileShareView.tsx+++ b/web/apps/share/src/components/file-share/FileShareView.tsx@@ -146,6 +146,16 @@ export const FileShareView: React.FC = () => {{/* File Info Display */}{fileInfo && !loading && (<>+ {(() => {+ const iconInfo = getLockerFileIcon(+ fileInfo.fileName,+ {+ lockerType: fileInfo.lockerType,+ },+ );++ return (+ <>{/* File Info - Centered */}<Boxsx={{@@ -161,10 +171,8 @@ export const FileShareView: React.FC = () => {{/* Large File Icon */}<Boxsx={{- backgroundColor: getLockerFileIcon(- fileInfo.fileName,- fileInfo.lockerType,- ).backgroundColor,+ backgroundColor:+ iconInfo.backgroundColor,borderRadius: "20px",padding: 1.8,display: "flex",@@ -172,12 +180,7 @@ export const FileShareView: React.FC = () => {justifyContent: "center",}}>- {- getLockerFileIcon(- fileInfo.fileName,- fileInfo.lockerType,- ).icon- }+ {iconInfo.icon}</Box>{/* File Name */}@@ -224,6 +227,9 @@ export const FileShareView: React.FC = () => {/>)}</Box>+ </>+ );+ })()}{/* Download Button - Only show if not a LockerInfoType */}{!fileInfo.lockerType && (diff --git a/web/apps/share/src/components/file-share/PublicShareScaffold.tsx b/web/apps/share/src/components/file-share/PublicShareScaffold.tsxnew file mode 100644index 0000000000..72d4fb27fa--- /dev/null+++ b/web/apps/share/src/components/file-share/PublicShareScaffold.tsx@@ -0,0 +1,76 @@+import { Box } from "@mui/material";+import Head from "next/head";+import React, { type ReactNode } from "react";++interface PublicShareScaffoldProps {+ children: ReactNode;+}++export const PublicShareScaffold: React.FC<PublicShareScaffoldProps> = ({+ children,+}) => {+ return (+ <>+ <Head>+ <meta name="robots" content="noindex, nofollow" />+ </Head>+ <Box+ sx={{+ minHeight: "100dvh",+ bgcolor: "#08090A",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ boxSizing: "border-box",+ "& ::selection": {+ backgroundColor: "#1071FF",+ color: "#FFFFFF",+ },+ "& ::-moz-selection": {+ backgroundColor: "#1071FF",+ color: "#FFFFFF",+ },+ }}+ >+ <Box+ sx={{+ width: "100%",+ background:+ "linear-gradient(135deg, #1071FF 0%, #0056CC 100%)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ px: { xs: 2, sm: 3 },+ pt: 2,+ pb: 2.5,+ }}+ >+ <a+ href="https://ente.com/locker"+ target="_blank"+ rel="noopener noreferrer"+ style={{ display: "block", lineHeight: 0 }}+ >+ <Box+ component="img"+ src="/images/ente-locker-white.svg"+ alt="Ente Locker"+ sx={{ height: { xs: "30px", md: "34px" } }}+ />+ </a>+ </Box>+ <Box+ sx={{+ width: "100%",+ flex: 1,+ display: "flex",+ flexDirection: "column",+ bgcolor: "#08090A",+ }}+ >+ {children}+ </Box>+ </Box>+ </>+ );+};diff --git a/web/apps/share/src/components/file-share/SharedItemDetails.tsx b/web/apps/share/src/components/file-share/SharedItemDetails.tsxnew file mode 100644index 0000000000..ea467e28ea--- /dev/null+++ b/web/apps/share/src/components/file-share/SharedItemDetails.tsx@@ -0,0 +1,187 @@+import ArrowBackIcon from "@mui/icons-material/ArrowBack";+import {+ Box,+ Button,+ CircularProgress,+ IconButton,+ Typography,+} from "@mui/material";+import React from "react";+import { formatFileSize } from "../../services/file-share";+import type { DecryptedFileInfo } from "../../types/file-share";+import { getLockerFileIcon } from "../../utils/file-type";+import { LockerTypeDisplay } from "./LockerTypeDisplay";++interface SharedItemDetailsProps {+ itemInfo: DecryptedFileInfo;+ downloading?: boolean;+ onDownload?: () => Promise<void> | void;+ onCopyContent: (content: string) => void;+ onBack?: () => void;+}++export const SharedItemDetails: React.FC<SharedItemDetailsProps> = ({+ itemInfo,+ downloading = false,+ onDownload,+ onCopyContent,+ onBack,+}) => {+ const iconInfo = getLockerFileIcon(itemInfo.fileName, {+ lockerType: itemInfo.lockerType,+ });++ // When there is a back button (collection context), content starts at the+ // top so the back button is immediately visible. Without a back button+ // (single-file context), locker items get extra top spacing to push the+ // content down from the logo, and regular file items are vertically centred.+ const topMargin = itemInfo.lockerType+ ? onBack+ ? 0+ : { xs: 16, md: "20dvh" }+ : 0;++ return (+ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent:+ itemInfo.lockerType || onBack ? "flex-start" : "center",+ width: "100%",+ maxWidth: 400,+ mx: "auto",+ flex: 1,+ px: 3,+ pb: 8,+ mt: topMargin,+ }}+ >+ {onBack && (+ <Box sx={{ width: "100%", mb: 4 }}>+ <IconButton+ onClick={onBack}+ sx={{+ color: "text.base",+ ml: -1,+ "&:hover": { bgcolor: "fill.faintHover" },+ }}+ >+ <ArrowBackIcon />+ </IconButton>+ </Box>+ )}++ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: 3,+ width: "100%",+ marginBottom: 4,+ }}+ >+ {/* Large File Icon */}+ <Box+ sx={{+ backgroundColor: iconInfo.backgroundColor,+ borderRadius: "20px",+ padding: 1.8,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {iconInfo.icon}+ </Box>++ {/* File Name */}+ <Typography+ variant="h5"+ sx={{+ fontWeight: 600,+ fontSize: itemInfo.lockerType ? "24px" : "22px",+ textAlign: "center",+ wordBreak: "break-word",+ color: "text.base",+ }}+ >+ {itemInfo.fileName}+ </Typography>++ {/* File Size - only show for regular files */}+ {!itemInfo.lockerType && (+ <Typography+ variant="body"+ sx={{+ color: "text.muted",+ mt: -2,+ fontSize: "1rem",+ }}+ >+ {itemInfo.fileSize > 0+ ? formatFileSize(itemInfo.fileSize)+ : "Unknown size"}+ </Typography>+ )}++ {/* Locker Type Display */}+ {itemInfo.lockerType && itemInfo.lockerInfoData && (+ <LockerTypeDisplay+ type={itemInfo.lockerType}+ data={itemInfo.lockerInfoData}+ onCopy={onCopyContent}+ />+ )}+ </Box>++ {/* Download Button - only for regular files */}+ {!itemInfo.lockerType && onDownload && (+ <Box sx={{ width: "100%", mt: 4 }}>+ <Button+ variant="contained"+ size="large"+ fullWidth+ onClick={onDownload}+ disabled={downloading}+ sx={{+ py: 2.5,+ fontSize: "1rem",+ fontWeight: 600,+ bgcolor: "accent.main",+ color: "accent.contrastText",+ "&:hover": {+ bgcolor: "accent.dark",+ },+ "&:disabled": {+ bgcolor: "accent.main",+ color: "accent.contrastText",+ opacity: 0.7,+ },+ borderRadius: "22px",+ textTransform: "none",+ }}+ >+ {downloading ? (+ <>+ <CircularProgress+ size={20}+ sx={{+ mr: 1,+ color: "accent.contrastText",+ }}+ />+ Downloading...+ </>+ ) : (+ "Download"+ )}+ </Button>+ </Box>+ )}+ </Box>+ );+};diff --git a/web/apps/share/src/hooks/useCollectionShare.ts b/web/apps/share/src/hooks/useCollectionShare.tsnew file mode 100644index 0000000000..91637c1535--- /dev/null+++ b/web/apps/share/src/hooks/useCollectionShare.ts@@ -0,0 +1,317 @@+import type { SingleInputFormProps } from "ente-base/components/SingleInputForm";+import { HTTPError, isHTTP401Error, isHTTPErrorWithStatus } from "ente-base/http";+import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";+import type { PublicURL } from "ente-media/collection";+import type { NotificationAttributes } from "ente-new/photos/components/Notification";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";+import {+ downloadPublicCollectionFile,+ fetchPublicCollectionShare,+ fetchPublicCollectionShareMetadata,+ type PublicCollectionShareInfo,+ type SharedCollectionItemInfo,+ verifyPublicCollectionPassword,+} from "../services/collection-share";++const extractCollectionTokenFromPath = (pathname: string): string | null => {+ const match = /^\/c\/([^/]+)\/?$/.exec(pathname);+ return match?.[1] ?? null;+};++const extractCollectionTokenFromURL = (url: URL): string | null =>+ extractCollectionTokenFromPath(url.pathname);++interface UseCollectionShareResult {+ loading: boolean;+ requiresPassword: boolean;+ downloadingItemID: number | null;+ downloadProgress: number | null;+ errorTitle: string | null;+ error: string | null;+ errorIsExpired: boolean;+ collectionInfo: PublicCollectionShareInfo | null;+ selectedItem: SharedCollectionItemInfo | null;+ notificationAttributes: NotificationAttributes | undefined;+ handleItemClick: (item: SharedCollectionItemInfo) => void;+ handleCloseItem: () => void;+ handleDownload: () => Promise<void>;+ handleSubmitPassword: SingleInputFormProps["onSubmit"];+ handleCopyContent: (content: string) => Promise<void>;+ setNotificationAttributes: (+ attributes: NotificationAttributes | undefined,+ ) => void;+}++interface CollectionShareLoadError {+ title: string;+ message: string;+ isExpired: boolean;+}++const collectionShareLoadError = async (+ err: unknown,+): Promise<CollectionShareLoadError> => {+ if (err instanceof HTTPError && err.res.status === 410) {+ try {+ const payload = (await err.res.clone().json()) as {+ error?: string;+ };+ if (payload.error === "expired token") {+ return {+ title: "Link expired",+ message: "This link has either expired or has been disabled.",+ isExpired: true,+ };+ }+ } catch {+ // Ignore payload parse failures and use the generic gone-state copy.+ }++ return {+ title: "Link expired",+ message: "This link has either expired or has been disabled.",+ isExpired: true,+ };+ }++ if (+ isHTTP401Error(err) ||+ isHTTPErrorWithStatus(err, 403) ||+ isHTTPErrorWithStatus(err, 404)+ ) {+ return {+ title: "Unable to open this collection",+ message:+ "This collection link is no longer available. It may have been removed or expired.",+ isExpired: false,+ };+ }++ return {+ title: "Unable to open this collection",+ message: "Unable to load this collection right now. Please try again later.",+ isExpired: false,+ };+};++export const useCollectionShare = (): UseCollectionShareResult => {+ const router = useRouter();+ const [loading, setLoading] = useState(true);+ const [downloadingItemID, setDownloadingItemID] = useState<number | null>(+ null,+ );+ const [downloadProgress, setDownloadProgress] = useState<number | null>(+ null,+ );+ const [errorTitle, setErrorTitle] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [errorIsExpired, setErrorIsExpired] = useState(false);+ const [collectionInfo, setCollectionInfo] =+ useState<PublicCollectionShareInfo | null>(null);+ const [selectedItem, setSelectedItem] =+ useState<SharedCollectionItemInfo | null>(null);+ const [accessToken, setAccessToken] = useState<string | null>(null);+ const [accessTokenJWT, setAccessTokenJWT] = useState<string | null>(null);+ const [collectionKey, setCollectionKey] = useState<string | null>(null);+ const [passwordProtectedPublicURL, setPasswordProtectedPublicURL] =+ useState<PublicURL | null>(null);+ const [notificationAttributes, setNotificationAttributes] =+ useState<NotificationAttributes>();+ const requiresPassword = !!passwordProtectedPublicURL && !accessTokenJWT;++ const loadCollection = useCallback(+ async (+ opts?: Partial<{+ accessToken: string;+ collectionKey: string;+ accessTokenJWT: string;+ }>,+ ) => {+ try {+ setLoading(true);+ setError(null);+ setErrorTitle(null);+ setErrorIsExpired(false);++ const url = new URL(window.location.href);+ const token =+ opts?.accessToken ?? extractCollectionTokenFromURL(url);+ if (!token) {+ setErrorTitle("Invalid collection link");+ setError("This collection link is invalid.");+ return;+ }++ const resolvedCollectionKey =+ opts?.collectionKey ??+ (await extractCollectionKeyFromShareURL(url));+ if (!resolvedCollectionKey) {+ setErrorTitle("Invalid collection link");+ setError("This collection link is invalid.");+ return;+ }++ const resolvedAccessTokenJWT = opts?.accessTokenJWT;++ setAccessToken(token);+ setCollectionKey(resolvedCollectionKey);++ const metadata = await fetchPublicCollectionShareMetadata(+ token,+ resolvedCollectionKey,+ );+ if (metadata.passwordEnabled && !resolvedAccessTokenJWT) {+ setPasswordProtectedPublicURL(metadata.publicURL ?? null);+ setCollectionInfo(null);+ return;+ }++ const info = await fetchPublicCollectionShare(+ {+ accessToken: token,+ accessTokenJWT: resolvedAccessTokenJWT,+ },+ resolvedCollectionKey,+ );+ setPasswordProtectedPublicURL(null);+ setCollectionInfo(info);+ } catch (err) {+ const loadError = await collectionShareLoadError(err);+ setErrorTitle(loadError.title);+ setError(loadError.message);+ setErrorIsExpired(loadError.isExpired);+ } finally {+ setLoading(false);+ }+ },+ [],+ );++ useEffect(() => {+ if (router.isReady) {+ void loadCollection();+ }+ }, [router.isReady, loadCollection]);++ const handleCloseItem = () => {+ setSelectedItem(null);+ };++ const handleDownloadItem = async (item: SharedCollectionItemInfo) => {+ const { fileDecryptionHeader, fileKey } = item;++ if (+ downloadingItemID !== null ||+ !accessToken ||+ !fileKey ||+ !fileDecryptionHeader+ ) {+ return;+ }++ setDownloadingItemID(item.id);+ setDownloadProgress(null);+ try {+ await downloadPublicCollectionFile(+ accessToken,+ item.id,+ fileKey,+ item.fileName,+ fileDecryptionHeader,+ ({ loaded, total }) => {+ if (total && total > 0) {+ setDownloadProgress(+ Math.min(100, Math.round((loaded / total) * 100)),+ );+ }+ },+ );+ } catch (err) {+ setNotificationAttributes({+ color: "critical",+ title:+ err instanceof Error+ ? err.message+ : "Failed to download file",+ });+ } finally {+ setDownloadingItemID(null);+ setDownloadProgress(null);+ }+ };++ const handleItemClick = (item: SharedCollectionItemInfo) => {+ if (downloadingItemID !== null) {+ return;+ }++ setSelectedItem(item);+ };++ const handleDownload = async () => {+ if (!selectedItem) {+ return;+ }+ await handleDownloadItem(selectedItem);+ };++ const handleCopyContent = async (content: string) => {+ try {+ await navigator.clipboard.writeText(content);+ } catch {+ setNotificationAttributes({+ color: "critical",+ title: "Failed to copy",+ });+ }+ };++ const handleSubmitPassword: SingleInputFormProps["onSubmit"] = async (+ password,+ setFieldError,+ ) => {+ if (!passwordProtectedPublicURL || !accessToken || !collectionKey) {+ return;+ }++ try {+ const jwtToken = await verifyPublicCollectionPassword(+ passwordProtectedPublicURL,+ password,+ accessToken,+ );+ setAccessTokenJWT(jwtToken);+ await loadCollection({+ accessToken,+ collectionKey,+ accessTokenJWT: jwtToken,+ });+ } catch (err) {+ if (isHTTP401Error(err)) {+ setFieldError("Incorrect password");+ return;+ }+ throw err;+ }+ };++ return {+ loading,+ requiresPassword,+ downloadingItemID,+ downloadProgress,+ errorTitle,+ error,+ errorIsExpired,+ collectionInfo,+ selectedItem,+ notificationAttributes,+ handleItemClick,+ handleCloseItem,+ handleDownload,+ handleSubmitPassword,+ handleCopyContent,+ setNotificationAttributes,+ };+};diff --git a/web/apps/share/src/pages/index.tsx b/web/apps/share/src/pages/index.tsxindex 69ac83f054..68b45a72b8 100644--- a/web/apps/share/src/pages/index.tsx+++ b/web/apps/share/src/pages/index.tsx@@ -1,12 +1,33 @@import { CustomHeadShare } from "ente-base/components/Head";import React, { useEffect, useState } from "react";+import { CollectionShareView } from "../components/file-share/CollectionShareView";import { FileShareView } from "../components/file-share/FileShareView";+const detectShareView = (): "file" | "collection" | null => {+ if (typeof window === "undefined") {+ return null;+ }++ const pathname = window.location.pathname;++ if (/^\/c\/[^/]+\/?$/.test(pathname)) {+ return "collection";+ }++ if (pathname === "/" || pathname === "") {+ return null;+ }++ return "file";+};+/**- * Index page that handles both root redirect and share links+ * Index page that handles root redirect, single-file share links, and+ * locker collection share links.** - Root domain (/) redirects to ente.com/locker- * - Share links (/token#key) render the FileShareView+ * - Single-file share links (/{token}#{key}) render FileShareView+ * - Collection share links (/c/{token}#{collectionKey}) render CollectionShareView** This page is served for all routes via:* - _redirects file for Cloudflare Pages@@ -15,25 +36,31 @@ import { FileShareView } from "../components/file-share/FileShareView";*/const Page: React.FC = () => {const [hideContent, setHideContent] = useState(false);+ const [shareView, setShareView] = useState<"file" | "collection" | null>(+ null,+ );useEffect(() => {- // Check if we're at the root path (client-side only)const pathname = window.location.pathname;+ setShareView(detectShareView());if (pathname === "/" || pathname === "") {- // Hide content before redirect to avoid error flashsetHideContent(true);- // Redirect to ente.com/locker for root pathwindow.location.href = "https://ente.com/locker";+ return;}}, []);- // Always render CustomHeadShare for SSR (ensures meta tags are in static HTML)return (<><CustomHeadShare title="Ente Locker" />- {/* Hide FileShareView only when we detect root path on client */}- {!hideContent && <FileShareView />}+ {!hideContent &&+ shareView &&+ (shareView === "collection" ? (+ <CollectionShareView />+ ) : (+ <FileShareView />+ ))}</>);};diff --git a/web/apps/share/src/services/collection-share.ts b/web/apps/share/src/services/collection-share.tsnew file mode 100644index 0000000000..6faf49f753--- /dev/null+++ b/web/apps/share/src/services/collection-share.ts@@ -0,0 +1,394 @@+import {+ decryptBox,+ decryptMetadataJSON,+ decryptStreamBytes,+ deriveKey,+} from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiOrigin, apiURL } from "ente-base/origins";+import {+ decryptRemoteCollection,+ RemoteCollection,+ type PublicURL,+} from "ente-media/collection";+import { FileDiffResponse, type RemoteEnteFile } from "ente-media/file";+import { z } from "zod";+import type { DecryptedFileInfo, LockerInfoData } from "../types/file-share";++interface ParsedLockerInfoData extends LockerInfoData {+ title?: string;+ name?: string;+}++interface ParsedLockerInfo {+ type?: string;+ data?: ParsedLockerInfoData;+}++export interface SharedCollectionItemInfo extends DecryptedFileInfo {+ collectionID: number;+ hasObject: boolean;+}++export interface PublicCollectionShareInfo {+ id: number;+ name: string;+ allowDownload: boolean;+ items: SharedCollectionItemInfo[];+}++export interface PublicCollectionShareMetadata {+ id: number;+ name: string;+ allowDownload: boolean;+ passwordEnabled: boolean;+ publicURL?: PublicURL;+ collectionKey: string;+}++interface DownloadProgress {+ loaded: number;+ total: number | null;+}++const VALID_INFO_TYPES = new Set([+ "note",+ "accountCredential",+ "physicalRecord",+ "emergencyContact",+]);++const normalizeLockerInfoType = (+ type: string | undefined,+): string | undefined => {+ switch (type) {+ case "note":+ return "note";+ case "physical-record":+ case "physicalRecord":+ return "physicalRecord";+ case "account-credential":+ case "accountCredential":+ return "accountCredential";+ case "emergency-contact":+ case "emergencyContact":+ return "emergencyContact";+ default:+ return undefined;+ }+};++const infoItemTitle = (+ infoType: string,+ infoData: ParsedLockerInfoData,+): string => {+ const namedTitle = infoData.title?.trim() || infoData.name?.trim();+ if (namedTitle) {+ return namedTitle;+ }++ switch (infoType) {+ case "note":+ return "Note";+ case "physicalRecord":+ return "Location";+ case "accountCredential":+ return "Secret";+ case "emergencyContact":+ return "Emergency Contact";+ default:+ return "Item";+ }+};++const toUploadedTime = (value: unknown, fallback: number) => {+ if (typeof value !== "number") {+ return fallback;+ }++ return value < 100_000_000_000_000 ? value * 1000 : value;+};++const parseLockerInfo = (rawInfo: unknown): ParsedLockerInfo | undefined => {+ if (!rawInfo) return undefined;++ const parsedInfo = (() => {+ if (typeof rawInfo === "string") {+ try {+ return JSON.parse(rawInfo) as ParsedLockerInfo;+ } catch {+ return undefined;+ }+ }++ if (typeof rawInfo === "object") {+ return rawInfo as ParsedLockerInfo;+ }++ return undefined;+ })();++ if (!parsedInfo) {+ return undefined;+ }++ return { ...parsedInfo, type: normalizeLockerInfoType(parsedInfo.type) };+};++const decryptRemoteFileToCollectionItem = async (+ remoteFile: RemoteEnteFile,+ collectionKey: string,+): Promise<SharedCollectionItemInfo> => {+ const fileKey = await decryptBox(+ {+ encryptedData: remoteFile.encryptedKey,+ nonce: remoteFile.keyDecryptionNonce,+ },+ collectionKey,+ );++ const metadata = (await decryptMetadataJSON(+ remoteFile.metadata,+ fileKey,+ )) as Record<string, unknown> | undefined;++ let pubMagicMetadata: Record<string, unknown> | undefined;+ if (remoteFile.pubMagicMetadata) {+ try {+ pubMagicMetadata = (await decryptMetadataJSON(+ {+ encryptedData: remoteFile.pubMagicMetadata.data,+ decryptionHeader: remoteFile.pubMagicMetadata.header,+ },+ fileKey,+ )) as Record<string, unknown> | undefined;+ } catch {+ pubMagicMetadata = undefined;+ }+ }++ const info = parseLockerInfo(pubMagicMetadata?.info);+ const isStructured =+ !!info?.type && !!info.data && VALID_INFO_TYPES.has(info.type);++ if (isStructured) {+ return {+ id: remoteFile.id,+ collectionID: remoteFile.collectionID,+ fileName: infoItemTitle(info.type!, info.data!),+ fileSize: info.data?.size ?? 0,+ uploadedTime: toUploadedTime(+ metadata?.creationTime,+ remoteFile.updationTime,+ ),+ fileKey,+ lockerType: info.type,+ lockerInfoData: info.data,+ hasObject: false,+ };+ }++ const metadataName =+ typeof metadata?.title === "string"+ ? metadata.title+ : typeof metadata?.fileName === "string"+ ? metadata.fileName+ : typeof metadata?.name === "string"+ ? metadata.name+ : undefined;+ const editedName =+ typeof pubMagicMetadata?.editedName === "string"+ ? pubMagicMetadata.editedName+ : undefined;++ return {+ id: remoteFile.id,+ collectionID: remoteFile.collectionID,+ fileName: editedName ?? metadataName ?? "File",+ fileSize:+ remoteFile.info?.fileSize ??+ (typeof metadata?.fileSize === "number"+ ? metadata.fileSize+ : typeof metadata?.size === "number"+ ? metadata.size+ : 0),+ uploadedTime: toUploadedTime(+ metadata?.creationTime,+ remoteFile.updationTime,+ ),+ fileDecryptionHeader: remoteFile.file.decryptionHeader,+ fileKey,+ hasObject: remoteFile.file.decryptionHeader.length > 0,+ };+};++const fetchPublicCollectionDiff = async (+ credentials: PublicAlbumsCredentials,+) => {+ const files: RemoteEnteFile[] = [];+ let sinceTime = 0;+ let hasMore = true;++ while (hasMore) {+ const res = await fetch(+ await apiURL("/public-collection/diff", { sinceTime }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);++ const parsed = FileDiffResponse.parse(await res.json());+ for (const file of parsed.diff) {+ sinceTime = Math.max(sinceTime, file.updationTime);+ if (!file.isDeleted) {+ files.push(file);+ }+ }+ hasMore = parsed.hasMore;+ }++ return files;+};++export const verifyPublicCollectionPassword = async (+ publicURL: PublicURL,+ password: string,+ accessToken: string,+) => {+ const passwordHash = await deriveKey(+ password,+ 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;+};++export const fetchPublicCollectionShareMetadata = async (+ accessToken: string,+ collectionKey: string,+): Promise<PublicCollectionShareMetadata> => {+ const res = await fetch(await apiURL("/public-collection/info"), {+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ });+ ensureOk(res);++ const data = (await res.json()) as { collection: unknown };+ const remoteCollection = RemoteCollection.parse(data.collection);+ const collection = await decryptRemoteCollection(+ remoteCollection,+ collectionKey,+ );++ const publicURL = collection.publicURLs[0];++ return {+ id: collection.id,+ name: collection.name,+ allowDownload: publicURL?.enableDownload ?? true,+ passwordEnabled: publicURL?.passwordEnabled ?? false,+ publicURL,+ collectionKey: collection.key,+ };+};++export const fetchPublicCollectionShare = async (+ credentials: PublicAlbumsCredentials,+ collectionKey: string,+): Promise<PublicCollectionShareInfo> => {+ const metadata = await fetchPublicCollectionShareMetadata(+ credentials.accessToken,+ collectionKey,+ );+ const remoteFiles = await fetchPublicCollectionDiff(credentials);+ const items = await Promise.all(+ remoteFiles.map((file) =>+ decryptRemoteFileToCollectionItem(file, metadata.collectionKey),+ ),+ );+ items.sort((a, b) => b.uploadedTime - a.uploadedTime);++ return {+ id: metadata.id,+ name: metadata.name,+ allowDownload: metadata.allowDownload,+ items,+ };+};++export const downloadPublicCollectionFile = async (+ accessToken: string,+ fileID: number,+ fileKey: string,+ fileName: string,+ fileDecryptionHeader: string,+ onProgress?: (progress: DownloadProgress) => void,+): Promise<void> => {+ const url = `${await apiOrigin()}/public-collection/files/download/${fileID}`;+ const response = await fetch(url, {+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ });++ if (!response.ok) {+ throw new Error(`Failed to download file: ${response.statusText}`);+ }++ const totalHeader = response.headers.get("content-length");+ const total = totalHeader ? Number.parseInt(totalHeader, 10) : null;++ let encryptedData: Uint8Array;+ if (response.body) {+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let loaded = 0;++ while (true) {+ const { done, value } = await reader.read();+ if (done) {+ break;+ }++ chunks.push(value);+ loaded += value.length;+ onProgress?.({ loaded, total });+ }++ encryptedData = new Uint8Array(loaded);+ let offset = 0;+ for (const chunk of chunks) {+ encryptedData.set(chunk, offset);+ offset += chunk.length;+ }+ } else {+ encryptedData = new Uint8Array(await response.arrayBuffer());+ onProgress?.({ loaded: encryptedData.length, total });+ }++ const decryptedData = await decryptStreamBytes(+ { encryptedData, decryptionHeader: fileDecryptionHeader },+ fileKey,+ );++ const blob = new Blob([new Uint8Array(decryptedData)]);+ const blobUrl = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = blobUrl;+ anchor.download = fileName;+ document.body.appendChild(anchor);+ anchor.click();+ document.body.removeChild(anchor);+ URL.revokeObjectURL(blobUrl);+};diff --git a/web/apps/share/src/utils/file-type.tsx b/web/apps/share/src/utils/file-type.tsxindex 4579e7c54a..0c4b31b105 100644--- a/web/apps/share/src/utils/file-type.tsx+++ b/web/apps/share/src/utils/file-type.tsx@@ -1,11 +1,11 @@import {- CallIcon,- CollectionsBookmarkIcon,+ Briefcase01Icon,+ ContactBookIcon,File02Icon,Image01Icon,- MailAccount01Icon,- StickyNote02Icon,- Video02Icon,+ LockPasswordIcon,+ NoteIcon,+ VideoReplayIcon,} from "hugeicons-react";import React from "react";@@ -21,6 +21,11 @@ interface LockerIconInfo {backgroundColor: string;}+interface LockerFileIconOptions {+ lockerType?: string;+ size?: number;+}+/*** Extract the file extension from a filename* Returns lowercase extension without the dot, or empty string if no extension@@ -104,33 +109,35 @@ const isDocumentExtension = (extension: string): boolean => {*/export const getLockerFileIcon = (fileName: string,- lockerType?: string,+ options: LockerFileIconOptions = {},): LockerIconInfo => {+ const { lockerType, size = 42 } = options;+// First priority: Check locker info typeif (lockerType) {switch (lockerType as LockerInfoType) {case LockerInfoType.Note:return {- icon: <StickyNote02Icon size={42} color="#FFA825" />,- backgroundColor: "rgba(255, 168, 37, 0.06)",+ icon: <NoteIcon size={size} color="#FF9800" />,+ backgroundColor: "#FF98000F",};case LockerInfoType.EmergencyContact:return {- icon: <CallIcon size={42} color="#DF61BB" />,- backgroundColor: "rgba(223, 97, 187, 0.06)",+ icon: <ContactBookIcon size={size} color="#F44336" />,+ backgroundColor: "#F443360F",};case LockerInfoType.AccountCredential:return {- icon: <MailAccount01Icon size={42} color="#666666" />,- backgroundColor: "rgba(102, 102, 102, 0.06)",+ icon: <LockPasswordIcon size={size} color="#1071FF" />,+ backgroundColor: "#1071FF0F",};case LockerInfoType.PhysicalRecord:return {- icon: <CollectionsBookmarkIcon size={42} color="#5FB7BB" />,- backgroundColor: "rgba(95, 183, 187, 0.06)",+ icon: <Briefcase01Icon size={size} color="#9C27B0" />,+ backgroundColor: "#9C27B00F",};}}@@ -140,28 +147,28 @@ export const getLockerFileIcon = (if (isImageExtension(extension)) {return {- icon: <Image01Icon size={42} color="#08C225" />,- backgroundColor: "rgba(8, 194, 37, 0.06)",+ icon: <Image01Icon size={size} color="#08C225" />,+ backgroundColor: "#08C2250F",};}if (isVideoExtension(extension)) {return {- icon: <Video02Icon size={42} color="#8A38F5" />,+ icon: <VideoReplayIcon size={size} color="#8A38F5" />,backgroundColor: "rgba(138, 56, 245, 0.06)",};}if (isDocumentExtension(extension)) {return {- icon: <File02Icon size={42} color="#FF1A53" />,+ icon: <File02Icon size={size} color="#FF1A53" />,backgroundColor: "rgba(255, 26, 83, 0.06)",};}// Default: Generic file iconreturn {- icon: <File02Icon size={42} color="#FF1A53" />,- backgroundColor: "rgba(255, 26, 83, 0.06)",+ icon: <File02Icon size={size} color="#757575" />,+ backgroundColor: "#FAFAFA",};};