Skip to content

armgit / ente

Public Imported from GitHub
0

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

fix: harden locker collection share web flow

AmanRajSinghMourya66eb8ec2cc1c
diff --git a/web/apps/share/src/components/file-share/CollectionShareView.tsx b/web/apps/share/src/components/file-share/CollectionShareView.tsx
index 0169ed7c8d..d75da43b63 100644
--- a/web/apps/share/src/components/file-share/CollectionShareView.tsx
+++ b/web/apps/share/src/components/file-share/CollectionShareView.tsx
@@ -2,11 +2,13 @@ import {
Box,
ButtonBase,
CircularProgress,
+ Paper,
Stack,
Typography,
} from "@mui/material";
import { SingleInputForm } from "ente-base/components/SingleInputForm";
import { Notification } from "ente-new/photos/components/Notification";
+import { t } from "i18next";
import React from "react";
import { useCollectionShare } from "../../hooks/useCollectionShare";
import { type SharedCollectionItemInfo } from "../../services/collection-share";
@@ -42,6 +44,13 @@ const itemSubtitle = (item: SharedCollectionItemInfo) => {
return "File";
};
+const translatedOrFallback = (key: string, fallback: string) => {
+ const translated = t(key);
+ return typeof translated === "string" && translated.trim()
+ ? translated
+ : fallback;
+};
+
const contentMaxWidth = 560;
export const CollectionShareView: React.FC = () => {
@@ -62,6 +71,12 @@ export const CollectionShareView: React.FC = () => {
handleCopyContent,
setNotificationAttributes,
} = useCollectionShare();
+ const passwordTitle = translatedOrFallback("password", "Password");
+ const passwordDescription = translatedOrFallback(
+ "link_password_description",
+ "Enter the password to unlock this collection.",
+ );
+ const unlockLabel = translatedOrFallback("unlock", "Unlock");
return (
<PublicShareScaffold>
@@ -119,36 +134,76 @@ export const CollectionShareView: React.FC = () => {
p: 3,
}}
>
- <Box sx={{ width: "100%", maxWidth: 420 }}>
+ <Paper
+ elevation={0}
+ sx={{
+ width: "100%",
+ maxWidth: 420,
+ px: { xs: 3, sm: 4 },
+ py: { xs: 3.5, sm: 4 },
+ borderRadius: "20px",
+ backgroundColor: "rgba(19, 21, 24, 0.96)",
+ border: "1px solid rgba(255, 255, 255, 0.08)",
+ boxShadow:
+ "0 24px 60px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.03)",
+ color: "#FFFFFF",
+ "& .MuiTypography-root": { color: "inherit" },
+ "& .MuiFormLabel-root": {
+ color: "rgba(255, 255, 255, 0.64)",
+ },
+ "& .MuiFormLabel-root.Mui-focused": {
+ color: "accent.light",
+ },
+ "& .MuiInputBase-root": {
+ backgroundColor: "rgba(255, 255, 255, 0.08)",
+ color: "#FFFFFF",
+ },
+ "& .MuiInputBase-input": { color: "#FFFFFF" },
+ "& .MuiInputAdornment-root": {
+ color: "rgba(255, 255, 255, 0.52)",
+ },
+ "& .MuiFormHelperText-root": {
+ color: "rgba(255, 255, 255, 0.6)",
+ },
+ "& .MuiButton-root": {
+ backgroundColor: "accent.main",
+ color: "accent.contrastText",
+ },
+ "& .MuiButton-root:hover": {
+ backgroundColor: "accent.dark",
+ },
+ "& .MuiButton-root.Mui-disabled": {
+ backgroundColor: "accent.main",
+ color: "accent.contrastText",
+ opacity: 0.7,
+ },
+ }}
+ >
<Typography
variant="h4"
- sx={{
- fontWeight: 700,
- color: "text.base",
- mb: 1.5,
- }}
+ sx={{ fontWeight: 700, color: "#FFFFFF", mb: 1.5 }}
>
- Password
+ {passwordTitle}
</Typography>
<Typography
variant="body"
- sx={{ color: "text.muted", mb: 2 }}
+ sx={{ color: "rgba(255, 255, 255, 0.72)", mb: 2 }}
>
- This collection link is password protected.
+ {passwordDescription}
</Typography>
<SingleInputForm
inputType="password"
- label="Password"
+ label={passwordTitle}
submitButtonColor="primary"
- submitButtonTitle="Unlock"
+ submitButtonTitle={unlockLabel}
onSubmit={handleSubmitPassword}
/>
- </Box>
+ </Paper>
</Box>
)}
{/* Item detail view - uses same component as single-file share */}
- {selectedItem && !loading && !requiresPassword && (
+ {selectedItem && !loading && !requiresPassword && !error && (
<SharedItemDetails
itemInfo={selectedItem}
downloading={downloadingItemID === selectedItem.id}
@@ -168,7 +223,8 @@ export const CollectionShareView: React.FC = () => {
{collectionInfo &&
!loading &&
!selectedItem &&
- !requiresPassword && (
+ !requiresPassword &&
+ !error && (
<Box
sx={{
width: "100%",
diff --git a/web/apps/share/src/hooks/useCollectionShare.ts b/web/apps/share/src/hooks/useCollectionShare.ts
index 91637c1535..8687947a91 100644
--- a/web/apps/share/src/hooks/useCollectionShare.ts
+++ b/web/apps/share/src/hooks/useCollectionShare.ts
@@ -1,10 +1,14 @@
import type { SingleInputFormProps } from "ente-base/components/SingleInputForm";
-import { HTTPError, isHTTP401Error, isHTTPErrorWithStatus } from "ente-base/http";
+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 { useCallback, useEffect, useRef, useState } from "react";
import {
downloadPublicCollectionFile,
fetchPublicCollectionShare,
@@ -49,6 +53,38 @@ interface CollectionShareLoadError {
isExpired: boolean;
}
+const accessTokenJWTStorageKey = (accessToken: string) =>
+ `share-collection-access-token-jwt:${accessToken}`;
+
+const savedAccessTokenJWT = (accessToken: string): string | null => {
+ try {
+ return window.localStorage.getItem(
+ accessTokenJWTStorageKey(accessToken),
+ );
+ } catch {
+ return null;
+ }
+};
+
+const saveAccessTokenJWT = (accessToken: string, accessTokenJWT: string) => {
+ try {
+ window.localStorage.setItem(
+ accessTokenJWTStorageKey(accessToken),
+ accessTokenJWT,
+ );
+ } catch {
+ // Ignore storage failures and continue with in-memory state.
+ }
+};
+
+const removeAccessTokenJWT = (accessToken: string) => {
+ try {
+ window.localStorage.removeItem(accessTokenJWTStorageKey(accessToken));
+ } catch {
+ // Ignore storage failures and continue with in-memory state.
+ }
+};
+
const collectionShareLoadError = async (
err: unknown,
): Promise<CollectionShareLoadError> => {
@@ -60,7 +96,8 @@ const collectionShareLoadError = async (
if (payload.error === "expired token") {
return {
title: "Link expired",
- message: "This link has either expired or has been disabled.",
+ message:
+ "This link has either expired or has been disabled.",
isExpired: true,
};
}
@@ -90,13 +127,15 @@ const collectionShareLoadError = async (
return {
title: "Unable to open this collection",
- message: "Unable to load this collection right now. Please try again later.",
+ message:
+ "Unable to load this collection right now. Please try again later.",
isExpired: false,
};
};
export const useCollectionShare = (): UseCollectionShareResult => {
const router = useRouter();
+ const isRevalidatingRef = useRef(false);
const [loading, setLoading] = useState(true);
const [downloadingItemID, setDownloadingItemID] = useState<number | null>(
null,
@@ -133,11 +172,14 @@ export const useCollectionShare = (): UseCollectionShareResult => {
setError(null);
setErrorTitle(null);
setErrorIsExpired(false);
+ setPasswordProtectedPublicURL(null);
const url = new URL(window.location.href);
const token =
opts?.accessToken ?? extractCollectionTokenFromURL(url);
if (!token) {
+ setCollectionInfo(null);
+ setSelectedItem(null);
setErrorTitle("Invalid collection link");
setError("This collection link is invalid.");
return;
@@ -147,36 +189,69 @@ export const useCollectionShare = (): UseCollectionShareResult => {
opts?.collectionKey ??
(await extractCollectionKeyFromShareURL(url));
if (!resolvedCollectionKey) {
+ setCollectionInfo(null);
+ setSelectedItem(null);
setErrorTitle("Invalid collection link");
setError("This collection link is invalid.");
return;
}
- const resolvedAccessTokenJWT = opts?.accessTokenJWT;
+ const storedAccessTokenJWT = savedAccessTokenJWT(token);
+ const resolvedAccessTokenJWT =
+ opts?.accessTokenJWT ?? storedAccessTokenJWT ?? undefined;
setAccessToken(token);
setCollectionKey(resolvedCollectionKey);
+ setAccessTokenJWT(resolvedAccessTokenJWT ?? null);
const metadata = await fetchPublicCollectionShareMetadata(
token,
resolvedCollectionKey,
);
- if (metadata.passwordEnabled && !resolvedAccessTokenJWT) {
+ if (!metadata.passwordEnabled && resolvedAccessTokenJWT) {
+ removeAccessTokenJWT(token);
+ setAccessTokenJWT(null);
+ }
+
+ const activeAccessTokenJWT = metadata.passwordEnabled
+ ? resolvedAccessTokenJWT
+ : undefined;
+
+ if (metadata.passwordEnabled && !activeAccessTokenJWT) {
setPasswordProtectedPublicURL(metadata.publicURL ?? null);
setCollectionInfo(null);
+ setSelectedItem(null);
return;
}
- const info = await fetchPublicCollectionShare(
- {
- accessToken: token,
- accessTokenJWT: resolvedAccessTokenJWT,
- },
- resolvedCollectionKey,
- );
+ let info: PublicCollectionShareInfo;
+ try {
+ info = await fetchPublicCollectionShare(
+ {
+ accessToken: token,
+ accessTokenJWT: activeAccessTokenJWT,
+ },
+ resolvedCollectionKey,
+ );
+ } catch (err) {
+ if (activeAccessTokenJWT && isHTTP401Error(err)) {
+ removeAccessTokenJWT(token);
+ setAccessTokenJWT(null);
+ setPasswordProtectedPublicURL(
+ metadata.publicURL ?? null,
+ );
+ setCollectionInfo(null);
+ return;
+ }
+ throw err;
+ }
+
setPasswordProtectedPublicURL(null);
setCollectionInfo(info);
} catch (err) {
+ setCollectionInfo(null);
+ setSelectedItem(null);
+ setPasswordProtectedPublicURL(null);
const loadError = await collectionShareLoadError(err);
setErrorTitle(loadError.title);
setError(loadError.message);
@@ -194,6 +269,39 @@ export const useCollectionShare = (): UseCollectionShareResult => {
}
}, [router.isReady, loadCollection]);
+ useEffect(() => {
+ if (!router.isReady) {
+ return;
+ }
+
+ const revalidate = () => {
+ if (document.visibilityState === "hidden" || isRevalidatingRef.current) {
+ return;
+ }
+
+ isRevalidatingRef.current = true;
+ void loadCollection().finally(() => {
+ isRevalidatingRef.current = false;
+ });
+ };
+
+ const onVisibilityChange = () => {
+ if (document.visibilityState === "visible") {
+ revalidate();
+ }
+ };
+
+ window.addEventListener("focus", revalidate);
+ window.addEventListener("pageshow", revalidate);
+ document.addEventListener("visibilitychange", onVisibilityChange);
+
+ return () => {
+ window.removeEventListener("focus", revalidate);
+ window.removeEventListener("pageshow", revalidate);
+ document.removeEventListener("visibilitychange", onVisibilityChange);
+ };
+ }, [router.isReady, loadCollection]);
+
const handleCloseItem = () => {
setSelectedItem(null);
};
@@ -214,7 +322,7 @@ export const useCollectionShare = (): UseCollectionShareResult => {
setDownloadProgress(null);
try {
await downloadPublicCollectionFile(
- accessToken,
+ { accessToken, accessTokenJWT: accessTokenJWT ?? undefined },
item.id,
fileKey,
item.fileName,
@@ -228,6 +336,13 @@ export const useCollectionShare = (): UseCollectionShareResult => {
},
);
} catch (err) {
+ if (accessTokenJWT && collectionKey && isHTTP401Error(err)) {
+ removeAccessTokenJWT(accessToken);
+ setAccessTokenJWT(null);
+ setSelectedItem(null);
+ await loadCollection({ accessToken, collectionKey });
+ return;
+ }
setNotificationAttributes({
color: "critical",
title:
@@ -282,6 +397,7 @@ export const useCollectionShare = (): UseCollectionShareResult => {
accessToken,
);
setAccessTokenJWT(jwtToken);
+ saveAccessTokenJWT(accessToken, jwtToken);
await loadCollection({
accessToken,
collectionKey,
diff --git a/web/apps/share/src/pages/index.tsx b/web/apps/share/src/pages/index.tsx
index 68b45a72b8..05d377b080 100644
--- a/web/apps/share/src/pages/index.tsx
+++ b/web/apps/share/src/pages/index.tsx
@@ -1,15 +1,10 @@
+import { Box, CircularProgress } from "@mui/material";
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;
-
+const detectShareView = (pathname: string): "file" | "collection" | null => {
if (/^\/c\/[^/]+\/?$/.test(pathname)) {
return "collection";
}
@@ -42,25 +37,36 @@ const Page: React.FC = () => {
useEffect(() => {
const pathname = window.location.pathname;
- setShareView(detectShareView());
+ const nextShareView = detectShareView(pathname);
+ setShareView(nextShareView);
- if (pathname === "/" || pathname === "") {
+ if (nextShareView === null) {
setHideContent(true);
window.location.href = "https://ente.com/locker";
- return;
}
}, []);
return (
<>
<CustomHeadShare title="Ente Locker" />
- {!hideContent &&
- shareView &&
- (shareView === "collection" ? (
- <CollectionShareView />
- ) : (
- <FileShareView />
- ))}
+ {!hideContent && shareView === null && (
+ <Box
+ sx={{
+ minHeight: "100dvh",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ bgcolor: "#08090A",
+ }}
+ >
+ <CircularProgress sx={{ color: "accent.main" }} size={32} />
+ </Box>
+ )}
+ {!hideContent && shareView === "collection" ? (
+ <CollectionShareView />
+ ) : !hideContent && shareView === "file" ? (
+ <FileShareView />
+ ) : null}
</>
);
};
diff --git a/web/apps/share/src/services/collection-share.ts b/web/apps/share/src/services/collection-share.ts
index 6faf49f753..7974eae3ee 100644
--- a/web/apps/share/src/services/collection-share.ts
+++ b/web/apps/share/src/services/collection-share.ts
@@ -236,7 +236,10 @@ const fetchPublicCollectionDiff = async (
while (hasMore) {
const res = await fetch(
await apiURL("/public-collection/diff", { sinceTime }),
- { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },
+ {
+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),
+ cache: "no-store",
+ },
);
ensureOk(res);
@@ -283,6 +286,7 @@ export const fetchPublicCollectionShareMetadata = async (
): Promise<PublicCollectionShareMetadata> => {
const res = await fetch(await apiURL("/public-collection/info"), {
headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
+ cache: "no-store",
});
ensureOk(res);
@@ -330,7 +334,7 @@ export const fetchPublicCollectionShare = async (
};
export const downloadPublicCollectionFile = async (
- accessToken: string,
+ credentials: PublicAlbumsCredentials,
fileID: number,
fileKey: string,
fileName: string,
@@ -339,12 +343,9 @@ export const downloadPublicCollectionFile = async (
): Promise<void> => {
const url = `${await apiOrigin()}/public-collection/files/download/${fileID}`;
const response = await fetch(url, {
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),
});
-
- if (!response.ok) {
- throw new Error(`Failed to download file: ${response.statusText}`);
- }
+ ensureOk(response);
const totalHeader = response.headers.get("content-length");
const total = totalHeader ? Number.parseInt(totalHeader, 10) : null;
diff --git a/web/apps/share/src/services/file-share.ts b/web/apps/share/src/services/file-share.ts
index 264dc9586e..82e7172724 100644
--- a/web/apps/share/src/services/file-share.ts
+++ b/web/apps/share/src/services/file-share.ts
@@ -55,6 +55,7 @@ export const fetchFileInfo = async (
const response = await fetch(url, {
headers: { "X-Auth-Access-Token": accessToken },
+ cache: "no-store",
});
if (!response.ok) {