Skip to content

armgit / ente

Public Imported from GitHub
0

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

Rework

Manav Rathi46dc71ebd228
diff --git a/web/apps/photos/src/pages/index.tsx b/web/apps/photos/src/pages/index.tsx
index 3ac7b0d771..d452129a18 100644
--- a/web/apps/photos/src/pages/index.tsx
+++ b/web/apps/photos/src/pages/index.tsx
@@ -9,9 +9,10 @@ import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton"
import { useBaseContext } from "ente-base/context";
import { albumsAppOrigin, customAPIHost } from "ente-base/origins";
import {
- haveAuthenticatedSession,
+ masterKeyFromSession,
updateSessionFromElectronSafeStorageIfNeeded,
} from "ente-base/session";
+import { savedAuthToken } from "ente-base/token";
import { canAccessIndexedDB } from "ente-gallery/services/files-db";
import { DevSettings } from "ente-new/photos/components/DevSettings";
import { t } from "i18next";
@@ -55,7 +56,10 @@ const Page: React.FC = () => {
});
} else {
await updateSessionFromElectronSafeStorageIfNeeded();
- if (await haveAuthenticatedSession()) {
+ if (
+ (await masterKeyFromSession()) &&
+ (await savedAuthToken())
+ ) {
await router.push("/gallery");
} else if (savedPartialLocalUser()?.email) {
await router.push("/verify");
diff --git a/web/packages/accounts/pages/credentials.tsx b/web/packages/accounts/pages/credentials.tsx
index b94dcfcb41..66cbd2680a 100644
--- a/web/packages/accounts/pages/credentials.tsx
+++ b/web/packages/accounts/pages/credentials.tsx
@@ -39,10 +39,10 @@ import {
verifySRP,
} from "ente-accounts/services/srp";
import {
+ decryptAndStoreToken,
generateAndSaveInteractiveKeyAttributes,
type KeyAttributes,
} from "ente-accounts/services/user";
-import { decryptAndStoreToken } from "ente-accounts/utils/helpers";
import { LinkButton } from "ente-base/components/LinkButton";
import { LoadingIndicator } from "ente-base/components/loaders";
import { useBaseContext } from "ente-base/context";
@@ -51,13 +51,13 @@ import { isDevBuild } from "ente-base/env";
import { clearLocalStorage } from "ente-base/local-storage";
import log from "ente-base/log";
import {
- haveAuthenticatedSession,
+ masterKeyFromSession,
saveMasterKeyInSessionAndSafeStore,
stashKeyEncryptionKeyInSessionStore,
unstashKeyEncryptionKeyFromSession,
updateSessionFromElectronSafeStorageIfNeeded,
} from "ente-base/session";
-import { saveAuthToken } from "ente-base/token";
+import { saveAuthToken, savedAuthToken } from "ente-base/token";
import { t } from "i18next";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
@@ -166,7 +166,7 @@ const Page: React.FC = () => {
}
await updateSessionFromElectronSafeStorageIfNeeded();
- if (await haveAuthenticatedSession()) {
+ if ((await masterKeyFromSession()) && (await savedAuthToken())) {
void router.push(appHomeRoute);
return;
}
@@ -177,7 +177,8 @@ const Page: React.FC = () => {
const kek = await unstashKeyEncryptionKeyFromSession();
const keyAttributes = savedKeyAttributes();
- // Refreshing an existing tab, or desktop app.
+ // Refreshing an existing tab, or desktop app, or only the token
+ // needs to decrypted and set.
if (kek && keyAttributes) {
const masterKey = await decryptBox(
{
diff --git a/web/packages/accounts/pages/passkeys/finish.tsx b/web/packages/accounts/pages/passkeys/finish.tsx
index b8fd76e89c..6d25ba5ba5 100644
--- a/web/packages/accounts/pages/passkeys/finish.tsx
+++ b/web/packages/accounts/pages/passkeys/finish.tsx
@@ -1,10 +1,12 @@
import {
- getData,
saveKeyAttributes,
- setLSUser,
+ updateSavedLocalUser,
} from "ente-accounts/services/accounts-db";
import { unstashRedirect } from "ente-accounts/services/redirect";
-import { TwoFactorAuthorizationResponse } from "ente-accounts/services/user";
+import {
+ resetSavedLocalUserTokens,
+ TwoFactorAuthorizationResponse,
+} from "ente-accounts/services/user";
import { LoadingIndicator } from "ente-base/components/loaders";
import { fromB64URLSafeNoPadding } from "ente-base/crypto";
import log from "ente-base/log";
@@ -95,10 +97,8 @@ const saveQueryCredentialsAndNavigateTo = async (
const { id, keyAttributes, encryptedToken } = decodedResponse;
- // TODO: See: [Note: empty token?]
- const token = undefined;
-
- await setLSUser({ ...getData("user"), token, encryptedToken, id });
+ await resetSavedLocalUserTokens(id, encryptedToken);
+ updateSavedLocalUser({ passkeySessionID: undefined });
saveKeyAttributes(keyAttributes);
return unstashRedirect() ?? "/credentials";
diff --git a/web/packages/accounts/pages/two-factor/verify.tsx b/web/packages/accounts/pages/two-factor/verify.tsx
index c11a1238a7..f56c186f8f 100644
--- a/web/packages/accounts/pages/two-factor/verify.tsx
+++ b/web/packages/accounts/pages/two-factor/verify.tsx
@@ -1,11 +1,13 @@
import { Verify2FACodeForm } from "ente-accounts/components/Verify2FACodeForm";
import {
- getData,
savedPartialLocalUser,
saveKeyAttributes,
- setLSUser,
+ updateSavedLocalUser,
} from "ente-accounts/services/accounts-db";
-import { verifyTwoFactor } from "ente-accounts/services/user";
+import {
+ resetSavedLocalUserTokens,
+ verifyTwoFactor,
+} from "ente-accounts/services/user";
import { LinkButton } from "ente-base/components/LinkButton";
import { useBaseContext } from "ente-base/context";
import { isHTTPErrorWithStatus } from "ente-base/http";
@@ -50,17 +52,8 @@ const Page: React.FC = () => {
try {
const { keyAttributes, encryptedToken, id } =
await verifyTwoFactor(otp, twoFactorSessionID);
- await setLSUser({
- ...getData("user"),
- id,
- // TODO: [Note: empty token?]
- //
- // The original code was parsing an token which is never going
- // to be present in the response, so effectively was always
- // setting token to undefined. So this works, but is it needed?
- token: undefined,
- encryptedToken,
- });
+ await resetSavedLocalUserTokens(id, encryptedToken);
+ updateSavedLocalUser({ twoFactorSessionID: undefined });
saveKeyAttributes(keyAttributes);
await router.push(unstashRedirect() ?? "/credentials");
} catch (e) {
diff --git a/web/packages/accounts/services/passkey.ts b/web/packages/accounts/services/passkey.ts
index 52f39ab7ec..b3cef840a1 100644
--- a/web/packages/accounts/services/passkey.ts
+++ b/web/packages/accounts/services/passkey.ts
@@ -1,9 +1,11 @@
import {
- getData,
saveKeyAttributes,
- setLSUser,
+ updateSavedLocalUser,
} from "ente-accounts/services/accounts-db";
-import { TwoFactorAuthorizationResponse } from "ente-accounts/services/user";
+import {
+ resetSavedLocalUserTokens,
+ TwoFactorAuthorizationResponse,
+} from "ente-accounts/services/user";
import { clientPackageName, isDesktop } from "ente-base/app";
import { encryptBox, generateKey } from "ente-base/crypto";
import {
@@ -260,7 +262,8 @@ export const saveCredentialsAndNavigateTo = async (
const { id, encryptedToken, keyAttributes } = response;
- await setLSUser({ ...getData("user"), encryptedToken, id });
+ await resetSavedLocalUserTokens(id, encryptedToken);
+ updateSavedLocalUser({ passkeySessionID: undefined });
saveKeyAttributes(keyAttributes);
return unstashRedirect() ?? "/credentials";
diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.ts
index 23ecf7b599..1729bce23b 100644
--- a/web/packages/accounts/services/user.ts
+++ b/web/packages/accounts/services/user.ts
@@ -1,12 +1,13 @@
import {
getData,
+ replaceSavedLocalUser,
savedKeyAttributes,
savedLocalUser,
+ savedPartialLocalUser,
saveKeyAttributes,
saveSRPAttributes,
setLSUser,
updateSavedLocalUser,
- type PartialLocalUser,
} from "ente-accounts/services/accounts-db";
import {
generateSRPSetupAttributes,
@@ -15,12 +16,14 @@ import {
type UpdatedKeyAttr,
} from "ente-accounts/services/srp";
import {
+ boxSealOpenBytes,
decryptBox,
deriveInteractiveKey,
deriveSensitiveKey,
encryptBox,
generateKey,
generateKeyPair,
+ toB64URLSafe,
} from "ente-base/crypto";
import { isDevBuild } from "ente-base/env";
import {
@@ -33,15 +36,12 @@ import {
ensureMasterKeyFromSession,
saveMasterKeyInSessionAndSafeStore,
} from "ente-base/session";
-import { savedAuthToken } from "ente-base/token";
+import { removeAuthToken, savedAuthToken } from "ente-base/token";
import { ensure } from "ente-utils/ensure";
import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod/v4";
import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";
-// TODO(RE): Temporary re-export
-export type { PartialLocalUser };
-
/**
* The locally persisted data we have about the user after they've logged in.
*
@@ -738,6 +738,74 @@ export const changePassword = async (password: string) => {
}
};
+/**
+ * Update the {@link encryptedToken} present in the saved partial local user.
+ *
+ * This function removes the {@link token}, if any, present in the saved partial
+ * local user and sets the provided {@link encryptedToken}.
+ *
+ * It is expected that the code will subsequently redirect to "/credentials",
+ * which should call {@link decryptAndStoreToken} which will decrypt the newly
+ * set {@link encryptedToken} and write out the decrypted value as the
+ * {@link token} in the saved local user.
+ *
+ * @param userID The ID of the user whose token this is. This is used as a
+ * sanity check to ensure that the we do not overwrite saved partial local user
+ * data for a different user.
+ *
+ * @param encryptedToken The newly obtained base64 encoded encrypted token from
+ * remote (e.g. as a result of the user verifying their email).
+ */
+export const resetSavedLocalUserTokens = async (
+ userID: number,
+ encryptedToken: string,
+) => {
+ const user = savedPartialLocalUser();
+ if (user?.id && user.id != userID) {
+ throw new Error(`User ID mismatch (${user.id}, ${userID})`);
+ }
+ replaceSavedLocalUser({ ...user, token: undefined, encryptedToken });
+ return removeAuthToken();
+};
+
+/**
+ * Decrypt the user's {@link encryptedToken}, if present, and use it to update
+ * both the locally saved user and the KV DB.
+ *
+ * @param keyAttributes The user's key attributes.
+ *
+ * @param masterKey The user's master key (base64 encoded).
+ */
+export const decryptAndStoreToken = async (
+ keyAttributes: KeyAttributes,
+ masterKey: string,
+) => {
+ const user = getData("user");
+ const { encryptedToken } = user;
+
+ if (encryptedToken && encryptedToken.length > 0) {
+ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
+ keyAttributes;
+ const privateKey = await decryptBox(
+ {
+ encryptedData: encryptedSecretKey,
+ nonce: secretKeyDecryptionNonce,
+ },
+ masterKey,
+ );
+
+ const decryptedToken = await toB64URLSafe(
+ await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),
+ );
+
+ await setLSUser({
+ ...user,
+ token: decryptedToken,
+ encryptedToken: null,
+ });
+ }
+};
+
const TwoFactorSecret = z.object({
/**
* The 2FA secret code.
@@ -958,12 +1026,11 @@ export const recoverTwoFactorFinish = async (
sessionID,
twoFactorSecret,
);
- await setLSUser({
- ...getData("user"),
- id,
+ await resetSavedLocalUserTokens(id, encryptedToken);
+ updateSavedLocalUser({
isTwoFactorEnabled: undefined,
- encryptedToken,
- token: undefined,
+ twoFactorSessionID: undefined,
+ passkeySessionID: undefined,
});
saveKeyAttributes(keyAttributes);
};
diff --git a/web/packages/accounts/utils/helpers.ts b/web/packages/accounts/utils/helpers.ts
deleted file mode 100644
index 9a980587f4..0000000000
--- a/web/packages/accounts/utils/helpers.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-// TODO: Audit this file, this can be better. e.g. do we need the Object.assign?
-
-import { getData, setLSUser } from "ente-accounts/services/accounts-db";
-import { type KeyAttributes } from "ente-accounts/services/user";
-import { boxSealOpenBytes, decryptBox, toB64URLSafe } from "ente-base/crypto";
-
-export async function decryptAndStoreToken(
- keyAttributes: KeyAttributes,
- masterKey: string,
-) {
- const user = getData("user");
- const { encryptedToken } = user;
-
- if (encryptedToken && encryptedToken.length > 0) {
- const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
- keyAttributes;
- const privateKey = await decryptBox(
- {
- encryptedData: encryptedSecretKey,
- nonce: secretKeyDecryptionNonce,
- },
- masterKey,
- );
-
- const decryptedToken = await toB64URLSafe(
- await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),
- );
-
- await setLSUser({
- ...user,
- token: decryptedToken,
- encryptedToken: null,
- });
- }
-}
diff --git a/web/packages/base/session.ts b/web/packages/base/session.ts
index 1486c31952..0d94ae0472 100644
--- a/web/packages/base/session.ts
+++ b/web/packages/base/session.ts
@@ -154,13 +154,6 @@ export const updateSessionFromElectronSafeStorageIfNeeded = async () => {
}
};
-/**
- * Return true if we both have a usable user's master key in session storage,
- * and their auth token in KV DB.
- */
-export const haveAuthenticatedSession = async () =>
- (await masterKeyFromSession()) && !!(await savedAuthToken());
-
/**
* Save the user's encypted key encryption key ("key") in session store
* temporarily, until we get back here after completing the second factor.
diff --git a/web/packages/base/token.ts b/web/packages/base/token.ts
index 87e6626118..109322b339 100644
--- a/web/packages/base/token.ts
+++ b/web/packages/base/token.ts
@@ -1,4 +1,4 @@
-import { getKVS, setKV } from "./kv";
+import { getKVS, removeKV, setKV } from "./kv";
/**
* Return the user's auth token, or throw an error.
@@ -33,3 +33,10 @@ export const savedAuthToken = () => getKVS("token");
* This is the setter corresponding to {@link savedAuthToken}.
*/
export const saveAuthToken = (token: string) => setKV("token", token);
+
+/**
+ * Remove the user's auth token from KV DB.
+ *
+ * See {@link saveAuthToken}.
+ */
+export const removeAuthToken = () => removeKV("token");