Skip to content

armgit / ente

Public Imported from GitHub
0

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

Swap

Manav Rathi167a81f1210f
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 0145788543..d4781a6611 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -21,7 +21,7 @@ import { Upload, type UploadTypeSelectorIntent } from "components/Upload";
import SelectedFileOptions from "components/pages/gallery/SelectedFileOptions";
import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
import { stashRedirect } from "ente-accounts/services/redirect";
-import { checkSessionValidity } from "ente-accounts/services/session";
+import { isSessionInvalid } from "ente-accounts/services/session";
import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import { NavbarBase } from "ente-base/components/Navbar";
import { CenteredRow } from "ente-base/components/containers";
@@ -32,7 +32,6 @@ import { errorDialogAttributes } from "ente-base/components/utils/dialog";
import { useIsSmallWidth } from "ente-base/components/utils/hooks";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
-import { getAuthToken } from "ente-base/local-user";
import log from "ente-base/log";
import {
clearSessionStorage,
@@ -101,7 +100,6 @@ import {
} from "ente-new/photos/services/user-details";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { FlexWrapper } from "ente-shared/components/Container";
-import { CustomError } from "ente-shared/error";
import { getData } from "ente-shared/storage/localStorage";
import {
getToken,
@@ -124,7 +122,6 @@ import {
} from "services/collectionService";
import exportService from "services/export";
import { uploadManager } from "services/upload-manager";
-import { isTokenValid } from "services/userService";
import {
GalleryContextType,
SelectedState,
@@ -548,16 +545,7 @@ const Page: React.FC = () => {
const handleSyncWithRemote = useCallback(
async (force = false, silent = false) => {
if (!navigator.onLine) return;
- if (
- !(await getAuthToken()) ||
- !(await checkSessionValidity()
- .then(({ status }) => status != "invalid")
- .catch(() => true))
- ) {
- // If we don't have an auth token, or if remote says that the
- // auth token is invalid, then show the session expired dialog.
- // Ignore other errors since we don't want to log the user out
- // on e.g. transient network issues.
+ if (await isSessionInvalid()) {
showSessionExpiredDialog();
return;
}
@@ -573,15 +561,7 @@ const Page: React.FC = () => {
const isForced = syncInProgress.current && force;
syncInProgress.current = true;
try {
- const token = getToken();
- if (!token) {
- return;
- }
- const tokenValid = await isTokenValid(token);
- if (!tokenValid) {
- throw new Error(CustomError.SESSION_EXPIRED);
- }
- !silent && showLoadingBar();
+ if (!silent) showLoadingBar();
await preCollectionAndFilesSync();
await handleFileAndCollectionSyncWithRemote();
// syncWithRemote is called with the force flag set to true before
@@ -593,16 +573,10 @@ const Page: React.FC = () => {
await postCollectionAndFilesSync();
}
} catch (e) {
- switch (e.message) {
- case CustomError.SESSION_EXPIRED:
- showSessionExpiredDialog();
- break;
- default:
- log.error("syncWithRemote failed", e);
- }
+ log.error("syncWithRemote failed", e);
} finally {
dispatch({ type: "clearUnsyncedState" });
- !silent && hideLoadingBar();
+ if (!silent) hideLoadingBar();
}
syncInProgress.current = false;
if (resync.current) {
diff --git a/web/apps/photos/src/services/userService.ts b/web/apps/photos/src/services/userService.ts
index 2665996f1d..4d7c790f4b 100644
--- a/web/apps/photos/src/services/userService.ts
+++ b/web/apps/photos/src/services/userService.ts
@@ -1,15 +1,9 @@
-import { HttpStatusCode } from "axios";
-import { putAttributes } from "ente-accounts/services/user";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import type { UserDetails } from "ente-new/photos/services/user-details";
-import { ApiError } from "ente-shared/error";
import HTTPService from "ente-shared/network/HTTPService";
-import { getData } from "ente-shared/storage/localStorage";
import { getToken } from "ente-shared/storage/localStorage/helpers";
-const HAS_SET_KEYS = "hasSetKeys";
-
export const getPublicKey = async (email: string) => {
const token = getToken();
@@ -21,44 +15,6 @@ export const getPublicKey = async (email: string) => {
return resp.data.publicKey;
};
-export const isTokenValid = async (token: string) => {
- try {
- const resp = await HTTPService.get(
- await apiURL("/users/session-validity/v2"),
- null,
- { "X-Auth-Token": token },
- );
- try {
- if (resp.data[HAS_SET_KEYS] === undefined) {
- throw Error("resp.data.hasSetKey undefined");
- }
- if (!resp.data.hasSetKeys) {
- try {
- await putAttributes(
- token,
- getData("originalKeyAttributes"),
- );
- } catch (e) {
- log.error("put attribute failed", e);
- }
- }
- } catch (e) {
- log.error("hasSetKeys not set in session validity response", e);
- }
- return true;
- } catch (e) {
- log.error("session-validity api call failed", e);
- if (
- e instanceof ApiError &&
- e.httpStatusCode === HttpStatusCode.Unauthorized
- ) {
- return false;
- } else {
- return true;
- }
- }
-};
-
export const getUserDetailsV2 = async (): Promise<UserDetails> => {
try {
const token = getToken();
diff --git a/web/packages/accounts/pages/generate.tsx b/web/packages/accounts/pages/generate.tsx
index 1c7211b9cd..776443b782 100644
--- a/web/packages/accounts/pages/generate.tsx
+++ b/web/packages/accounts/pages/generate.tsx
@@ -35,7 +35,6 @@ import { useEffect, useState } from "react";
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
- const [token, setToken] = useState<string>();
const [user, setUser] = useState<User>();
const [openRecoveryKey, setOpenRecoveryKey] = useState(false);
const [loading, setLoading] = useState(true);
@@ -59,7 +58,6 @@ const Page: React.FC = () => {
} else if (keyAttributes?.encryptedKey) {
void router.push("/credentials");
} else {
- setToken(user.token);
setLoading(false);
}
}, [router]);
@@ -72,8 +70,7 @@ const Page: React.FC = () => {
const { keyAttributes, masterKey, srpSetupAttributes } =
await generateKeyAndSRPAttributes(passphrase);
- // TODO: Refactor the code to not require this ensure
- await putAttributes(token!, keyAttributes);
+ await putAttributes(keyAttributes);
await configureSRP(srpSetupAttributes);
await generateAndSaveIntermediateKeyAttributes(
passphrase,
diff --git a/web/packages/accounts/pages/verify.tsx b/web/packages/accounts/pages/verify.tsx
index 2375ca303b..2780c04c45 100644
--- a/web/packages/accounts/pages/verify.tsx
+++ b/web/packages/accounts/pages/verify.tsx
@@ -137,11 +137,11 @@ const Page: React.FC = () => {
setData("keyAttributes", keyAttributes);
setData("originalKeyAttributes", keyAttributes);
} else {
- if (getData("originalKeyAttributes")) {
- await putAttributes(
- token!,
- getData("originalKeyAttributes"),
- );
+ const originalKeyAttributes = getData(
+ "originalKeyAttributes",
+ );
+ if (originalKeyAttributes) {
+ await putAttributes(originalKeyAttributes);
}
if (getData("srpSetupAttributes")) {
const srpSetupAttributes: SRPSetupAttributes =
diff --git a/web/packages/accounts/services/session.ts b/web/packages/accounts/services/session.ts
index 8b6d3e29d3..54f2dff2ac 100644
--- a/web/packages/accounts/services/session.ts
+++ b/web/packages/accounts/services/session.ts
@@ -1,9 +1,5 @@
import { authenticatedRequestHeaders, HTTPError } from "ente-base/http";
-import {
- ensureAuthToken,
- ensureLocalUser,
- getAuthToken,
-} from "ente-base/local-user";
+import { ensureLocalUser, getAuthToken } from "ente-base/local-user";
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import { getData } from "ente-shared/storage/localStorage";
@@ -12,7 +8,7 @@ import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
import type { SRPAttributes } from "./srp-remote";
import { getSRPAttributes } from "./srp-remote";
-import { putAttributes } from "./user";
+import { putAttributes, RemoteKeyAttributes } from "./user";
type SessionValidity =
| { status: "invalid" }
@@ -25,12 +21,7 @@ type SessionValidity =
const SessionValidityResponse = z.object({
hasSetKeys: z.boolean(),
- // TODO: Update me when we have a zod type for KeyAttributes.
- keyAttributes: z
- .object({})
- .passthrough()
- .nullish()
- .transform(nullToUndefined),
+ keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
});
/**
@@ -92,11 +83,7 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
// deployments).
const { keyAttributes } = SessionValidityResponse.parse(await res.json());
if (keyAttributes) {
- // Assume it is a `KeyAttributes`.
- //
- // Enhancement: Convert this to a zod validation.
- // TODO: Update me when we have a zod type for KeyAttributes.
- const remoteKeyAttributes = keyAttributes as KeyAttributes;
+ const remoteKeyAttributes = keyAttributes satisfies KeyAttributes;
// We should have these values locally if we reach here.
const email = ensureLocalUser().email;
@@ -149,8 +136,9 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
* ends in logging the user out, and we don't want to log the user out on on
* e.g. transient network issues.
*/
-export const isAuthTokenInvalid = async (): Promise<boolean> => {
- if (!(await getAuthToken())) {
+export const isSessionInvalid = async (): Promise<boolean> => {
+ const token = await getAuthToken();
+ if (!token) {
return true; /* No saved token, session is invalid */
}
@@ -165,10 +153,9 @@ export const isAuthTokenInvalid = async (): Promise<boolean> => {
const { hasSetKeys } = SessionValidityResponse.parse(await res.json());
if (!hasSetKeys) {
- await putAttributes(
- await ensureAuthToken(),
- getData("originalKeyAttributes"),
- );
+ const originalKeyAttributes = getData("originalKeyAttributes");
+ if (originalKeyAttributes)
+ await putAttributes(originalKeyAttributes);
}
} catch (e) {
log.warn("Failed to check session validity", e);
diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.ts
index e37e66a189..3033366e49 100644
--- a/web/packages/accounts/services/user.ts
+++ b/web/packages/accounts/services/user.ts
@@ -127,7 +127,7 @@ export const verifyEmail = async (
/**
* Zod schema for {@link KeyAttributes}.
*/
-const RemoteKeyAttributes = z.object({
+export const RemoteKeyAttributes = z.object({
kekSalt: z.string(),
encryptedKey: z.string(),
keyDecryptionNonce: z.string(),
@@ -195,17 +195,17 @@ export type TwoFactorAuthorizationResponse = z.infer<
typeof TwoFactorAuthorizationResponse
>;
-export const putAttributes = async (
- token: string,
- keyAttributes: KeyAttributes,
-) =>
- HTTPService.put(
- await apiURL("/users/attributes"),
- { keyAttributes },
- undefined,
- { "X-Auth-Token": token },
+/**
+ * Update or set the user's {@link KeyAttributes} on remote.
+ */
+export const putAttributes = async (keyAttributes: KeyAttributes) =>
+ ensureOk(
+ await fetch(await apiURL("/users/attributes"), {
+ method: "PUT",
+ headers: await authenticatedRequestHeaders(),
+ body: JSON.stringify({ keyAttributes }),
+ }),
);
-
/**
* Log the user out on remote, if possible and needed.
*/
diff --git a/web/packages/shared/storage/localStorage/index.ts b/web/packages/shared/storage/localStorage/index.ts
index 0e167615a0..ec8491e04d 100644
--- a/web/packages/shared/storage/localStorage/index.ts
+++ b/web/packages/shared/storage/localStorage/index.ts
@@ -65,7 +65,7 @@ export const setLSUser = async (user: object) => {
export const migrateKVToken = async (user: unknown) => {
// Throw an error if the data is in local storage but not in IndexedDB. This
// is a pre-cursor to inlining this code.
- // TODO(REL): Remove this sanity check after a few days.
+ // TODO: Remove this sanity check eventually when this code is revisited.
const oldLSUser = getData("user");
const wasMissing =
oldLSUser &&