Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use Locker session for collection keys

Manav Rathi7ad5912cef74
diff --git a/rust/bindings/wasm/locker/Cargo.toml b/rust/bindings/wasm/locker/Cargo.toml
index af79556856..987926427d 100644
--- a/rust/bindings/wasm/locker/Cargo.toml
+++ b/rust/bindings/wasm/locker/Cargo.toml
@@ -6,4 +6,4 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
-ente-wasm-lib = { workspace = true, features = ["accounts", "contacts", "crypto-file", "crypto-seal"] }
+ente-wasm-lib = { workspace = true, features = ["accounts", "collections", "contacts", "crypto-file", "crypto-seal"] }
diff --git a/web/apps/locker/src/components/ItemCard.tsx b/web/apps/locker/src/components/ItemCard.tsx
index 7360acad3f..dc5b050779 100644
--- a/web/apps/locker/src/components/ItemCard.tsx
+++ b/web/apps/locker/src/components/ItemCard.tsx
@@ -34,7 +34,6 @@ import React, { useCallback, useState } from "react";
interface ItemCardProps {
item: LockerItem;
- masterKey?: string;
onClick: () => void;
isTrashView?: boolean;
isIncomingShared?: boolean;
@@ -53,7 +52,6 @@ interface ItemCardProps {
export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
item,
- masterKey,
onClick,
isTrashView,
isIncomingShared,
@@ -78,23 +76,18 @@ export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
const longPressTriggeredRef = React.useRef(false);
const handleDownload = useCallback(async () => {
- if (!masterKey || downloading || !hasDownloadableObject(item)) return;
+ if (downloading || !hasDownloadableObject(item)) return;
setDownloading(true);
setDownloadProgress(null);
try {
const fileName = getItemTitle(item);
- await downloadLockerFile(
- item.id,
- fileName,
- masterKey,
- ({ loaded, total }) => {
- if (total && total > 0) {
- setDownloadProgress(
- Math.min(100, Math.round((loaded / total) * 100)),
- );
- }
- },
- );
+ await downloadLockerFile(item.id, fileName, ({ loaded, total }) => {
+ if (total && total > 0) {
+ setDownloadProgress(
+ Math.min(100, Math.round((loaded / total) * 100)),
+ );
+ }
+ });
} catch (e) {
log.error(`Failed to download file ${item.id}`, e);
setDownloadError(true);
@@ -102,7 +95,7 @@ export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
setDownloading(false);
setDownloadProgress(null);
}
- }, [item, masterKey, downloading]);
+ }, [item, downloading]);
const title = getItemTitle(item);
const downloadable = hasDownloadableObject(item);
@@ -175,12 +168,7 @@ export const ItemCard: React.FC<ItemCardProps> = React.memo(function ItemCard({
}
return;
}
- if (
- !isTrashView &&
- item.type === "file" &&
- masterKey &&
- downloadable
- ) {
+ if (!isTrashView && item.type === "file" && downloadable) {
void handleDownload();
return;
}
diff --git a/web/apps/locker/src/components/ItemDetailView.tsx b/web/apps/locker/src/components/ItemDetailView.tsx
index 5bdef936ff..b5c165184e 100644
--- a/web/apps/locker/src/components/ItemDetailView.tsx
+++ b/web/apps/locker/src/components/ItemDetailView.tsx
@@ -35,7 +35,6 @@ import React, { useCallback, useState } from "react";
interface ItemDetailViewProps {
item: LockerItem | null;
- masterKey?: string;
onClose: () => void;
onEdit?: (item: LockerItem) => void;
onDelete?: (item: LockerItem) => void;
@@ -46,7 +45,6 @@ interface ItemDetailViewProps {
export const ItemDetailView: React.FC<ItemDetailViewProps> = ({
item,
- masterKey,
onClose,
onEdit,
onDelete,
@@ -78,7 +76,7 @@ export const ItemDetailView: React.FC<ItemDetailViewProps> = ({
}, []);
const handleDownload = useCallback(async () => {
- if (!item || !masterKey || downloading) {
+ if (!item || downloading) {
return;
}
@@ -88,7 +86,6 @@ export const ItemDetailView: React.FC<ItemDetailViewProps> = ({
await downloadLockerFile(
item.id,
getItemTitle(item),
- masterKey,
({ loaded, total }) => {
if (total && total > 0) {
setDownloadProgress(
@@ -104,7 +101,7 @@ export const ItemDetailView: React.FC<ItemDetailViewProps> = ({
setDownloading(false);
setDownloadProgress(null);
}
- }, [downloading, item, masterKey]);
+ }, [downloading, item]);
return (
<Drawer
@@ -223,39 +220,33 @@ export const ItemDetailView: React.FC<ItemDetailViewProps> = ({
data={item.data as GenericFileData}
onCopy={copyToClipboard}
/>
- {masterKey && (
- <Stack sx={{ mt: 1, gap: 1 }}>
- <Button
- variant="contained"
- endIcon={
- downloading &&
- downloadProgress !== null ? (
- <CircularProgress
- variant="determinate"
- value={downloadProgress}
- size={16}
- thickness={6}
- color="inherit"
- />
- ) : undefined
- }
- startIcon={
- <FileDownloadOutlinedIcon />
- }
- onClick={() =>
- void handleDownload()
- }
- disabled={downloading}
- fullWidth
- >
- {downloading
- ? downloadProgress !== null
- ? `${t("downloading")} ${downloadProgress}%`
- : t("downloading")
- : t("download")}
- </Button>
- </Stack>
- )}
+ <Stack sx={{ mt: 1, gap: 1 }}>
+ <Button
+ variant="contained"
+ endIcon={
+ downloading &&
+ downloadProgress !== null ? (
+ <CircularProgress
+ variant="determinate"
+ value={downloadProgress}
+ size={16}
+ thickness={6}
+ color="inherit"
+ />
+ ) : undefined
+ }
+ startIcon={<FileDownloadOutlinedIcon />}
+ onClick={() => void handleDownload()}
+ disabled={downloading}
+ fullWidth
+ >
+ {downloading
+ ? downloadProgress !== null
+ ? `${t("downloading")} ${downloadProgress}%`
+ : t("downloading")
+ : t("download")}
+ </Button>
+ </Stack>
</>
)}
{onShareLink && (
diff --git a/web/apps/locker/src/components/ItemList.tsx b/web/apps/locker/src/components/ItemList.tsx
index 4f192751e0..3de3953151 100644
--- a/web/apps/locker/src/components/ItemList.tsx
+++ b/web/apps/locker/src/components/ItemList.tsx
@@ -72,7 +72,6 @@ const uniqueCollectionsByID = (collections: LockerCollection[]) => {
interface ItemListProps {
collections: LockerCollection[];
- masterKey?: string;
trashItems?: LockerItem[];
isTrashView: boolean;
isCollectionsView: boolean;
@@ -103,7 +102,6 @@ const contentMaxWidth = 560;
export const ItemList: React.FC<ItemListProps> = ({
collections,
- masterKey,
trashItems,
isTrashView,
isCollectionsView,
@@ -609,9 +607,6 @@ export const ItemList: React.FC<ItemListProps> = ({
}, [isCreatingFileLink, isDeleteFileLinkConfirmOpen, isDeletingFileLink]);
const openFileLinkDialog = useCallback(
async (item: LockerItem) => {
- if (!masterKey) {
- return;
- }
if (!canShareLockerFileLink(item, currentUserID)) {
setFeedbackMessage(t("shareNotSupportedForSharedFiles"));
return;
@@ -621,10 +616,7 @@ export const ItemList: React.FC<ItemListProps> = ({
setActiveFileLink(null);
setIsCreatingFileLink(true);
try {
- const link = await getOrCreateLockerFileShareLink(
- item.id,
- masterKey,
- );
+ const link = await getOrCreateLockerFileShareLink(item.id);
setActiveFileLink(link);
} catch (error) {
log.error(
@@ -641,7 +633,7 @@ export const ItemList: React.FC<ItemListProps> = ({
setIsCreatingFileLink(false);
}
},
- [currentUserID, masterKey],
+ [currentUserID],
);
const copyActiveFileLink = useCallback(async () => {
if (!activeFileLink?.url) {
@@ -703,11 +695,7 @@ export const ItemList: React.FC<ItemListProps> = ({
}
}, [activeFileLink?.linkID, activeFileLinkItem]);
const downloadSelectedFiles = useCallback(async () => {
- if (
- !masterKey ||
- bulkDownloading ||
- selectedDownloadableItems.length === 0
- ) {
+ if (bulkDownloading || selectedDownloadableItems.length === 0) {
return;
}
@@ -718,11 +706,7 @@ export const ItemList: React.FC<ItemListProps> = ({
});
try {
for (const [index, item] of selectedDownloadableItems.entries()) {
- await downloadLockerFile(
- item.id,
- getItemTitle(item),
- masterKey,
- );
+ await downloadLockerFile(item.id, getItemTitle(item));
setBulkDownloadProgress({
completed: index + 1,
total: selectedDownloadableItems.length,
@@ -745,7 +729,6 @@ export const ItemList: React.FC<ItemListProps> = ({
}
}, [
bulkDownloading,
- masterKey,
selectedDownloadableItems,
skippedDownloadSelectionCount,
stopSelectionMode,
@@ -901,7 +884,6 @@ export const ItemList: React.FC<ItemListProps> = ({
<ItemsSection
items={homeFilteredItems}
- masterKey={masterKey}
isTrashView={false}
onEditItem={onEditItem}
onDeleteItem={onDeleteItem}
@@ -1060,7 +1042,6 @@ export const ItemList: React.FC<ItemListProps> = ({
<ItemsSection
items={sortedItems}
- masterKey={masterKey}
isTrashView={isTrashView}
onEditItem={onEditItem}
onDeleteItem={onDeleteItem}
@@ -1190,7 +1171,6 @@ export const ItemList: React.FC<ItemListProps> = ({
<ItemsSection
items={sortedItems}
- masterKey={masterKey}
isTrashView={isTrashView}
onEditItem={onEditItem}
onDeleteItem={onDeleteItem}
@@ -1243,9 +1223,7 @@ export const ItemList: React.FC<ItemListProps> = ({
allSelected={allVisibleItemsSelected}
bulkDownloading={bulkDownloading}
bulkDownloadProgress={bulkDownloadProgress}
- canDownload={
- !!masterKey && selectedDownloadableItems.length > 0
- }
+ canDownload={selectedDownloadableItems.length > 0}
canDelete={
!!onDeleteItems && selectedVisibleItems.length > 0
}
@@ -1258,7 +1236,6 @@ export const ItemList: React.FC<ItemListProps> = ({
<ItemDetailView
item={selectedItem}
- masterKey={masterKey}
onClose={() => setSelectedItemID(null)}
onEdit={
onEditItem &&
@@ -1438,7 +1415,6 @@ const SectionHeader: React.FC<{
const ItemsSection: React.FC<{
items: LockerItem[];
- masterKey?: string;
isTrashView: boolean;
onEditItem?: (item: LockerItem) => void;
onDeleteItem?: (item: LockerItem) => void;
@@ -1454,7 +1430,6 @@ const ItemsSection: React.FC<{
emptyState: React.ReactNode;
}> = ({
items,
- masterKey,
isTrashView,
onEditItem,
onDeleteItem,
@@ -1482,7 +1457,6 @@ const ItemsSection: React.FC<{
<ItemCard
key={item.id}
item={item}
- masterKey={masterKey}
isTrashView={isTrashView}
isIncomingShared={!isOwnedByCurrentUser}
onClick={() => onSelectItem(item)}
diff --git a/web/apps/locker/src/components/lockerPage/use-locker-actions.tsx b/web/apps/locker/src/components/lockerPage/use-locker-actions.tsx
index 54b4bff934..c44f664cbb 100644
--- a/web/apps/locker/src/components/lockerPage/use-locker-actions.tsx
+++ b/web/apps/locker/src/components/lockerPage/use-locker-actions.tsx
@@ -447,10 +447,10 @@ export const useLockerActions = ({
clearUploadRefreshTimeout();
uploadRefreshTimeoutRef.current = window.setTimeout(() => {
uploadRefreshTimeoutRef.current = null;
- void refreshData(masterKey);
+ void refreshData();
}, delayMs);
},
- [clearUploadRefreshTimeout, masterKey, refreshData],
+ [clearUploadRefreshTimeout, refreshData],
);
const scheduleUploadFollowUpRefreshes = useCallback(() => {
@@ -458,10 +458,10 @@ export const useLockerActions = ({
uploadFollowUpRefreshTimeoutsRef.current =
UPLOAD_REFRESH_FOLLOW_UP_DELAYS_MS.map((delayMs) =>
window.setTimeout(() => {
- void refreshData(masterKey);
+ void refreshData();
}, delayMs),
);
- }, [clearUploadFollowUpRefreshes, masterKey, refreshData]);
+ }, [clearUploadFollowUpRefreshes, refreshData]);
const handleCreateItem = useCallback(
async (
@@ -497,7 +497,7 @@ export const useLockerActions = ({
async (uploadedCount: number) => {
clearUploadRefreshTimeout();
clearUploadFollowUpRefreshes();
- await refreshData(masterKey);
+ await refreshData();
scheduleUploadFollowUpRefreshes();
setToast(
uploadedCount === 1
@@ -508,7 +508,6 @@ export const useLockerActions = ({
[
clearUploadFollowUpRefreshes,
clearUploadRefreshTimeout,
- masterKey,
refreshData,
scheduleUploadFollowUpRefreshes,
],
@@ -531,9 +530,9 @@ export const useLockerActions = ({
if (type === "file") {
const editedName =
typeof data.name === "string" ? data.name : "";
- await updateFileItem(editItem.id, editedName, masterKey);
+ await updateFileItem(editItem.id, editedName);
} else {
- await updateInfoItem(editItem.id, type, data, masterKey);
+ await updateInfoItem(editItem.id, type, data);
}
await updateItemCollections(editItem.id, collectionIDs, masterKey);
@@ -695,18 +694,14 @@ export const useLockerActions = ({
const handleRestoreItem = useCallback(
async (item: LockerItem, collectionID: number) => {
- if (!masterKey) {
- return;
- }
await restoreFromTrash(
[{ id: item.id, collectionID: item.collectionID }],
collectionID,
- masterKey,
);
await refreshData();
setToast(t("filesRestoredSuccessfully", { count: 1 }));
},
- [masterKey, refreshData],
+ [refreshData],
);
const handleEmptyTrash = useCallback(() => {
@@ -889,14 +884,11 @@ export const useLockerActions = ({
const handleRenameCollection = useCallback(
async (collectionID: number, newName: string) => {
- if (!masterKey) {
- return;
- }
- await renameCollectionAPI(collectionID, newName, masterKey);
+ await renameCollectionAPI(collectionID, newName);
await refreshData();
setToast(t("collectionRenamedSuccessfully"));
},
- [masterKey, refreshData],
+ [refreshData],
);
const handleDeleteCollection = useCallback(
@@ -1003,14 +995,11 @@ export const useLockerActions = ({
const handleShareCollection = useCallback(
async (collectionID: number, email: string) => {
- if (!masterKey) {
- throw new Error("No master key");
- }
- await shareCollectionAPI(collectionID, email, masterKey);
+ await shareCollectionAPI(collectionID, email);
await refreshData();
setToast(t("collectionSharedSuccessfully"));
},
- [masterKey, refreshData],
+ [refreshData],
);
const handleUnshareCollection = useCallback(
diff --git a/web/apps/locker/src/components/lockerPage/use-locker-data.ts b/web/apps/locker/src/components/lockerPage/use-locker-data.ts
index 0f02a182e8..bcd6c98725 100644
--- a/web/apps/locker/src/components/lockerPage/use-locker-data.ts
+++ b/web/apps/locker/src/components/lockerPage/use-locker-data.ts
@@ -269,46 +269,36 @@ export const useLockerData = ({
}
}, [loadLockerUsage]);
- const fetchAndStoreLockerData = useCallback(
- async (key: string) => {
- const requestID = ++latestDataRequestRef.current;
+ const fetchAndStoreLockerData = useCallback(async () => {
+ const requestID = ++latestDataRequestRef.current;
- const data = await syncLockerState(key);
+ const data = await syncLockerState();
- if (
- !mountedRef.current ||
- requestID !== latestDataRequestRef.current
- ) {
- return;
- }
+ if (!mountedRef.current || requestID !== latestDataRequestRef.current) {
+ return;
+ }
- setCollections(data.collections);
- setTrashItems(data.trashItems);
- setTrashLastUpdatedAt(data.trashLastUpdatedAt);
- setInitialLoadError(null);
- void refreshUserDetailsForSyncState(data);
- },
- [refreshUserDetailsForSyncState],
- );
+ setCollections(data.collections);
+ setTrashItems(data.trashItems);
+ setTrashLastUpdatedAt(data.trashLastUpdatedAt);
+ setInitialLoadError(null);
+ void refreshUserDetailsForSyncState(data);
+ }, [refreshUserDetailsForSyncState]);
- const refreshData = useCallback(
- async (mk?: string) => {
- const key = mk ?? masterKey;
- if (!key) {
- return;
- }
+ const refreshData = useCallback(async () => {
+ if (!masterKey) {
+ return;
+ }
- try {
- await fetchAndStoreLockerData(key);
- } catch (error) {
- log.error("Failed to refresh locker data", error);
- if (isHTTP401Error(error)) {
- showMiniDialog(sessionExpiredDialogAttributes(logout));
- }
+ try {
+ await fetchAndStoreLockerData();
+ } catch (error) {
+ log.error("Failed to refresh locker data", error);
+ if (isHTTP401Error(error)) {
+ showMiniDialog(sessionExpiredDialogAttributes(logout));
}
- },
- [fetchAndStoreLockerData, logout, masterKey, showMiniDialog],
- );
+ }
+ }, [fetchAndStoreLockerData, logout, masterKey, showMiniDialog]);
useEffect(() => {
let cancelled = false;
@@ -344,7 +334,7 @@ export const useLockerData = ({
);
});
- const persisted = await loadPersistedLockerState(mk);
+ const persisted = await loadPersistedLockerState();
if (canApplyState() && persisted.hasPersistedState) {
setCollections(persisted.collections);
setTrashItems(persisted.trashItems);
@@ -354,7 +344,7 @@ export const useLockerData = ({
void refreshUserDetailsForSyncState(persisted);
}
- await fetchAndStoreLockerData(mk);
+ await fetchAndStoreLockerData();
if (canApplyState()) {
setHasFetched(true);
}
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index 0ea4cb9ddf..c5b1cb670a 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -189,7 +189,6 @@ export const LockerPage: React.FC = () => {
>
<ItemList
collections={collections}
- masterKey={masterKey}
trashItems={isTrashView ? trashItems : undefined}
isTrashView={isTrashView}
isCollectionsView={isCollectionsView}
diff --git a/web/apps/locker/src/services/authenticated-session.ts b/web/apps/locker/src/services/authenticated-session.ts
index f2c98d170f..3073eeb034 100644
--- a/web/apps/locker/src/services/authenticated-session.ts
+++ b/web/apps/locker/src/services/authenticated-session.ts
@@ -15,7 +15,7 @@ let generation = 0;
export const openAuthenticatedSession = lockerSessions.open;
-export const authenticatedLegacySession = async () => {
+const savedSessionCredentials = async () => {
const startedGeneration = generation;
const userID = ensureLocalUser().id;
const [authToken, masterKeyB64] = await Promise.all([
@@ -27,6 +27,19 @@ export const authenticatedLegacySession = async () => {
}
if (!masterKeyB64) throw new Error("Missing current master key");
if (!authToken) throw new Error("Missing auth token");
+ return { userID, authToken, masterKeyB64 };
+};
+
+export const ensureAuthenticatedSession = async () => {
+ const current = lockerSessions.current();
+ if (current) return current;
+
+ const { userID, authToken, masterKeyB64 } = await savedSessionCredentials();
+ return lockerSessions.open(userID, authToken, masterKeyB64);
+};
+
+export const authenticatedLegacySession = async () => {
+ const { userID, authToken, masterKeyB64 } = await savedSessionCredentials();
return legacySessions.open(userID, authToken, masterKeyB64);
};
@@ -42,6 +55,7 @@ function sessionCache<T extends Pick<Session, "free" | "updateAuthToken">>(
let current: { key: string; opening: Promise<T> } | undefined;
return {
+ current: () => current?.opening,
open: async (
userID: number,
authToken: string,
diff --git a/web/apps/locker/src/services/remote-collection-mutations.ts b/web/apps/locker/src/services/remote-collection-mutations.ts
index e855a93950..2b9b9c1b0e 100644
--- a/web/apps/locker/src/services/remote-collection-mutations.ts
+++ b/web/apps/locker/src/services/remote-collection-mutations.ts
@@ -23,13 +23,11 @@ interface CollectionMutationDeps {
decryptFileKeyForCollection: (
fileID: number,
collectionID: number,
- masterKey: string,
) => Promise<string>;
buildEncryptedFileMoveItem: (
fileID: number,
fromCollectionID: number,
toCollectionID: number,
- masterKey: string,
) => Promise<EncryptedCollectionFileItem>;
removeFilesFromCollection: (
collectionID: number,
@@ -44,7 +42,6 @@ interface CollectionMutationDeps {
fileID: number,
fileKey: string,
targetCollectionIDs: number[],
- masterKey: string,
) => Promise<void>;
}
@@ -171,11 +168,7 @@ export const updateItemCollectionsWithDeps = async (
) ?? currentCollectionIDs[0])
: undefined;
const sourceFileKeyForAdd = sourceCollectionIDForAdd
- ? await decryptFileKeyForCollection(
- fileID,
- sourceCollectionIDForAdd,
- masterKey,
- )
+ ? await decryptFileKeyForCollection(fileID, sourceCollectionIDForAdd)
: null;
// Add the new memberships before removing existing ones so the file
@@ -188,7 +181,6 @@ export const updateItemCollectionsWithDeps = async (
fileID,
sourceFileKeyForAdd,
collectionIDsToAdd,
- masterKey,
);
}
@@ -218,7 +210,6 @@ export const updateItemCollectionsWithDeps = async (
fileID,
collectionID,
targetCollectionID,
- masterKey,
),
]);
}
@@ -272,7 +263,6 @@ export const deleteCollectionKeepingFilesWithDeps = async (
item.id,
collectionID,
targetCollectionID,
- masterKey,
),
);
}
diff --git a/web/apps/locker/src/services/remote-collection-sharing.ts b/web/apps/locker/src/services/remote-collection-sharing.ts
index 79038c31e1..5dc8b27bd4 100644
--- a/web/apps/locker/src/services/remote-collection-sharing.ts
+++ b/web/apps/locker/src/services/remote-collection-sharing.ts
@@ -19,7 +19,6 @@ interface CollectionSharingDeps<TCollectionRecord> {
) => TCollectionRecord | undefined;
decryptCollectionKey: (
collectionRecord: TCollectionRecord,
- masterKey: string,
) => Promise<string>;
updateCollectionShareesInCache: (
collectionID: number,
@@ -53,7 +52,6 @@ export const fetchCollectionShareesWithDeps = async <TCollectionRecord>(
export const shareCollectionWithDeps = async <TCollectionRecord>(
collectionID: number,
email: string,
- masterKey: string,
deps: CollectionSharingDeps<TCollectionRecord>,
): Promise<LockerCollectionParticipant[]> => {
const collectionRecord = deps.getCollectionRecord(collectionID);
@@ -61,10 +59,7 @@ export const shareCollectionWithDeps = async <TCollectionRecord>(
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await deps.decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await deps.decryptCollectionKey(collectionRecord);
const publicKey = await getPublicKey(email);
const encryptedKey = await boxSeal(collectionKey, publicKey);
diff --git a/web/apps/locker/src/services/remote-collections.ts b/web/apps/locker/src/services/remote-collections.ts
index 79001c400e..96892dfd5a 100644
--- a/web/apps/locker/src/services/remote-collections.ts
+++ b/web/apps/locker/src/services/remote-collections.ts
@@ -14,13 +14,12 @@ interface RenameCollectionDeps<TCollectionRecord> {
) => TCollectionRecord | undefined;
decryptCollectionKey: (
collectionRecord: TCollectionRecord,
- masterKey: string,
) => Promise<string>;
}
interface EnsureUncategorizedDeps<TCollectionRecord> {
findCollectionByType: (type: string) => TCollectionRecord | undefined;
- refetchCollections: (masterKey: string) => Promise<void>;
+ refetchCollections: () => Promise<void>;
}
const ensureCollectionWithTypeWithDeps = async <
@@ -37,7 +36,7 @@ const ensureCollectionWithTypeWithDeps = async <
}
await createCollectionWithDeps(name, masterKey, type);
- await deps.refetchCollections(masterKey);
+ await deps.refetchCollections();
collection = deps.findCollectionByType(type);
if (!collection) {
@@ -100,7 +99,6 @@ export const ensureFavoritesCollectionWithDeps = async <
export const renameCollectionWithDeps = async <TCollectionRecord>(
collectionID: number,
newName: string,
- masterKey: string,
deps: RenameCollectionDeps<TCollectionRecord>,
): Promise<void> => {
const collectionRecord = deps.getCollectionRecord(collectionID);
@@ -108,10 +106,7 @@ export const renameCollectionWithDeps = async <TCollectionRecord>(
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await deps.decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await deps.decryptCollectionKey(collectionRecord);
const nameB64 = stringToB64(newName);
const encryptedName = await encryptBox(nameB64, collectionKey);
diff --git a/web/apps/locker/src/services/remote-read.ts b/web/apps/locker/src/services/remote-read.ts
index 8286ed58fc..ce4eb7f040 100644
--- a/web/apps/locker/src/services/remote-read.ts
+++ b/web/apps/locker/src/services/remote-read.ts
@@ -3,22 +3,21 @@ import type {
LockerCollectionParticipant,
LockerItem,
} from "@/types";
-import { ensureLocalUser } from "ente-accounts/services/user";
import { fetchFile } from "ente-base/file-download";
import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import log from "ente-base/log";
import { apiURL, customAPIOrigin } from "ente-base/origins";
import {
- boxSealOpen,
createStreamDecryptor,
decryptBox,
decryptBoxBytes,
decryptMetadataJSON,
encryptBox,
+ openCollectionKey,
stringToB64,
} from "ente-locker-wasm";
import { z } from "zod";
-import { ensureUserKeyPair } from "./account-keys";
+import { ensureAuthenticatedSession } from "./authenticated-session";
import { fromInfoTypeWireValue } from "./info-type-wire";
import {
type StoredTrashFileRecord,
@@ -346,7 +345,6 @@ const encryptCollectionPayload = async (
const toEncryptedCollectionRecord = (
collection: RemoteCollection,
- masterKey: string,
): Promise<EncryptedCollectionRecord> => {
const record: EncryptedCollectionRecord = {
id: collection.id,
@@ -361,7 +359,7 @@ const toEncryptedCollectionRecord = (
};
const buildEncryptedRecord = async () => {
- const collectionKey = await decryptCollectionKey(record, masterKey);
+ const collectionKey = await decryptCollectionKey(record);
const payload: LockerCollectionPayload = {
owner: {
...toLockerCollectionParticipant(collection.owner),
@@ -480,7 +478,6 @@ const fetchEncryptedFilesForCollection = async (
};
const decryptStoredTrash = async (
- masterKey: string,
cache: LockerEncryptedCache,
trashFiles: StoredTrashFileRecord[],
lastUpdatedAt: number,
@@ -496,10 +493,7 @@ const decryptStoredTrash = async (
}
try {
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const item = await decryptFileToLockerItem(
record,
collectionKey,
@@ -531,25 +525,16 @@ const buildStoredTrashFileRecord = (
export const decryptCollectionKey = async (
record: EncryptedCollectionRecord,
- masterKey: string,
-): Promise<string> => {
- const currentUserID = ensureLocalUser().id;
- if (record.ownerID === currentUserID) {
- return decryptBox(
- {
- encryptedData: record.encryptedKey,
- nonce: record.keyDecryptionNonce!,
- },
- masterKey,
- );
- }
-
- return boxSealOpen(record.encryptedKey, await ensureUserKeyPair());
-};
+): Promise<string> =>
+ openCollectionKey(
+ await ensureAuthenticatedSession(),
+ record.ownerID,
+ record.encryptedKey,
+ record.keyDecryptionNonce,
+ );
const decryptFileKeyForRecordFromCollections = async (
record: EncryptedFileRecord,
- masterKey: string,
collections: Map<number, EncryptedCollectionRecord>,
): Promise<string> => {
const collectionRecord = collections.get(record.collectionID);
@@ -557,10 +542,7 @@ const decryptFileKeyForRecordFromCollections = async (
throw new Error(`Collection ${record.collectionID} not found in cache`);
}
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
return decryptBox(
{
encryptedData: record.encryptedKey,
@@ -572,12 +554,10 @@ const decryptFileKeyForRecordFromCollections = async (
export const decryptFileKeyForRecord = async (
record: EncryptedFileRecord,
- masterKey: string,
): Promise<string> => {
const cacheSnapshot = getLockerCacheSnapshot();
return decryptFileKeyForRecordFromCollections(
record,
- masterKey,
cacheSnapshot.collections,
);
};
@@ -671,7 +651,6 @@ const decryptFileToLockerItem = async (
};
const decryptAllData = async (
- masterKey: string,
cache: LockerEncryptedCache,
): Promise<DecryptAllDataResult> => {
const activeCollectionRecords = [...cache.collections.values()].filter(
@@ -695,10 +674,7 @@ const decryptAllData = async (
for (const collectionRecord of activeCollectionRecords) {
try {
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const collectionDetails = await decryptCollectionDetails(
collectionRecord,
collectionKey,
@@ -782,7 +758,6 @@ const withoutFailedCollections = (
};
const hydrateLockerState = async (
- masterKey: string,
collections: Map<number, EncryptedCollectionRecord>,
files: EncryptedFileRecord[],
trashFiles: StoredTrashFileRecord[],
@@ -790,7 +765,7 @@ const hydrateLockerState = async (
): Promise<LockerHydratedState> => {
const activeCache = buildLockerCache(collections, files, []);
- const decrypted = await decryptAllData(masterKey, activeCache);
+ const decrypted = await decryptAllData(activeCache);
if (
decrypted.totalCollectionCount > 0 &&
decrypted.collections.length === 0
@@ -813,7 +788,6 @@ const hydrateLockerState = async (
}
const trash = await decryptStoredTrash(
- masterKey,
hydratedCache,
trashFiles,
trashLastUpdatedAt,
@@ -828,29 +802,25 @@ const hydrateLockerState = async (
};
};
-export const loadPersistedLockerState = async (
- masterKey: string,
-): Promise<LockerPersistedState> => {
- const snapshot = await loadLockerSnapshotFromDB();
- const hydrated = await hydrateLockerState(
- masterKey,
- snapshot.collections,
- snapshot.files,
- snapshot.trashFiles,
- snapshot.trashSinceTime,
- );
+export const loadPersistedLockerState =
+ async (): Promise<LockerPersistedState> => {
+ const snapshot = await loadLockerSnapshotFromDB();
+ const hydrated = await hydrateLockerState(
+ snapshot.collections,
+ snapshot.files,
+ snapshot.trashFiles,
+ snapshot.trashSinceTime,
+ );
- return {
- ...hydrated,
- collectionsSinceTime: snapshot.collectionsSinceTime,
- trashSinceTime: snapshot.trashSinceTime,
- hasPersistedState: snapshot.hasPersistedState,
+ return {
+ ...hydrated,
+ collectionsSinceTime: snapshot.collectionsSinceTime,
+ trashSinceTime: snapshot.trashSinceTime,
+ hasPersistedState: snapshot.hasPersistedState,
+ };
};
-};
-export const syncLockerState = async (
- masterKey: string,
-): Promise<LockerHydratedState> => {
+export const syncLockerState = async (): Promise<LockerHydratedState> => {
const snapshot = await loadLockerSnapshotFromDB();
const collectionChanges = await fetchEncryptedCollections(
snapshot.collectionsSinceTime,
@@ -865,7 +835,7 @@ export const syncLockerState = async (
latestCollectionsSinceTime,
change.updationTime,
);
- const record = await toEncryptedCollectionRecord(change, masterKey);
+ const record = await toEncryptedCollectionRecord(change);
changedCollections.push(record);
if (record.isDeleted) {
deletedCollectionIDs.push(record.id);
@@ -946,7 +916,6 @@ export const syncLockerState = async (
const nextSnapshot = await loadLockerSnapshotFromDB();
const hydrated = await hydrateLockerState(
- masterKey,
nextSnapshot.collections,
nextSnapshot.files,
nextSnapshot.trashFiles,
@@ -960,22 +929,17 @@ export const syncLockerState = async (
};
};
-export const fetchLockerData = async (
- masterKey: string,
-): Promise<LockerCollection[]> =>
- (await syncLockerState(masterKey)).collections;
+export const fetchLockerData = async (): Promise<LockerCollection[]> =>
+ (await syncLockerState()).collections;
-export const fetchLockerTrash = async (
- masterKey: string,
-): Promise<LockerTrashData> => {
- const state = await syncLockerState(masterKey);
+export const fetchLockerTrash = async (): Promise<LockerTrashData> => {
+ const state = await syncLockerState();
return { items: state.trashItems, lastUpdatedAt: state.trashLastUpdatedAt };
};
export const downloadLockerFile = async (
fileID: number,
fileName: string,
- masterKey: string,
onProgress?: (progress: { loaded: number; total?: number }) => void,
): Promise<void> => {
const fileRecord = getEncryptedFileRecord(fileID);
@@ -1003,10 +967,7 @@ export const downloadLockerFile = async (
let fileKey: string;
try {
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
fileKey = await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
diff --git a/web/apps/locker/src/services/remote-uploads.ts b/web/apps/locker/src/services/remote-uploads.ts
index 6d3c72829e..eeac883aec 100644
--- a/web/apps/locker/src/services/remote-uploads.ts
+++ b/web/apps/locker/src/services/remote-uploads.ts
@@ -58,13 +58,11 @@ interface UploadDeps<TCollectionRecord> {
) => TCollectionRecord | undefined;
decryptCollectionKey: (
collectionRecord: TCollectionRecord,
- masterKey: string,
) => Promise<string>;
addFileToCollections: (
fileID: number,
fileKey: string,
targetCollectionIDs: number[],
- masterKey: string,
) => Promise<void>;
}
@@ -283,7 +281,6 @@ const createAggregateUploadProgressReporter = (
export const uploadLockerFileWithDeps = async <TCollectionRecord>(
file: File,
collectionIDs: number[],
- masterKey: string,
deps: UploadDeps<TCollectionRecord>,
onProgress?: (progress: LockerUploadProgress) => void,
): Promise<number> => {
@@ -443,10 +440,7 @@ export const uploadLockerFileWithDeps = async <TCollectionRecord>(
if (!collectionRecord) {
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await deps.decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await deps.decryptCollectionKey(collectionRecord);
const encryptedKey = await encryptBox(fileKey, collectionKey);
const now = Date.now();
@@ -509,7 +503,6 @@ export const uploadLockerFileWithDeps = async <TCollectionRecord>(
created.id,
fileKey,
additionalCollectionIDs,
- masterKey,
);
}
return created.id;
diff --git a/web/apps/locker/src/services/remote.ts b/web/apps/locker/src/services/remote.ts
index cdd2996b9f..742dcaa3cc 100644
--- a/web/apps/locker/src/services/remote.ts
+++ b/web/apps/locker/src/services/remote.ts
@@ -215,14 +215,13 @@ export const fetchLockerFileShareLinks = (): Promise<
export const getOrCreateLockerFileShareLink = async (
fileID: number,
- masterKey: string,
): Promise<LockerFileShareLink> => {
const fileRecord = getEncryptedFileRecord(fileID);
if (!fileRecord) {
throw new Error(`File ${fileID} not found in cache`);
}
- const fileKey = await decryptFileKeyForRecord(fileRecord, masterKey);
+ const fileKey = await decryptFileKeyForRecord(fileRecord);
const payload = await prepareFileLinkSecretPayload(fileKey);
const res = await fetch(await apiURL("/files/share-url"), {
@@ -295,10 +294,7 @@ export const createInfoItem = async (
if (!collectionRecord)
throw new Error(`Collection ${collectionID} not in cache`);
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const fileKey = await generateKey();
@@ -357,7 +353,6 @@ export const createInfoItem = async (
created.id,
fileKey,
additionalCollectionIDs,
- masterKey,
);
}
};
@@ -366,7 +361,6 @@ export const updateInfoItem = async (
fileID: number,
infoType: LockerItemType,
infoData: Record<string, unknown>,
- masterKey: string,
): Promise<void> => {
const fileRecord = getEncryptedFileRecord(fileID);
if (!fileRecord) throw new Error(`File ${fileID} not in cache`);
@@ -375,10 +369,7 @@ export const updateInfoItem = async (
if (!collectionRecord)
throw new Error(`Collection ${fileRecord.collectionID} not in cache`);
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const fileKey = await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
@@ -442,7 +433,6 @@ export const updateInfoItem = async (
export const updateFileItem = async (
fileID: number,
title: string,
- masterKey: string,
): Promise<void> => {
const fileRecord = getEncryptedFileRecord(fileID);
if (!fileRecord) throw new Error(`File ${fileID} not in cache`);
@@ -451,10 +441,7 @@ export const updateFileItem = async (
if (!collectionRecord)
throw new Error(`Collection ${fileRecord.collectionID} not in cache`);
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const fileKey = await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
@@ -571,7 +558,6 @@ const addFileToCollections = async (
fileID: number,
fileKey: string,
targetCollectionIDs: number[],
- masterKey: string,
): Promise<void> => {
for (const targetCollectionID of targetCollectionIDs) {
const collectionRecord = getCollectionRecord(targetCollectionID);
@@ -579,10 +565,7 @@ const addFileToCollections = async (
throw new Error(`Collection ${targetCollectionID} not in cache`);
}
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const encryptedFileKey = await encryptBox(fileKey, collectionKey);
const res = await fetch(await apiURL("/collections/add-files"), {
@@ -622,7 +605,6 @@ const batchValues = <T>(
const decryptFileKeyForCollection = async (
fileID: number,
collectionID: number,
- masterKey: string,
): Promise<string> => {
const fileRecord = getEncryptedFileRecord(fileID, collectionID);
if (!fileRecord) {
@@ -636,10 +618,7 @@ const decryptFileKeyForCollection = async (
throw new Error(`Collection ${collectionID} not in cache`);
}
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
return await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
@@ -653,20 +632,14 @@ const buildEncryptedFileMoveItem = async (
fileID: number,
fromCollectionID: number,
toCollectionID: number,
- masterKey: string,
): Promise<EncryptedCollectionFileItem> => {
- const fileKey = await decryptFileKeyForCollection(
- fileID,
- fromCollectionID,
- masterKey,
- );
+ const fileKey = await decryptFileKeyForCollection(fileID, fromCollectionID);
const targetCollectionRecord = getCollectionRecord(toCollectionID);
if (!targetCollectionRecord) {
throw new Error(`Collection ${toCollectionID} not in cache`);
}
const targetCollectionKey = await decryptCollectionKey(
targetCollectionRecord,
- masterKey,
);
const encryptedFileKey = await encryptBox(fileKey, targetCollectionKey);
@@ -738,16 +711,12 @@ const createCollectionMutationDeps = () => ({
export const restoreFromTrash = async (
items: Pick<LockerItem, "id" | "collectionID">[],
targetCollectionID: number,
- masterKey: string,
): Promise<void> => {
const collectionRecord = getCollectionRecord(targetCollectionID);
if (!collectionRecord)
throw new Error(`Collection ${targetCollectionID} not in cache`);
- const collectionKey = await decryptCollectionKey(
- collectionRecord,
- masterKey,
- );
+ const collectionKey = await decryptCollectionKey(collectionRecord);
const buildRestorePayload = async (
candidateItems: Pick<LockerItem, "id" | "collectionID">[],
@@ -777,10 +746,8 @@ export const restoreFromTrash = async (
continue;
}
- const origCollectionKey = await decryptCollectionKey(
- origCollectionRecord,
- masterKey,
- );
+ const origCollectionKey =
+ await decryptCollectionKey(origCollectionRecord);
const fileKey = await decryptBox(
{
encryptedData: fileRecord.encryptedKey,
@@ -802,7 +769,7 @@ export const restoreFromTrash = async (
let { files, skippedFileIDs } = await buildRestorePayload(items);
if (files.length === 0 && skippedFileIDs.length > 0) {
- await fetchLockerTrash(masterKey);
+ await fetchLockerTrash();
({ files, skippedFileIDs } = await buildRestorePayload(items));
}
@@ -842,8 +809,8 @@ const ensureUncategorizedCollection = async (masterKey: string) => {
return ensureUncategorizedCollectionWithDeps(masterKey, {
findCollectionByType: (type) =>
findCollectionByType(type, currentUserID),
- refetchCollections: async (masterKey) => {
- await fetchLockerData(masterKey);
+ refetchCollections: async () => {
+ await fetchLockerData();
},
});
};
@@ -853,8 +820,8 @@ const ensureFavoritesCollection = async (masterKey: string) => {
return ensureFavoritesCollectionWithDeps(masterKey, {
findCollectionByType: (type) =>
findCollectionByType(type, currentUserID),
- refetchCollections: async (resolvedMasterKey) => {
- await fetchLockerData(resolvedMasterKey);
+ refetchCollections: async () => {
+ await fetchLockerData();
},
});
};
@@ -862,9 +829,8 @@ const ensureFavoritesCollection = async (masterKey: string) => {
export const renameCollection = async (
collectionID: number,
newName: string,
- masterKey: string,
): Promise<void> => {
- await renameCollectionWithDeps(collectionID, newName, masterKey, {
+ await renameCollectionWithDeps(collectionID, newName, {
getCollectionRecord,
decryptCollectionKey,
});
@@ -902,9 +868,8 @@ export const fetchCollectionSharees = async (
export const shareCollection = async (
collectionID: number,
email: string,
- masterKey: string,
): Promise<LockerCollectionParticipant[]> => {
- return shareCollectionWithDeps(collectionID, email, masterKey, {
+ return shareCollectionWithDeps(collectionID, email, {
getCollectionRecord,
decryptCollectionKey,
updateCollectionShareesInCache,
@@ -991,7 +956,6 @@ export const uploadLockerFile = async (
return uploadLockerFileWithDeps(
file,
targetCollectionIDs,
- masterKey,
{ getCollectionRecord, decryptCollectionKey, addFileToCollections },
onProgress,
);
diff --git a/web/apps/locker/tests/authenticated-session.test.ts b/web/apps/locker/tests/authenticated-session.test.ts
index 591b727234..859568717b 100644
--- a/web/apps/locker/tests/authenticated-session.test.ts
+++ b/web/apps/locker/tests/authenticated-session.test.ts
@@ -62,6 +62,9 @@ test("opens each artifact only when needed, reuses sessions, and clears both at
expect(await sessions.openAuthenticatedSession(1, "token", "key")).toBe(
locker,
);
+ expect(await sessions.ensureAuthenticatedSession()).toBe(locker);
+ expect(masterKeyFromSession).not.toHaveBeenCalled();
+ expect(openLocker).toHaveBeenCalledTimes(1);
expect(openLegacy).not.toHaveBeenCalled();
const first = sessions.authenticatedLegacySession();
@@ -83,6 +86,19 @@ test("opens each artifact only when needed, reuses sessions, and clears both at
expect(openLegacy).toHaveBeenCalledTimes(2);
});
+test("retries a failed Locker session", async () => {
+ const locker = mockSession();
+ openLocker
+ .mockRejectedValueOnce(new Error("Download failed"))
+ .mockResolvedValueOnce(locker);
+
+ await expect(sessions.ensureAuthenticatedSession()).rejects.toThrow(
+ "Download failed",
+ );
+ expect(await sessions.ensureAuthenticatedSession()).toBe(locker);
+ expect(openLocker).toHaveBeenCalledTimes(2);
+});
+
test("logout during credential lookup cannot reopen a Legacy session", async () => {
const key = Promise.withResolvers<string>();
masterKeyFromSession.mockReturnValue(key.promise);
diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.ts
index d7313bb9a7..a29404e287 100644
--- a/web/packages/wasm/locker/index.ts
+++ b/web/packages/wasm/locker/index.ts
@@ -14,6 +14,19 @@ export type { OpenSessionInput, Session } from "./pkg/ente_locker_wasm";
export const openSession = async (input: OpenSessionInput): Promise<Session> =>
(await wasm()).openSession(input);
+export const openCollectionKey = async (
+ session: Session,
+ ownerID: number,
+ encryptedKey: string,
+ keyDecryptionNonce?: string,
+) =>
+ (await wasm()).collectionsOpenKey(
+ session,
+ BigInt(ownerID),
+ encryptedKey,
+ keyDecryptionNonce,
+ );
+
export const contactsGetDiff = async (
session: Session,
wrappedRootContactKey: WrappedRootContactKey | undefined,