Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Prune comments in the media and accounts packages

Manav Rathi5ef5a59f6c51
diff --git a/web/packages/accounts-rs/components/CodeBlock.tsx b/web/packages/accounts-rs/components/CodeBlock.tsx
index 63fd696064..b4b08b34d4 100644
--- a/web/packages/accounts-rs/components/CodeBlock.tsx
+++ b/web/packages/accounts-rs/components/CodeBlock.tsx
@@ -8,18 +8,9 @@ import { t } from "i18next";
import React from "react";
interface CodeBlockProps {
- /**
- * The code (an arbitrary string) to show.
- *
- * If not present, then an activity indicator will be shown.
- */
code: string | undefined;
}
-/**
- * A component that shows a "code" (e.g. the user's recovery key, or a 2FA setup
- * code), alongwith a button to copy it.
- */
export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
if (!code) {
return (
@@ -42,7 +33,6 @@ export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
padding: "16px 44px 16px 16px",
wordBreak: "break-word",
color: "accent.contrastText",
- // Increase the line height from the body default.
lineHeight: 1.5,
}}
>
@@ -56,9 +46,6 @@ export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
};
interface CopyButtonProps {
- /**
- * The code to copy when the button is clicked.
- */
code: string;
}
diff --git a/web/packages/accounts-rs/components/LoginComponents.tsx b/web/packages/accounts-rs/components/LoginComponents.tsx
index e56ba359f2..d24efbf516 100644
--- a/web/packages/accounts-rs/components/LoginComponents.tsx
+++ b/web/packages/accounts-rs/components/LoginComponents.tsx
@@ -20,15 +20,6 @@ import {
} from "./layouts/centered-paper";
interface HeaderCaptionProps {
- /**
- * If specified, then a caption to display below the title (which is
- * expected to be passed as the `children`).
- *
- * The components which use the {@link HeaderCaptionProps} that they'll have
- * the same height irrespective of whether or not the caption is provided.
- * This allows us to use this component to get a similar look across various
- * pages in the login flow (some of which have a caption, some which not).
- */
caption?: string;
}
@@ -87,13 +78,9 @@ export const AccountsPageFooterWithHost: React.FC<React.PropsWithChildren> = ({
};
interface VerifyingPasskeyProps {
- /** ID of the current passkey verification session. */
passkeySessionID: string;
- /** The email of the user whose passkey we're verifying. */
email: string | undefined;
- /** Called when the user wants to redirect again. */
onRetry: () => void;
- /** Perform the (possibly app specific) logout sequence. */
logout: () => void;
showMiniDialog: (attrs: MiniDialogAttributes) => void;
}
diff --git a/web/packages/accounts-rs/components/LoginContents.tsx b/web/packages/accounts-rs/components/LoginContents.tsx
index aa29f820d5..dd4f8be92f 100644
--- a/web/packages/accounts-rs/components/LoginContents.tsx
+++ b/web/packages/accounts-rs/components/LoginContents.tsx
@@ -20,22 +20,10 @@ import { z } from "zod";
import { AccountsPageTitleWithCaption } from "./LoginComponents";
interface LoginContentsProps {
- /**
- * Reactive value of {@link customAPIHost}.
- */
host: string | undefined;
- /**
- * Called when the user clicks the signup option instead.
- */
onSignUp: () => void;
}
-/**
- * A contents of the "login" form.
- *
- * It is used both on the "/login" page, and as the embedded login form on the
- * "/" page where the user can toggle between the signup and login forms inline.
- */
export const LoginContents: React.FC<LoginContentsProps> = ({
onSignUp,
host,
@@ -45,7 +33,6 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
const isEnsu = appName === "ensu";
useEffect(() => {
- // Check if we're in a join album context
const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
setIsJoinAlbumContext(!!joinAlbumContext);
}, []);
@@ -136,7 +123,6 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
margin="normal"
disabled={formik.isSubmitting}
error={!!formik.errors.email}
- // See: [Note: Use space as default TextField helperText]
helperText={formik.errors.email ?? " "}
/>
<Input sx={{ display: "none" }} type="password" value="" />
@@ -164,7 +150,7 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
variant="mini"
sx={{ color: "text.faint", minHeight: "16px" }}
>
- {host ?? "" /* prevent layout shift with a minHeight */}
+ {host ?? ""}
</Typography>
</Stack>
</AccountsPageFooter>
diff --git a/web/packages/accounts-rs/components/NewPasswordForm.tsx b/web/packages/accounts-rs/components/NewPasswordForm.tsx
index 36f471c64a..d6ed3dc3cd 100644
--- a/web/packages/accounts-rs/components/NewPasswordForm.tsx
+++ b/web/packages/accounts-rs/components/NewPasswordForm.tsx
@@ -10,41 +10,14 @@ import { Trans } from "react-i18next";
import { PasswordStrengthHint } from "./PasswordStrength";
export interface NewPasswordFormProps {
- /**
- * The email of the user whose password we are setting.
- *
- * This is used to show a hidden input field of type email (and the provided
- * value) to aid password managers to detect and save the new password,
- * associating it with the user's email.
- */
userEmail: string;
- /**
- * The title of the form's submit button.
- */
submitButtonTitle: string;
- /**
- * Submission handler. A callback invoked when the submit button is pressed.
- *
- * @param password The new password entered by the user. The form will first
- * check that both of the passwords entered by the user match, and that the
- * password is not too weak.
- *
- * @param setPasswordsFieldError A function that can be called to show an
- * error message below the password fields.
- */
onSubmit: (
password: string,
setPasswordsFieldError: (message: string) => void,
) => Promise<void>;
}
-/**
- * A form showing two password input fields, a password strength indicator, and
- * a submit button.
- *
- * This form can be used both for the initial setup of the password, and for
- * later changing it.
- */
export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
userEmail,
submitButtonTitle,
@@ -93,6 +66,8 @@ export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
{t("pick_password_hint")}
</Typography>
+ {/* This hidden email input helps password managers associate the
+ new password with the user's email. */}
<Input
sx={{ display: "none" }}
name="email"
@@ -129,7 +104,6 @@ export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
value={formik.values.confirmPassword}
onChange={formik.handleChange}
error={!!formik.errors.confirmPassword}
- // See: [Note: Use space as default TextField helperText]
helperText={formik.errors.confirmPassword ?? " "}
disabled={formik.isSubmitting}
fullWidth
diff --git a/web/packages/accounts-rs/components/RecoveryKey.tsx b/web/packages/accounts-rs/components/RecoveryKey.tsx
index 11211a14bf..2cc0f9a5ae 100644
--- a/web/packages/accounts-rs/components/RecoveryKey.tsx
+++ b/web/packages/accounts-rs/components/RecoveryKey.tsx
@@ -64,12 +64,9 @@ export const RecoveryKey: React.FC<RecoveryKeyProps> = ({
fullScreen={fullScreen}
open={open}
onClose={onClose}
- // [Note: maxWidth "xs" on MUI dialogs]
- //
- // While logically the "xs" breakpoint doesn't make sense as a
- // maxWidth value (since as a breakpoint it's value is 0), in
- // practice MUI has hardcoded its value to a reasonable 444px.
- // https://github.com/mui/material-ui/issues/34646.
+ // MUI hardcodes the dialog maxWidth for "xs" to 444px, even though
+ // the "xs" breakpoint itself is 0.
+ // https://github.com/mui/material-ui/issues/34646
maxWidth="xs"
fullWidth
>
diff --git a/web/packages/accounts-rs/components/SecondFactorChoice.tsx b/web/packages/accounts-rs/components/SecondFactorChoice.tsx
index 251db57014..63445b77f4 100644
--- a/web/packages/accounts-rs/components/SecondFactorChoice.tsx
+++ b/web/packages/accounts-rs/components/SecondFactorChoice.tsx
@@ -7,18 +7,9 @@ import React from "react";
export type SecondFactorType = "totp" | "passkey";
type SecondFactorChoiceProps = ModalVisibilityProps & {
- /**
- * Callback invoked with the selected choice.
- *
- * The dialog will automatically be closed before this callback is invoked.
- */
onSelect: (factor: SecondFactorType) => void;
};
-/**
- * A {@link Dialog} that allow the user to choose which second factor they'd
- * like to verify during login.
- */
export const SecondFactorChoice: React.FC<SecondFactorChoiceProps> = ({
open,
onClose,
diff --git a/web/packages/accounts-rs/components/SignUpContents.tsx b/web/packages/accounts-rs/components/SignUpContents.tsx
index 47793ef19f..607c43798c 100644
--- a/web/packages/accounts-rs/components/SignUpContents.tsx
+++ b/web/packages/accounts-rs/components/SignUpContents.tsx
@@ -50,18 +50,10 @@ import {
interface SignUpContentsProps {
router: NextRouter;
- /** Called when the user clicks the login option instead. */
onLogin: () => void;
- /** Reactive value of {@link customAPIHost}. */
host: string | undefined;
}
-/**
- * A contents of the "signup" form.
- *
- * It is used both on the "/signup" page itself, and as a subcomponent of the
- * "/" page where the user can toggle between the signup and login forms inline.
- */
export const SignUpContents: React.FC<SignUpContentsProps> = ({
router,
onLogin,
@@ -71,7 +63,6 @@ export const SignUpContents: React.FC<SignUpContentsProps> = ({
const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);
useEffect(() => {
- // Check if we're in a join album context
const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
setIsJoinAlbumContext(!!joinAlbumContext);
}, []);
@@ -312,8 +303,8 @@ export const SignUpContents: React.FC<SignUpContentsProps> = ({
mt: 1,
textAlign: "center",
color: "text.muted",
- // Prevent layout shift by using a minHeight equal to the
- // lineHeight of the eventual content that'll be shown.
+ // The minHeight, equal to the lineHeight of the eventual
+ // content, prevents layout shift.
minHeight: theme.typography.small.lineHeight,
})}
>
diff --git a/web/packages/accounts-rs/components/Verify2FACodeForm.tsx b/web/packages/accounts-rs/components/Verify2FACodeForm.tsx
index ef412f0469..60800c5997 100644
--- a/web/packages/accounts-rs/components/Verify2FACodeForm.tsx
+++ b/web/packages/accounts-rs/components/Verify2FACodeForm.tsx
@@ -8,28 +8,10 @@ import React, { useEffect, useState } from "react";
import OtpInput from "react-otp-input";
interface Verify2FACodeFormProps {
- /**
- * Called when the user submits the OTP.
- *
- * The submission can happen in two ways:
- * 1. The fill-in all the required 6 digits, or
- * 2. They press the "Enable" button.
- *
- * The form will stay in a submitting state until this callback returns.
- *
- * @param otp The OTP that the user entered.
- */
onSubmit: (otp: string) => Promise<void>;
- /**
- * The label for the submit button.
- */
submitButtonText: string;
}
-/**
- * A form that can be used to ask the user to fill in a 6 digit OTP that their
- * authenticator app is providing them with.
- */
export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({
onSubmit,
submitButtonText,
@@ -50,7 +32,9 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({
onSubmit: async ({ otp }, { setFieldError, resetForm }) => {
try {
await onSubmit(otp);
- resetForm(); // Prevent resubmission via the useEffect.
+ // Reset the form, otherwise the auto-submit effect below
+ // resubmits.
+ resetForm();
} catch (e) {
log.error("Failed to submit 2FA code", e);
resetForm();
diff --git a/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx b/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx
index 3c21af031d..f0937352e9 100644
--- a/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx
+++ b/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx
@@ -13,75 +13,14 @@ import { t } from "i18next";
import { useCallback, useState } from "react";
export interface VerifyMasterPasswordFormProps {
- /**
- * The email of the user whose password we're trying to verify.
- */
userEmail: string;
- /**
- * The user's SRP attributes.
- *
- * The SRP attributes are used to derive the KEK from the user's password.
- * If they are not present, the {@link keyAttributes} will be used instead.
- *
- * At least one of {@link srpAttributes} and {@link keyAttributes} must be
- * present, otherwise the verification will fail.
- */
srpAttributes?: SRPAttributes;
- /**
- * The user's key attributes.
- *
- * If they are present, they are used to derive the KEK from the user's
- * password when {@link srpAttributes} are not present. This is the case
- * when the user has already logged in (or signed up) on this client before,
- * and is now doing a reauthentication.
- *
- * If they are not present, then {@link getKeyAttributes} must be present
- * and will be used to obtain the user's key attributes. This is the case
- * when the user is logging into a new client.
- */
keyAttributes: KeyAttributes | undefined;
- /**
- * A callback invoked when the form wants to get {@link KeyAttributes}.
- *
- * It is only provided during the login flow, where we do not have
- * {@link keyAttributes} already available for the user. In case the form is
- * used for reauthenticating the user after they've already logged in, then
- * this function will not be provided.
- *
- * @returns The user's key attributes obtained from remote, or
- * "redirecting-second-factor" if the user has an additional second factor
- * verification required and the app is redirecting there.
- *
- * @throws A Error with message
- * {@link srpVerificationUnauthorizedErrorMessage} to signal that either
- * that the password is incorrect, or no account with the provided email
- * exists.
- */
getKeyAttributes?: (
srpAttributes: SRPAttributes,
kek: string,
) => Promise<KeyAttributes | "redirecting-second-factor" | undefined>;
- /**
- * The title of the submit button on the form.
- */
submitButtonTitle: string;
- /**
- * The callback invoked with the verified password, and all the other
- * auxillary information that was ascertained when verifying it.
- *
- * @param key The user's master key obtained after decrypting it by using
- * the KEK derived from their password.
- *
- * @param kek The key used for encrypting the user's master key.
- *
- * @param keyAttributes The user's key attributes (either those that we
- * started with, or those that we fetched on the way using
- * {@link getKeyAttributes}).
- *
- * @param password The plaintext password. This can be used during login to
- * derive another encrypted key using interactive mem/ops limits for faster
- * reauthentication after the initial login.
- */
onVerify: (
key: string,
kek: string,
@@ -90,15 +29,6 @@ export interface VerifyMasterPasswordFormProps {
) => void;
}
-/**
- * A form with a text field that can be used to ask the user to verify their
- * password.
- *
- * We use it both during the initial authentication (the "/credentials" page,
- * shown when logging in, or reopening the web app in a new tab), and when the
- * user is trying to perform a sensitive action when already logged in and
- * having a session (the {@link AuthenticateUser} component).
- */
export const VerifyMasterPasswordForm: React.FC<
VerifyMasterPasswordFormProps
> = ({
@@ -173,8 +103,6 @@ export const VerifyMasterPasswordForm: React.FC<
try {
const result = await getKeyAttributes(srpAttributes, kek);
if (result == "redirecting-second-factor") {
- // Two factor enabled, user has been redirected to the
- // corresponding second factor verification page.
return;
} else {
keyAttributes = result;
diff --git a/web/packages/accounts-rs/components/layouts/centered-paper.tsx b/web/packages/accounts-rs/components/layouts/centered-paper.tsx
index 521707f864..712fedc2b7 100644
--- a/web/packages/accounts-rs/components/layouts/centered-paper.tsx
+++ b/web/packages/accounts-rs/components/layouts/centered-paper.tsx
@@ -3,19 +3,6 @@ import { CenteredFill } from "ente-base/components/containers";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { NavbarBase } from "ente-base/components/Navbar";
-/**
- * An ad-hoc component that abstracts the layout common to many of the pages
- * exported by the the accounts package.
- *
- * The layout is roughly:
- * - Set height to 100vh
- * - An app bar at the top
- * - Center a {@link Paper} in the rest of the space.
- * - The children passed to this component go within this {@link Paper}.
- *
- * {@link AccountsPageTitle} and {@link AccountsPageFooter} are meant to be used
- * in tandem with, as children of, {@link AccountsPageContents}.
- */
export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({
children,
}) => (
@@ -77,9 +64,7 @@ export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({
direction="row"
sx={{
mx: "4px",
- // Put the items to the side,
justifyContent: "space-between",
- // Unless there is just one, in which case center it.
"& :only-child": { marginInline: "auto" },
}}
>
diff --git a/web/packages/accounts-rs/components/utils/dialog.ts b/web/packages/accounts-rs/components/utils/dialog.ts
index 333d06a509..52583614cb 100644
--- a/web/packages/accounts-rs/components/utils/dialog.ts
+++ b/web/packages/accounts-rs/components/utils/dialog.ts
@@ -1,15 +1,6 @@
import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import { t } from "i18next";
-/**
- * {@link MiniDialogAttributes} for showing asking the user to login again when
- * their session has expired.
- *
- * There is one button, which allows them to logout.
- *
- * @param onLogin Called when the user presses the "Login" button on the error
- * dialog.
- */
export const sessionExpiredDialogAttributes = (
onLogin: () => void,
): MiniDialogAttributes => ({
diff --git a/web/packages/accounts-rs/components/utils/second-factor-choice.ts b/web/packages/accounts-rs/components/utils/second-factor-choice.ts
index d908018cc7..5abfb28a30 100644
--- a/web/packages/accounts-rs/components/utils/second-factor-choice.ts
+++ b/web/packages/accounts-rs/components/utils/second-factor-choice.ts
@@ -1,22 +1,11 @@
-/**
- * @file This code is conceputally related to `SecondFactorChoice.tsx`, but
- * needs to be in a separate file to allow fast refresh.
- */
+// This hook is in a separate file from SecondFactorChoice.tsx so that fast
+// refresh keeps working.
import type { EmailOrSRPVerificationResponse } from "ente-accounts-rs/services/user";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { useCallback, useMemo, useRef } from "react";
import type { SecondFactorType } from "../SecondFactorChoice";
-/**
- * A convenience hook for keeping track of the state and logic that is needed
- * after password verification to determine which second factor (if any) we
- * should be asking the user for.
- *
- * This is a rather ad-hoc abstraction meant to be used in a very specific way;
- * the only intent is to reduce code duplication between the two pages that need
- * this choice.
- */
export const useSecondFactorChoiceIfNeeded = () => {
const resolveSecondFactorChoice = useRef<
| ((value: SecondFactorType | PromiseLike<SecondFactorType>) => void)
@@ -46,18 +35,13 @@ export const useSecondFactorChoiceIfNeeded = () => {
passkeySessionID: _passkeySessionID,
} = response;
- // When the user has both TOTP and pk set as the second factor,
- // we'll get two session IDs. For backward compat, the TOTP session
- // ID will be in a V2 attribute during a transient migration period.
- //
- // Note the use of || instead of ?? since _twoFactorSessionIDV1 will
- // be an empty string, not undefined, if it is unset.
+ // Use || and not ?? since an unset _twoFactorSessionIDV1 is an
+ // empty string, not undefined.
const _twoFactorSessionID =
_twoFactorSessionIDV1 || _twoFactorSessionIDV2;
let passkeySessionID: string | undefined;
let twoFactorSessionID: string | undefined;
- // If both factors are set, ask the user which one they want to use.
if (_twoFactorSessionID && _passkeySessionID) {
const choice = await new Promise<SecondFactorType>(
(resolve) => {
diff --git a/web/packages/accounts-rs/components/utils/use-redirect.ts b/web/packages/accounts-rs/components/utils/use-redirect.ts
index 03a2a3992b..e457d062d3 100644
--- a/web/packages/accounts-rs/components/utils/use-redirect.ts
+++ b/web/packages/accounts-rs/components/utils/use-redirect.ts
@@ -3,15 +3,6 @@ import { useRouter } from "next/router";
import { useEffect } from "react";
import { stashRedirect } from "../../services/redirect";
-/**
- * Redirect to the appropriate credential step (password reverify, or a full
- * login) and then back to the current page if the user's master key is not
- * present in the session storage.
- *
- * @param currentPageSlug The slug for the current page where this hook is being
- * used. If a redirect happens, then this slug will be stashed and used to
- * redirect back here after the credentials have been obtained.
- */
export const useRedirectIfNeedsCredentials = (currentPageSlug: string) => {
const router = useRouter();
diff --git a/web/packages/accounts-rs/pages/change-email.tsx b/web/packages/accounts-rs/pages/change-email.tsx
index ddefd3c0b1..871883a59c 100644
--- a/web/packages/accounts-rs/pages/change-email.tsx
+++ b/web/packages/accounts-rs/pages/change-email.tsx
@@ -19,10 +19,6 @@ import { useCallback, useState } from "react";
import { Trans } from "react-i18next";
import { z } from "zod";
-/**
- * A page that allows a user to change the email address associated with their
- * Ente account.
- */
const Page: React.FC = () => {
useRedirectIfNeedsCredentials("/change-email");
@@ -131,11 +127,6 @@ const ChangeEmailForm: React.FC = () => {
value={formik.values.email}
onChange={formik.handleChange}
error={!!formik.errors.email}
- // See: [Note: Use space as default TextField helperText]
- //
- // Also, we only need keep the extra space until the email
- // has been entered (since the email field is read only
- // after that).
helperText={
formik.errors.email ?? (requestedEmail ? "" : " ")
}
diff --git a/web/packages/accounts-rs/pages/change-password.tsx b/web/packages/accounts-rs/pages/change-password.tsx
index 5fcae97ab6..41762d3458 100644
--- a/web/packages/accounts-rs/pages/change-password.tsx
+++ b/web/packages/accounts-rs/pages/change-password.tsx
@@ -22,17 +22,11 @@ import {
} from "../components/NewPasswordForm";
import { savedLocalUser } from "../services/accounts-db";
-/**
- * A page that allows a user to reset or change their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const [user, setUser] = useState<LocalUser | undefined>(undefined);
const router = useRouter();
- // We're invoked with the "?op=reset" query parameter in the recovery flow.
const isReset = router.query.op == "reset";
useEffect(() => {
@@ -56,9 +50,6 @@ export default Page;
interface PageContentsProps {
user: LocalUser;
- /**
- * True if the password is being reset during the account recovery flow.
- */
isReset: boolean;
}
diff --git a/web/packages/accounts-rs/pages/credentials.tsx b/web/packages/accounts-rs/pages/credentials.tsx
index b82850297d..bc84a76532 100644
--- a/web/packages/accounts-rs/pages/credentials.tsx
+++ b/web/packages/accounts-rs/pages/credentials.tsx
@@ -63,19 +63,6 @@ import { t } from "i18next";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to authenticate using their password.
- *
- * It is shown in two cases:
- *
- * - Initial authentication, when the user is logging in on to a new client.
- *
- * - Subsequent reauthentication, when the user opens the web app in a new tab.
- * Such a tab won't have the user's master key in session storage, so we ask
- * the user to reauthenticate using their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
@@ -118,14 +105,13 @@ const Page: React.FC = () => {
// Set a flag that causes new interactive key attributes to
// be generated.
saveIsFirstLogin();
- // This should be a rare occurrence, instead of building the
- // scaffolding to update all the in-memory state, just
- // reload everything.
+ // This should be rare; instead of updating all the
+ // in-memory state, just reload the page.
window.location.reload();
}
} catch (e) {
- // Ignore errors since we shouldn't be logging the user out for
- // potentially transient issues.
+ // Ignore errors; a potentially transient issue must not log the
+ // user out.
log.warn("Ignoring error when determining session validity", e);
}
}, [logout, showMiniDialog]);
@@ -179,8 +165,8 @@ const Page: React.FC = () => {
const kek = await unstashKeyEncryptionKeyFromSession();
const keyAttributes = savedKeyAttributes();
- // Refreshing an existing tab, or desktop app, or only the token
- // needs to decrypted and set.
+ // Refreshing an existing tab, or the desktop app: the stashed KEK
+ // decrypts the master key without asking for the password again.
if (kek && keyAttributes) {
const masterKey = await decryptBox(
{
@@ -241,8 +227,6 @@ const Page: React.FC = () => {
await verifySRP(srpAttributes, kek),
);
- // If we had to ask remote for the key attributes, it is the
- // initial login on this client.
saveIsFirstLogin();
if (passkeySessionID) {
@@ -265,8 +249,6 @@ const Page: React.FC = () => {
void router.push("/two-factor/verify");
return "redirecting-second-factor";
} else {
- // In rare cases, if the user hasn't already setup their key
- // attributes, we might get the plaintext token from remote.
if (token) await saveAuthToken(token);
updateSavedLocalUser({
id,
@@ -287,12 +269,10 @@ const Page: React.FC = () => {
useCallback(
(key, kek, keyAttributes, password) => {
void (async () => {
- // Currently the page will get reloaded if any of the
- // attributes have changed, so we don't need to worry about
- // the KEK having been generated using stale credentials.
- //
- // This await on the promise is here to only ensure we're
- // done with the check before we let the user in.
+ // The page reloads if any attributes changed, so the KEK
+ // cannot have been generated from stale credentials. The
+ // await only makes sure the check is done before we let
+ // the user in.
if (sessionValidityCheck) await sessionValidityCheck;
const updatedKeyAttributes = savedIsFirstLogin()
@@ -323,15 +303,10 @@ const Page: React.FC = () => {
}
if (passkeyVerificationData) {
- // We only need to handle this scenario when running in the desktop app
- // because the web app will navigate to Passkey verification URL.
- // However, still we add an additional `globalThis.electron` check to
- // show a spinner. This prevents the VerifyingPasskey component from
- // being disorientingly shown for a fraction of a second as the redirect
- // happens on the web app.
- //
- // See: [Note: Passkey verification in the desktop app]
-
+ // Only the desktop app needs this UI; the web app is already
+ // navigating to the passkey verification URL. Show a spinner on web
+ // so that the VerifyingPasskey component does not flash before the
+ // redirect completes.
if (!globalThis.electron) {
return <LoadingIndicator />;
}
diff --git a/web/packages/accounts-rs/pages/generate.tsx b/web/packages/accounts-rs/pages/generate.tsx
index f9a8f67aaa..5e64229658 100644
--- a/web/packages/accounts-rs/pages/generate.tsx
+++ b/web/packages/accounts-rs/pages/generate.tsx
@@ -39,12 +39,6 @@ import {
type NewPasswordFormProps,
} from "../components/NewPasswordForm";
-/**
- * A page that allows the user to generate key attributes if needed, and shows
- * them their recovery key if they just signed up.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
diff --git a/web/packages/accounts-rs/pages/login.tsx b/web/packages/accounts-rs/pages/login.tsx
index f722876666..62f8e13658 100644
--- a/web/packages/accounts-rs/pages/login.tsx
+++ b/web/packages/accounts-rs/pages/login.tsx
@@ -6,135 +6,6 @@ import { customAPIHost } from "ente-base/origins";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to login into their existing Ente account.
- *
- * [Note: Login pages]
- *
- * There are multiple pages that comprise the login flow, with redirects amongst
- * themselves depending on various scenarios and partial login states.
- *
- * - "/signup" - A page that allows the user to signup for a new Ente account.
- *
- * - Redirects to "/login" if the user chooses the "already have an account"
- * option.
- *
- * - Redirects to "/verify" if there is already an `email` present in the
- * saved partial local user, or after obtaining the email.
- *
- * - "/login" - A page that allows the user to login into their existing Ente
- * account.
- *
- * - Redirects to "/signup" if the user chooses the "create new account"
- * option.
- *
- * - Redirects to "/verify" if there is already an `email` present in the
- * saved partial local user, or after obtaining the email if the user's has
- * enabled email verification for their account.
- *
- * - Redirects to "/credentials" after obtaining the email if the user has not
- * enabled email verification for their account.
- *
- * - "/verify" - A page that allows the user to verify their email.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/credentials" if both saved key attributes and a `token`
- * (or `encryptedToken`) in present in the saved partial local user, or if
- * email verification is not needed, or when email verification completes
- * and remote sent us key attributes (which will happen on login).
- *
- * - Redirects to "/generate" once email verification is complete and the user
- * does not have key attributes (which will happen for new signups).
- *
- * - Redirects to "/two-factor/verify" when email verification completes and
- * the user has setup a TOTP second factor that also needs to be verified.
- *
- * - Redirects to the passkey app when email verification completes and the
- * user has setup a passkey that also needs to be verified. Before
- * redirecting, `inflightPasskeySessionID` in saved in session storage.
- *
- * - "/credentials" - A page that allows the user to enter their password to
- * authenticate (initial login) or reauthenticate (new web app tab)
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/two-factor/verify" if saved key attributes are not present
- * once password is verified and the user has setup a TOTP second factor
- * that also needs to be verified.
- *
- * - Redirects to the passkey app once password is verified if saved key
- * attributes are not present if the user has setup a passkey that also
- * needs to be verified. Before redirecting, `inflightPasskeySessionID` is
- * saved in session storage.
- *
- * - Redirects to the `appHomeRoute` otherwise (e.g. /gallery). **The flow is
- * complete**.
- *
- * - "/generate" - A page that allows the user to generate key attributes if
- * needed, and shows them their recovery key if they just signed up.
- *
- * - Redirects to "/" if there is no `email` or `token` present in the saved
- * partial user.
- *
- * - Redirects to `appHomeRoute` after viewing the recovery key if they have a
- * master key in session, or after setting the password and then viewing the
- * recovery key (if they did not have a master key in session store).
- *
- * - Redirects to "/credentials" if if they don't have a master key in session
- * store but have saved original key attributes.
- *
- * - "/recover" - A page that allows the user to recover their master key using
- * their recovery key.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/verify" if there is no `encryptedToken` (or `token`)
- * present in the saved partial local user.
- *
- * - Redirects to "/generate" if there are no saved key attributes.
- *
- * - Redirects to "/change-password" once the recovery key is verified.
- *
- * - "/change-password" - A page that allows the user to reset their password.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * user, and after successfully changing the password.
- *
- * - "/two-factor/verify" - A page that allows the user to verify their TOTP
- * based second factor.
- *
- * - Redirects to "/" if there is no `email` or `twoFactorSessionID` in the
- * saved partial local user.
- *
- * - Redirects to "/credentials" if `isTwoFactorEnabled` is not `true` and
- * either of `encryptedToken` or `token` is present in the saved partial
- * local user.
- *
- * - "/passkeys/finish" - A page where the accounts app hands off control back
- * to us (the calling app) once the passkey has been verified.
- *
- * - Redirects to "/" if there is no matching `inflightPasskeySessionID` in
- * session storage.
- *
- * - Redirects to "/credentials" otherwise.
- *
- * - "/two-factor/recover" and "/passkeys/recover" - Pages that allow the user
- * to reset or bypass their second factor if they possess their recovery key.
- * Both pages work similarly, except for the second factor they act on.
- *
- * - Redirect to "/" if there is no `email` or `twoFactorSessionID` /
- * `passkeySessionID` in the saved partial local user.
- *
- * - Redirect to "/generate" if there is an `encryptedToken` or `token` in the
- * saved partial local user.
- *
- * - Redirect to "/credentials" after recovery.
- *
- */
const Page: React.FC = () => {
const [loading, setLoading] = useState(true);
const [host, setHost] = useState<string | undefined>(undefined);
diff --git a/web/packages/accounts-rs/pages/passkeys/finish.tsx b/web/packages/accounts-rs/pages/passkeys/finish.tsx
index 01f36b3f02..072cf763c2 100644
--- a/web/packages/accounts-rs/pages/passkeys/finish.tsx
+++ b/web/packages/accounts-rs/pages/passkeys/finish.tsx
@@ -15,23 +15,13 @@ import { nullToUndefined } from "ente-utils/transform";
import { useRouter } from "next/router";
import React, { useEffect } from "react";
-/**
- * The page where the accounts app hands back control to us once the passkey has
- * been verified.
- *
- * See: [Note: Login pages]
- *
- * [Note: Finish passkey flow in the requesting app]
- *
- * The passkey finish step needs to happen in the context of the client which
- * invoked the passkey flow since it needs to save the obtained credentials
- * in local storage (which is tied to the current origin).
- */
+// The passkey finish step must run in the app that invoked the passkey flow:
+// it saves the obtained credentials to local storage, which is tied to the
+// origin.
const Page: React.FC = () => {
const router = useRouter();
useEffect(() => {
- // Extract response from query params.
const searchParams = new URLSearchParams(window.location.search);
const passkeySessionID = searchParams.get("passkeySessionID");
const response = searchParams.get("response");
@@ -47,28 +37,10 @@ const Page: React.FC = () => {
export default Page;
-/**
- * Extract credentials from a successful passkey flow "response" query parameter
- * and save them to local storage for use by subsequent steps (or normal
- * functioning) of the app.
- *
- * @param passkeySessionID The string that is passed as the "passkeySessionID"
- * query parameter to us.
- *
- * @param response The string that is passed as the "response" query parameter to
- * us (we're the final "finish" page in the passkey flow).
- *
- * @returns the slug that we should navigate to now.
- */
const saveQueryCredentialsAndNavigateTo = async (
passkeySessionID: string,
response: string,
) => {
- // This function's implementation is on the same lines as that of the
- // `saveCredentialsAndNavigateTo` function in passkey utilities.
- //
- // See: [Note: Ending the passkey flow]
-
const inflightPasskeySessionID = nullToUndefined(
sessionStorage.getItem("inflightPasskeySessionID"),
);
@@ -77,9 +49,8 @@ const saveQueryCredentialsAndNavigateTo = async (
!inflightPasskeySessionID ||
passkeySessionID != inflightPasskeySessionID
) {
- // This is not the princess we were looking for. However, we have
- // already entered this castle. Redirect back to home without changing
- // any state, hopefully this will get the user back to where they were.
+ // This is a stale or unexpected redirect. Do not change any state;
+ // just send the user back home.
log.info(
`Ignoring redirect for unexpected passkeySessionID ${passkeySessionID}`,
);
@@ -88,8 +59,6 @@ const saveQueryCredentialsAndNavigateTo = async (
clearInflightPasskeySessionID();
- // Decode response string (inverse of the steps we perform in
- // `passkeyAuthenticationSuccessRedirectURL`).
const decodedResponse = TwoFactorAuthorizationResponse.parse(
JSON.parse(
new TextDecoder().decode(await fromB64URLSafeNoPadding(response)),
diff --git a/web/packages/accounts-rs/pages/recover.tsx b/web/packages/accounts-rs/pages/recover.tsx
index 9a62d60320..ea6eac283d 100644
--- a/web/packages/accounts-rs/pages/recover.tsx
+++ b/web/packages/accounts-rs/pages/recover.tsx
@@ -33,12 +33,6 @@ import { t } from "i18next";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to enter their recovery key to recover their
- * master key if they've forgotten their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { showMiniDialog } = useBaseContext();
diff --git a/web/packages/accounts-rs/pages/signup.tsx b/web/packages/accounts-rs/pages/signup.tsx
index 0f6fdd5e97..d895fc5774 100644
--- a/web/packages/accounts-rs/pages/signup.tsx
+++ b/web/packages/accounts-rs/pages/signup.tsx
@@ -6,11 +6,6 @@ import { customAPIHost } from "ente-base/origins";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to signup for a new Ente account.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const [loading, setLoading] = useState(true);
const [host, setHost] = useState<string | undefined>(undefined);
diff --git a/web/packages/accounts-rs/pages/two-factor/recover.tsx b/web/packages/accounts-rs/pages/two-factor/recover.tsx
index 0fc56b5d30..3a84ca403d 100644
--- a/web/packages/accounts-rs/pages/two-factor/recover.tsx
+++ b/web/packages/accounts-rs/pages/two-factor/recover.tsx
@@ -30,10 +30,6 @@ export interface RecoverPageProps {
twoFactorType: TwoFactorType;
}
-/**
- * A page where the user can enter their recovery key to reset or bypass their
- * second factor in case they no longer have access to it.
- */
const Page: React.FC<RecoverPageProps> = ({ twoFactorType }) => {
const { logout, showMiniDialog, onGenericError } = useBaseContext();
diff --git a/web/packages/accounts-rs/pages/two-factor/setup.tsx b/web/packages/accounts-rs/pages/two-factor/setup.tsx
index d75cead67a..db32a79268 100644
--- a/web/packages/accounts-rs/pages/two-factor/setup.tsx
+++ b/web/packages/accounts-rs/pages/two-factor/setup.tsx
@@ -82,7 +82,7 @@ const ContentsPaper = styled(Paper)(({ theme }) => ({
marginBlock: theme.spacing(2),
padding: theme.spacing(5, 3),
[theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },
- // Wide enough to fit the QR code secret in one line under default settings.
+ // This width fits the QR code secret in one line under default settings.
width: "min(440px, 85vw)",
minHeight: "375px",
display: "flex",
diff --git a/web/packages/accounts-rs/pages/two-factor/verify.tsx b/web/packages/accounts-rs/pages/two-factor/verify.tsx
index 67c70eba63..0c17135365 100644
--- a/web/packages/accounts-rs/pages/two-factor/verify.tsx
+++ b/web/packages/accounts-rs/pages/two-factor/verify.tsx
@@ -21,11 +21,6 @@ import {
} from "../../components/layouts/centered-paper";
import { unstashRedirect } from "../../services/redirect";
-/**
- * A page that allows the user to verify their TOTP based second factor.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout } = useBaseContext();
diff --git a/web/packages/accounts-rs/pages/verify.tsx b/web/packages/accounts-rs/pages/verify.tsx
index 3d9ad834d5..da60372313 100644
--- a/web/packages/accounts-rs/pages/verify.tsx
+++ b/web/packages/accounts-rs/pages/verify.tsx
@@ -54,11 +54,6 @@ import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
import { Trans } from "react-i18next";
-/**
- * A page that allows the user to verify their email.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
@@ -108,9 +103,6 @@ const Page: React.FC = () => {
await verifyEmail(email, ott, cleanedReferral),
);
- // The following flow is similar to (but not the same) as what
- // happens after `verifySRP` in the `/credentials` page.
-
if (passkeySessionID) {
updateSavedLocalUser({ passkeySessionID });
saveIsFirstLogin();
@@ -173,15 +165,10 @@ const Page: React.FC = () => {
}
if (passkeyVerificationData) {
- // We only need to handle this scenario when running in the desktop app
- // because the web app will navigate to Passkey verification URL.
- // However, still we add an additional `globalThis.electron` check to
- // show a spinner. This prevents the VerifyingPasskey component from
- // being disorientingly shown for a fraction of a second as the redirect
- // happens on the web app.
- //
- // See: [Note: Passkey verification in the desktop app]
-
+ // Only the desktop app needs this UI; the web app is already
+ // navigating to the passkey verification URL. Show a spinner on web
+ // so that the VerifyingPasskey component does not flash before the
+ // redirect completes.
if (!globalThis.electron) {
return <LoadingIndicator />;
}
@@ -246,12 +233,6 @@ const Page: React.FC = () => {
export default Page;
-/**
- * A function called during page load to see if a redirection is required
- *
- * @returns The slug to redirect to, if needed. Otherwise an object containing
- * the saved partial user's email.
- */
const redirectionIfNeededOrEmail = async () => {
const user = savedPartialLocalUser();
@@ -264,25 +245,13 @@ const redirectionIfNeededOrEmail = async () => {
return "/credentials";
}
- // If we're coming here during the recover flow, do not redirect.
if (stashedRedirect() == "/recover") return { email };
- // The user might have email verification disabled, but after previously
- // entering their email on the login screen, they might've closed the tab
- // before proceeding (or opened a us in a new tab at this point).
- //
- // In such cases, we'll end up here with an email present.
- //
- // To distinguish this scenario from the normal email verification flow, we
- // can check to see the SRP attributes (the login page would've fetched and
- // saved them). If they are present and indicate that email verification is
- // not required, redirect to the password verification page.
-
const srpAttributes = savedSRPAttributes();
if (srpAttributes && !srpAttributes.isEmailMFAEnabled) {
- // Fetch the latest SRP attributes instead of relying on the potentially
- // stale stored values. This is an infrequent scenario path, so extra
- // API calls are fine.
+ // Fetch the latest SRP attributes instead of trusting the potentially
+ // stale saved values. This path is infrequent, so the extra API call
+ // is fine.
const latestSRPAttributes = await getSRPAttributes(email);
if (latestSRPAttributes && !latestSRPAttributes.isEmailMFAEnabled) {
return "/credentials";
diff --git a/web/packages/accounts-rs/services/accounts-db.ts b/web/packages/accounts-rs/services/accounts-db.ts
index 4a10d2f5bf..6931e3c597 100644
--- a/web/packages/accounts-rs/services/accounts-db.ts
+++ b/web/packages/accounts-rs/services/accounts-db.ts
@@ -1,21 +1,6 @@
-/**
- * @file [Note: Accounts DB]
- *
- * The accounts package stores various state both during the login / signup
- * flow, and post login to identify the logged in user.
- *
- * This state is stored in local storage.
- *
- * Most of this state is meant to be transitory - various bits and bobs that we
- * accumulate and want to persist as the user goes through the login or signup
- * flow. One the user is successfully logged in and the first pull has
- * completed, then only a few of these are expected to remain:
- *
- * - "user"
- * - "keyAttributes"
- * - "originalKeyAttributes"
- * - "srpAttributes"
- */
+// All of the state in this file is kept in the browser's localStorage, which
+// is not accessible to web workers, so these functions only work on the main
+// thread.
import { savedAuthToken } from "ente-base/token";
import { nullToUndefined } from "ente-utils/transform";
@@ -31,52 +16,6 @@ import {
type LocalUser,
} from "./user";
-/**
- * The local storage data about the user before login or signup is complete.
- *
- * [Note: Partial local user]
- *
- * During login or signup, the user object exists in various partial states in
- * local storage.
- *
- * - Initially, there is no user object in local storage.
- *
- * - When the user enters their email, the email property of the stored object
- * is set, but nothing else.
- *
- * - After they verify their password, we have two cases: if second factor
- * verification is not set, and when it is set.
- *
- * - If second factor verification is not set, then after verifying their
- * password their {@link id} and {@link encryptedToken} will get filled in,
- * and {@link isTwoFactorEnabled} will be set to false.
- *
- * - If they have second factor verification set, then after verifying their
- * password {@link isTwoFactorEnabled} and {@link twoFactorSessionID} will
- * also get filled in. Once they verify their TOTP based second factor, their
- * {@link id} and {@link encryptedToken} will also get filled in.
- *
- * - If they have a passkey set as a second factor set, then after verifying
- * their password the {@link passkeySessionID} will be set.
- *
- * - As the login or signup sequence completes, a {@link token} obtained from
- * the {@link encryptedToken} will be written out, and the
- * {@link encryptedToken} cleared since it is not needed anymore.
- *
- * So while the underlying storage is the same, we offer two APIs for code to
- * obtain the user:
- *
- * - Before login is complete, or when it is unknown if login is complete or
- * not, then {@link savedPartialLocalUser} can be used to obtain a
- * {@link PartialLocalUser} with all of its properties set to be optional (and
- * some additional properties not available in the regular user object).
- *
- * - When we know that the login has completed, we can use either
- * {@link savedLocalUser} (which returns `undefined` if our assumption is
- * false) or {@link ensureSavedLocalUser} (which throws if our assumption is
- * false) to obtain an object with all the properties expected to be present
- * for a locally persisted user set to be required.
- */
export interface PartialLocalUser {
id?: number;
email?: string;
@@ -97,11 +36,6 @@ const PartialLocalUser = z.object({
passkeySessionID: z.string().nullish().transform(nullToUndefined),
});
-/**
- * Zod schema for the {@link LocalUser} TypeScript type.
- *
- * The type itself is in `user.ts`.
- */
const LocalUser = z.object({
id: z.number(),
email: z.string(),
@@ -109,177 +43,73 @@ const LocalUser = z.object({
isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
});
-/**
- * Return the local storage value of the user's data.
- *
- * This function is meant to be called during the login or signup sequence.
- * After the user is logged in, use {@link savedLocalUser} or
- * {@link ensureLocalUser} instead.
- *
- * Use {@link replaceSavedLocalUser} to updated the saved value.
- */
export const savedPartialLocalUser = (): PartialLocalUser | undefined => {
const jsonString = localStorage.getItem("user");
if (!jsonString) return undefined;
return PartialLocalUser.parse(JSON.parse(jsonString));
};
-/**
- * Save the users data as we accrue it during the signup or login flow.
- *
- * See: [Note: Partial local user].
- *
- * This method replaces the existing data. Use {@link updateSavedLocalUser} to
- * update selected fields while keeping the other fields as it is.
- */
export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>
localStorage.setItem("user", JSON.stringify(partialLocalUser));
-/**
- * Partially update the saved user data.
- *
- * This is a delta variant of {@link replaceSavedLocalUser}, which replaces the
- * entire saved object, while this function spreads the provided {@link updates}
- * onto the currently saved value.
- *
- * @param updates A subset of {@link PartialLocalUser} fields that we'd like to
- * update. The other fields, if present in local storage, remain unchanged.
- */
export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>
replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });
-/**
- * Return data about the logged-in user, if someone is indeed logged in.
- * Otherwise return `undefined`.
- *
- * The user's data is stored in the browser's localStorage. Thus, this function
- * only works from the main thread, not from web workers since local storage is
- * not accessible to web workers.
- *
- * There is no setter corresponding to this function since this is only a view
- * on data saved using {@link replaceSavedLocalUser} or
- * {@link updateSavedLocalUser}.
- *
- * See: [Note: Partial local user] for more about the whole shebang.
- */
export const savedLocalUser = (): LocalUser | undefined => {
const jsonString = localStorage.getItem("user");
if (!jsonString) return undefined;
- // We might have some data, but not all of it. So do a non-throwing parse.
+ // During login the saved user object can be partial, so do a non-throwing
+ // parse.
const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));
return success ? data : undefined;
};
-/**
- * Return true if the saved user token in local storage and the persisted auth
- * token are out of sync.
- *
- * Call this explicitly when validating app startup state. The synchronous local
- * user accessors intentionally avoid triggering async mismatch checks because
- * they are often used during render.
- */
+// The synchronous local user accessors intentionally do not run this async
+// consistency check since they are often called during render. Call this
+// explicitly when validating app startup state.
export const isSavedUserTokenMismatch = async () => {
const savedUserToken = savedPartialLocalUser()?.token;
const authToken = await savedAuthToken();
return authToken ? savedUserToken !== authToken : !!savedUserToken;
};
-/**
- * Return true if the user's data is in local storage but not in IndexedDB.
- *
- * This acts a sanity check on IndexedDB by ensuring that if the user has a
- * token in local storage, then it should also be present in IndexedDB.
- */
export const isLocalStorageAndIndexedDBMismatch = async () =>
savedPartialLocalUser()?.token && !(await savedAuthToken());
-/**
- * Return the user's {@link KeyAttributes} if they are present in local storage.
- *
- * The key attributes are stored in the browser's localStorage. Thus, this
- * function only works from the main thread, not from web workers (local storage
- * is not accessible to web workers).
- *
- * See also: [Note: Original vs interactive key attributes]
- */
export const savedKeyAttributes = (): KeyAttributes | undefined => {
const jsonString = localStorage.getItem("keyAttributes");
if (!jsonString) return undefined;
return RemoteKeyAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link KeyAttributes} in local storage.
- *
- * Use {@link savedKeyAttributes} to retrieve them.
- */
export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>
localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));
-/**
- * Return the user's original {@link KeyAttributes} if they are present in local
- * storage.
- *
- * [Note: Original vs interactive key attributes]
- *
- * This function is similar to {@link savedKeyAttributes} except it returns the
- * user's "original" key attributes. These are the key attributes that were
- * either freshly generated (if the user signed up on this client) or were
- * fetched from remote (otherwise).
- *
- * > NOTE: Currently the code does not guarantee that savedOriginalKeyAttributes
- * > will always be set when savedKeyAttributes is set.
- *
- * In contrast, the regular key attributes get overwritten by the local only
- * interactive key attributes for the user's convenience. See the documentation
- * of {@link generateAndSaveInteractiveKeyAttributes} for more details.
- */
+// Unlike the "keyAttributes" entry, which can get overwritten by locally
+// generated interactive key attributes, the "originalKeyAttributes" entry
+// retains the key attributes that were freshly generated at signup or fetched
+// from remote.
export const savedOriginalKeyAttributes = (): KeyAttributes | undefined => {
const jsonString = localStorage.getItem("originalKeyAttributes");
if (!jsonString) return undefined;
return RemoteKeyAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link KeyAttributes} in local storage.
- *
- * Once saved, these values are not replaced (in contrast with the regular key
- * attributes which can get overwritten with interactive ones).
- *
- * Use {@link savedOriginalKeyAttributes} to retrieve them.
- */
export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>
localStorage.setItem(
"originalKeyAttributes",
JSON.stringify(keyAttributes),
);
-/**
- * Return the user's {@link SRPAttributes} if they are present in local storage.
- *
- * Like key attributes, SRP attributes are also stored in the browser's local
- * storage so will not be accessible to web workers.
- */
export const savedSRPAttributes = (): SRPAttributes | undefined => {
const jsonString = localStorage.getItem("srpAttributes");
if (!jsonString) return undefined;
return RemoteSRPAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link SRPAttributes} in local storage.
- *
- * Use {@link savedSRPAttributes} to retrieve them.
- */
export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>
localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));
-/**
- * Save {@link SRPSetupAttributes} in local storage for later use via
- * {@link unstashAfterUseSRPSetupAttributes}.
- *
- * See: [Note: SRP setup attributes]
- */
export const stashSRPSetupAttributes = (
srpSetupAttributes: SRPSetupAttributes,
) =>
@@ -288,16 +118,6 @@ export const stashSRPSetupAttributes = (
JSON.stringify(srpSetupAttributes),
);
-/**
- * Retrieve the {@link SRPSetupAttributes}, if any, that were stashed by a
- * previous call to {@link stashSRPSetupAttributes}.
- *
- * - If they are found, then invoke the provided callback ({@link cb}) with the
- * value. If the promise returned by the callback fulfills, then remove the
- * stashed value from local storage.
- *
- * - If they are not found, then the callback is not invoked.
- */
export const unstashAfterUseSRPSetupAttributes = async (
cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,
) => {
@@ -308,33 +128,13 @@ export const unstashAfterUseSRPSetupAttributes = async (
localStorage.removeItem("srpSetupAttributes");
};
-/**
- * Zod schema for the legacy format in which the {@link savedIsFirstLogin} and
- * {@link savedJustSignedUp} flags were saved in local storage.
- *
- * Starting 1.7.15-beta (July 2025), we started saving the booleans directly,
- * but when reading we fallback to the old format if needed. This fallback can
- * be removed, and soonish, since these are transient flags that are saved
- * during the login / signup sequence and wouldn't be expected to remain in the
- * user's local storage for long anyway. (tag: Migration).
- */
+// Legacy format in which the "isFirstLogin" and "justSignedUp" flags were
+// saved. Readers fall back to it since it can still be present in users' local
+// storage. (tag: Migration)
const LocalLegacyBooleanFlag = z.object({
status: z.boolean().nullish().transform(nullToUndefined),
});
-/**
- * Return `true` if it is the user's first login on this client.
- *
- * The {@link savedIsFirstLogin} flag is saved in local storage (using
- * {@link saveIsFirstLogin}) if we determine during the login flow that it a
- * fresh login on this client. If so, we
- *
- * - Generate interactive key attributes for them, and
- *
- * - Display them a special indicator post login to notify them that the first
- * load might take extra time. At this point, we also clear the flag (the read
- * and clear is done by the same {@link getAndClearIsFirstLogin} function).
- */
export const savedIsFirstLogin = () => {
const jsonString = localStorage.getItem("isFirstLogin");
if (!jsonString) return false;
@@ -347,33 +147,16 @@ export const savedIsFirstLogin = () => {
}
};
-/**
- * Save a flag in local storage to indicate that this is the user's first login
- * on this client.
- *
- * This is the setter corresponding to {@link savedIsFirstLogin}.
- */
export const saveIsFirstLogin = () => {
localStorage.setItem("isFirstLogin", JSON.stringify({ status: true }));
};
-/**
- * Get the saved value of the local storage flag that indicates that this is the
- * user' first login on this client. Also remove the flag after reading.
- *
- * The flag can be set by using {@link saveIsFirstLogin}, and can be read
- * without clearing it by using {@link savedIsFirstLogin}.
- */
export const getAndClearIsFirstLogin = () => {
const result = savedIsFirstLogin();
localStorage.removeItem("isFirstLogin");
return result;
};
-/**
- * Return `true` if the user created a new account on this client during the
- * current (in-progress) or just completed login / signup sequence.
- */
export const savedJustSignedUp = () => {
const jsonString = localStorage.getItem("justSignedUp");
if (!jsonString) return false;
@@ -386,45 +169,20 @@ export const savedJustSignedUp = () => {
}
};
-/**
- * Save a flag in local storage to indicate that the user signed up for a
- * new Ente account during the current login / signup sequence.
- *
- * This is the setter corresponding to {@link savedJustSignedUp}.
- */
export const saveJustSignedUp = () => {
localStorage.setItem("justSignedUp", JSON.stringify({ status: true }));
};
-/**
- * Get the saved value of the local storage flag that indicates that the user just
- * signed up. Also remove the flag from local storage after reading.
- *
- * The flag can be set by using {@link saveJustSignedUp}, and can be read
- * without clearing it by using {@link savedJustSignedUp}.
- */
export const getAndClearJustSignedUp = () => {
const result = savedJustSignedUp();
localStorage.removeItem("justSignedUp");
return result;
};
-/**
- * Save the referral source entered by the user on the signup screen in local
- * storage.
- *
- * The saved value can be retrieved post email verification using
- * {@link unstashReferralSource}.
- */
export const stashReferralSource = (referralSource: string) => {
localStorage.setItem("referralSource", referralSource);
};
-/**
- * Retrieve the previously saved referral source (using
- * {@link stashReferralSource}), returning the saved value and also clearing it
- * from local storage.
- */
export const unstashReferralSource = () => {
const referralSource = localStorage.getItem("referralSource");
if (!referralSource) return undefined;
diff --git a/web/packages/accounts-rs/services/logout.ts b/web/packages/accounts-rs/services/logout.ts
index 6f82db608d..14dda04142 100644
--- a/web/packages/accounts-rs/services/logout.ts
+++ b/web/packages/accounts-rs/services/logout.ts
@@ -6,16 +6,8 @@ import log from "ente-base/log";
import { clearStashedRedirect } from "./redirect";
import { remoteLogoutIfNeeded } from "./user";
-/**
- * Logout sequence common to all apps that rely on the accounts package.
- *
- * [Note: Do not throw during logout]
- *
- * This function is guaranteed to not thrown any errors, and will try to
- * independently complete all the steps in the sequence that can be completed.
- * This allows the user to logout and start again even if somehow their account
- * gets in an unexpected state.
- */
+// This function must not throw. Each step runs independently and ignores
+// errors so that logout completes even from a broken account state.
export const accountLogout = async () => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
@@ -54,14 +46,9 @@ export const accountLogout = async () => {
}
};
-/**
- * This is a subset of the cleanup of local persistence that has already
- * happened during {@link accountLogout}. However, once the logout sequence is
- * complete, we do these specific steps again to clear any state that might've
- * been persisted meanwhile because of in-flight requests getting completed.
- *
- * Post this, we'll reload the page so that in-flight requests are discarded.
- */
+// Called after the logout sequence completes to again clear state that
+// in-flight requests may have persisted meanwhile. The caller then reloads
+// the page so that remaining in-flight requests are discarded.
export const logoutClearStateAgain = async () => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
diff --git a/web/packages/accounts-rs/services/passkey.ts b/web/packages/accounts-rs/services/passkey.ts
index 64fe3a2c39..3160162efa 100644
--- a/web/packages/accounts-rs/services/passkey.ts
+++ b/web/packages/accounts-rs/services/passkey.ts
@@ -19,29 +19,16 @@ import { z } from "zod";
import { getUserRecoveryKey } from "./recovery-key";
import { unstashRedirect } from "./redirect";
-/**
- * Construct a redirect URL to take the user to Ente accounts app to
- * authenticate using their second factor, a passkey they've configured.
- *
- * On successful verification, the accounts app will redirect back to our
- * `/passkeys/finish` page.
- *
- * @param accountsURL The URL for the accounts app (provided to us by remote in
- * the email or SRP verification response).
- *
- * @param passkeySessionID An identifier provided by museum for this passkey
- * verification session.
- */
export const passkeyVerificationRedirectURL = (
accountsURL: string,
passkeySessionID: string,
) => {
const clientPackage = clientPackageName;
- // Using `window.location.origin` will work both when we're running in a web
- // browser, and in our desktop app. See: [Note: Using deeplinks to navigate
- // in desktop app]
+ // In the desktop app, window.location.origin is the custom app protocol
+ // origin, which doubles as the deeplink back into the app.
const redirect = `${window.location.origin}/passkeys/finish`;
- // See: [Note: Conditional passkey recover option on accounts]
+ // The desktop app's own waiting screen already shows a recovery option, so
+ // it does not ask the accounts app to show one.
const recoverOption: Record<string, string> = isDesktop
? {}
: { recover: `${window.location.origin}/passkeys/recover` };
@@ -55,61 +42,30 @@ export const passkeyVerificationRedirectURL = (
};
interface OpenPasskeyVerificationURLOptions {
- /**
- * The passkeySessionID for which we are redirecting.
- *
- * This is compared to the saved session id in the browser's session storage
- * to allow us to ignore redirects to the passkey flow finish page except
- * the ones for this specific session we're awaiting.
- */
passkeySessionID: string;
- /** The URL to redirect to or open in the system browser. */
url: string;
}
-/**
- * Open or redirect to a passkey verification URL previously constructed using
- * {@link passkeyVerificationRedirectURL}.
- *
- * [Note: Passkey verification in the desktop app]
- *
- * Our desktop app bundles the web app and serves it over a custom protocol.
- * Passkeys are tied to origins, and will not work with this custom protocol
- * even if we move the passkey creation and authentication inline to within the
- * Photos web app.
- *
- * Thus, passkey creation and authentication in the desktop app works the same
- * way it works in the mobile app - the system browser is invoked to open the
- * accounts app origin (e.g. accounts.ente.com) returned by remote.
- *
- * - For passkey creation, this is a one-way open. Passkeys get created at the
- * accounts app origin, and that's it.
- *
- * - For passkey verification, the flow is two-way. We register a custom
- * protocol and provide that as a return path redirect. Passkey authentication
- * happens at the accounts app origin, and on success there is redirected back
- * to the desktop app.
- */
+// Passkeys are tied to web origins and do not work over the custom protocol
+// that the desktop app uses to serve the bundled web app. So the desktop app
+// (like the mobile app) opens the accounts app origin in the system browser,
+// and on successful verification the accounts app redirects back to the
+// desktop app via a registered custom protocol.
export const openPasskeyVerificationURL = ({
passkeySessionID,
url,
}: OpenPasskeyVerificationURLOptions) => {
+ // The finish page ignores redirects whose session id does not match the
+ // inflight value saved here.
sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);
if (globalThis.electron) window.open(url);
else window.location.href = url;
};
-/**
- * Open a new window showing a page on the Ente accounts app where the user can
- * see and their manage their passkeys.
- */
export const openAccountsManagePasskeysPage = async () => {
- // Check if the user has passkey recovery enabled.
const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();
if (!isPasskeyRecoveryEnabled) {
- // If not, enable it for them by creating the necessary recovery
- // information to prevent them from getting locked out.
const resetSecret = await generateKey();
const { encryptedData, nonce } = await encryptBox(
resetSecret,
@@ -118,8 +74,6 @@ export const openAccountsManagePasskeysPage = async () => {
await configurePasskeyRecovery(resetSecret, encryptedData, nonce);
}
- // Redirect to the Ente Accounts app where they can view and add and manage
- // their passkeys.
const { accountsToken: token, accountsUrl: accountsURL } =
await getAccountsTokenAndURL();
const params = new URLSearchParams({ token });
@@ -128,15 +82,9 @@ export const openAccountsManagePasskeysPage = async () => {
};
const TwoFactorRecoveryStatus = z.object({
- /**
- * `true` if the passkey recovery setup has been completed.
- */
isPasskeyRecoveryEnabled: z.boolean(),
});
-/**
- * Obtain the second factor recovery status from remote.
- */
export const getTwoFactorRecoveryStatus = async () => {
const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {
headers: await authenticatedRequestHeaders(),
@@ -145,10 +93,6 @@ export const getTwoFactorRecoveryStatus = async () => {
return TwoFactorRecoveryStatus.parse(await res.json());
};
-/**
- * Allow the user to bypass their passkeys by saving the provided recovery
- * credentials on remote.
- */
const configurePasskeyRecovery = async (
secret: string,
userSecretCipher: string,
@@ -169,53 +113,18 @@ const configurePasskeyRecovery = async (
),
);
-/**
- * Fetch an Ente Accounts specific JWT token.
- *
- * This token can be used to authenticate with the Ente accounts app running at
- * accountsURL (the result contains both pieces of information).
- */
const getAccountsTokenAndURL = async () => {
const res = await fetch(await apiURL("/users/accounts-token"), {
headers: await authenticatedRequestHeaders(),
});
ensureOk(res);
return z
- .object({
- // The origin that serves the accounts app.
- accountsUrl: z.string(),
- // A token that can be used to authenticate with the accounts app.
- accountsToken: z.string(),
- })
+ .object({ accountsUrl: z.string(), accountsToken: z.string() })
.parse(await res.json());
};
-/**
- * The passkey session whose status we are trying to check has already expired.
- * The user should attempt to login again.
- */
export const passkeySessionExpiredErrorMessage = "Passkey session has expired";
-/**
- * Check if the user has already authenticated using their passkey for the given
- * session.
- *
- * This is useful in case the automatic redirect back from the accounts app to
- * the desktop app does not work for some reason. In such cases, the user can
- * press the "Check status" button: we'll make an API call to see if the
- * authentication has already completed, and if so, get the same "response"
- * object we'd have gotten as a query parameter in a redirect in
- * {@link saveCredentialsAndNavigateTo} on the "/passkeys/finish" page.
- *
- * @param sessionID The passkey session whose session we wish to check the
- * status of.
- *
- * @returns A {@link TwoFactorAuthorizationResponse} if the passkey
- * authentication has completed, and `undefined` otherwise.
- *
- * @throws In addition to arbitrary errors, it throws errors with the message
- * {@link passkeySessionExpiredErrorMessage}.
- */
export const checkPasskeyVerificationStatus = async (
sessionID: string,
): Promise<TwoFactorAuthorizationResponse | undefined> => {
@@ -226,38 +135,16 @@ export const checkPasskeyVerificationStatus = async (
if (!res.ok) {
if (res.status == 404 || res.status == 410)
throw new Error(passkeySessionExpiredErrorMessage);
- if (res.status == 400) return undefined; /* verification pending */
+ // Remote uses 400 to indicate that verification is still pending.
+ if (res.status == 400) return undefined;
throw new HTTPError(res);
}
return TwoFactorAuthorizationResponse.parse(await res.json());
};
-/**
- * Extract credentials from a successful passkey verification response and save
- * them to local storage for use by subsequent steps (or normal functioning) of
- * the app.
- *
- * @param response The result of a successful
- * {@link checkPasskeyVerificationStatus}.
- *
- * @returns the slug that we should navigate to now.
- */
export const saveCredentialsAndNavigateTo = async (
response: TwoFactorAuthorizationResponse,
) => {
- // [Note: Ending the passkey flow]
- //
- // The implementation of this function is similar to that of the
- // `saveQueryCredentialsAndNavigateTo` on the "/passkeys/finish" page.
- //
- // This one, `saveCredentialsAndNavigateTo`, is used when the user presses
- // the check verification status button on the page that triggered the
- // passkey flow (when they're using the desktop app).
- //
- // The other one, `saveQueryCredentialsAndNavigateTo`, is used when the user
- // goes through the passkey flow in the browser itself (when they are using
- // the web app).
-
clearInflightPasskeySessionID();
const { id, encryptedToken, keyAttributes } = response;
@@ -269,12 +156,6 @@ export const saveCredentialsAndNavigateTo = async (
return unstashRedirect() ?? "/credentials";
};
-/**
- * Remove the inflight passkey session ID, if any, present in session storage.
- *
- * This should be called whenever we get back control from the passkey app to
- * clean up after ourselves.
- */
export const clearInflightPasskeySessionID = () => {
sessionStorage.removeItem("inflightPasskeySessionID");
};
diff --git a/web/packages/accounts-rs/services/recovery-key.ts b/web/packages/accounts-rs/services/recovery-key.ts
index 9dbb869130..e037e94631 100644
--- a/web/packages/accounts-rs/services/recovery-key.ts
+++ b/web/packages/accounts-rs/services/recovery-key.ts
@@ -10,37 +10,14 @@ import { ensureMasterKeyFromSession } from "ente-accounts-rs/services/session-st
import { saveKeyAttributes } from "./accounts-db";
import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";
-/**
- * Convert the provided BIP-39 mnemonic string into its base64 representation.
- *
- * @param recoveryKeyMnemonicOrHex The BIP-39 mnemonic (24 word) string
- * representing the recovery key. For legacy compatibility, the function also
- * works if provided the hex representation of the recovery key.
- *
- * @returns A base64 string representing the underlying bytes of the recovery key.
- */
+// For legacy compatibility, the hex representation of the recovery key is
+// accepted in addition to the 24 word BIP-39 mnemonic.
export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) =>
recoveryKeyFromMnemonicOrHex(recoveryKeyMnemonicOrHex);
-/**
- * Convert the provided base64 encoded recovery key into its BIP-39 mnemonic.
- *
- * @param recoveryKey The base64 encoded recovery key to mnemonize.
- *
- * @returns A 24-word mnemonic that serves as the user visible recovery key.
- */
export const recoveryKeyToMnemonic = async (recoveryKey: string) =>
recoveryKeyToMnemonicRust(recoveryKey);
-/**
- * Return the (decrypted) recovery key of the logged in user, reading it from
- * local storage.
- *
- * As a fallback for old accounts that generated recovery keys on first view,
- * this function will also generate a new recovery key if needed.
- *
- * @returns The user's base64 encoded recovery key.
- */
export const getUserRecoveryKey = async () => {
const masterKey = await ensureMasterKeyFromSession();
@@ -61,15 +38,8 @@ export const getUserRecoveryKey = async () => {
}
};
-/**
- * Generate a new recovery key, tell remote about it, update our local state,
- * and then return it.
- *
- * This function is meant only for (very!) old accounts for whom the app did not
- * generate recovery keys on sign up but instead generated them on first view.
- *
- * @returns a new base64 encoded recovery key.
- */
+// Very old accounts did not get a recovery key at sign up; for them one is
+// generated lazily when it is first needed.
const createNewRecoveryKey = async (
masterKey: string,
existingKeyAttributes: KeyAttributes,
diff --git a/web/packages/accounts-rs/services/redirect.ts b/web/packages/accounts-rs/services/redirect.ts
index aeed7ef72a..878617c9cc 100644
--- a/web/packages/accounts-rs/services/redirect.ts
+++ b/web/packages/accounts-rs/services/redirect.ts
@@ -1,17 +1,14 @@
import { appName } from "ente-base/app";
-/**
- * The default page ("home route") for each of our apps.
- *
- * This is where we redirect to after successful authentication.
- */
+// The page to redirect to after successful authentication. The cast, embed and
+// share apps do not use this; their "/" entries are arbitrary values.
export const appHomeRoute: string = {
accounts: "/passkeys",
albums: "/",
auth: "/auth",
- cast: "/" /* The cast app doesn't use this, this is an arbitrary value. */,
- embed: "/" /* The embed app doesn't use this either. */,
- share: "/" /* The locker public app also doesn't use this. */,
+ cast: "/",
+ embed: "/",
+ share: "/",
photos: "/gallery",
ensu: "/",
locker: "/locker",
@@ -21,9 +18,6 @@ export const appHomeRoute: string = {
let _stashedRedirect: string | undefined;
-/**
- * An in-memory redirect saved during the login flow (mostly).
- */
export const stashedRedirect = () => _stashedRedirect;
export const stashRedirect = (r: string) => (_stashedRedirect = r);
diff --git a/web/packages/accounts-rs/services/session-storage.ts b/web/packages/accounts-rs/services/session-storage.ts
index 1a65a52105..539edd7c22 100644
--- a/web/packages/accounts-rs/services/session-storage.ts
+++ b/web/packages/accounts-rs/services/session-storage.ts
@@ -1,9 +1,6 @@
import { z } from "zod";
import { decryptBox, encryptBox, generateKey } from "./crypto";
-/**
- * Remove all data stored in session storage (data tied to the browser tab).
- */
export const clearSessionStorage = () => sessionStorage.clear();
const SessionKeyData = z.object({
diff --git a/web/packages/accounts-rs/services/session.ts b/web/packages/accounts-rs/services/session.ts
index 61cfdf29ef..0541bf17c8 100644
--- a/web/packages/accounts-rs/services/session.ts
+++ b/web/packages/accounts-rs/services/session.ts
@@ -27,69 +27,18 @@ type SessionValidity =
const SessionValidityResponse = z.object({
hasSetKeys: z.boolean(),
- /**
- * Will not be present if {@link hasSetKeys} is `false`.
- */
keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
});
-/**
- * Check if the local token and/or key attributes we have are still valid.
- *
- * This function does not take any parameters because it reads the current state
- * (key attributes) from local storage.
- *
- * @returns
- *
- * - status "invalid" if the current token has been invalidated,
- * - status "valid" normally
- * - status "validButPasswordChanged" we detected that user changed their
- * password on a different device (without choosing the option to log out of
- * all existing sessions).
- *
- * ---
- *
- * [Note: Handling password changes]
- *
- * If the user changes their password on a different device, then we need to
- * update our local state so that we use the latest password for verification.
- *
- * There is a straightforward way of doing this by always making a blocking API
- * call before showing the password unlock page, however that would add latency
- * to the 99% user experience (of normal unlocks) for the 1% case (they've
- * changed their password elsewhere).
- *
- * The approach we instead use is to make an non-blocking `/session-validity`
- * API call when this page is loaded. Usually this'll complete well before the
- * password enters their password and presses "Sign in", but we also
- * transparently await for this API call to finish before initiating the actual
- * verification. Thus there is no extra latency in the happy paths.
- *
- * The `/session-validity` API call tells us:
- *
- * 1. Whether or not the session has been invalidated (by the user choosing to
- * log out from all devices elsewhere).
- *
- * 2. What are their latest key attributes.
- *
- * If the session has been invalidated, we log them out here too.
- *
- * If the key attributes we get are different from the ones we have locally, we
- * regenerate new ones locally, and then use those for verifying the password
- * subsequently.
- */
export const checkSessionValidity = async (): Promise<SessionValidity> => {
const res = await fetch(await apiURL("/users/session-validity/v2"), {
headers: await authenticatedRequestHeaders(),
});
if (!res.ok) {
- if (res.status == 401)
- return { status: "invalid" }; /* session is no longer valid */
+ if (res.status == 401) return { status: "invalid" };
else throw new HTTPError(res);
}
- // See if the response contains keyAttributes (it will not if `hasSetKeys`
- // in the response is `false`).
const { keyAttributes } = SessionValidityResponse.parse(await res.json());
if (keyAttributes) {
const remoteKeyAttributes = keyAttributes;
@@ -98,23 +47,16 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
const email = ensureLocalUser().email;
const localSRPAttributes = savedSRPAttributes()!;
- // Fetch the remote SRP attributes.
- //
- // The key attributes we have saved locally are the locally generated
- // ones for interactive usage, and thus they'll always differ from the
- // ones we get from remote. To detect if the user changed their
- // password, we also need to fetch their SRP attributes (which will be
- // identical between remote and us if the password is the same).
+ // The key attributes we have saved locally are regenerated locally
+ // for interactive usage and thus always differ from the remote ones,
+ // so they cannot be compared to detect a password change. The SRP
+ // attributes can be: they match remote when the password is the same.
const remoteSRPAttributes = await getSRPAttributes(email);
- // If we get something (and usually we should),
if (remoteSRPAttributes) {
- // See if it is different from the one we have locally. Use the kekSalt
- // as a proxy for comparing the entire object (The kekSalt will be
- // different if a new password has been generated).
+ // The kekSalt changes when a new password is set, so it serves as
+ // a proxy for comparing the entire SRP attributes object.
if (remoteSRPAttributes.kekSalt != localSRPAttributes.kekSalt) {
- // The token is still valid, but the key and SRP attributes have
- // changed.
return {
status: "validButPasswordChanged",
updatedKeyAttributes: remoteKeyAttributes,
@@ -124,31 +66,13 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
}
}
- // The token is still valid.
return { status: "valid" };
};
-/**
- * Return `true` if the user does not have a saved auth token, of it is no
- * longer valid. If needed, also update the key attributes at remote.
- *
- * This is a subset of {@link checkSessionValidity} that has been tailored for
- * use during each remote pull, to detect if the user has been logged out
- * elsewhere.
- *
- * @returns `true` if either we don't have an auth token, or if remote tells us
- * that the auth token (and the associated session) has been invalidated. In all
- * other cases, return `false`.
- *
- * In particular, this function doesn't throw and instead returns `false` on
- * errors. This is because returning `true` will trigger a blocking alert that
- * 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 isSessionInvalid = async (): Promise<boolean> => {
const token = await savedAuthToken();
if (!token) {
- return true; /* No saved token, session is invalid */
+ return true;
}
try {
@@ -156,7 +80,7 @@ export const isSessionInvalid = async (): Promise<boolean> => {
headers: await authenticatedRequestHeaders(),
});
if (!res.ok) {
- if (res.status == 401) return true; /* session is no longer valid */
+ if (res.status == 401) return true;
else throw new HTTPError(res);
}
@@ -168,10 +92,10 @@ export const isSessionInvalid = async (): Promise<boolean> => {
}
} catch (e) {
log.warn("Failed to check session validity", e);
- // Don't logout user on potentially transient errors.
+ // Returning true would log the user out, so do not do that on
+ // potentially transient errors.
return false;
}
- // Everything seems ok.
return false;
};
diff --git a/web/packages/accounts-rs/services/sessions.ts b/web/packages/accounts-rs/services/sessions.ts
index 5b252083f7..f0bec949bf 100644
--- a/web/packages/accounts-rs/services/sessions.ts
+++ b/web/packages/accounts-rs/services/sessions.ts
@@ -2,67 +2,28 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { z } from "zod";
-/**
- * Zod schema for an individual session returned by the API.
- */
const Session = z.object({
- /**
- * The session token.
- */
token: z.string(),
- /**
- * The time (epoch microseconds) when the session was created.
- */
creationTime: z.number(),
- /**
- * The IP address from which the session was created.
- */
ip: z.string(),
- /**
- * The raw user agent string.
- */
ua: z.string(),
- /**
- * A human-readable version of the user agent.
- */
prettyUA: z.string(),
- /**
- * The time (epoch microseconds) when the session was last used.
- */
lastUsedTime: z.number(),
});
-/**
- * TypeScript type for a session, derived from the Zod schema.
- */
export type Session = z.infer<typeof Session>;
-/**
- * Zod schema for the sessions API response.
- */
const SessionsResponse = z.object({ sessions: z.array(Session) });
-/**
- * Fetch all active sessions for the current user.
- *
- * @returns A promise that resolves to an array of {@link Session} objects,
- * sorted by last used time (most recent first).
- */
export const getActiveSessions = async (): Promise<Session[]> => {
const res = await fetch(await apiURL("/users/sessions"), {
headers: await authenticatedRequestHeaders(),
});
ensureOk(res);
const { sessions } = SessionsResponse.parse(await res.json());
- // Sort by last used time, most recent first.
return sessions.sort((a, b) => b.lastUsedTime - a.lastUsedTime);
};
-/**
- * Terminate a specific session.
- *
- * @param token The token of the session to terminate.
- */
export const terminateSession = async (token: string): Promise<void> => {
const url = await apiURL("/users/session");
const res = await fetch(`${url}?token=${encodeURIComponent(token)}`, {
diff --git a/web/packages/accounts-rs/services/user.ts b/web/packages/accounts-rs/services/user.ts
index 5ed718f50b..3475b0aadb 100644
--- a/web/packages/accounts-rs/services/user.ts
+++ b/web/packages/accounts-rs/services/user.ts
@@ -42,235 +42,42 @@ import { z } from "zod";
import { clearInflightPasskeySessionID } from "./passkey";
import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";
-/**
- * The locally persisted data we have about the user after they've logged in.
- *
- * This type arguably belongs to accounts-db (since that's what persists it and
- * its shadow alias, {@link PartialLocalUser}), but since most code that will
- * need this will need this after login has completed, and will be using the
- * {@link ensureLocalUser} method below, we keep this in the same file to reduce
- * the need to import the type from a separate file.
- */
export interface LocalUser {
- /**
- * The user's ID.
- */
id: number;
- /**
- * The email associated with the user's Ente account.
- */
email: string;
- /**
- * The user's (plaintext) auth token.
- *
- * It is used for making API calls on their behalf, by passing this token as
- * the value of the X-Auth-Token header in the HTTP request.
- *
- * Usually you shouldn't be needing to access this property; instead use
- * {@link savedAuthToken()} which is kept in sync with this value, and lives
- * in IndexedDB and thus can also be used in web workers.
- */
+ // Prefer savedAuthToken over this property; it is kept in sync with this
+ // value and, being in IndexedDB, is also usable in web workers.
token: string;
- /**
- * `true` if the TOTP based second factor is enabled for the user.
- */
isTwoFactorEnabled?: boolean;
}
-/**
- * Return the currently logged in {@link LocalUser}, throwing it the user is not
- * logged in.
- *
- * This is a wrapper over the {@link savedLocalUser} function that throws if no
- * one is logged in. A more appropriate name for this function, keeping in line
- * with the conventions the other methods follow, would've been
- * {@link ensureSavedLocalUser}. The shorter name is for readability.
- */
export const ensureLocalUser = (): LocalUser =>
ensureExpectedLoggedInValue(savedLocalUser());
-/**
- * A function throws an error if a value that is expected to be truthy when the
- * user is logged in is instead falsey.
- *
- * This is meant as a convenience wrapper to assert that a value we expect when
- * the user is logged in is indeed there.
- */
export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {
if (!t) throw new Error("Not logged in");
return t;
};
-/**
- * The user's various encrypted keys and their related attributes.
- *
- * - Attributes to derive the KEK, the (master) key encryption key.
- * - Encrypted master key (with KEK)
- * - Encrypted master key (with recovery key)
- * - Encrypted recovery key (with master key).
- * - Public key and encrypted private key (with master key).
- *
- * The various "key" attributes are base64 encoded representations of the
- * underlying binary data.
- *
- * [Note: Key attribute mutability]
- *
- * The key attributes contain two subsets:
- *
- * - Attributes that changes when the user changes their password. These are the
- * {@link UpdatedKeyAttr}.
- *
- * - All other attributes never change after initial setup.
- */
export interface KeyAttributes {
- /**
- * The user's master key encrypted with the key encryption key.
- *
- * Base64 encoded.
- *
- * [Note: Key encryption key]
- *
- * The user's master key is encrypted with a "key encryption key" (lovingly
- * called a "KEK" sometimes).
- *
- * The KEK itself is derived from the user's password.
- *
- * 1. User enters password on new device.
- *
- * 2. Client derives KEK from this password (using the {@link kekSalt},
- * {@link opsLimit} and {@link memLimit} as parameters for the
- * derivation).
- *
- * 3. Client use KEK to decrypt the master key from {@link encryptedKey} and
- * {@link keyDecryptionNonce}.
- */
encryptedKey: string;
- /**
- * The nonce used during the encryption of the master key.
- *
- * Base64 encoded.
- *
- * @see {@link encryptedKey}.
- */
keyDecryptionNonce: string;
- /**
- * The salt used during the derivation of the KEK.
- *
- * Base64 encoded.
- *
- * [Note: KEK three tuple]
- *
- * The three tuple (kekSalt, opsLimit, memLimit) is needed (along with the
- * user's password) to rederive the KEK when the user logs in on a new
- * client (See: [Note: Key encryption key]).
- *
- * The client can obtain these three by fetching their key attributes from
- * remote, however unless {@link isEmailMFAEnabled} is enabled (which is not
- * by default), then the user's credentials are verified using SRP instead
- * of email verification. So as a convenience for this (majority) flow,
- * remote also provides this exact same three tuple as part of the
- * {@link SRPAttributes} fetched from remote.
- *
- * So on remote the KEK three tuple is the same whether it be part of key
- * attributes or SRP attributes. When the user changes their password, both
- * of them also get updated simulataneously (they use the same storage).
- *
- * However, on the client side these two sets of three tuples might diverge
- * because of the client generating interactive key attributes. When that
- * happens, the locally saved key attributes will be overwritten by the KEK
- * three tuple for the new generated interactive KEK parameters, while the
- * SRP attributes will continue to reflect the "original" KEK three tuple we
- * got from remote.
- */
kekSalt: string;
- /**
- * The operation limit used during the derivation of the KEK.
- *
- * The {@link opsLimit} and {@link memLimit} are complementary parameters
- * that define the amount of work done by the key derivation function. See
- * the {@link deriveKey}, {@link deriveSensitiveKey} and
- * {@link deriveInteractiveKey} functions for more detail about them.
- *
- * See: [Note: Key encryption key].
- */
opsLimit: number;
- /**
- * The memory limit used during the derivation of the KEK.
- *
- * See {@link opsLimit} for more details.
- */
memLimit: number;
- /**
- * The user's public key (part of their public-key keypair, the other half
- * being the {@link encryptedSecretKey}).
- *
- * Base64 encoded.
- */
publicKey: string;
- /**
- * The user's private key (part of their public-key keypair, the other half
- * being the {@link publicKey}) encrypted with their master key.
- *
- * Base64 encoded.
- *
- * [Note: privateKey and secretKey]
- *
- * The nomenclature for the key pair follows libsodium's conventions
- * (https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation),
- * who possibly chose public + secret instead of public + private to avoid
- * confusion with shorthand notation (pk).
- *
- * However, the library author later changed their mind on this, so while
- * libsodium itself (the C library) and the documentation uses "secretKey",
- * the JavaScript implementation (libsodium.js) uses "privateKey".
- *
- * This structure uses the term "secretKey" since that is what the remote
- * protocol already was based on. Within the web app codebase, we use
- * "privateKey" since that is what the underlying libsodium.js uses.
- */
+ // libsodium and the wire protocol call this the "secret" key, but
+ // libsodium.js calls it the "private" key; the codebase uses "privateKey"
+ // to match libsodium.js.
+ // https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation
encryptedSecretKey: string;
- /**
- * The nonce used during the encryption of {@link encryptedSecretKey}.
- */
secretKeyDecryptionNonce: string;
- /**
- * The user's master key after being encrypted with their recovery key.
- *
- * Base64 encoded.
- *
- * This allows the user to recover their master key if they forget their
- * password but still have their recovery key.
- *
- * Note: This value doesn't change after being initially created.
- */
masterKeyEncryptedWithRecoveryKey?: string;
- /**
- * The nonce used during the encryption of
- * {@link masterKeyEncryptedWithRecoveryKey}.
- *
- * Base64 encoded.
- */
masterKeyDecryptionNonce?: string;
- /**
- * The user's recovery key after being encrypted with their master key.
- *
- * Base64 encoded.
- *
- * Note: This value doesn't change after being initially created.
- */
recoveryKeyEncryptedWithMasterKey?: string;
- /**
- * The nonce used during the encryption of
- * {@link recoveryKeyEncryptedWithMasterKey}.
- *
- * Base64 encoded.
- */
recoveryKeyDecryptionNonce?: string;
}
-/**
- * Zod schema for {@link KeyAttributes}.
- */
export const RemoteKeyAttributes = z.object({
kekSalt: z.string(),
encryptedKey: z.string(),
@@ -292,10 +99,6 @@ export const RemoteKeyAttributes = z.object({
recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
});
-/**
- * A variant of {@link savedKeyAttributes} that throws if keyAttributes are not
- * present in local storage.
- */
export const ensureSavedKeyAttributes = (): KeyAttributes =>
ensureExpectedLoggedInValue(savedKeyAttributes());
@@ -323,9 +126,6 @@ export const getPublicKey = async (email: string) => {
.publicKey;
};
-/**
- * Fetch the TOTP based two-factor status for the logged in user from remote.
- */
export const getTwoFactorStatus = async () => {
const res = await fetch(await apiURL("/users/two-factor/status"), {
headers: await authenticatedRequestHeaders(),
@@ -340,14 +140,6 @@ export interface GenerateKeysAndAttributesResult {
keyAttributes: KeyAttributes;
}
-/**
- * Generate a new set of key attributes.
- *
- * @param password The password to use for deriving the key encryption key.
- *
- * @returns a newly generated master key (base64 string), kek (base64 string)
- * and the key attributes associated with the combination.
- */
export async function generateKeysAndAttributes(
password: string,
): Promise<GenerateKeysAndAttributesResult> {
@@ -395,9 +187,6 @@ export async function generateKeysAndAttributes(
return { masterKey, kek, keyAttributes };
}
-/**
- * Update or set the user's {@link KeyAttributes} on remote.
- */
export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>
ensureOk(
await fetch(await apiURL("/users/attributes"), {
@@ -414,14 +203,8 @@ export interface RecoveryKeyAttributes {
recoveryKeyDecryptionNonce: string;
}
-/**
- * Update the encrypted recovery key attributes for the logged in user.
- *
- * In practice, this is not expected to be called and is meant as a rare
- * fallback for very old accounts created prior to recovery key related
- * attributes being assigned on account setup. Even for these, it'll be called
- * only once.
- */
+// This is a rare fallback for very old accounts that predate recovery key
+// attributes being set during account setup.
export const putUserRecoveryKeyAttributes = async (
recoveryKeyAttributes: RecoveryKeyAttributes,
) =>
@@ -433,20 +216,6 @@ export const putUserRecoveryKeyAttributes = async (
}),
);
-/**
- * Ask remote to send a OTP / OTT to the given email to verify that the user has
- * access to it. Subsequent the app will pass this OTT back via the
- * {@link verifyOTT} method.
- *
- * @param email The email to verify.
- *
- * @param purpose In which context is the email being verified. Remote applies
- * additional business rules depending on this. For example, passing the purpose
- * "login" ensures that the OTT is only sent to an already registered email.
- *
- * In cases where the purpose is ambiguous (e.g. we're not sure if it is an
- * existing login or a new signup), the purpose can be set to `undefined`.
- */
export const sendOTT = async (
email: string,
purpose: "change" | "signup" | "login" | undefined,
@@ -459,106 +228,17 @@ export const sendOTT = async (
}),
);
-/**
- * The response from remote on a successful user verification, either via
- * {@link verifyEmail} or {@link verifySRP}.
- *
- * The {@link id} is always present. The rest of the values are are optional
- * since only a subset of them will be returned depending on the case:
- *
- * 1. If the user has both passkeys and TOTP based second factor enabled, then
- * the following will be set:
- * - {@link passkeySessionID}, {@link accountsUrl}
- * - {@link twoFactorSessionIDV2}
- *
- * 2. If the user has only passkeys enabled, then the following will be set:
- * - {@link passkeySessionID}, {@link accountsUrl}
- *
- * 3. If the user has only TOTP based second factor enabled, then the following
- * will be set:
- * - {@link twoFactorSessionID}
- *
- * 4. If the user doesn't have any second factor, but has already setup their
- * key attributes, then the following will be set:
- * - {@link keyAttributes}
- * - {@link encryptedToken}
- *
- * 5. Finally, in the rare case that the user has not yet setup their key
- * attributes, then the following will be set:
- * - {@link token}
- */
export interface EmailOrSRPVerificationResponse {
- /**
- * The user's ID.
- */
id: number;
- /**
- * The user's key attributes.
- *
- * These will be set (along with the {@link encryptedToken}) if the user
- * does not have a second factor.
- */
keyAttributes?: KeyAttributes;
- /**
- * The base64 representation of an encrypted auth token, encrypted using the
- * user's public key.
- *
- * These will be set (along with the {@link keyAttributes}) if the user
- * does not have a second factor.
- */
encryptedToken?: string;
- /**
- * The base64 representation of an auth token.
- *
- * This will be set in the rare edge case for when the user has not yet
- * setup their key attributes.
- */
token?: string;
- /**
- * A session ID that can be used to complete the TOTP based second factor.
- *
- * This will be set if the user has enabled a TOTP based second factor but
- * has not enabled passkeys.
- */
twoFactorSessionID?: string;
- /**
- * A session ID that can be used to complete passkey verification.
- *
- * This will be set if the user has added a passkey to their account.
- */
passkeySessionID?: string;
- /**
- * Base URL for the accounts app where we should redirect to for passkey
- * verification.
- *
- * This will only be set if the user has setup a passkey (i.e., whenever
- * {@link passkeySessionID} is defined).
- */
accountsUrl?: string;
- /**
- * A session ID that can be used to complete the TOTP based second fator.
- *
- * This will be set in lieu of {@link twoFactorSessionID} if the user has
- * setup both passkeys and TOTP based two factors are enabled for their
- * account.
- *
- * ---
- *
- * Historical context: {@link twoFactorSessionIDV2} is only set if user has
- * both passkey and two factor enabled. This is to ensure older clients keep
- * using passkey flow when both are set. It is intended to be removed once
- * all clients starts surfacing both options for performing 2FA.
- *
- * See also {@link useSecondFactorChoiceIfNeeded}.
- */
twoFactorSessionIDV2?: string;
}
-/**
- * Zod schema for the {@link EmailOrSRPVerificationResponse} type.
- *
- * See: [Note: Duplicated Zod schema and TypeScript type]
- */
const RemoteEmailOrSRPVerificationResponseBase = z.object({
id: z.number(),
keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
@@ -586,35 +266,13 @@ const RemoteEmailOrSRPVerificationResponse =
accountsUrlForPasskeyRefinement,
);
-/**
- * A specialization of {@link RemoteEmailOrSRPVerificationResponse} for SRP
- * verification, which results in the {@link srpM2} field in addition to the
- * other ones.
- *
- * The declaration conceptually belongs to `srp.ts`, but is here to avoid cyclic
- * dependencies.
- */
+// This declaration conceptually belongs to srp.ts, but lives here to avoid a
+// cyclic dependency.
export const RemoteSRPVerificationResponse =
RemoteEmailOrSRPVerificationResponseBase.extend({
- /**
- * The SRP M2 (evidence message), the proof that the server has the
- * verifier.
- */
srpM2: z.string(),
}).refine(requireAccountsUrlForPasskey, accountsUrlForPasskeyRefinement);
-/**
- * Verify user's access to the given {@link email} by comparing the OTT that
- * remote previously sent to that email.
- *
- * @param email The email to verify.
- *
- * @param ott The OTT that the user entered.
- *
- * @param source During signup, we ask the user the referral "source" through
- * which they heard about Ente. When present (i.e. during signup, and if the
- * user indeed provided it), that source should be passed as this parameter.
- */
export const verifyEmail = async (
email: string,
ott: string,
@@ -629,13 +287,10 @@ export const verifyEmail = async (
return RemoteEmailOrSRPVerificationResponse.parse(await res.json());
};
-/**
- * Log the user out on remote, if possible and needed.
- */
export const remoteLogoutIfNeeded = async () => {
if (!(await savedAuthToken())) {
- // If the logout is attempted during the login / signup flow itself,
- // then we won't have an auth token. Handle that gracefully.
+ // The logout was attempted during the login / signup flow itself, so
+ // there is no auth token yet and nothing to log out on remote.
return;
}
@@ -644,45 +299,16 @@ export const remoteLogoutIfNeeded = async () => {
headers: await authenticatedRequestHeaders(),
});
if (res.status == 401) {
- // Ignore if we get a 401 Unauthorized, this is expected to happen on
- // token expiry.
+ // A 401 is expected when the token has already expired; ignore it.
return;
}
ensureOk(res);
};
-/**
- * Generate a new local-only KEK (key encryption key) suitable for interactive
- * use and update the locally saved key attributes to reflect it.
- *
- * See {@link deriveInteractiveKey} for more details.
- *
- * In brief, after the initial password verification, we create a new
- * inetractive KEK derived from the same password as the original KEK, but with
- * so called interactive mem and ops limits which result in a noticeably faster
- * key derivation.
- *
- * We then overwrite the encrypted master key, encryption nonce and the KEK
- * derivation parameters (see: [Note: KEK three tuple]) in the locally persisted
- * {@link KeyAttributes} so that these interactive parameters get used
- * subsequent reauthentication.
- *
- * These are more ergonomic for the user especially in the web app where they
- * need to enter their password to access their masterKey when repopening the
- * app in a new tab (on desktop we can avoid this by using OS storage, see
- * [Note: Safe storage and interactive KEK attributes]).
- *
- * @param password The user's password.
- *
- * @param keyAttributes The existing "original" key attributes, which we
- * might've generated locally (new signup) or fetched from remote (existing
- * login).
- *
- * @param masterKey The user's master key (base64 encoded).
- *
- * @returns the update key attributes.
- */
+// The interactive KEK and the key attributes this function saves are local
+// only and are never sent to remote; the saved SRP attributes retain the
+// original KEK derivation parameters from remote.
export const generateAndSaveInteractiveKeyAttributes = async (
password: string,
keyAttributes: KeyAttributes,
@@ -710,22 +336,11 @@ export const generateAndSaveInteractiveKeyAttributes = async (
return interactiveKeyAttributes;
};
-/**
- * Change the email associated with the user's account (both locally and on
- * remote)
- *
- * @param email The new email.
- *
- * @param ott The verification code that was sent to the new email.
- */
export const changeEmail = async (email: string, ott: string) => {
await postChangeEmail(email, ott);
updateSavedLocalUser({ email });
};
-/**
- * Change the email associated with the user's account on remote.
- */
const postChangeEmail = async (email: string, ott: string) =>
ensureOk(
await fetch(await apiURL("/users/change-email"), {
@@ -735,17 +350,11 @@ const postChangeEmail = async (email: string, ott: string) =>
}),
);
-/**
- * Change the user's password on both remote and locally.
- *
- * @param password The new password.
- */
export const changePassword = async (password: string) => {
const user = ensureLocalUser();
const masterKey = await ensureMasterKeyFromSession();
const keyAttributes = ensureSavedKeyAttributes();
- // Generate new KEK.
const {
key: kek,
salt: kekSalt,
@@ -753,7 +362,6 @@ export const changePassword = async (password: string) => {
memLimit,
} = await deriveSensitiveKey(password);
- // Generate new key attributes.
const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
await encryptBox(masterKey, kek);
const updatedKeyAttr: UpdatedKeyAttr = {
@@ -764,20 +372,16 @@ export const changePassword = async (password: string) => {
memLimit,
};
- // Update SRP and key attributes on remote.
await updateSRPAndKeyAttributes(
await generateSRPSetupAttributes(kek),
updatedKeyAttr,
);
- // Update SRP attributes locally.
await getAndSaveSRPAttributes(user.email);
const srpAttributes = await getSRPAttributes(user.email);
saveSRPAttributes(ensure(srpAttributes));
- // Update key attributes locally, generating a new interactive kek while
- // we're at it.
await generateAndSaveInteractiveKeyAttributes(
password,
{ ...keyAttributes, ...updatedKeyAttr },
@@ -785,25 +389,6 @@ export const changePassword = async (password: string) => {
);
};
-/**
- * Update the {@link id} and {@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 decryptAndStoreTokenIfNeeded} 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 also saved to
- * the partial local user (after doing a sanity check that we're not replacing
- * partial data with a different userID).
- *
- * @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,
@@ -821,14 +406,6 @@ export const resetSavedLocalUserTokens = async (
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 decryptAndStoreTokenIfNeeded = async (
keyAttributes: KeyAttributes,
masterKey: string,
@@ -852,25 +429,13 @@ export const decryptAndStoreTokenIfNeeded = async (
};
const TwoFactorSecret = z.object({
- /**
- * The 2FA secret code.
- */
secretCode: z.string(),
- /**
- * A base64 encoded "image/png".
- */
+ // The value is a base64 encoded PNG image.
qrCode: z.string(),
});
export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;
-/**
- * Start a TOTP based two factor setup process by fetching a secret code (and
- * the corresponding QR code) from remote.
- *
- * Once the user provides us with a TOTP generated using the provided secret, we
- * can finish the setup with {@link setupTwoFactorFinish}.
- */
export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {
const res = await fetch(await apiURL("/users/two-factor/setup"), {
method: "POST",
@@ -880,18 +445,6 @@ export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {
return TwoFactorSecret.parse(await res.json());
};
-/**
- * Finish the TOTP based two factor setup by provided a previously obtained
- * secret (using {@link setupTwoFactor}) and the current TOTP generated using
- * that secret.
- *
- * This updates both the state both locally and on remote.
- *
- * @param secretCode The value of {@link secretCode} from the
- * {@link TwoFactorSecret} obtained by {@link setupTwoFactor}.
- *
- * @param totp The current TOTP corresponding to {@link secretCode}.
- */
export const setupTwoFactorFinish = async (
secretCode: string,
totp: string,
@@ -905,9 +458,6 @@ export const setupTwoFactorFinish = async (
updateSavedLocalUser({ isTwoFactorEnabled: true });
};
-/**
- * Disable TOTP based two-factor authentication for the logged in user.
- */
export const disableTwoFactor = async () => {
ensureOk(
await fetch(await apiURL("/users/two-factor/disable"), {
@@ -919,28 +469,11 @@ export const disableTwoFactor = async () => {
};
interface EnableTwoFactorRequest {
- /**
- * The current value of the TOTP corresponding to the two factor {@link
- * secretCode} obtained from a previous call to {@link setupTwoFactor}.
- */
code: string;
- /**
- * The {@link secretCode} encrypted with the user's recovery key.
- *
- * This is used in the case of second factor recovery.
- */
encryptedTwoFactorSecret: string;
- /**
- * The nonce that was used when encrypting {@link encryptedTwoFactorSecret}.
- */
twoFactorSecretDecryptionNonce: string;
}
-/**
- * Enable the TOTP based two factor for the user by providing the current 2FA
- * code corresponding the two factor secret, and encrypted secrets for future
- * recovery (if needed).
- */
const enableTwoFactor = async (req: EnableTwoFactorRequest) =>
ensureOk(
await fetch(await apiURL("/users/two-factor/enable"), {
@@ -950,22 +483,9 @@ const enableTwoFactor = async (req: EnableTwoFactorRequest) =>
}),
);
-/**
- * The result of a successful two factor verification (TOTP or passkey),
- * recovery removal (TOTP) or recovery bypass (passkey).
- */
export const TwoFactorAuthorizationResponse = z.object({
- /**
- * The user's ID.
- */
id: z.number(),
- /**
- * The user's key attributes.
- */
keyAttributes: RemoteKeyAttributes,
- /**
- * A encrypted auth token.
- */
encryptedToken: z.string(),
});
@@ -986,17 +506,10 @@ export const verifyTwoFactor = async (
return TwoFactorAuthorizationResponse.parse(await res.json());
};
-/** The type of the second factor we're trying to act on */
export type TwoFactorType = "totp" | "passkey";
const TwoFactorRecoveryResponse = z.object({
- /**
- * The recovery secret, encrypted using the user's recovery key.
- */
encryptedSecret: z.string(),
- /**
- * The nonce used during encryption of {@link encryptedSecret}.
- */
secretDecryptionNonce: z.string(),
});
@@ -1004,35 +517,6 @@ export type TwoFactorRecoveryResponse = z.infer<
typeof TwoFactorRecoveryResponse
>;
-/**
- * Initiate second factor reset or bypass by requesting the encrypted second
- * factor recovery secret (and nonce) from remote. The user can then decrypt
- * these using their recovery key to reset or bypass their second factor.
- *
- * @param twoFactorType The type of second factor to reset or bypass.
- *
- * @param sessionID A two factor session ID ({@link twoFactorSessionID} or
- * {@link passkeySessionID}) for the user.
- *
- * [Note: Second factor recovery]
- *
- * 1. When setting up a TOTP based second factor, client sends a (encrypted 2fa
- * recovery secret, nonce) pair to remote. This is a randomly generated
- * secret (and nonce) encrypted using the user's recovery key.
- *
- * 2. Similarly, when setting up a passkey as the second factor, the client
- * sends a encrypted recovery secret (see {@link configurePasskeyRecovery}).
- *
- * 3. When the user wishes to reset or bypass their second factor, the client
- * asks remote for these encrypted secrets (using {@link getRecoverTwoFactor}).
- *
- * 4. User then enters their recovery key, which the client uses to decrypt the
- * recovery secret and provide it back to remote for verification (using
- * {@link removeTwoFactor}).
- *
- * 5. If the recovery secret matches, then remote resets (TOTP based) or bypass
- * (passkey based) the user's second factor.
- */
export const getRecoverTwoFactor = async (
twoFactorType: TwoFactorType,
sessionID: string,
@@ -1045,29 +529,6 @@ export const getRecoverTwoFactor = async (
return TwoFactorRecoveryResponse.parse(await res.json());
};
-/**
- * Finish the second factor recovery / bypass initiated by
- * {@link getRecoverTwoFactor} using the provided recovery key mnemonic entered
- * by the user.
- *
- * See: [Note: Second factor recovery].
- *
- * This completes the recovery process both locally, and on remote.
- *
- * @param twoFactorType The second factor type (same value as what would've been
- * passed to {@link getRecoverTwoFactor} for obtaining
- * {@link recoveryResponse}).
- *
- * @param sessionID The second factor session ID (same value as what would've
- * been passed to {@link getRecoverTwoFactor} for obtaining
- * {@link recoveryResponse}).
- *
- * @param recoveryResponse The response to a previous call to
- * {@link getRecoverTwoFactor}.
- *
- * @param recoveryKeyMnemonic The 24-word BIP-39 recovery key mnemonic provided
- * by the user to complete recovery.
- */
export const recoverTwoFactorFinish = async (
twoFactorType: TwoFactorType,
sessionID: string,
diff --git a/web/packages/accounts/components/CodeBlock.tsx b/web/packages/accounts/components/CodeBlock.tsx
index 63fd696064..b4b08b34d4 100644
--- a/web/packages/accounts/components/CodeBlock.tsx
+++ b/web/packages/accounts/components/CodeBlock.tsx
@@ -8,18 +8,9 @@ import { t } from "i18next";
import React from "react";
interface CodeBlockProps {
- /**
- * The code (an arbitrary string) to show.
- *
- * If not present, then an activity indicator will be shown.
- */
code: string | undefined;
}
-/**
- * A component that shows a "code" (e.g. the user's recovery key, or a 2FA setup
- * code), alongwith a button to copy it.
- */
export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
if (!code) {
return (
@@ -42,7 +33,6 @@ export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
padding: "16px 44px 16px 16px",
wordBreak: "break-word",
color: "accent.contrastText",
- // Increase the line height from the body default.
lineHeight: 1.5,
}}
>
@@ -56,9 +46,6 @@ export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
};
interface CopyButtonProps {
- /**
- * The code to copy when the button is clicked.
- */
code: string;
}
diff --git a/web/packages/accounts/components/LoginComponents.tsx b/web/packages/accounts/components/LoginComponents.tsx
index fb70567e16..e432ceac63 100644
--- a/web/packages/accounts/components/LoginComponents.tsx
+++ b/web/packages/accounts/components/LoginComponents.tsx
@@ -20,15 +20,6 @@ import {
} from "./layouts/centered-paper";
interface HeaderCaptionProps {
- /**
- * If specified, then a caption to display below the title (which is
- * expected to be passed as the `children`).
- *
- * The components which use the {@link HeaderCaptionProps} that they'll have
- * the same height irrespective of whether or not the caption is provided.
- * This allows us to use this component to get a similar look across various
- * pages in the login flow (some of which have a caption, some which not).
- */
caption?: string;
}
@@ -87,13 +78,9 @@ export const AccountsPageFooterWithHost: React.FC<React.PropsWithChildren> = ({
};
interface VerifyingPasskeyProps {
- /** ID of the current passkey verification session. */
passkeySessionID: string;
- /** The email of the user whose passkey we're verifying. */
email: string | undefined;
- /** Called when the user wants to redirect again. */
onRetry: () => void;
- /** Perform the (possibly app specific) logout sequence. */
logout: () => void;
showMiniDialog: (attrs: MiniDialogAttributes) => void;
}
diff --git a/web/packages/accounts/components/LoginContents.tsx b/web/packages/accounts/components/LoginContents.tsx
index cecd3c0e6e..49ae97692e 100644
--- a/web/packages/accounts/components/LoginContents.tsx
+++ b/web/packages/accounts/components/LoginContents.tsx
@@ -20,22 +20,10 @@ import { z } from "zod";
import { AccountsPageTitleWithCaption } from "./LoginComponents";
interface LoginContentsProps {
- /**
- * Reactive value of {@link customAPIHost}.
- */
host: string | undefined;
- /**
- * Called when the user clicks the signup option instead.
- */
onSignUp: () => void;
}
-/**
- * A contents of the "login" form.
- *
- * It is used both on the "/login" page, and as the embedded login form on the
- * "/" page where the user can toggle between the signup and login forms inline.
- */
export const LoginContents: React.FC<LoginContentsProps> = ({
onSignUp,
host,
@@ -45,7 +33,6 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
const isEnsu = appName === "ensu";
useEffect(() => {
- // Check if we're in a join album context
const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
setIsJoinAlbumContext(!!joinAlbumContext);
}, []);
@@ -136,7 +123,6 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
margin="normal"
disabled={formik.isSubmitting}
error={!!formik.errors.email}
- // See: [Note: Use space as default TextField helperText]
helperText={formik.errors.email ?? " "}
/>
<Input sx={{ display: "none" }} type="password" value="" />
@@ -164,7 +150,7 @@ export const LoginContents: React.FC<LoginContentsProps> = ({
variant="mini"
sx={{ color: "text.faint", minHeight: "16px" }}
>
- {host ?? "" /* prevent layout shift with a minHeight */}
+ {host ?? ""}
</Typography>
</Stack>
</AccountsPageFooter>
diff --git a/web/packages/accounts/components/NewPasswordForm.tsx b/web/packages/accounts/components/NewPasswordForm.tsx
index df0eff863c..561fbcbb5d 100644
--- a/web/packages/accounts/components/NewPasswordForm.tsx
+++ b/web/packages/accounts/components/NewPasswordForm.tsx
@@ -10,41 +10,14 @@ import { Trans } from "react-i18next";
import { PasswordStrengthHint } from "./PasswordStrength";
export interface NewPasswordFormProps {
- /**
- * The email of the user whose password we are setting.
- *
- * This is used to show a hidden input field of type email (and the provided
- * value) to aid password managers to detect and save the new password,
- * associating it with the user's email.
- */
userEmail: string;
- /**
- * The title of the form's submit button.
- */
submitButtonTitle: string;
- /**
- * Submission handler. A callback invoked when the submit button is pressed.
- *
- * @param password The new password entered by the user. The form will first
- * check that both of the passwords entered by the user match, and that the
- * password is not too weak.
- *
- * @param setPasswordsFieldError A function that can be called to show an
- * error message below the password fields.
- */
onSubmit: (
password: string,
setPasswordsFieldError: (message: string) => void,
) => Promise<void>;
}
-/**
- * A form showing two password input fields, a password strength indicator, and
- * a submit button.
- *
- * This form can be used both for the initial setup of the password, and for
- * later changing it.
- */
export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
userEmail,
submitButtonTitle,
@@ -93,6 +66,8 @@ export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
{t("pick_password_hint")}
</Typography>
+ {/* This hidden email input helps password managers associate the
+ new password with the user's email. */}
<Input
sx={{ display: "none" }}
name="email"
@@ -129,7 +104,6 @@ export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
value={formik.values.confirmPassword}
onChange={formik.handleChange}
error={!!formik.errors.confirmPassword}
- // See: [Note: Use space as default TextField helperText]
helperText={formik.errors.confirmPassword ?? " "}
disabled={formik.isSubmitting}
fullWidth
diff --git a/web/packages/accounts/components/RecoveryKey.tsx b/web/packages/accounts/components/RecoveryKey.tsx
index 11211a14bf..2cc0f9a5ae 100644
--- a/web/packages/accounts/components/RecoveryKey.tsx
+++ b/web/packages/accounts/components/RecoveryKey.tsx
@@ -64,12 +64,9 @@ export const RecoveryKey: React.FC<RecoveryKeyProps> = ({
fullScreen={fullScreen}
open={open}
onClose={onClose}
- // [Note: maxWidth "xs" on MUI dialogs]
- //
- // While logically the "xs" breakpoint doesn't make sense as a
- // maxWidth value (since as a breakpoint it's value is 0), in
- // practice MUI has hardcoded its value to a reasonable 444px.
- // https://github.com/mui/material-ui/issues/34646.
+ // MUI hardcodes the dialog maxWidth for "xs" to 444px, even though
+ // the "xs" breakpoint itself is 0.
+ // https://github.com/mui/material-ui/issues/34646
maxWidth="xs"
fullWidth
>
diff --git a/web/packages/accounts/components/SecondFactorChoice.tsx b/web/packages/accounts/components/SecondFactorChoice.tsx
index 251db57014..63445b77f4 100644
--- a/web/packages/accounts/components/SecondFactorChoice.tsx
+++ b/web/packages/accounts/components/SecondFactorChoice.tsx
@@ -7,18 +7,9 @@ import React from "react";
export type SecondFactorType = "totp" | "passkey";
type SecondFactorChoiceProps = ModalVisibilityProps & {
- /**
- * Callback invoked with the selected choice.
- *
- * The dialog will automatically be closed before this callback is invoked.
- */
onSelect: (factor: SecondFactorType) => void;
};
-/**
- * A {@link Dialog} that allow the user to choose which second factor they'd
- * like to verify during login.
- */
export const SecondFactorChoice: React.FC<SecondFactorChoiceProps> = ({
open,
onClose,
diff --git a/web/packages/accounts/components/SignUpContents.tsx b/web/packages/accounts/components/SignUpContents.tsx
index 3674820b07..8b0dde3935 100644
--- a/web/packages/accounts/components/SignUpContents.tsx
+++ b/web/packages/accounts/components/SignUpContents.tsx
@@ -50,18 +50,10 @@ import {
interface SignUpContentsProps {
router: NextRouter;
- /** Called when the user clicks the login option instead. */
onLogin: () => void;
- /** Reactive value of {@link customAPIHost}. */
host: string | undefined;
}
-/**
- * A contents of the "signup" form.
- *
- * It is used both on the "/signup" page itself, and as a subcomponent of the
- * "/" page where the user can toggle between the signup and login forms inline.
- */
export const SignUpContents: React.FC<SignUpContentsProps> = ({
router,
onLogin,
@@ -71,7 +63,6 @@ export const SignUpContents: React.FC<SignUpContentsProps> = ({
const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);
useEffect(() => {
- // Check if we're in a join album context
const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
setIsJoinAlbumContext(!!joinAlbumContext);
}, []);
@@ -312,8 +303,8 @@ export const SignUpContents: React.FC<SignUpContentsProps> = ({
mt: 1,
textAlign: "center",
color: "text.muted",
- // Prevent layout shift by using a minHeight equal to the
- // lineHeight of the eventual content that'll be shown.
+ // The minHeight, equal to the lineHeight of the eventual
+ // content, prevents layout shift.
minHeight: theme.typography.small.lineHeight,
})}
>
diff --git a/web/packages/accounts/components/Verify2FACodeForm.tsx b/web/packages/accounts/components/Verify2FACodeForm.tsx
index 2e3cb1c2d8..820e108b5d 100644
--- a/web/packages/accounts/components/Verify2FACodeForm.tsx
+++ b/web/packages/accounts/components/Verify2FACodeForm.tsx
@@ -8,28 +8,10 @@ import React, { useEffect, useState } from "react";
import OtpInput from "react-otp-input";
interface Verify2FACodeFormProps {
- /**
- * Called when the user submits the OTP.
- *
- * The submission can happen in two ways:
- * 1. The fill-in all the required 6 digits, or
- * 2. They press the "Enable" button.
- *
- * The form will stay in a submitting state until this callback returns.
- *
- * @param otp The OTP that the user entered.
- */
onSubmit: (otp: string) => Promise<void>;
- /**
- * The label for the submit button.
- */
submitButtonText: string;
}
-/**
- * A form that can be used to ask the user to fill in a 6 digit OTP that their
- * authenticator app is providing them with.
- */
export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({
onSubmit,
submitButtonText,
@@ -50,7 +32,9 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({
onSubmit: async ({ otp }, { setFieldError, resetForm }) => {
try {
await onSubmit(otp);
- resetForm(); // Prevent resubmission via the useEffect.
+ // Reset the form, otherwise the auto-submit effect below
+ // resubmits.
+ resetForm();
} catch (e) {
log.error("Failed to submit 2FA code", e);
resetForm();
diff --git a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx b/web/packages/accounts/components/VerifyMasterPasswordForm.tsx
index c974886508..93fa323875 100644
--- a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx
+++ b/web/packages/accounts/components/VerifyMasterPasswordForm.tsx
@@ -13,75 +13,14 @@ import { t } from "i18next";
import { useCallback, useState } from "react";
export interface VerifyMasterPasswordFormProps {
- /**
- * The email of the user whose password we're trying to verify.
- */
userEmail: string;
- /**
- * The user's SRP attributes.
- *
- * The SRP attributes are used to derive the KEK from the user's password.
- * If they are not present, the {@link keyAttributes} will be used instead.
- *
- * At least one of {@link srpAttributes} and {@link keyAttributes} must be
- * present, otherwise the verification will fail.
- */
srpAttributes?: SRPAttributes;
- /**
- * The user's key attributes.
- *
- * If they are present, they are used to derive the KEK from the user's
- * password when {@link srpAttributes} are not present. This is the case
- * when the user has already logged in (or signed up) on this client before,
- * and is now doing a reauthentication.
- *
- * If they are not present, then {@link getKeyAttributes} must be present
- * and will be used to obtain the user's key attributes. This is the case
- * when the user is logging into a new client.
- */
keyAttributes: KeyAttributes | undefined;
- /**
- * A callback invoked when the form wants to get {@link KeyAttributes}.
- *
- * It is only provided during the login flow, where we do not have
- * {@link keyAttributes} already available for the user. In case the form is
- * used for reauthenticating the user after they've already logged in, then
- * this function will not be provided.
- *
- * @returns The user's key attributes obtained from remote, or
- * "redirecting-second-factor" if the user has an additional second factor
- * verification required and the app is redirecting there.
- *
- * @throws A Error with message
- * {@link srpVerificationUnauthorizedErrorMessage} to signal that either
- * that the password is incorrect, or no account with the provided email
- * exists.
- */
getKeyAttributes?: (
srpAttributes: SRPAttributes,
kek: string,
) => Promise<KeyAttributes | "redirecting-second-factor" | undefined>;
- /**
- * The title of the submit button on the form.
- */
submitButtonTitle: string;
- /**
- * The callback invoked with the verified password, and all the other
- * auxillary information that was ascertained when verifying it.
- *
- * @param key The user's master key obtained after decrypting it by using
- * the KEK derived from their password.
- *
- * @param kek The key used for encrypting the user's master key.
- *
- * @param keyAttributes The user's key attributes (either those that we
- * started with, or those that we fetched on the way using
- * {@link getKeyAttributes}).
- *
- * @param password The plaintext password. This can be used during login to
- * derive another encrypted key using interactive mem/ops limits for faster
- * reauthentication after the initial login.
- */
onVerify: (
key: string,
kek: string,
@@ -90,15 +29,6 @@ export interface VerifyMasterPasswordFormProps {
) => void;
}
-/**
- * A form with a text field that can be used to ask the user to verify their
- * password.
- *
- * We use it both during the initial authentication (the "/credentials" page,
- * shown when logging in, or reopening the web app in a new tab), and when the
- * user is trying to perform a sensitive action when already logged in and
- * having a session (the {@link AuthenticateUser} component).
- */
export const VerifyMasterPasswordForm: React.FC<
VerifyMasterPasswordFormProps
> = ({
@@ -173,8 +103,6 @@ export const VerifyMasterPasswordForm: React.FC<
try {
const result = await getKeyAttributes(srpAttributes, kek);
if (result == "redirecting-second-factor") {
- // Two factor enabled, user has been redirected to the
- // corresponding second factor verification page.
return;
} else {
keyAttributes = result;
diff --git a/web/packages/accounts/components/layouts/centered-paper.tsx b/web/packages/accounts/components/layouts/centered-paper.tsx
index 521707f864..712fedc2b7 100644
--- a/web/packages/accounts/components/layouts/centered-paper.tsx
+++ b/web/packages/accounts/components/layouts/centered-paper.tsx
@@ -3,19 +3,6 @@ import { CenteredFill } from "ente-base/components/containers";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { NavbarBase } from "ente-base/components/Navbar";
-/**
- * An ad-hoc component that abstracts the layout common to many of the pages
- * exported by the the accounts package.
- *
- * The layout is roughly:
- * - Set height to 100vh
- * - An app bar at the top
- * - Center a {@link Paper} in the rest of the space.
- * - The children passed to this component go within this {@link Paper}.
- *
- * {@link AccountsPageTitle} and {@link AccountsPageFooter} are meant to be used
- * in tandem with, as children of, {@link AccountsPageContents}.
- */
export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({
children,
}) => (
@@ -77,9 +64,7 @@ export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({
direction="row"
sx={{
mx: "4px",
- // Put the items to the side,
justifyContent: "space-between",
- // Unless there is just one, in which case center it.
"& :only-child": { marginInline: "auto" },
}}
>
diff --git a/web/packages/accounts/components/utils/dialog.ts b/web/packages/accounts/components/utils/dialog.ts
index 333d06a509..52583614cb 100644
--- a/web/packages/accounts/components/utils/dialog.ts
+++ b/web/packages/accounts/components/utils/dialog.ts
@@ -1,15 +1,6 @@
import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import { t } from "i18next";
-/**
- * {@link MiniDialogAttributes} for showing asking the user to login again when
- * their session has expired.
- *
- * There is one button, which allows them to logout.
- *
- * @param onLogin Called when the user presses the "Login" button on the error
- * dialog.
- */
export const sessionExpiredDialogAttributes = (
onLogin: () => void,
): MiniDialogAttributes => ({
diff --git a/web/packages/accounts/components/utils/second-factor-choice.ts b/web/packages/accounts/components/utils/second-factor-choice.ts
index 1557255ae3..1930a7156d 100644
--- a/web/packages/accounts/components/utils/second-factor-choice.ts
+++ b/web/packages/accounts/components/utils/second-factor-choice.ts
@@ -1,22 +1,11 @@
-/**
- * @file This code is conceputally related to `SecondFactorChoice.tsx`, but
- * needs to be in a separate file to allow fast refresh.
- */
+// This hook is in a separate file from SecondFactorChoice.tsx so that fast
+// refresh keeps working.
import type { EmailOrSRPVerificationResponse } from "ente-accounts/services/user";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { useCallback, useMemo, useRef } from "react";
import type { SecondFactorType } from "../SecondFactorChoice";
-/**
- * A convenience hook for keeping track of the state and logic that is needed
- * after password verification to determine which second factor (if any) we
- * should be asking the user for.
- *
- * This is a rather ad-hoc abstraction meant to be used in a very specific way;
- * the only intent is to reduce code duplication between the two pages that need
- * this choice.
- */
export const useSecondFactorChoiceIfNeeded = () => {
const resolveSecondFactorChoice = useRef<
| ((value: SecondFactorType | PromiseLike<SecondFactorType>) => void)
@@ -46,18 +35,13 @@ export const useSecondFactorChoiceIfNeeded = () => {
passkeySessionID: _passkeySessionID,
} = response;
- // When the user has both TOTP and pk set as the second factor,
- // we'll get two session IDs. For backward compat, the TOTP session
- // ID will be in a V2 attribute during a transient migration period.
- //
- // Note the use of || instead of ?? since _twoFactorSessionIDV1 will
- // be an empty string, not undefined, if it is unset.
+ // Use || and not ?? since an unset _twoFactorSessionIDV1 is an
+ // empty string, not undefined.
const _twoFactorSessionID =
_twoFactorSessionIDV1 || _twoFactorSessionIDV2;
let passkeySessionID: string | undefined;
let twoFactorSessionID: string | undefined;
- // If both factors are set, ask the user which one they want to use.
if (_twoFactorSessionID && _passkeySessionID) {
const choice = await new Promise<SecondFactorType>(
(resolve) => {
diff --git a/web/packages/accounts/components/utils/use-redirect.ts b/web/packages/accounts/components/utils/use-redirect.ts
index de34afc717..7d162946f9 100644
--- a/web/packages/accounts/components/utils/use-redirect.ts
+++ b/web/packages/accounts/components/utils/use-redirect.ts
@@ -3,15 +3,6 @@ import { useRouter } from "next/router";
import { useEffect } from "react";
import { stashRedirect } from "../../services/redirect";
-/**
- * Redirect to the appropriate credential step (password reverify, or a full
- * login) and then back to the current page if the user's master key is not
- * present in the session storage.
- *
- * @param currentPageSlug The slug for the current page where this hook is being
- * used. If a redirect happens, then this slug will be stashed and used to
- * redirect back here after the credentials have been obtained.
- */
export const useRedirectIfNeedsCredentials = (currentPageSlug: string) => {
const router = useRouter();
diff --git a/web/packages/accounts/pages/change-email.tsx b/web/packages/accounts/pages/change-email.tsx
index 8464ff3edb..fa6052730c 100644
--- a/web/packages/accounts/pages/change-email.tsx
+++ b/web/packages/accounts/pages/change-email.tsx
@@ -19,10 +19,6 @@ import { useCallback, useState } from "react";
import { Trans } from "react-i18next";
import { z } from "zod";
-/**
- * A page that allows a user to change the email address associated with their
- * Ente account.
- */
const Page: React.FC = () => {
useRedirectIfNeedsCredentials("/change-email");
@@ -131,11 +127,6 @@ const ChangeEmailForm: React.FC = () => {
value={formik.values.email}
onChange={formik.handleChange}
error={!!formik.errors.email}
- // See: [Note: Use space as default TextField helperText]
- //
- // Also, we only need keep the extra space until the email
- // has been entered (since the email field is read only
- // after that).
helperText={
formik.errors.email ?? (requestedEmail ? "" : " ")
}
diff --git a/web/packages/accounts/pages/change-password.tsx b/web/packages/accounts/pages/change-password.tsx
index 88b67b42a9..7330cd9480 100644
--- a/web/packages/accounts/pages/change-password.tsx
+++ b/web/packages/accounts/pages/change-password.tsx
@@ -19,17 +19,11 @@ import {
} from "../components/NewPasswordForm";
import { savedLocalUser } from "../services/accounts-db";
-/**
- * A page that allows a user to reset or change their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const [user, setUser] = useState<LocalUser | undefined>(undefined);
const router = useRouter();
- // We're invoked with the "?op=reset" query parameter in the recovery flow.
const isReset = router.query.op == "reset";
useEffect(() => {
@@ -53,9 +47,6 @@ export default Page;
interface PageContentsProps {
user: LocalUser;
- /**
- * True if the password is being reset during the account recovery flow.
- */
isReset: boolean;
}
diff --git a/web/packages/accounts/pages/credentials.tsx b/web/packages/accounts/pages/credentials.tsx
index aab0ae6d1b..e8817716af 100644
--- a/web/packages/accounts/pages/credentials.tsx
+++ b/web/packages/accounts/pages/credentials.tsx
@@ -63,19 +63,6 @@ import { t } from "i18next";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to authenticate using their password.
- *
- * It is shown in two cases:
- *
- * - Initial authentication, when the user is logging in on to a new client.
- *
- * - Subsequent reauthentication, when the user opens the web app in a new tab.
- * Such a tab won't have the user's master key in session storage, so we ask
- * the user to reauthenticate using their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
@@ -118,14 +105,13 @@ const Page: React.FC = () => {
// Set a flag that causes new interactive key attributes to
// be generated.
saveIsFirstLogin();
- // This should be a rare occurrence, instead of building the
- // scaffolding to update all the in-memory state, just
- // reload everything.
+ // This should be rare; instead of updating all the
+ // in-memory state, just reload the page.
window.location.reload();
}
} catch (e) {
- // Ignore errors since we shouldn't be logging the user out for
- // potentially transient issues.
+ // Ignore errors; a potentially transient issue must not log the
+ // user out.
log.warn("Ignoring error when determining session validity", e);
}
}, [logout, showMiniDialog]);
@@ -179,8 +165,8 @@ const Page: React.FC = () => {
const kek = await unstashKeyEncryptionKeyFromSession();
const keyAttributes = savedKeyAttributes();
- // Refreshing an existing tab, or desktop app, or only the token
- // needs to decrypted and set.
+ // Refreshing an existing tab, or the desktop app: the stashed KEK
+ // decrypts the master key without asking for the password again.
if (kek && keyAttributes) {
const masterKey = await decryptBox(
{
@@ -241,8 +227,6 @@ const Page: React.FC = () => {
await verifySRP(srpAttributes, kek),
);
- // If we had to ask remote for the key attributes, it is the
- // initial login on this client.
saveIsFirstLogin();
if (passkeySessionID) {
@@ -265,8 +249,6 @@ const Page: React.FC = () => {
void router.push("/two-factor/verify");
return "redirecting-second-factor";
} else {
- // In rare cases, if the user hasn't already setup their key
- // attributes, we might get the plaintext token from remote.
if (token) await saveAuthToken(token);
updateSavedLocalUser({
id,
@@ -287,12 +269,10 @@ const Page: React.FC = () => {
useCallback(
(key, kek, keyAttributes, password) => {
void (async () => {
- // Currently the page will get reloaded if any of the
- // attributes have changed, so we don't need to worry about
- // the KEK having been generated using stale credentials.
- //
- // This await on the promise is here to only ensure we're
- // done with the check before we let the user in.
+ // The page reloads if any attributes changed, so the KEK
+ // cannot have been generated from stale credentials. The
+ // await only makes sure the check is done before we let
+ // the user in.
if (sessionValidityCheck) await sessionValidityCheck;
const updatedKeyAttributes = savedIsFirstLogin()
@@ -323,15 +303,10 @@ const Page: React.FC = () => {
}
if (passkeyVerificationData) {
- // We only need to handle this scenario when running in the desktop app
- // because the web app will navigate to Passkey verification URL.
- // However, still we add an additional `globalThis.electron` check to
- // show a spinner. This prevents the VerifyingPasskey component from
- // being disorientingly shown for a fraction of a second as the redirect
- // happens on the web app.
- //
- // See: [Note: Passkey verification in the desktop app]
-
+ // Only the desktop app needs this UI; the web app is already
+ // navigating to the passkey verification URL. Show a spinner on web
+ // so that the VerifyingPasskey component does not flash before the
+ // redirect completes.
if (!globalThis.electron) {
return <LoadingIndicator />;
}
diff --git a/web/packages/accounts/pages/generate.tsx b/web/packages/accounts/pages/generate.tsx
index 6d8da16bb1..8e7ab6e0f3 100644
--- a/web/packages/accounts/pages/generate.tsx
+++ b/web/packages/accounts/pages/generate.tsx
@@ -39,12 +39,6 @@ import {
type NewPasswordFormProps,
} from "../components/NewPasswordForm";
-/**
- * A page that allows the user to generate key attributes if needed, and shows
- * them their recovery key if they just signed up.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
diff --git a/web/packages/accounts/pages/login.tsx b/web/packages/accounts/pages/login.tsx
index bfa311a03a..5469f3fc3e 100644
--- a/web/packages/accounts/pages/login.tsx
+++ b/web/packages/accounts/pages/login.tsx
@@ -6,135 +6,6 @@ import { customAPIHost } from "ente-base/origins";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to login into their existing Ente account.
- *
- * [Note: Login pages]
- *
- * There are multiple pages that comprise the login flow, with redirects amongst
- * themselves depending on various scenarios and partial login states.
- *
- * - "/signup" - A page that allows the user to signup for a new Ente account.
- *
- * - Redirects to "/login" if the user chooses the "already have an account"
- * option.
- *
- * - Redirects to "/verify" if there is already an `email` present in the
- * saved partial local user, or after obtaining the email.
- *
- * - "/login" - A page that allows the user to login into their existing Ente
- * account.
- *
- * - Redirects to "/signup" if the user chooses the "create new account"
- * option.
- *
- * - Redirects to "/verify" if there is already an `email` present in the
- * saved partial local user, or after obtaining the email if the user's has
- * enabled email verification for their account.
- *
- * - Redirects to "/credentials" after obtaining the email if the user has not
- * enabled email verification for their account.
- *
- * - "/verify" - A page that allows the user to verify their email.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/credentials" if both saved key attributes and a `token`
- * (or `encryptedToken`) in present in the saved partial local user, or if
- * email verification is not needed, or when email verification completes
- * and remote sent us key attributes (which will happen on login).
- *
- * - Redirects to "/generate" once email verification is complete and the user
- * does not have key attributes (which will happen for new signups).
- *
- * - Redirects to "/two-factor/verify" when email verification completes and
- * the user has setup a TOTP second factor that also needs to be verified.
- *
- * - Redirects to the passkey app when email verification completes and the
- * user has setup a passkey that also needs to be verified. Before
- * redirecting, `inflightPasskeySessionID` in saved in session storage.
- *
- * - "/credentials" - A page that allows the user to enter their password to
- * authenticate (initial login) or reauthenticate (new web app tab)
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/two-factor/verify" if saved key attributes are not present
- * once password is verified and the user has setup a TOTP second factor
- * that also needs to be verified.
- *
- * - Redirects to the passkey app once password is verified if saved key
- * attributes are not present if the user has setup a passkey that also
- * needs to be verified. Before redirecting, `inflightPasskeySessionID` is
- * saved in session storage.
- *
- * - Redirects to the `appHomeRoute` otherwise (e.g. /gallery). **The flow is
- * complete**.
- *
- * - "/generate" - A page that allows the user to generate key attributes if
- * needed, and shows them their recovery key if they just signed up.
- *
- * - Redirects to "/" if there is no `email` or `token` present in the saved
- * partial user.
- *
- * - Redirects to `appHomeRoute` after viewing the recovery key if they have a
- * master key in session, or after setting the password and then viewing the
- * recovery key (if they did not have a master key in session store).
- *
- * - Redirects to "/credentials" if if they don't have a master key in session
- * store but have saved original key attributes.
- *
- * - "/recover" - A page that allows the user to recover their master key using
- * their recovery key.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * local user.
- *
- * - Redirects to "/verify" if there is no `encryptedToken` (or `token`)
- * present in the saved partial local user.
- *
- * - Redirects to "/generate" if there are no saved key attributes.
- *
- * - Redirects to "/change-password" once the recovery key is verified.
- *
- * - "/change-password" - A page that allows the user to reset their password.
- *
- * - Redirects to "/" if there is no `email` present in the saved partial
- * user, and after successfully changing the password.
- *
- * - "/two-factor/verify" - A page that allows the user to verify their TOTP
- * based second factor.
- *
- * - Redirects to "/" if there is no `email` or `twoFactorSessionID` in the
- * saved partial local user.
- *
- * - Redirects to "/credentials" if `isTwoFactorEnabled` is not `true` and
- * either of `encryptedToken` or `token` is present in the saved partial
- * local user.
- *
- * - "/passkeys/finish" - A page where the accounts app hands off control back
- * to us (the calling app) once the passkey has been verified.
- *
- * - Redirects to "/" if there is no matching `inflightPasskeySessionID` in
- * session storage.
- *
- * - Redirects to "/credentials" otherwise.
- *
- * - "/two-factor/recover" and "/passkeys/recover" - Pages that allow the user
- * to reset or bypass their second factor if they possess their recovery key.
- * Both pages work similarly, except for the second factor they act on.
- *
- * - Redirect to "/" if there is no `email` or `twoFactorSessionID` /
- * `passkeySessionID` in the saved partial local user.
- *
- * - Redirect to "/generate" if there is an `encryptedToken` or `token` in the
- * saved partial local user.
- *
- * - Redirect to "/credentials" after recovery.
- *
- */
const Page: React.FC = () => {
const [loading, setLoading] = useState(true);
const [host, setHost] = useState<string | undefined>(undefined);
diff --git a/web/packages/accounts/pages/passkeys/finish.tsx b/web/packages/accounts/pages/passkeys/finish.tsx
index 7a1f6ddcf8..3b34c8a0aa 100644
--- a/web/packages/accounts/pages/passkeys/finish.tsx
+++ b/web/packages/accounts/pages/passkeys/finish.tsx
@@ -15,23 +15,13 @@ import { nullToUndefined } from "ente-utils/transform";
import { useRouter } from "next/router";
import React, { useEffect } from "react";
-/**
- * The page where the accounts app hands back control to us once the passkey has
- * been verified.
- *
- * See: [Note: Login pages]
- *
- * [Note: Finish passkey flow in the requesting app]
- *
- * The passkey finish step needs to happen in the context of the client which
- * invoked the passkey flow since it needs to save the obtained credentials
- * in local storage (which is tied to the current origin).
- */
+// The passkey finish step must run in the app that invoked the passkey flow:
+// it saves the obtained credentials to local storage, which is tied to the
+// origin.
const Page: React.FC = () => {
const router = useRouter();
useEffect(() => {
- // Extract response from query params.
const searchParams = new URLSearchParams(window.location.search);
const passkeySessionID = searchParams.get("passkeySessionID");
const response = searchParams.get("response");
@@ -47,28 +37,10 @@ const Page: React.FC = () => {
export default Page;
-/**
- * Extract credentials from a successful passkey flow "response" query parameter
- * and save them to local storage for use by subsequent steps (or normal
- * functioning) of the app.
- *
- * @param passkeySessionID The string that is passed as the "passkeySessionID"
- * query parameter to us.
- *
- * @param response The string that is passed as the "response" query parameter to
- * us (we're the final "finish" page in the passkey flow).
- *
- * @returns the slug that we should navigate to now.
- */
const saveQueryCredentialsAndNavigateTo = async (
passkeySessionID: string,
response: string,
) => {
- // This function's implementation is on the same lines as that of the
- // `saveCredentialsAndNavigateTo` function in passkey utilities.
- //
- // See: [Note: Ending the passkey flow]
-
const inflightPasskeySessionID = nullToUndefined(
sessionStorage.getItem("inflightPasskeySessionID"),
);
@@ -77,9 +49,8 @@ const saveQueryCredentialsAndNavigateTo = async (
!inflightPasskeySessionID ||
passkeySessionID != inflightPasskeySessionID
) {
- // This is not the princess we were looking for. However, we have
- // already entered this castle. Redirect back to home without changing
- // any state, hopefully this will get the user back to where they were.
+ // This is a stale or unexpected redirect. Do not change any state;
+ // just send the user back home.
log.info(
`Ignoring redirect for unexpected passkeySessionID ${passkeySessionID}`,
);
@@ -88,8 +59,6 @@ const saveQueryCredentialsAndNavigateTo = async (
clearInflightPasskeySessionID();
- // Decode response string (inverse of the steps we perform in
- // `passkeyAuthenticationSuccessRedirectURL`).
const decodedResponse = TwoFactorAuthorizationResponse.parse(
JSON.parse(
new TextDecoder().decode(await fromB64URLSafeNoPadding(response)),
diff --git a/web/packages/accounts/pages/recover.tsx b/web/packages/accounts/pages/recover.tsx
index ac4b791e7c..0ee6fb8a2b 100644
--- a/web/packages/accounts/pages/recover.tsx
+++ b/web/packages/accounts/pages/recover.tsx
@@ -30,12 +30,6 @@ import { t } from "i18next";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to enter their recovery key to recover their
- * master key if they've forgotten their password.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { showMiniDialog } = useBaseContext();
diff --git a/web/packages/accounts/pages/signup.tsx b/web/packages/accounts/pages/signup.tsx
index 5d06da4dad..dfea7a50c7 100644
--- a/web/packages/accounts/pages/signup.tsx
+++ b/web/packages/accounts/pages/signup.tsx
@@ -6,11 +6,6 @@ import { customAPIHost } from "ente-base/origins";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
-/**
- * A page that allows the user to signup for a new Ente account.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const [loading, setLoading] = useState(true);
const [host, setHost] = useState<string | undefined>(undefined);
diff --git a/web/packages/accounts/pages/two-factor/recover.tsx b/web/packages/accounts/pages/two-factor/recover.tsx
index 4683847c43..e84ef3bec7 100644
--- a/web/packages/accounts/pages/two-factor/recover.tsx
+++ b/web/packages/accounts/pages/two-factor/recover.tsx
@@ -30,10 +30,6 @@ export interface RecoverPageProps {
twoFactorType: TwoFactorType;
}
-/**
- * A page where the user can enter their recovery key to reset or bypass their
- * second factor in case they no longer have access to it.
- */
const Page: React.FC<RecoverPageProps> = ({ twoFactorType }) => {
const { logout, showMiniDialog, onGenericError } = useBaseContext();
diff --git a/web/packages/accounts/pages/two-factor/setup.tsx b/web/packages/accounts/pages/two-factor/setup.tsx
index 14764ff619..59fc64305f 100644
--- a/web/packages/accounts/pages/two-factor/setup.tsx
+++ b/web/packages/accounts/pages/two-factor/setup.tsx
@@ -82,7 +82,7 @@ const ContentsPaper = styled(Paper)(({ theme }) => ({
marginBlock: theme.spacing(2),
padding: theme.spacing(5, 3),
[theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },
- // Wide enough to fit the QR code secret in one line under default settings.
+ // This width fits the QR code secret in one line under default settings.
width: "min(440px, 85vw)",
minHeight: "375px",
display: "flex",
diff --git a/web/packages/accounts/pages/two-factor/verify.tsx b/web/packages/accounts/pages/two-factor/verify.tsx
index e0038ef9ae..f2b1f920e7 100644
--- a/web/packages/accounts/pages/two-factor/verify.tsx
+++ b/web/packages/accounts/pages/two-factor/verify.tsx
@@ -21,11 +21,6 @@ import {
} from "../../components/layouts/centered-paper";
import { unstashRedirect } from "../../services/redirect";
-/**
- * A page that allows the user to verify their TOTP based second factor.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout } = useBaseContext();
diff --git a/web/packages/accounts/pages/verify.tsx b/web/packages/accounts/pages/verify.tsx
index 7ffcffa231..cb6b367757 100644
--- a/web/packages/accounts/pages/verify.tsx
+++ b/web/packages/accounts/pages/verify.tsx
@@ -54,11 +54,6 @@ import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
import { Trans } from "react-i18next";
-/**
- * A page that allows the user to verify their email.
- *
- * See: [Note: Login pages]
- */
const Page: React.FC = () => {
const { logout, showMiniDialog } = useBaseContext();
@@ -108,9 +103,6 @@ const Page: React.FC = () => {
await verifyEmail(email, ott, cleanedReferral),
);
- // The following flow is similar to (but not the same) as what
- // happens after `verifySRP` in the `/credentials` page.
-
if (passkeySessionID) {
updateSavedLocalUser({ passkeySessionID });
saveIsFirstLogin();
@@ -173,15 +165,10 @@ const Page: React.FC = () => {
}
if (passkeyVerificationData) {
- // We only need to handle this scenario when running in the desktop app
- // because the web app will navigate to Passkey verification URL.
- // However, still we add an additional `globalThis.electron` check to
- // show a spinner. This prevents the VerifyingPasskey component from
- // being disorientingly shown for a fraction of a second as the redirect
- // happens on the web app.
- //
- // See: [Note: Passkey verification in the desktop app]
-
+ // Only the desktop app needs this UI; the web app is already
+ // navigating to the passkey verification URL. Show a spinner on web
+ // so that the VerifyingPasskey component does not flash before the
+ // redirect completes.
if (!globalThis.electron) {
return <LoadingIndicator />;
}
@@ -246,12 +233,6 @@ const Page: React.FC = () => {
export default Page;
-/**
- * A function called during page load to see if a redirection is required
- *
- * @returns The slug to redirect to, if needed. Otherwise an object containing
- * the saved partial user's email.
- */
const redirectionIfNeededOrEmail = async () => {
const user = savedPartialLocalUser();
@@ -264,25 +245,13 @@ const redirectionIfNeededOrEmail = async () => {
return "/credentials";
}
- // If we're coming here during the recover flow, do not redirect.
if (stashedRedirect() == "/recover") return { email };
- // The user might have email verification disabled, but after previously
- // entering their email on the login screen, they might've closed the tab
- // before proceeding (or opened a us in a new tab at this point).
- //
- // In such cases, we'll end up here with an email present.
- //
- // To distinguish this scenario from the normal email verification flow, we
- // can check to see the SRP attributes (the login page would've fetched and
- // saved them). If they are present and indicate that email verification is
- // not required, redirect to the password verification page.
-
const srpAttributes = savedSRPAttributes();
if (srpAttributes && !srpAttributes.isEmailMFAEnabled) {
- // Fetch the latest SRP attributes instead of relying on the potentially
- // stale stored values. This is an infrequent scenario path, so extra
- // API calls are fine.
+ // Fetch the latest SRP attributes instead of trusting the potentially
+ // stale saved values. This path is infrequent, so the extra API call
+ // is fine.
const latestSRPAttributes = await getSRPAttributes(email);
if (latestSRPAttributes && !latestSRPAttributes.isEmailMFAEnabled) {
return "/credentials";
diff --git a/web/packages/accounts/services/accounts-db.ts b/web/packages/accounts/services/accounts-db.ts
index c3b45965d8..14058e0a3a 100644
--- a/web/packages/accounts/services/accounts-db.ts
+++ b/web/packages/accounts/services/accounts-db.ts
@@ -1,21 +1,6 @@
-/**
- * @file [Note: Accounts DB]
- *
- * The accounts package stores various state both during the login / signup
- * flow, and post login to identify the logged in user.
- *
- * This state is stored in local storage.
- *
- * Most of this state is meant to be transitory - various bits and bobs that we
- * accumulate and want to persist as the user goes through the login or signup
- * flow. One the user is successfully logged in and the first pull has
- * completed, then only a few of these are expected to remain:
- *
- * - "user"
- * - "keyAttributes"
- * - "originalKeyAttributes"
- * - "srpAttributes"
- */
+// All of the state in this file is kept in the browser's localStorage, which
+// is not accessible to web workers, so these functions only work on the main
+// thread.
import { savedAuthToken } from "ente-base/token";
import { nullToUndefined } from "ente-utils/transform";
@@ -31,52 +16,6 @@ import {
type LocalUser,
} from "./user";
-/**
- * The local storage data about the user before login or signup is complete.
- *
- * [Note: Partial local user]
- *
- * During login or signup, the user object exists in various partial states in
- * local storage.
- *
- * - Initially, there is no user object in local storage.
- *
- * - When the user enters their email, the email property of the stored object
- * is set, but nothing else.
- *
- * - After they verify their password, we have two cases: if second factor
- * verification is not set, and when it is set.
- *
- * - If second factor verification is not set, then after verifying their
- * password their {@link id} and {@link encryptedToken} will get filled in,
- * and {@link isTwoFactorEnabled} will be set to false.
- *
- * - If they have second factor verification set, then after verifying their
- * password {@link isTwoFactorEnabled} and {@link twoFactorSessionID} will
- * also get filled in. Once they verify their TOTP based second factor, their
- * {@link id} and {@link encryptedToken} will also get filled in.
- *
- * - If they have a passkey set as a second factor set, then after verifying
- * their password the {@link passkeySessionID} will be set.
- *
- * - As the login or signup sequence completes, a {@link token} obtained from
- * the {@link encryptedToken} will be written out, and the
- * {@link encryptedToken} cleared since it is not needed anymore.
- *
- * So while the underlying storage is the same, we offer two APIs for code to
- * obtain the user:
- *
- * - Before login is complete, or when it is unknown if login is complete or
- * not, then {@link savedPartialLocalUser} can be used to obtain a
- * {@link PartialLocalUser} with all of its properties set to be optional (and
- * some additional properties not available in the regular user object).
- *
- * - When we know that the login has completed, we can use either
- * {@link savedLocalUser} (which returns `undefined` if our assumption is
- * false) or {@link ensureSavedLocalUser} (which throws if our assumption is
- * false) to obtain an object with all the properties expected to be present
- * for a locally persisted user set to be required.
- */
export interface PartialLocalUser {
id?: number;
email?: string;
@@ -97,11 +36,6 @@ const PartialLocalUser = z.object({
passkeySessionID: z.string().nullish().transform(nullToUndefined),
});
-/**
- * Zod schema for the {@link LocalUser} TypeScript type.
- *
- * The type itself is in `user.ts`.
- */
const LocalUser = z.object({
id: z.number(),
email: z.string(),
@@ -109,163 +43,64 @@ const LocalUser = z.object({
isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
});
-/**
- * Return the local storage value of the user's data.
- *
- * This function is meant to be called during the login or signup sequence.
- * After the user is logged in, use {@link savedLocalUser} or
- * {@link ensureLocalUser} instead.
- *
- * Use {@link replaceSavedLocalUser} to updated the saved value.
- */
export const savedPartialLocalUser = (): PartialLocalUser | undefined => {
const jsonString = localStorage.getItem("user");
if (!jsonString) return undefined;
return PartialLocalUser.parse(JSON.parse(jsonString));
};
-/**
- * Save the users data as we accrue it during the signup or login flow.
- *
- * See: [Note: Partial local user].
- *
- * This method replaces the existing data. Use {@link updateSavedLocalUser} to
- * update selected fields while keeping the other fields as it is.
- */
export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>
localStorage.setItem("user", JSON.stringify(partialLocalUser));
-/**
- * Partially update the saved user data.
- *
- * This is a delta variant of {@link replaceSavedLocalUser}, which replaces the
- * entire saved object, while this function spreads the provided {@link updates}
- * onto the currently saved value.
- *
- * @param updates A subset of {@link PartialLocalUser} fields that we'd like to
- * update. The other fields, if present in local storage, remain unchanged.
- */
export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>
replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });
-/**
- * Return data about the logged-in user, if someone is indeed logged in.
- * Otherwise return `undefined`.
- *
- * The user's data is stored in the browser's localStorage. Thus, this function
- * only works from the main thread, not from web workers since local storage is
- * not accessible to web workers.
- *
- * There is no setter corresponding to this function since this is only a view
- * on data saved using {@link replaceSavedLocalUser} or
- * {@link updateSavedLocalUser}.
- *
- * See: [Note: Partial local user] for more about the whole shebang.
- */
export const savedLocalUser = (): LocalUser | undefined => {
const jsonString = localStorage.getItem("user");
if (!jsonString) return undefined;
- // We might have some data, but not all of it. So do a non-throwing parse.
+ // During login the saved user object can be partial, so do a non-throwing
+ // parse.
const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));
return success ? data : undefined;
};
-/**
- * Return true if the user's data is in local storage but not in IndexedDB.
- *
- * This acts a sanity check on IndexedDB by ensuring that if the user has a
- * token in local storage, then it should also be present in IndexedDB.
- */
export const isLocalStorageAndIndexedDBMismatch = async () =>
savedPartialLocalUser()?.token && !(await savedAuthToken());
-/**
- * Return the user's {@link KeyAttributes} if they are present in local storage.
- *
- * The key attributes are stored in the browser's localStorage. Thus, this
- * function only works from the main thread, not from web workers (local storage
- * is not accessible to web workers).
- *
- * See also: [Note: Original vs interactive key attributes]
- */
export const savedKeyAttributes = (): KeyAttributes | undefined => {
const jsonString = localStorage.getItem("keyAttributes");
if (!jsonString) return undefined;
return RemoteKeyAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link KeyAttributes} in local storage.
- *
- * Use {@link savedKeyAttributes} to retrieve them.
- */
export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>
localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));
-/**
- * Return the user's original {@link KeyAttributes} if they are present in local
- * storage.
- *
- * [Note: Original vs interactive key attributes]
- *
- * This function is similar to {@link savedKeyAttributes} except it returns the
- * user's "original" key attributes. These are the key attributes that were
- * either freshly generated (if the user signed up on this client) or were
- * fetched from remote (otherwise).
- *
- * > NOTE: Currently the code does not guarantee that savedOriginalKeyAttributes
- * > will always be set when savedKeyAttributes is set.
- *
- * In contrast, the regular key attributes get overwritten by the local only
- * interactive key attributes for the user's convenience. See the documentation
- * of {@link generateAndSaveInteractiveKeyAttributes} for more details.
- */
+// Unlike the "keyAttributes" entry, which can get overwritten by locally
+// generated interactive key attributes, the "originalKeyAttributes" entry
+// retains the key attributes that were freshly generated at signup or fetched
+// from remote.
export const savedOriginalKeyAttributes = (): KeyAttributes | undefined => {
const jsonString = localStorage.getItem("originalKeyAttributes");
if (!jsonString) return undefined;
return RemoteKeyAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link KeyAttributes} in local storage.
- *
- * Once saved, these values are not replaced (in contrast with the regular key
- * attributes which can get overwritten with interactive ones).
- *
- * Use {@link savedOriginalKeyAttributes} to retrieve them.
- */
export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>
localStorage.setItem(
"originalKeyAttributes",
JSON.stringify(keyAttributes),
);
-/**
- * Return the user's {@link SRPAttributes} if they are present in local storage.
- *
- * Like key attributes, SRP attributes are also stored in the browser's local
- * storage so will not be accessible to web workers.
- */
export const savedSRPAttributes = (): SRPAttributes | undefined => {
const jsonString = localStorage.getItem("srpAttributes");
if (!jsonString) return undefined;
return RemoteSRPAttributes.parse(JSON.parse(jsonString));
};
-/**
- * Save the user's {@link SRPAttributes} in local storage.
- *
- * Use {@link savedSRPAttributes} to retrieve them.
- */
export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>
localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));
-/**
- * Save {@link SRPSetupAttributes} in local storage for later use via
- * {@link unstashAfterUseSRPSetupAttributes}.
- *
- * See: [Note: SRP setup attributes]
- */
export const stashSRPSetupAttributes = (
srpSetupAttributes: SRPSetupAttributes,
) =>
@@ -274,16 +109,6 @@ export const stashSRPSetupAttributes = (
JSON.stringify(srpSetupAttributes),
);
-/**
- * Retrieve the {@link SRPSetupAttributes}, if any, that were stashed by a
- * previous call to {@link stashSRPSetupAttributes}.
- *
- * - If they are found, then invoke the provided callback ({@link cb}) with the
- * value. If the promise returned by the callback fulfills, then remove the
- * stashed value from local storage.
- *
- * - If they are not found, then the callback is not invoked.
- */
export const unstashAfterUseSRPSetupAttributes = async (
cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,
) => {
@@ -294,33 +119,13 @@ export const unstashAfterUseSRPSetupAttributes = async (
localStorage.removeItem("srpSetupAttributes");
};
-/**
- * Zod schema for the legacy format in which the {@link savedIsFirstLogin} and
- * {@link savedJustSignedUp} flags were saved in local storage.
- *
- * Starting 1.7.15-beta (July 2025), we started saving the booleans directly,
- * but when reading we fallback to the old format if needed. This fallback can
- * be removed, and soonish, since these are transient flags that are saved
- * during the login / signup sequence and wouldn't be expected to remain in the
- * user's local storage for long anyway. (tag: Migration).
- */
+// Legacy format in which the "isFirstLogin" and "justSignedUp" flags were
+// saved. Readers fall back to it since it can still be present in users' local
+// storage. (tag: Migration)
const LocalLegacyBooleanFlag = z.object({
status: z.boolean().nullish().transform(nullToUndefined),
});
-/**
- * Return `true` if it is the user's first login on this client.
- *
- * The {@link savedIsFirstLogin} flag is saved in local storage (using
- * {@link saveIsFirstLogin}) if we determine during the login flow that it a
- * fresh login on this client. If so, we
- *
- * - Generate interactive key attributes for them, and
- *
- * - Display them a special indicator post login to notify them that the first
- * load might take extra time. At this point, we also clear the flag (the read
- * and clear is done by the same {@link getAndClearIsFirstLogin} function).
- */
export const savedIsFirstLogin = () => {
const jsonString = localStorage.getItem("isFirstLogin");
if (!jsonString) return false;
@@ -333,33 +138,16 @@ export const savedIsFirstLogin = () => {
}
};
-/**
- * Save a flag in local storage to indicate that this is the user's first login
- * on this client.
- *
- * This is the setter corresponding to {@link savedIsFirstLogin}.
- */
export const saveIsFirstLogin = () => {
localStorage.setItem("isFirstLogin", JSON.stringify({ status: true }));
};
-/**
- * Get the saved value of the local storage flag that indicates that this is the
- * user' first login on this client. Also remove the flag after reading.
- *
- * The flag can be set by using {@link saveIsFirstLogin}, and can be read
- * without clearing it by using {@link savedIsFirstLogin}.
- */
export const getAndClearIsFirstLogin = () => {
const result = savedIsFirstLogin();
localStorage.removeItem("isFirstLogin");
return result;
};
-/**
- * Return `true` if the user created a new account on this client during the
- * current (in-progress) or just completed login / signup sequence.
- */
export const savedJustSignedUp = () => {
const jsonString = localStorage.getItem("justSignedUp");
if (!jsonString) return false;
@@ -372,45 +160,20 @@ export const savedJustSignedUp = () => {
}
};
-/**
- * Save a flag in local storage to indicate that the user signed up for a
- * new Ente account during the current login / signup sequence.
- *
- * This is the setter corresponding to {@link savedJustSignedUp}.
- */
export const saveJustSignedUp = () => {
localStorage.setItem("justSignedUp", JSON.stringify({ status: true }));
};
-/**
- * Get the saved value of the local storage flag that indicates that the user just
- * signed up. Also remove the flag from local storage after reading.
- *
- * The flag can be set by using {@link saveJustSignedUp}, and can be read
- * without clearing it by using {@link savedJustSignedUp}.
- */
export const getAndClearJustSignedUp = () => {
const result = savedJustSignedUp();
localStorage.removeItem("justSignedUp");
return result;
};
-/**
- * Save the referral source entered by the user on the signup screen in local
- * storage.
- *
- * The saved value can be retrieved post email verification using
- * {@link unstashReferralSource}.
- */
export const stashReferralSource = (referralSource: string) => {
localStorage.setItem("referralSource", referralSource);
};
-/**
- * Retrieve the previously saved referral source (using
- * {@link stashReferralSource}), returning the saved value and also clearing it
- * from local storage.
- */
export const unstashReferralSource = () => {
const referralSource = localStorage.getItem("referralSource");
if (!referralSource) return undefined;
diff --git a/web/packages/accounts/services/logout.ts b/web/packages/accounts/services/logout.ts
index 8b860d5707..014ecab9f6 100644
--- a/web/packages/accounts/services/logout.ts
+++ b/web/packages/accounts/services/logout.ts
@@ -6,16 +6,8 @@ import { clearSessionStorage } from "ente-base/session";
import { clearStashedRedirect } from "./redirect";
import { remoteLogoutIfNeeded } from "./user";
-/**
- * Logout sequence common to all apps that rely on the accounts package.
- *
- * [Note: Do not throw during logout]
- *
- * This function is guaranteed to not thrown any errors, and will try to
- * independently complete all the steps in the sequence that can be completed.
- * This allows the user to logout and start again even if somehow their account
- * gets in an unexpected state.
- */
+// This function must not throw. Each step runs independently and ignores
+// errors so that logout completes even from a broken account state.
export const accountLogout = async () => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
@@ -54,14 +46,9 @@ export const accountLogout = async () => {
}
};
-/**
- * This is a subset of the cleanup of local persistence that has already
- * happened during {@link accountLogout}. However, once the logout sequence is
- * complete, we do these specific steps again to clear any state that might've
- * been persisted meanwhile because of in-flight requests getting completed.
- *
- * Post this, we'll reload the page so that in-flight requests are discarded.
- */
+// Called after the logout sequence completes to again clear state that
+// in-flight requests may have persisted meanwhile. The caller then reloads
+// the page so that remaining in-flight requests are discarded.
export const logoutClearStateAgain = async () => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
diff --git a/web/packages/accounts/services/passkey.ts b/web/packages/accounts/services/passkey.ts
index f213281b6f..b0a4c0795b 100644
--- a/web/packages/accounts/services/passkey.ts
+++ b/web/packages/accounts/services/passkey.ts
@@ -19,29 +19,16 @@ import { z } from "zod";
import { getUserRecoveryKey } from "./recovery-key";
import { unstashRedirect } from "./redirect";
-/**
- * Construct a redirect URL to take the user to Ente accounts app to
- * authenticate using their second factor, a passkey they've configured.
- *
- * On successful verification, the accounts app will redirect back to our
- * `/passkeys/finish` page.
- *
- * @param accountsURL The URL for the accounts app (provided to us by remote in
- * the email or SRP verification response).
- *
- * @param passkeySessionID An identifier provided by museum for this passkey
- * verification session.
- */
export const passkeyVerificationRedirectURL = (
accountsURL: string,
passkeySessionID: string,
) => {
const clientPackage = clientPackageName;
- // Using `window.location.origin` will work both when we're running in a web
- // browser, and in our desktop app. See: [Note: Using deeplinks to navigate
- // in desktop app]
+ // In the desktop app, window.location.origin is the custom app protocol
+ // origin, which doubles as the deeplink back into the app.
const redirect = `${window.location.origin}/passkeys/finish`;
- // See: [Note: Conditional passkey recover option on accounts]
+ // The desktop app's own waiting screen already shows a recovery option, so
+ // it does not ask the accounts app to show one.
const recoverOption: Record<string, string> = isDesktop
? {}
: { recover: `${window.location.origin}/passkeys/recover` };
@@ -55,61 +42,30 @@ export const passkeyVerificationRedirectURL = (
};
interface OpenPasskeyVerificationURLOptions {
- /**
- * The passkeySessionID for which we are redirecting.
- *
- * This is compared to the saved session id in the browser's session storage
- * to allow us to ignore redirects to the passkey flow finish page except
- * the ones for this specific session we're awaiting.
- */
passkeySessionID: string;
- /** The URL to redirect to or open in the system browser. */
url: string;
}
-/**
- * Open or redirect to a passkey verification URL previously constructed using
- * {@link passkeyVerificationRedirectURL}.
- *
- * [Note: Passkey verification in the desktop app]
- *
- * Our desktop app bundles the web app and serves it over a custom protocol.
- * Passkeys are tied to origins, and will not work with this custom protocol
- * even if we move the passkey creation and authentication inline to within the
- * Photos web app.
- *
- * Thus, passkey creation and authentication in the desktop app works the same
- * way it works in the mobile app - the system browser is invoked to open the
- * accounts app origin (e.g. accounts.ente.com) returned by remote.
- *
- * - For passkey creation, this is a one-way open. Passkeys get created at the
- * accounts app origin, and that's it.
- *
- * - For passkey verification, the flow is two-way. We register a custom
- * protocol and provide that as a return path redirect. Passkey authentication
- * happens at the accounts app origin, and on success there is redirected back
- * to the desktop app.
- */
+// Passkeys are tied to web origins and do not work over the custom protocol
+// that the desktop app uses to serve the bundled web app. So the desktop app
+// (like the mobile app) opens the accounts app origin in the system browser,
+// and on successful verification the accounts app redirects back to the
+// desktop app via a registered custom protocol.
export const openPasskeyVerificationURL = ({
passkeySessionID,
url,
}: OpenPasskeyVerificationURLOptions) => {
+ // The finish page ignores redirects whose session id does not match the
+ // inflight value saved here.
sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);
if (globalThis.electron) window.open(url);
else window.location.href = url;
};
-/**
- * Open a new window showing a page on the Ente accounts app where the user can
- * see and their manage their passkeys.
- */
export const openAccountsManagePasskeysPage = async () => {
- // Check if the user has passkey recovery enabled.
const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();
if (!isPasskeyRecoveryEnabled) {
- // If not, enable it for them by creating the necessary recovery
- // information to prevent them from getting locked out.
const resetSecret = await generateKey();
const { encryptedData, nonce } = await encryptBox(
resetSecret,
@@ -118,8 +74,6 @@ export const openAccountsManagePasskeysPage = async () => {
await configurePasskeyRecovery(resetSecret, encryptedData, nonce);
}
- // Redirect to the Ente Accounts app where they can view and add and manage
- // their passkeys.
const { accountsToken: token, accountsUrl: accountsURL } =
await getAccountsTokenAndURL();
const params = new URLSearchParams({ token });
@@ -128,15 +82,9 @@ export const openAccountsManagePasskeysPage = async () => {
};
const TwoFactorRecoveryStatus = z.object({
- /**
- * `true` if the passkey recovery setup has been completed.
- */
isPasskeyRecoveryEnabled: z.boolean(),
});
-/**
- * Obtain the second factor recovery status from remote.
- */
export const getTwoFactorRecoveryStatus = async () => {
const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {
headers: await authenticatedRequestHeaders(),
@@ -145,10 +93,6 @@ export const getTwoFactorRecoveryStatus = async () => {
return TwoFactorRecoveryStatus.parse(await res.json());
};
-/**
- * Allow the user to bypass their passkeys by saving the provided recovery
- * credentials on remote.
- */
const configurePasskeyRecovery = async (
secret: string,
userSecretCipher: string,
@@ -169,53 +113,18 @@ const configurePasskeyRecovery = async (
),
);
-/**
- * Fetch an Ente Accounts specific JWT token.
- *
- * This token can be used to authenticate with the Ente accounts app running at
- * accountsURL (the result contains both pieces of information).
- */
const getAccountsTokenAndURL = async () => {
const res = await fetch(await apiURL("/users/accounts-token"), {
headers: await authenticatedRequestHeaders(),
});
ensureOk(res);
return z
- .object({
- // The origin that serves the accounts app.
- accountsUrl: z.string(),
- // A token that can be used to authenticate with the accounts app.
- accountsToken: z.string(),
- })
+ .object({ accountsUrl: z.string(), accountsToken: z.string() })
.parse(await res.json());
};
-/**
- * The passkey session whose status we are trying to check has already expired.
- * The user should attempt to login again.
- */
export const passkeySessionExpiredErrorMessage = "Passkey session has expired";
-/**
- * Check if the user has already authenticated using their passkey for the given
- * session.
- *
- * This is useful in case the automatic redirect back from the accounts app to
- * the desktop app does not work for some reason. In such cases, the user can
- * press the "Check status" button: we'll make an API call to see if the
- * authentication has already completed, and if so, get the same "response"
- * object we'd have gotten as a query parameter in a redirect in
- * {@link saveCredentialsAndNavigateTo} on the "/passkeys/finish" page.
- *
- * @param sessionID The passkey session whose session we wish to check the
- * status of.
- *
- * @returns A {@link TwoFactorAuthorizationResponse} if the passkey
- * authentication has completed, and `undefined` otherwise.
- *
- * @throws In addition to arbitrary errors, it throws errors with the message
- * {@link passkeySessionExpiredErrorMessage}.
- */
export const checkPasskeyVerificationStatus = async (
sessionID: string,
): Promise<TwoFactorAuthorizationResponse | undefined> => {
@@ -226,38 +135,16 @@ export const checkPasskeyVerificationStatus = async (
if (!res.ok) {
if (res.status == 404 || res.status == 410)
throw new Error(passkeySessionExpiredErrorMessage);
- if (res.status == 400) return undefined; /* verification pending */
+ // Remote uses 400 to indicate that verification is still pending.
+ if (res.status == 400) return undefined;
throw new HTTPError(res);
}
return TwoFactorAuthorizationResponse.parse(await res.json());
};
-/**
- * Extract credentials from a successful passkey verification response and save
- * them to local storage for use by subsequent steps (or normal functioning) of
- * the app.
- *
- * @param response The result of a successful
- * {@link checkPasskeyVerificationStatus}.
- *
- * @returns the slug that we should navigate to now.
- */
export const saveCredentialsAndNavigateTo = async (
response: TwoFactorAuthorizationResponse,
) => {
- // [Note: Ending the passkey flow]
- //
- // The implementation of this function is similar to that of the
- // `saveQueryCredentialsAndNavigateTo` on the "/passkeys/finish" page.
- //
- // This one, `saveCredentialsAndNavigateTo`, is used when the user presses
- // the check verification status button on the page that triggered the
- // passkey flow (when they're using the desktop app).
- //
- // The other one, `saveQueryCredentialsAndNavigateTo`, is used when the user
- // goes through the passkey flow in the browser itself (when they are using
- // the web app).
-
clearInflightPasskeySessionID();
const { id, encryptedToken, keyAttributes } = response;
@@ -269,12 +156,6 @@ export const saveCredentialsAndNavigateTo = async (
return unstashRedirect() ?? "/credentials";
};
-/**
- * Remove the inflight passkey session ID, if any, present in session storage.
- *
- * This should be called whenever we get back control from the passkey app to
- * clean up after ourselves.
- */
export const clearInflightPasskeySessionID = () => {
sessionStorage.removeItem("inflightPasskeySessionID");
};
diff --git a/web/packages/accounts/services/recovery-key.ts b/web/packages/accounts/services/recovery-key.ts
index 3f2648ee6a..dff29f9006 100644
--- a/web/packages/accounts/services/recovery-key.ts
+++ b/web/packages/accounts/services/recovery-key.ts
@@ -11,18 +11,12 @@ import { ensureMasterKeyFromSession } from "ente-base/session";
import { saveKeyAttributes } from "./accounts-db";
import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";
-// Mobile client library only supports English.
+// The wordlist must stay English since the BIP-39 library used by the mobile
+// clients only supports English.
bip39.setDefaultWordlist("english");
-/**
- * Convert the provided BIP-39 mnemonic string into its base64 representation.
- *
- * @param recoveryKeyMnemonicOrHex The BIP-39 mnemonic (24 word) string
- * representing the recovery key. For legacy compatibility, the function also
- * works if provided the hex representation of the recovery key.
- *
- * @returns A base64 string representing the underlying bytes of the recovery key.
- */
+// For legacy compatibility, the hex representation of the recovery key is
+// accepted in addition to the 24 word BIP-39 mnemonic.
export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) => {
const trimmedInput = recoveryKeyMnemonicOrHex
.trim()
@@ -32,7 +26,6 @@ export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) => {
.join(" ");
let recoveryKeyHex: string;
- // Check if user is entering mnemonic recovery key.
if (trimmedInput.indexOf(" ") > 0) {
if (trimmedInput.split(" ").length != 24) {
throw new Error("recovery code should have 24 words");
@@ -45,25 +38,9 @@ export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) => {
return fromHex(recoveryKeyHex);
};
-/**
- * Convert the provided base64 encoded recovery key into its BIP-39 mnemonic.
- *
- * @param recoveryKey The base64 encoded recovery key to mnemonize.
- *
- * @returns A 24-word mnemonic that serves as the user visible recovery key.
- */
export const recoveryKeyToMnemonic = async (recoveryKey: string) =>
bip39.entropyToMnemonic(await toHex(recoveryKey));
-/**
- * Return the (decrypted) recovery key of the logged in user, reading it from
- * local storage.
- *
- * As a fallback for old accounts that generated recovery keys on first view,
- * this function will also generate a new recovery key if needed.
- *
- * @returns The user's base64 encoded recovery key.
- */
export const getUserRecoveryKey = async () => {
const masterKey = await ensureMasterKeyFromSession();
@@ -84,15 +61,8 @@ export const getUserRecoveryKey = async () => {
}
};
-/**
- * Generate a new recovery key, tell remote about it, update our local state,
- * and then return it.
- *
- * This function is meant only for (very!) old accounts for whom the app did not
- * generate recovery keys on sign up but instead generated them on first view.
- *
- * @returns a new base64 encoded recovery key.
- */
+// Very old accounts did not get a recovery key at sign up; for them one is
+// generated lazily when it is first needed.
const createNewRecoveryKey = async (
masterKey: string,
existingKeyAttributes: KeyAttributes,
diff --git a/web/packages/accounts/services/redirect.ts b/web/packages/accounts/services/redirect.ts
index aeed7ef72a..878617c9cc 100644
--- a/web/packages/accounts/services/redirect.ts
+++ b/web/packages/accounts/services/redirect.ts
@@ -1,17 +1,14 @@
import { appName } from "ente-base/app";
-/**
- * The default page ("home route") for each of our apps.
- *
- * This is where we redirect to after successful authentication.
- */
+// The page to redirect to after successful authentication. The cast, embed and
+// share apps do not use this; their "/" entries are arbitrary values.
export const appHomeRoute: string = {
accounts: "/passkeys",
albums: "/",
auth: "/auth",
- cast: "/" /* The cast app doesn't use this, this is an arbitrary value. */,
- embed: "/" /* The embed app doesn't use this either. */,
- share: "/" /* The locker public app also doesn't use this. */,
+ cast: "/",
+ embed: "/",
+ share: "/",
photos: "/gallery",
ensu: "/",
locker: "/locker",
@@ -21,9 +18,6 @@ export const appHomeRoute: string = {
let _stashedRedirect: string | undefined;
-/**
- * An in-memory redirect saved during the login flow (mostly).
- */
export const stashedRedirect = () => _stashedRedirect;
export const stashRedirect = (r: string) => (_stashedRedirect = r);
diff --git a/web/packages/accounts/services/session.ts b/web/packages/accounts/services/session.ts
index c87a1722ef..faf4e5191b 100644
--- a/web/packages/accounts/services/session.ts
+++ b/web/packages/accounts/services/session.ts
@@ -27,69 +27,18 @@ type SessionValidity =
const SessionValidityResponse = z.object({
hasSetKeys: z.boolean(),
- /**
- * Will not be present if {@link hasSetKeys} is `false`.
- */
keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
});
-/**
- * Check if the local token and/or key attributes we have are still valid.
- *
- * This function does not take any parameters because it reads the current state
- * (key attributes) from local storage.
- *
- * @returns
- *
- * - status "invalid" if the current token has been invalidated,
- * - status "valid" normally
- * - status "validButPasswordChanged" we detected that user changed their
- * password on a different device (without choosing the option to log out of
- * all existing sessions).
- *
- * ---
- *
- * [Note: Handling password changes]
- *
- * If the user changes their password on a different device, then we need to
- * update our local state so that we use the latest password for verification.
- *
- * There is a straightforward way of doing this by always making a blocking API
- * call before showing the password unlock page, however that would add latency
- * to the 99% user experience (of normal unlocks) for the 1% case (they've
- * changed their password elsewhere).
- *
- * The approach we instead use is to make an non-blocking `/session-validity`
- * API call when this page is loaded. Usually this'll complete well before the
- * password enters their password and presses "Sign in", but we also
- * transparently await for this API call to finish before initiating the actual
- * verification. Thus there is no extra latency in the happy paths.
- *
- * The `/session-validity` API call tells us:
- *
- * 1. Whether or not the session has been invalidated (by the user choosing to
- * log out from all devices elsewhere).
- *
- * 2. What are their latest key attributes.
- *
- * If the session has been invalidated, we log them out here too.
- *
- * If the key attributes we get are different from the ones we have locally, we
- * regenerate new ones locally, and then use those for verifying the password
- * subsequently.
- */
export const checkSessionValidity = async (): Promise<SessionValidity> => {
const res = await fetch(await apiURL("/users/session-validity/v2"), {
headers: await authenticatedRequestHeaders(),
});
if (!res.ok) {
- if (res.status == 401)
- return { status: "invalid" }; /* session is no longer valid */
+ if (res.status == 401) return { status: "invalid" };
else throw new HTTPError(res);
}
- // See if the response contains keyAttributes (it will not if `hasSetKeys`
- // in the response is `false`).
const { keyAttributes } = SessionValidityResponse.parse(await res.json());
if (keyAttributes) {
const remoteKeyAttributes = keyAttributes;
@@ -98,23 +47,16 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
const email = ensureLocalUser().email;
const localSRPAttributes = savedSRPAttributes()!;
- // Fetch the remote SRP attributes.
- //
- // The key attributes we have saved locally are the locally generated
- // ones for interactive usage, and thus they'll always differ from the
- // ones we get from remote. To detect if the user changed their
- // password, we also need to fetch their SRP attributes (which will be
- // identical between remote and us if the password is the same).
+ // The key attributes we have saved locally are regenerated locally
+ // for interactive usage and thus always differ from the remote ones,
+ // so they cannot be compared to detect a password change. The SRP
+ // attributes can be: they match remote when the password is the same.
const remoteSRPAttributes = await getSRPAttributes(email);
- // If we get something (and usually we should),
if (remoteSRPAttributes) {
- // See if it is different from the one we have locally. Use the kekSalt
- // as a proxy for comparing the entire object (The kekSalt will be
- // different if a new password has been generated).
+ // The kekSalt changes when a new password is set, so it serves as
+ // a proxy for comparing the entire SRP attributes object.
if (remoteSRPAttributes.kekSalt != localSRPAttributes.kekSalt) {
- // The token is still valid, but the key and SRP attributes have
- // changed.
return {
status: "validButPasswordChanged",
updatedKeyAttributes: remoteKeyAttributes,
@@ -124,31 +66,13 @@ export const checkSessionValidity = async (): Promise<SessionValidity> => {
}
}
- // The token is still valid.
return { status: "valid" };
};
-/**
- * Return `true` if the user does not have a saved auth token, of it is no
- * longer valid. If needed, also update the key attributes at remote.
- *
- * This is a subset of {@link checkSessionValidity} that has been tailored for
- * use during each remote pull, to detect if the user has been logged out
- * elsewhere.
- *
- * @returns `true` if either we don't have an auth token, or if remote tells us
- * that the auth token (and the associated session) has been invalidated. In all
- * other cases, return `false`.
- *
- * In particular, this function doesn't throw and instead returns `false` on
- * errors. This is because returning `true` will trigger a blocking alert that
- * 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 isSessionInvalid = async (): Promise<boolean> => {
const token = await savedAuthToken();
if (!token) {
- return true; /* No saved token, session is invalid */
+ return true;
}
try {
@@ -156,7 +80,7 @@ export const isSessionInvalid = async (): Promise<boolean> => {
headers: await authenticatedRequestHeaders(),
});
if (!res.ok) {
- if (res.status == 401) return true; /* session is no longer valid */
+ if (res.status == 401) return true;
else throw new HTTPError(res);
}
@@ -168,10 +92,10 @@ export const isSessionInvalid = async (): Promise<boolean> => {
}
} catch (e) {
log.warn("Failed to check session validity", e);
- // Don't logout user on potentially transient errors.
+ // Returning true would log the user out, so do not do that on
+ // potentially transient errors.
return false;
}
- // Everything seems ok.
return false;
};
diff --git a/web/packages/accounts/services/sessions.ts b/web/packages/accounts/services/sessions.ts
index 5b252083f7..f0bec949bf 100644
--- a/web/packages/accounts/services/sessions.ts
+++ b/web/packages/accounts/services/sessions.ts
@@ -2,67 +2,28 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { z } from "zod";
-/**
- * Zod schema for an individual session returned by the API.
- */
const Session = z.object({
- /**
- * The session token.
- */
token: z.string(),
- /**
- * The time (epoch microseconds) when the session was created.
- */
creationTime: z.number(),
- /**
- * The IP address from which the session was created.
- */
ip: z.string(),
- /**
- * The raw user agent string.
- */
ua: z.string(),
- /**
- * A human-readable version of the user agent.
- */
prettyUA: z.string(),
- /**
- * The time (epoch microseconds) when the session was last used.
- */
lastUsedTime: z.number(),
});
-/**
- * TypeScript type for a session, derived from the Zod schema.
- */
export type Session = z.infer<typeof Session>;
-/**
- * Zod schema for the sessions API response.
- */
const SessionsResponse = z.object({ sessions: z.array(Session) });
-/**
- * Fetch all active sessions for the current user.
- *
- * @returns A promise that resolves to an array of {@link Session} objects,
- * sorted by last used time (most recent first).
- */
export const getActiveSessions = async (): Promise<Session[]> => {
const res = await fetch(await apiURL("/users/sessions"), {
headers: await authenticatedRequestHeaders(),
});
ensureOk(res);
const { sessions } = SessionsResponse.parse(await res.json());
- // Sort by last used time, most recent first.
return sessions.sort((a, b) => b.lastUsedTime - a.lastUsedTime);
};
-/**
- * Terminate a specific session.
- *
- * @param token The token of the session to terminate.
- */
export const terminateSession = async (token: string): Promise<void> => {
const url = await apiURL("/users/session");
const res = await fetch(`${url}?token=${encodeURIComponent(token)}`, {
diff --git a/web/packages/accounts/services/srp.ts b/web/packages/accounts/services/srp.ts
index 31dff87b5f..599816b04b 100644
--- a/web/packages/accounts/services/srp.ts
+++ b/web/packages/accounts/services/srp.ts
@@ -19,179 +19,15 @@ import {
type EmailOrSRPVerificationResponse,
} from "./user";
-/**
- * The SRP attributes for a user.
- *
- * These are created by a client on signup, saved to remote. During logins, they
- * are fetched from remote. In both cases they are also persisted in local
- * storage (both network ops and local storage use the same schema).
- *
- * [Note: SRP]
- *
- * The SRP (Secure Remote Password) protocol is a modified Diffie-Hellman key
- * exchange that allows the remote to verify the user's possession of a
- * password, and the user to ensure that remote is not being impersonated,
- * without the password ever leaving the device.
- *
- * It is used as an (user selectable) alternative to email verification.
- *
- * For more about the what and why, see the announcement blog post
- * https://ente.com/blog/ente-adopts-secure-remote-passwords/
- *
- * Here we do not focus on the math (the above blog post links to reference
- * material, and there is also an RFC), but instead of the various bits of
- * information that get exchanged.
- *
- * Broadly, there are two scenarios: SRP setup, and SRP verification.
- *
- * [Note: SRP setup] -------------------
- *
- * During SRP setup, client generates
- *
- * 01. A SRP user ID (a new UUID-v4)
- * 02. A SRP password (deterministically derived from their regular KEK)
- * 03. A SRP salt (randomly generated)
- *
- * These 3 things are enough to create a SRP verifier and client. The SRP client
- * can just be thought of an ephemeral stateful mechanism to avoid passing all
- * the state accrued so far to each operation. Each time when creating a SRP
- * client, the app generates a new random secret and uses it during init.
- *
- * 04. Compute verifier = computeSRPVerifier({ userID, password, salt })
- * 05. Generates a new (ephemeral and random) clientSecret
- * 06. Create client = new SRPClient({ userID, password, salt, clientSecret })
- *
- * The client (app) then starts the setup ceremony with remote:
- *
- * 07. Use SRP client to conjure secret `a` and use that to compute a public A
- * 08. Send { userID, salt, verifier, A } to remote ("/users/srp/setup")
- *
- * Remote then:
- *
- * 09. Generates a new (ephemeral and random) serverSecret
- * 10. Saves { userID, serverSecret, A } into SRP sessions table
- * 11. Creates server = new SRPServer({ verifier, serverSecret })
- * 12. Uses SRP server to conjure secret `b` and use that to compute a public B
- * 13. Stashes { sessionID, userID, salt, verifier } into SRP setups table
- * 14. Returns { setupID, B } to client
- *
- * Client then
- *
- * 15. Tells its SRP client about B
- * 16. Computes SRP M1 (evidence message) using the SRP client
- * 17. Sends { setupID, M1 } to remote ("/users/srp/complete")
- *
- * Remote then
- *
- * 18. Uses setupID to read the stashed { sessionID, verifier }
- * 19. Uses sessionID to read { serverSecret, A }
- * 20. Recreates server = new SRPServer({ verifier, serverSecret })
- * 21. Sets server.A
- * 22. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)
- * 23. Returns M2
- *
- * Client then
- *
- * 24. Verifies M2
- *
- * SRP setup is now complete.
- *
- * A similar flow is used when the user changes their password. On password
- * change, a new KEK is generated, thus the SRP password also changes, and so a
- * subset of the steps above are done to update both client and remote.
- *
- * [Note: SRP verification] -----------------------
- *
- * When the user is signing on a new device, the client
- *
- * 01. Fetches SRP attributes for a user to get { (SRP) userID, (SRP) salt }
- * 02. Rederives SRP password from their KEK
- * 03. Generates a new (ephemeral and random) clientSecret
- * 04. Creates client = new SRPClient({ userID, password, salt, clientSecret })
- * 05. Uses SRP client to conjure secret `a` and use that to compute a public A
- * 06. Sends { userID, A } to remote ("/users/srp/create-session")
- *
- * Remote
- *
- * 07. Retrieves { verifier } corresponding to the userID
- * 08. Generates a new (ephemeral and random) serverSecret
- * 09. Saves { userID, serverSecret, A } into SRP sessions table
- * 10. Creates server = new SRPServer({ verifier, serverSecret })
- * 11. Sets server.A
- * 12. Uses SRP server to conjure secret `b` and use that to compute a public B
- * 13. Returns { sessionID, B } to client
- *
- * Client then
- *
- * 14. Sets client.B
- * 15. Computes M1 (evidence message)
- * 16. Sends { userID, sessionID, M1 } to remote ("/users/srp/verify-session")
- *
- * Remote
- *
- * 17. Retrieves { verifier } corresponding to the userID
- * 17. Retrieves { serverSecret, A } using sessionID
- * 18. Recreates server = new SRPServer({ verifier, serverSecret })
- * 19. Sets server.A
- * 20. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)
- * 21. Returns M2
- *
- * Client then
- *
- * 22. Verifies M2
- *
- * SRP verification is now complete.
- */
export interface SRPAttributes {
- /**
- * The SRP user ID for the (Ente) user.
- *
- * Each Ente user gets a new randomly generated UUID v4 assigned as their
- * SRP user ID during SRP setup.
- */
srpUserID: string;
- /**
- * The SRP salt.
- *
- * This is a randomly generated salt created for each SRP user during SRP
- * setup. It is not meant to be secret.
- */
srpSalt: string;
- /**
- * The mem limit used during the KEK derivation from the password.
- *
- * See also the discussion in {@link kekSalt}.
- */
memLimit: number;
- /**
- * The ops limit used during the KEK derivation from the password.
- *
- * See also the discussion in {@link kekSalt}.
- */
opsLimit: number;
- /**
- * The salt used during the KEK derivation from the password.
- *
- * Base64 encoded.
- *
- * This is the same value as the {@link kekSalt} in {@link KeyAttributes},
- * made available by remote also as part of SRP attributes for convenience.
- * See: [Note: KEK three tuple] for more details.
- */
kekSalt: string;
- /**
- * If true, then the client should use email verification instead of SRP.
- */
isEmailMFAEnabled: boolean;
}
-/**
- * Zod schema for the {@link SRPAttributes} TypeScript type.
- *
- * We retain the SRP attributes response we get from remote verbatim when saving
- * it to local storage, so the same schema describes both the remote type and
- * the local storage type.
- */
export const RemoteSRPAttributes = z.object({
srpUserID: z.string(),
srpSalt: z.string(),
@@ -201,16 +37,6 @@ export const RemoteSRPAttributes = z.object({
isEmailMFAEnabled: z.boolean(),
});
-/**
- * Fetch the {@link SRPAttributes} from remote for the Ente user with the
- * provided email.
- *
- * Returns `undefined` if either there is no Ente user with the given
- * {@link email}, or if there is a a user but they've not yet completed the SRP
- * setup ceremony.
- *
- * @param email The email of the user whose SRP attributes we're fetching.
- */
export const getSRPAttributes = async (
email: string,
): Promise<SRPAttributes | undefined> => {
@@ -223,30 +49,10 @@ export const getSRPAttributes = async (
.attributes;
};
-/**
- * A local-only structure holding information required for SRP setup.
- *
- * [Note: SRP setup attributes]
- *
- * In some cases, there might be a step between the client having access to the
- * KEK (which we need for generating the SRP attributes, in particular the SRP
- * password) and the time where the client can proceed with the SRP setup (which
- * can only happen once we have an auth token).
- *
- * For example, when the user is signing up for a new account, the client has
- * the KEK on the signup screen since the user just set their password, but then
- * has to redirect to the screen for email verification, and it is only after
- * email verification that the client obtains an auth token and the SRP setup
- * can proceed (at which point it doesn't have access to the password and so
- * cannot derive the KEK).
- *
- * This gap is not just about different screens, but since there is an email
- * verification step involved, it might take time enough for the browser tab to
- * get closed and reopened. So instead of keeping the attributes we need to
- * continue with the SRP setup after email verification in memory, we
- * temporarily stash them in local storage using an object that conforms to the
- * following {@link SRPSetupAttributes} schema.
- */
+// SRP setup needs the KEK (to derive these values) but can complete only
+// after the client has an auth token, which during signup arrives only after
+// email verification. That verification can outlast the browser tab, so these
+// values are stashed in local storage rather than kept in memory.
export const SRPSetupAttributes = z.object({
srpUserID: z.string(),
srpSalt: z.string(),
@@ -256,12 +62,6 @@ export const SRPSetupAttributes = z.object({
export type SRPSetupAttributes = z.infer<typeof SRPSetupAttributes>;
-/**
- * Generate {@link SRPSetupAttributes} from the provided {@link kek}.
- *
- * @param kek The designated key encryption key (base64 encoded) for the user.
- * This will be used to (deterministically) derive a SRP password.
- */
export const generateSRPSetupAttributes = async (
kek: string,
): Promise<SRPSetupAttributes> => {
@@ -283,19 +83,10 @@ export const generateSRPSetupAttributes = async (
return { srpUserID, srpSalt, srpVerifier, loginSubKey };
};
-/**
- * Derive a "login sub-key" (which is really an arbitrary binary value, not
- * human generated) for use as the SRP user password by applying a deterministic
- * KDF (Key Derivation Function) to the provided {@link kek}.
- *
- * @param kek The user's KEK (key encryption key) as a base64 string.
- *
- * @returns A base64 encoded key that can be used as the SRP user password.
- */
const deriveSRPLoginSubKey = async (kek: string) => {
const kekSubKeyBytes = await deriveSubKeyBytes(kek, 32, 1, "loginctx");
- // Use the first 16 bytes (128 bits) of the KEK's KDF subkey as the SRP
- // password (instead of entire 32 bytes).
+ // Derive 32 bytes and use the first 16 as the SRP password. Asking the
+ // KDF for 16 bytes directly would produce a different value.
return toB64(kekSubKeyBytes.slice(0, 16));
};
@@ -303,22 +94,9 @@ const b64ToBuffer = (base64: string) => Buffer.from(base64, "base64");
const bufferToB64 = (buffer: Buffer) => buffer.toString("base64");
-/**
- * Use the provided {@link SRPSetupAttributes} to, well, setup SRP.
- *
- * See: [Note: SRP setup]
- *
- * @param srpSetupAttributes SRP setup attributes.
- */
export const setupSRP = async (srpSetupAttributes: SRPSetupAttributes) =>
srpSetupOrReconfigure(srpSetupAttributes, completeSRPSetup);
-/**
- * A function that is called by {@link srpSetupOrReconfigure} to exchange the
- * evidence message M1 for the evidence message M2 from remote.
- *
- * It is passed M1, and is expected to fulfill with M2.
- */
type SRPSetupOrReconfigureExchangeCallback = ({
setupID,
srpM1,
@@ -327,17 +105,6 @@ type SRPSetupOrReconfigureExchangeCallback = ({
srpM1: string;
}) => Promise<{ srpM2: string }>;
-/**
- * Use the provided {@link SRPSetupAttributes} to either setup (afresh) or
- * reconfigure SRP (when the user changes their password).
- *
- * The flow (described in [Note: SRP setup]) is mostly the same except the tail
- * end of the process where we exchange the evidence message M1 for the evidence
- * message M2 from remote. To handle this variance, we provide a callback
- * {@link exchangeCB}) that is invoked at this point in the sequence.
- *
- * @param srpSetupAttributes SRP setup attributes.
- */
const srpSetupOrReconfigure = async (
{ srpSalt, srpUserID, srpVerifier, loginSubKey }: SRPSetupAttributes,
exchangeCB: SRPSetupOrReconfigureExchangeCallback,
@@ -376,8 +143,6 @@ const generateSRPClient = async (
b64ToBuffer(srpSalt),
Buffer.from(srpUserID),
b64ToBuffer(loginSubKey),
- // The random `clientKey` parameterizes the current instance
- // of the SRP client.
clientKey!,
false,
),
@@ -396,11 +161,6 @@ const SetupSRPResponse = z.object({ setupID: z.string(), srpB: z.string() });
type SetupSRPResponse = z.infer<typeof SetupSRPResponse>;
-/**
- * Initiate SRP setup on remote.
- *
- * Part of the [Note: SRP setup] sequence.
- */
const startSRPSetup = async (
setupSRPRequest: SetupSRPRequest,
): Promise<SetupSRPResponse> => {
@@ -425,11 +185,6 @@ const CompleteSRPSetupResponse = z.object({
type CompleteSRPSetupResponse = z.infer<typeof CompleteSRPSetupResponse>;
-/**
- * Complete a previously initiated SRP setup on remote.
- *
- * Part of the [Note: SRP setup] sequence.
- */
const completeSRPSetup = async (
completeSRPSetupRequest: CompleteSRPSetupRequest,
) => {
@@ -442,24 +197,9 @@ const completeSRPSetup = async (
return CompleteSRPSetupResponse.parse(await res.json());
};
-/**
- * Fetch the SRP attributes from remote and use them to update the SRP
- * attributes we have saved locally.
- *
- * This function is intended to be called after {@link srpSetupOrReconfigure} to
- * also update our local state to match remote.
- *
- * @param userEmail The email of the user whose SRP attributes we want to fetch.
- * This should be the email address of the logged in user, or the user who is
- * going through the login / signup sequence currently.
- */
export const getAndSaveSRPAttributes = async (userEmail: string) =>
saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));
-/**
- * The subset of {@link KeyAttributes} that get updated when the user changes
- * their password.
- */
export interface UpdatedKeyAttr {
kekSalt: string;
encryptedKey: string;
@@ -468,18 +208,6 @@ export interface UpdatedKeyAttr {
memLimit: number;
}
-/**
- * Update the user's affected key and SRP attributes when they change their
- * password.
- *
- * The flow on changing password is similar to the flow on initial SRP setup,
- * with some differences at the tail end of the flow. See: [Note: SRP setup].
- *
- * @param srpSetupAttributes Attributes for the user's updated SRP setup.
- *
- * @param updatedKeyAttr The subset of the user's key attributes which need to
- * be updated to reflect their changed password.
- */
export const updateSRPAndKeyAttributes = (
srpSetupAttributes: SRPSetupAttributes,
updatedKeyAttr: UpdatedKeyAttr,
@@ -492,10 +220,8 @@ export interface UpdateSRPAndKeysRequest {
setupID: string;
srpM1: string;
updatedKeyAttr: UpdatedKeyAttr;
- /**
- * If true (default), then all existing sessions for the user will be
- * invalidated.
- */
+ // Remote treats an omitted value as true, invalidating all other sessions
+ // of the user.
logOutOtherDevices?: boolean;
}
@@ -506,12 +232,6 @@ const UpdateSRPAndKeysResponse = z.object({
type UpdateSRPAndKeysResponse = z.infer<typeof UpdateSRPAndKeysResponse>;
-/**
- * Update the SRP attributes and a subset of the key attributes on remote.
- *
- * This is invoked during the flow when the user changes their password, and SRP
- * needs to be reconfigured. See: [Note: SRP setup].
- */
const updateSRPAndKeys = async (
updateSRPAndKeysRequest: UpdateSRPAndKeysRequest,
): Promise<UpdateSRPAndKeysResponse> => {
@@ -524,31 +244,9 @@ const updateSRPAndKeys = async (
return UpdateSRPAndKeysResponse.parse(await res.json());
};
-/**
- * The message of the {@link Error} that is thrown by {@link verifySRP} if
- * remote fails SRP verification with a HTTP 401.
- *
- * The API contract allows for a SRP verification 401 both because of incorrect
- * credentials or a non existent account.
- */
export const srpVerificationUnauthorizedErrorMessage =
"SRP verification failed (HTTP 401 Unauthorized)";
-/**
- * Log the user in to a new device by performing SRP verification.
- *
- * This function implements the flow described in [Note: SRP verification].
- *
- * @param srpAttributes The user's SRP attributes.
- *
- * @param kek The user's key encryption key as a base64 string.
- *
- * @returns If SRP verification is successful, it returns a
- * {@link EmailOrSRPVerificationResponse}.
- *
- * @throws An Error with {@link srpVerificationUnauthorizedErrorMessage} in case
- * there is no such account, or if the credentials (kek) are incorrect.
- */
export const verifySRP = async (
{ srpUserID, srpSalt }: SRPAttributes,
kek: string,
@@ -556,7 +254,6 @@ export const verifySRP = async (
const loginSubKey = await deriveSRPLoginSubKey(kek);
const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);
- // Send A, obtain B.
const { srpB, sessionID } = await createSRPSession({
srpUserID,
srpA: bufferToB64(srpClient.computeA()),
@@ -564,7 +261,6 @@ export const verifySRP = async (
srpClient.setB(b64ToBuffer(srpB));
- // Send M1, obtain M2.
const { srpM2, ...rest } = await verifySRPSession({
sessionID,
srpUserID,
diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.ts
index 5a86304593..c5268ac657 100644
--- a/web/packages/accounts/services/user.ts
+++ b/web/packages/accounts/services/user.ts
@@ -42,235 +42,42 @@ import { z } from "zod";
import { clearInflightPasskeySessionID } from "./passkey";
import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";
-/**
- * The locally persisted data we have about the user after they've logged in.
- *
- * This type arguably belongs to accounts-db (since that's what persists it and
- * its shadow alias, {@link PartialLocalUser}), but since most code that will
- * need this will need this after login has completed, and will be using the
- * {@link ensureLocalUser} method below, we keep this in the same file to reduce
- * the need to import the type from a separate file.
- */
export interface LocalUser {
- /**
- * The user's ID.
- */
id: number;
- /**
- * The email associated with the user's Ente account.
- */
email: string;
- /**
- * The user's (plaintext) auth token.
- *
- * It is used for making API calls on their behalf, by passing this token as
- * the value of the X-Auth-Token header in the HTTP request.
- *
- * Usually you shouldn't be needing to access this property; instead use
- * {@link savedAuthToken()} which is kept in sync with this value, and lives
- * in IndexedDB and thus can also be used in web workers.
- */
+ // Prefer savedAuthToken over this property; it is kept in sync with this
+ // value and, being in IndexedDB, is also usable in web workers.
token: string;
- /**
- * `true` if the TOTP based second factor is enabled for the user.
- */
isTwoFactorEnabled?: boolean;
}
-/**
- * Return the currently logged in {@link LocalUser}, throwing it the user is not
- * logged in.
- *
- * This is a wrapper over the {@link savedLocalUser} function that throws if no
- * one is logged in. A more appropriate name for this function, keeping in line
- * with the conventions the other methods follow, would've been
- * {@link ensureSavedLocalUser}. The shorter name is for readability.
- */
export const ensureLocalUser = (): LocalUser =>
ensureExpectedLoggedInValue(savedLocalUser());
-/**
- * A function throws an error if a value that is expected to be truthy when the
- * user is logged in is instead falsey.
- *
- * This is meant as a convenience wrapper to assert that a value we expect when
- * the user is logged in is indeed there.
- */
export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {
if (!t) throw new Error("Not logged in");
return t;
};
-/**
- * The user's various encrypted keys and their related attributes.
- *
- * - Attributes to derive the KEK, the (master) key encryption key.
- * - Encrypted master key (with KEK)
- * - Encrypted master key (with recovery key)
- * - Encrypted recovery key (with master key).
- * - Public key and encrypted private key (with master key).
- *
- * The various "key" attributes are base64 encoded representations of the
- * underlying binary data.
- *
- * [Note: Key attribute mutability]
- *
- * The key attributes contain two subsets:
- *
- * - Attributes that changes when the user changes their password. These are the
- * {@link UpdatedKeyAttr}.
- *
- * - All other attributes never change after initial setup.
- */
export interface KeyAttributes {
- /**
- * The user's master key encrypted with the key encryption key.
- *
- * Base64 encoded.
- *
- * [Note: Key encryption key]
- *
- * The user's master key is encrypted with a "key encryption key" (lovingly
- * called a "KEK" sometimes).
- *
- * The KEK itself is derived from the user's password.
- *
- * 1. User enters password on new device.
- *
- * 2. Client derives KEK from this password (using the {@link kekSalt},
- * {@link opsLimit} and {@link memLimit} as parameters for the
- * derivation).
- *
- * 3. Client use KEK to decrypt the master key from {@link encryptedKey} and
- * {@link keyDecryptionNonce}.
- */
encryptedKey: string;
- /**
- * The nonce used during the encryption of the master key.
- *
- * Base64 encoded.
- *
- * @see {@link encryptedKey}.
- */
keyDecryptionNonce: string;
- /**
- * The salt used during the derivation of the KEK.
- *
- * Base64 encoded.
- *
- * [Note: KEK three tuple]
- *
- * The three tuple (kekSalt, opsLimit, memLimit) is needed (along with the
- * user's password) to rederive the KEK when the user logs in on a new
- * client (See: [Note: Key encryption key]).
- *
- * The client can obtain these three by fetching their key attributes from
- * remote, however unless {@link isEmailMFAEnabled} is enabled (which is not
- * by default), then the user's credentials are verified using SRP instead
- * of email verification. So as a convenience for this (majority) flow,
- * remote also provides this exact same three tuple as part of the
- * {@link SRPAttributes} fetched from remote.
- *
- * So on remote the KEK three tuple is the same whether it be part of key
- * attributes or SRP attributes. When the user changes their password, both
- * of them also get updated simulataneously (they use the same storage).
- *
- * However, on the client side these two sets of three tuples might diverge
- * because of the client generating interactive key attributes. When that
- * happens, the locally saved key attributes will be overwritten by the KEK
- * three tuple for the new generated interactive KEK parameters, while the
- * SRP attributes will continue to reflect the "original" KEK three tuple we
- * got from remote.
- */
kekSalt: string;
- /**
- * The operation limit used during the derivation of the KEK.
- *
- * The {@link opsLimit} and {@link memLimit} are complementary parameters
- * that define the amount of work done by the key derivation function. See
- * the {@link deriveKey}, {@link deriveSensitiveKey} and
- * {@link deriveInteractiveKey} functions for more detail about them.
- *
- * See: [Note: Key encryption key].
- */
opsLimit: number;
- /**
- * The memory limit used during the derivation of the KEK.
- *
- * See {@link opsLimit} for more details.
- */
memLimit: number;
- /**
- * The user's public key (part of their public-key keypair, the other half
- * being the {@link encryptedSecretKey}).
- *
- * Base64 encoded.
- */
publicKey: string;
- /**
- * The user's private key (part of their public-key keypair, the other half
- * being the {@link publicKey}) encrypted with their master key.
- *
- * Base64 encoded.
- *
- * [Note: privateKey and secretKey]
- *
- * The nomenclature for the key pair follows libsodium's conventions
- * (https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation),
- * who possibly chose public + secret instead of public + private to avoid
- * confusion with shorthand notation (pk).
- *
- * However, the library author later changed their mind on this, so while
- * libsodium itself (the C library) and the documentation uses "secretKey",
- * the JavaScript implementation (libsodium.js) uses "privateKey".
- *
- * This structure uses the term "secretKey" since that is what the remote
- * protocol already was based on. Within the web app codebase, we use
- * "privateKey" since that is what the underlying libsodium.js uses.
- */
+ // libsodium and the wire protocol call this the "secret" key, but
+ // libsodium.js calls it the "private" key; the codebase uses "privateKey"
+ // to match libsodium.js.
+ // https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation
encryptedSecretKey: string;
- /**
- * The nonce used during the encryption of {@link encryptedSecretKey}.
- */
secretKeyDecryptionNonce: string;
- /**
- * The user's master key after being encrypted with their recovery key.
- *
- * Base64 encoded.
- *
- * This allows the user to recover their master key if they forget their
- * password but still have their recovery key.
- *
- * Note: This value doesn't change after being initially created.
- */
masterKeyEncryptedWithRecoveryKey?: string;
- /**
- * The nonce used during the encryption of
- * {@link masterKeyEncryptedWithRecoveryKey}.
- *
- * Base64 encoded.
- */
masterKeyDecryptionNonce?: string;
- /**
- * The user's recovery key after being encrypted with their master key.
- *
- * Base64 encoded.
- *
- * Note: This value doesn't change after being initially created.
- */
recoveryKeyEncryptedWithMasterKey?: string;
- /**
- * The nonce used during the encryption of
- * {@link recoveryKeyEncryptedWithMasterKey}.
- *
- * Base64 encoded.
- */
recoveryKeyDecryptionNonce?: string;
}
-/**
- * Zod schema for {@link KeyAttributes}.
- */
export const RemoteKeyAttributes = z.object({
kekSalt: z.string(),
encryptedKey: z.string(),
@@ -292,10 +99,6 @@ export const RemoteKeyAttributes = z.object({
recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
});
-/**
- * A variant of {@link savedKeyAttributes} that throws if keyAttributes are not
- * present in local storage.
- */
export const ensureSavedKeyAttributes = (): KeyAttributes =>
ensureExpectedLoggedInValue(savedKeyAttributes());
@@ -305,14 +108,6 @@ export interface GenerateKeysAndAttributesResult {
keyAttributes: KeyAttributes;
}
-/**
- * Generate a new set of key attributes.
- *
- * @param password The password to use for deriving the key encryption key.
- *
- * @returns a newly generated master key (base64 string), kek (base64 string)
- * and the key attributes associated with the combination.
- */
export async function generateKeysAndAttributes(
password: string,
): Promise<GenerateKeysAndAttributesResult> {
@@ -360,9 +155,6 @@ export async function generateKeysAndAttributes(
return { masterKey, kek, keyAttributes };
}
-/**
- * Update or set the user's {@link KeyAttributes} on remote.
- */
export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>
ensureOk(
await fetch(await apiURL("/users/attributes"), {
@@ -379,14 +171,8 @@ export interface RecoveryKeyAttributes {
recoveryKeyDecryptionNonce: string;
}
-/**
- * Update the encrypted recovery key attributes for the logged in user.
- *
- * In practice, this is not expected to be called and is meant as a rare
- * fallback for very old accounts created prior to recovery key related
- * attributes being assigned on account setup. Even for these, it'll be called
- * only once.
- */
+// This is a rare fallback for very old accounts that predate recovery key
+// attributes being set during account setup.
export const putUserRecoveryKeyAttributes = async (
recoveryKeyAttributes: RecoveryKeyAttributes,
) =>
@@ -398,20 +184,6 @@ export const putUserRecoveryKeyAttributes = async (
}),
);
-/**
- * Ask remote to send a OTP / OTT to the given email to verify that the user has
- * access to it. Subsequent the app will pass this OTT back via the
- * {@link verifyOTT} method.
- *
- * @param email The email to verify.
- *
- * @param purpose In which context is the email being verified. Remote applies
- * additional business rules depending on this. For example, passing the purpose
- * "login" ensures that the OTT is only sent to an already registered email.
- *
- * In cases where the purpose is ambiguous (e.g. we're not sure if it is an
- * existing login or a new signup), the purpose can be set to `undefined`.
- */
export const sendOTT = async (
email: string,
purpose: "change" | "signup" | "login" | undefined,
@@ -424,106 +196,17 @@ export const sendOTT = async (
}),
);
-/**
- * The response from remote on a successful user verification, either via
- * {@link verifyEmail} or {@link verifySRP}.
- *
- * The {@link id} is always present. The rest of the values are are optional
- * since only a subset of them will be returned depending on the case:
- *
- * 1. If the user has both passkeys and TOTP based second factor enabled, then
- * the following will be set:
- * - {@link passkeySessionID}, {@link accountsUrl}
- * - {@link twoFactorSessionIDV2}
- *
- * 2. If the user has only passkeys enabled, then the following will be set:
- * - {@link passkeySessionID}, {@link accountsUrl}
- *
- * 3. If the user has only TOTP based second factor enabled, then the following
- * will be set:
- * - {@link twoFactorSessionID}
- *
- * 4. If the user doesn't have any second factor, but has already setup their
- * key attributes, then the following will be set:
- * - {@link keyAttributes}
- * - {@link encryptedToken}
- *
- * 5. Finally, in the rare case that the user has not yet setup their key
- * attributes, then the following will be set:
- * - {@link token}
- */
export interface EmailOrSRPVerificationResponse {
- /**
- * The user's ID.
- */
id: number;
- /**
- * The user's key attributes.
- *
- * These will be set (along with the {@link encryptedToken}) if the user
- * does not have a second factor.
- */
keyAttributes?: KeyAttributes;
- /**
- * The base64 representation of an encrypted auth token, encrypted using the
- * user's public key.
- *
- * These will be set (along with the {@link keyAttributes}) if the user
- * does not have a second factor.
- */
encryptedToken?: string;
- /**
- * The base64 representation of an auth token.
- *
- * This will be set in the rare edge case for when the user has not yet
- * setup their key attributes.
- */
token?: string;
- /**
- * A session ID that can be used to complete the TOTP based second factor.
- *
- * This will be set if the user has enabled a TOTP based second factor but
- * has not enabled passkeys.
- */
twoFactorSessionID?: string;
- /**
- * A session ID that can be used to complete passkey verification.
- *
- * This will be set if the user has added a passkey to their account.
- */
passkeySessionID?: string;
- /**
- * Base URL for the accounts app where we should redirect to for passkey
- * verification.
- *
- * This will only be set if the user has setup a passkey (i.e., whenever
- * {@link passkeySessionID} is defined).
- */
accountsUrl?: string;
- /**
- * A session ID that can be used to complete the TOTP based second fator.
- *
- * This will be set in lieu of {@link twoFactorSessionID} if the user has
- * setup both passkeys and TOTP based two factors are enabled for their
- * account.
- *
- * ---
- *
- * Historical context: {@link twoFactorSessionIDV2} is only set if user has
- * both passkey and two factor enabled. This is to ensure older clients keep
- * using passkey flow when both are set. It is intended to be removed once
- * all clients starts surfacing both options for performing 2FA.
- *
- * See also {@link useSecondFactorChoiceIfNeeded}.
- */
twoFactorSessionIDV2?: string;
}
-/**
- * Zod schema for the {@link EmailOrSRPVerificationResponse} type.
- *
- * See: [Note: Duplicated Zod schema and TypeScript type]
- */
const RemoteEmailOrSRPVerificationResponseBase = z.object({
id: z.number(),
keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
@@ -551,35 +234,13 @@ const RemoteEmailOrSRPVerificationResponse =
accountsUrlForPasskeyRefinement,
);
-/**
- * A specialization of {@link RemoteEmailOrSRPVerificationResponse} for SRP
- * verification, which results in the {@link srpM2} field in addition to the
- * other ones.
- *
- * The declaration conceptually belongs to `srp.ts`, but is here to avoid cyclic
- * dependencies.
- */
+// This declaration conceptually belongs to srp.ts, but lives here to avoid a
+// cyclic dependency.
export const RemoteSRPVerificationResponse =
RemoteEmailOrSRPVerificationResponseBase.extend({
- /**
- * The SRP M2 (evidence message), the proof that the server has the
- * verifier.
- */
srpM2: z.string(),
}).refine(requireAccountsUrlForPasskey, accountsUrlForPasskeyRefinement);
-/**
- * Verify user's access to the given {@link email} by comparing the OTT that
- * remote previously sent to that email.
- *
- * @param email The email to verify.
- *
- * @param ott The OTT that the user entered.
- *
- * @param source During signup, we ask the user the referral "source" through
- * which they heard about Ente. When present (i.e. during signup, and if the
- * user indeed provided it), that source should be passed as this parameter.
- */
export const verifyEmail = async (
email: string,
ott: string,
@@ -594,13 +255,10 @@ export const verifyEmail = async (
return RemoteEmailOrSRPVerificationResponse.parse(await res.json());
};
-/**
- * Log the user out on remote, if possible and needed.
- */
export const remoteLogoutIfNeeded = async () => {
if (!(await savedAuthToken())) {
- // If the logout is attempted during the login / signup flow itself,
- // then we won't have an auth token. Handle that gracefully.
+ // The logout was attempted during the login / signup flow itself, so
+ // there is no auth token yet and nothing to log out on remote.
return;
}
@@ -609,45 +267,16 @@ export const remoteLogoutIfNeeded = async () => {
headers: await authenticatedRequestHeaders(),
});
if (res.status == 401) {
- // Ignore if we get a 401 Unauthorized, this is expected to happen on
- // token expiry.
+ // A 401 is expected when the token has already expired; ignore it.
return;
}
ensureOk(res);
};
-/**
- * Generate a new local-only KEK (key encryption key) suitable for interactive
- * use and update the locally saved key attributes to reflect it.
- *
- * See {@link deriveInteractiveKey} for more details.
- *
- * In brief, after the initial password verification, we create a new
- * inetractive KEK derived from the same password as the original KEK, but with
- * so called interactive mem and ops limits which result in a noticeably faster
- * key derivation.
- *
- * We then overwrite the encrypted master key, encryption nonce and the KEK
- * derivation parameters (see: [Note: KEK three tuple]) in the locally persisted
- * {@link KeyAttributes} so that these interactive parameters get used
- * subsequent reauthentication.
- *
- * These are more ergonomic for the user especially in the web app where they
- * need to enter their password to access their masterKey when repopening the
- * app in a new tab (on desktop we can avoid this by using OS storage, see
- * [Note: Safe storage and interactive KEK attributes]).
- *
- * @param password The user's password.
- *
- * @param keyAttributes The existing "original" key attributes, which we
- * might've generated locally (new signup) or fetched from remote (existing
- * login).
- *
- * @param masterKey The user's master key (base64 encoded).
- *
- * @returns the update key attributes.
- */
+// The interactive KEK and the key attributes this function saves are local
+// only and are never sent to remote; the saved SRP attributes retain the
+// original KEK derivation parameters from remote.
export const generateAndSaveInteractiveKeyAttributes = async (
password: string,
keyAttributes: KeyAttributes,
@@ -675,22 +304,11 @@ export const generateAndSaveInteractiveKeyAttributes = async (
return interactiveKeyAttributes;
};
-/**
- * Change the email associated with the user's account (both locally and on
- * remote)
- *
- * @param email The new email.
- *
- * @param ott The verification code that was sent to the new email.
- */
export const changeEmail = async (email: string, ott: string) => {
await postChangeEmail(email, ott);
updateSavedLocalUser({ email });
};
-/**
- * Change the email associated with the user's account on remote.
- */
const postChangeEmail = async (email: string, ott: string) =>
ensureOk(
await fetch(await apiURL("/users/change-email"), {
@@ -700,17 +318,11 @@ const postChangeEmail = async (email: string, ott: string) =>
}),
);
-/**
- * Change the user's password on both remote and locally.
- *
- * @param password The new password.
- */
export const changePassword = async (password: string) => {
const user = ensureLocalUser();
const masterKey = await ensureMasterKeyFromSession();
const keyAttributes = ensureSavedKeyAttributes();
- // Generate new KEK.
const {
key: kek,
salt: kekSalt,
@@ -718,7 +330,6 @@ export const changePassword = async (password: string) => {
memLimit,
} = await deriveSensitiveKey(password);
- // Generate new key attributes.
const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
await encryptBox(masterKey, kek);
const updatedKeyAttr: UpdatedKeyAttr = {
@@ -729,20 +340,16 @@ export const changePassword = async (password: string) => {
memLimit,
};
- // Update SRP and key attributes on remote.
await updateSRPAndKeyAttributes(
await generateSRPSetupAttributes(kek),
updatedKeyAttr,
);
- // Update SRP attributes locally.
await getAndSaveSRPAttributes(user.email);
const srpAttributes = await getSRPAttributes(user.email);
saveSRPAttributes(ensure(srpAttributes));
- // Update key attributes locally, generating a new interactive kek while
- // we're at it.
await generateAndSaveInteractiveKeyAttributes(
password,
{ ...keyAttributes, ...updatedKeyAttr },
@@ -750,25 +357,6 @@ export const changePassword = async (password: string) => {
);
};
-/**
- * Update the {@link id} and {@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 decryptAndStoreTokenIfNeeded} 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 also saved to
- * the partial local user (after doing a sanity check that we're not replacing
- * partial data with a different userID).
- *
- * @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,
@@ -786,14 +374,6 @@ export const resetSavedLocalUserTokens = async (
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 decryptAndStoreTokenIfNeeded = async (
keyAttributes: KeyAttributes,
masterKey: string,
@@ -817,25 +397,13 @@ export const decryptAndStoreTokenIfNeeded = async (
};
const TwoFactorSecret = z.object({
- /**
- * The 2FA secret code.
- */
secretCode: z.string(),
- /**
- * A base64 encoded "image/png".
- */
+ // The value is a base64 encoded PNG image.
qrCode: z.string(),
});
export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;
-/**
- * Start a TOTP based two factor setup process by fetching a secret code (and
- * the corresponding QR code) from remote.
- *
- * Once the user provides us with a TOTP generated using the provided secret, we
- * can finish the setup with {@link setupTwoFactorFinish}.
- */
export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {
const res = await fetch(await apiURL("/users/two-factor/setup"), {
method: "POST",
@@ -845,18 +413,6 @@ export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {
return TwoFactorSecret.parse(await res.json());
};
-/**
- * Finish the TOTP based two factor setup by provided a previously obtained
- * secret (using {@link setupTwoFactor}) and the current TOTP generated using
- * that secret.
- *
- * This updates both the state both locally and on remote.
- *
- * @param secretCode The value of {@link secretCode} from the
- * {@link TwoFactorSecret} obtained by {@link setupTwoFactor}.
- *
- * @param totp The current TOTP corresponding to {@link secretCode}.
- */
export const setupTwoFactorFinish = async (
secretCode: string,
totp: string,
@@ -871,28 +427,11 @@ export const setupTwoFactorFinish = async (
};
interface EnableTwoFactorRequest {
- /**
- * The current value of the TOTP corresponding to the two factor {@link
- * secretCode} obtained from a previous call to {@link setupTwoFactor}.
- */
code: string;
- /**
- * The {@link secretCode} encrypted with the user's recovery key.
- *
- * This is used in the case of second factor recovery.
- */
encryptedTwoFactorSecret: string;
- /**
- * The nonce that was used when encrypting {@link encryptedTwoFactorSecret}.
- */
twoFactorSecretDecryptionNonce: string;
}
-/**
- * Enable the TOTP based two factor for the user by providing the current 2FA
- * code corresponding the two factor secret, and encrypted secrets for future
- * recovery (if needed).
- */
const enableTwoFactor = async (req: EnableTwoFactorRequest) =>
ensureOk(
await fetch(await apiURL("/users/two-factor/enable"), {
@@ -902,22 +441,9 @@ const enableTwoFactor = async (req: EnableTwoFactorRequest) =>
}),
);
-/**
- * The result of a successful two factor verification (TOTP or passkey),
- * recovery removal (TOTP) or recovery bypass (passkey).
- */
export const TwoFactorAuthorizationResponse = z.object({
- /**
- * The user's ID.
- */
id: z.number(),
- /**
- * The user's key attributes.
- */
keyAttributes: RemoteKeyAttributes,
- /**
- * A encrypted auth token.
- */
encryptedToken: z.string(),
});
@@ -938,17 +464,10 @@ export const verifyTwoFactor = async (
return TwoFactorAuthorizationResponse.parse(await res.json());
};
-/** The type of the second factor we're trying to act on */
export type TwoFactorType = "totp" | "passkey";
const TwoFactorRecoveryResponse = z.object({
- /**
- * The recovery secret, encrypted using the user's recovery key.
- */
encryptedSecret: z.string(),
- /**
- * The nonce used during encryption of {@link encryptedSecret}.
- */
secretDecryptionNonce: z.string(),
});
@@ -956,35 +475,6 @@ export type TwoFactorRecoveryResponse = z.infer<
typeof TwoFactorRecoveryResponse
>;
-/**
- * Initiate second factor reset or bypass by requesting the encrypted second
- * factor recovery secret (and nonce) from remote. The user can then decrypt
- * these using their recovery key to reset or bypass their second factor.
- *
- * @param twoFactorType The type of second factor to reset or bypass.
- *
- * @param sessionID A two factor session ID ({@link twoFactorSessionID} or
- * {@link passkeySessionID}) for the user.
- *
- * [Note: Second factor recovery]
- *
- * 1. When setting up a TOTP based second factor, client sends a (encrypted 2fa
- * recovery secret, nonce) pair to remote. This is a randomly generated
- * secret (and nonce) encrypted using the user's recovery key.
- *
- * 2. Similarly, when setting up a passkey as the second factor, the client
- * sends a encrypted recovery secret (see {@link configurePasskeyRecovery}).
- *
- * 3. When the user wishes to reset or bypass their second factor, the client
- * asks remote for these encrypted secrets (using {@link getRecoverTwoFactor}).
- *
- * 4. User then enters their recovery key, which the client uses to decrypt the
- * recovery secret and provide it back to remote for verification (using
- * {@link removeTwoFactor}).
- *
- * 5. If the recovery secret matches, then remote resets (TOTP based) or bypass
- * (passkey based) the user's second factor.
- */
export const getRecoverTwoFactor = async (
twoFactorType: TwoFactorType,
sessionID: string,
@@ -997,29 +487,6 @@ export const getRecoverTwoFactor = async (
return TwoFactorRecoveryResponse.parse(await res.json());
};
-/**
- * Finish the second factor recovery / bypass initiated by
- * {@link getRecoverTwoFactor} using the provided recovery key mnemonic entered
- * by the user.
- *
- * See: [Note: Second factor recovery].
- *
- * This completes the recovery process both locally, and on remote.
- *
- * @param twoFactorType The second factor type (same value as what would've been
- * passed to {@link getRecoverTwoFactor} for obtaining
- * {@link recoveryResponse}).
- *
- * @param sessionID The second factor session ID (same value as what would've
- * been passed to {@link getRecoverTwoFactor} for obtaining
- * {@link recoveryResponse}).
- *
- * @param recoveryResponse The response to a previous call to
- * {@link getRecoverTwoFactor}.
- *
- * @param recoveryKeyMnemonic The 24-word BIP-39 recovery key mnemonic provided
- * by the user to complete recovery.
- */
export const recoverTwoFactorFinish = async (
twoFactorType: TwoFactorType,
sessionID: string,
diff --git a/web/packages/media/collection.ts b/web/packages/media/collection.ts
index 4a9850bd37..0c99cfb3ce 100644
--- a/web/packages/media/collection.ts
+++ b/web/packages/media/collection.ts
@@ -11,117 +11,24 @@ import {
type MagicMetadata,
} from "./magic-metadata";
-/**
- * A collection, as used and persisted locally by the client.
- *
- * A collection is, well, a collection of files. It is roughly equivalent to an
- * "album" (which is also the term we use in the UI), but there can also be
- * special type of collections like "favorites" which have special behaviour.
- *
- * A collection contains zero or more files ({@link EnteFile}).
- *
- * A collection can be owned by the user (in whose context this code is
- * running), or might be a collection that is shared with them.
- */
export interface Collection {
- /**
- * The collection's globally unique ID.
- *
- * The collection's ID is a integer assigned by remote as the identifier for
- * an {@link Collection} when it is created. It is globally unique across
- * all collections on an Ente instance (i.e., it is not scoped to a user).
- */
id: number;
- /**
- * Information about the user who owns the collection.
- *
- * Each collection is owned by exactly one user. The owner may optionally
- * choose to share it with additional users, granting them varying level of
- * privileges.
- *
- * Within the {@link CollectionUser} instance of the {@link owner} field:
- *
- * - {@link email} will be set only if this is a shared collection that does
- * not belong to the current user.
- * - {@link role} will be blank.
- */
owner: CollectionUser;
- /**
- * The "collection key" (base64 encoded).
- *
- * The collection key is used to encrypt and decrypt that files that are
- * associated with the collection. See: [Note: Collection file].
- */
key: string;
- /**
- * The name of the collection.
- */
name: string;
- /**
- * The type of the collection.
- *
- * Expected to be one of {@link CollectionType}.
- */
type: string;
- /**
- * The other Ente users with whom the collection has been shared with.
- *
- * Within the {@link CollectionUser} instances of the {@link sharee} field:
- *
- * - {@link email} will be set.
- * - {@link role} is expected to be one of "VIEWER" or "COLLABORATOR".
- */
sharees: CollectionUser[];
- /**
- * Public links that can be used to access and update the collection.
- */
publicURLs: PublicURL[];
- /**
- * The last time the collection was updated (epoch microseconds).
- *
- * The collection is considered updated both
- *
- * - When the files associated with it modified (added, removed); and
- * - When the collection's own fields are modified.
- */
updationTime: number;
- /**
- * Private mutable metadata associated with the collection that is only
- * visible to the owner of the collection.
- *
- * See: [Note: Metadatum]
- */
+ // Private to the owner; never visible to sharees.
magicMetadata?: MagicMetadata<CollectionPrivateMagicMetadataData>;
- /**
- * Public mutable metadata associated with the collection that is visible to
- * all users with whom the collection has been shared.
- *
- * See: [Note: Metadatum]
- */
+ // Visible to everyone with whom the collection is shared.
pubMagicMetadata?: MagicMetadata<CollectionPublicMagicMetadataData>;
- /**
- * Private mutable metadata associated with the collection that is only
- * visible to the current user if they're not the owner of the collection.
- *
- * Sometimes also referred to as "shareeMagicMetadata".
- *
- * This is metadata associated with each "share", and is only visible to
- * (and editable by) the user with which the collection has been shared, not
- * the owner. Each user with whom the collection has been shared gets their
- * own private copy. This allows each user to keep their own metadata
- * associated with a shared album (e.g. archive status).
- *
- * See: [Note: Metadatum]
- */
+ // Set by and visible to only the individual sharee; the owner and other
+ // sharees never see it.
sharedMagicMetadata?: MagicMetadata<CollectionShareeMagicMetadataData>;
}
-/**
- * The known set of values for the {@link type} field of a {@link Collection}.
- *
- * This is the list of values, see {@link CollectionType} for the corresponding
- * TypeScript type.
- */
export const collectionTypes = [
"album",
"folder",
@@ -129,52 +36,6 @@ export const collectionTypes = [
"uncategorized",
] as const;
-/**
- * The type of a collection.
- *
- * - "album" - A regular "Ente Album" that the user sees in their library.
- *
- * - "folder" - An Ente Album that is also associated with an OS album on the
- * user's mobile device.
- *
- * A collection of type "folder" is created by the mobile app if there is an
- * associated on-device album for the new Ente album being created.
- *
- * This separation between "album" and "folder" allows different mobile
- * clients to push to the same Folder ("Camera", "Screenshots"), not allowing
- * for duplicate folders with the same name, while still allowing users to
- * create different albums with the same name.
- *
- * The web/desktop app does not create collections of type "folder", and
- * otherwise treats them as aliases for "album".
- *
- * - "favorites" - A special collection consisting of the items that the user
- * has marked as their favorites.
- *
- * The user can have at most one collection of type "favorites" (enforced at
- * remote). This collection is created on demand by the client where the user
- * first marks an item as a favorite. The user can choose to share their
- * "favorites" with other users, so it is possible for there to be multiple
- * collections of type "favorites" present in our local database, however only
- * one of those will belong to the logged in user (cf `owner.id`).
- *
- * - "uncategorized" - A special collection consisting of items that do not
- * belong to any other collection.
- *
- * In the remote schema, each item ({@link EnteFile}) is always associated
- * with a collection. The same item may belong to multiple collections (See:
- * [Note: Collection file]), but it must belong to at least one collection.
- *
- * In some scenarios, e.g. when deleting the last collection to which a file
- * belongs, the file would thus get orphaned and violate the schema
- * invariants. So in such cases, the client which is performing the
- * corresponding operation moves the file to the user's special
- * "uncategorized" collection, creating it if needed.
- *
- * Similar to "favorites", the user can own only one "uncategorized"
- * collection. Shared collections of this type can also be present locally,
- * so callers must include the owner when resolving the user's collection.
- */
export type CollectionType = (typeof collectionTypes)[number];
interface CollectionTypeAndOwner {
@@ -182,6 +43,13 @@ interface CollectionTypeAndOwner {
owner: { id: number };
}
+// A file must always belong to at least one collection. A client that would
+// otherwise orphan a file (e.g. when deleting the last collection containing
+// it) must instead move the file to the user's "uncategorized" collection,
+// creating that if needed.
+//
+// Shared collections of type "uncategorized" can also be present locally, so
+// the owner check is needed to find the user's own one.
export const findUserUncategorizedCollection = <
T extends CollectionTypeAndOwner,
>(
@@ -193,23 +61,6 @@ export const findUserUncategorizedCollection = <
collection.type == "uncategorized" && collection.owner.id == userID,
);
-/**
- * The privilege level of a participant associated with a collection.
- *
- * - "VIEWER" - Has read-only access to files in the collection.
- *
- * - "COLLABORATOR" - Can additionally add files from the collection, and remove
- * files that they added from the collection (i.e., files they "own").
- *
- * - "ADMIN" - Can manage participants (invite/remove) similar to the owner, but
- * cannot delete the collection or remove the owner.
- *
- * - "OWNER" - The owner of the collection. Can remove any file, including those
- * added by other users, from the collection.
- *
- * It is guaranteed that a there will be exactly one participant of type OWNER,
- * and their user ID will be the same as the collection `owner.id`.
- */
export type CollectionParticipantRole =
| "VIEWER"
| "COLLABORATOR"
@@ -217,67 +68,18 @@ export type CollectionParticipantRole =
| "OWNER"
| "UNKNOWN";
-/**
- * A subset of {@link CollectionParticipantRole} that are applicable when
- * sharing a collection with another Ente user.
- */
export type CollectionNewParticipantRole = "VIEWER" | "COLLABORATOR" | "ADMIN";
-/**
- * Information about the user associated with a collection, either as an owner,
- * or as someone with whom the collection has been shared with.
- */
export interface CollectionUser {
- /**
- * The ID of the underlying {@link User} that this {@link CollectionUser}
- * stands for.
- */
id: number;
- /**
- * The email of the user.
- *
- * - The email is present for the {@link owner} only for shared collections
- * that do not belong to the current user.
- * - The email is present for all {@link sharees}.
- * - Remote uses a blank string to indicate absent values.
- */
email?: string;
- /**
- * The association / privilege level of the user with the collection.
- *
- * Expected to be one of {@link CollectionParticipantRole}.
- *
- * - The role is not present (blank string) for the {@link owner}.
- * - The role is present, and one of "VIEWER" and "COLLABORATOR" for the
- * {@link sharees}.
- * - Remote uses a blank string to indicate absent values.
- */
role?: string;
}
-/**
- * Zod schema for {@link CollectionUser}.
- *
- * [Note: Enums in remote objects]
- *
- * In some cases remote returns a value which is part of a known set. The
- * underlying type might be an integer or a string.
- *
- * While Zod allows us to validate enum types during a parse, we refrain from
- * doing this as this would cause existing clients to break if remote were to in
- * the future add new enum cases.
- *
- * This is especially pertinent for objects which we might persist locally,
- * since the client code which persists the object might not know about a
- * particular enum case but a future client which reads the saved value might.
- *
- * So we keep the underlying data type (string or number) as it is instead of
- * converting / validating to an enum or discarding unknown values.
- *
- * As an example consider the {@link role} item in {@link RemoteCollectionUser}.
- * There is a known set of values ({@link CollectionParticipantRole}) this can
- * be, but in the Zod schema we keep the data type as a string.
- */
+// Enum-like remote fields (e.g. role) are deliberately kept as plain strings
+// or numbers instead of being validated against a closed enum. Validating
+// would break existing clients when remote adds new cases, and persisted
+// values must remain readable by future clients that understand them.
export const RemoteCollectionUser = z.looseObject({
id: z.number(),
email: z.string().nullish().transform(nullToUndefined),
@@ -286,93 +88,24 @@ export const RemoteCollectionUser = z.looseObject({
type RemoteCollectionUser = z.infer<typeof RemoteCollectionUser>;
-/**
- * A public link for a shared collection.
- *
- * This structure contains a (partial^) URL that can be used to access the
- * shared collection, along with other attributes of the link.
- *
- * ^ The URL is partial because it doesn't have the URL fragment, which is
- * client side only as it contains the decryption key
- */
export interface PublicURL {
- /**
- * A URL that can be used access the shared collection.
- *
- * This will be of the form "https://<public-albums-app>/<token>", e.g.,
- * "https://albums.ente.com/xxxxxx".
- *
- * In particular, this URL does not contain the URL fragment (the part after
- * the "#"). URL fragments are client side only, and not sent to remote.
- * They contain the decryption key.
- *
- * The client can use this field to form the fully usable URL, e.g.
- * "https://albums.ente.com/xxxxxx#yyy...yyy", and provide it to the user
- * for sharing.
- */
+ // The URL is of the form "https://albums.ente.com/<token>", without a
+ // fragment. The decryption key is client side only and never reaches
+ // remote; the client appends it as the fragment to form the shareable URL.
url: string;
- /**
- * The number of unique devices which can access the collection using the
- * public URL.
- *
- * Set to 0 to indicate no device limit.
- */
deviceLimit: number;
- /**
- * The epoch microseconds until which the link is valid.
- *
- * Set to 0 to indicate no expiry.
- */
+ // This is an epoch microseconds timestamp; 0 means no expiry.
validTill: number;
- /**
- * `true` if downloads are enabled from this link.
- *
- * When creating a new link this is `true` by default, and can optionally be
- * disabled in the public link settings.
- */
enableDownload: boolean;
enableJoin: boolean;
- /**
- * `true` if people can use the public link to upload new files to the
- * shared collection.
- */
enableCollect: boolean;
- /**
- * `true` if comments are enabled on this public link.
- */
enableComment: boolean;
- /**
- * `true` if the link is password protected.
- *
- * When this is `true`, {@link nonce}, {@link memLimit} and {@link opsLimit}
- * will also be set.
- */
passwordEnabled: boolean;
- /**
- * The nonce to use when hashing the password.
- *
- * Only present when {@link passwordEnabled} is `true`.
- */
nonce?: string;
- /**
- * The ops limit to use when hashing the password.
- *
- * Only present when {@link passwordEnabled} is `true`.
- */
opsLimit?: number;
- /**
- * The mem limit to use when hashing the password.
- *
- * Only present when {@link passwordEnabled} is `true`.
- */
memLimit?: number;
}
-/**
- * Zod schema for the {@link PublicURL} we use in our interactions with remote.
- *
- * We also use the same schema when persisting the collection locally.
- */
export const RemotePublicURL = z.looseObject({
url: z.string(),
deviceLimit: z.number(),
@@ -387,76 +120,21 @@ export const RemotePublicURL = z.looseObject({
opsLimit: z.number().nullish().transform(nullToUndefined),
});
-/**
- * Zod schema for {@link Collection}.
- *
- * [Note: Use looseObject when parsing JSON that will get persisted]
- *
- * While not always necessary, for a few cases (files and collections being the
- * most prominent and important) we try to retain any unknown fields in the JSON
- * we get from remote, so that future versions of the client with support for
- * fields unbeknownst to the current one can read and use them.
- *
- * In such cases, the nested objects should also (recursively) use the
- * looseObject schema. But not always - in some cases where the structures we
- * use are well established, e.g. {@link RemoteMagicMetadata} - we use the
- * default Zod behaviour of discarding unknown fields.
- *
- * > Note that even in the case of {@link RemoteMagicMetadata}, we still apply
- * > looseObject to the payload itself.
- * >
- * > See: [Note: Use looseObject for metadata Zod schemas]
- *
- * Unlike metadata, where we do strictly want to retain unknown or unacted on
- * fields, in the more general case we are okay with being a bit loose with
- * looseObject, and even intentionally dropping fields that we know we're not
- * going to use on the current client. Such looseness is okay because even if we
- * need to use them in the future, we can always refetch the objects again
- * (while in the case of metadata, we need to also push our changes to remote,
- * so it is functionally important for us to retain the source verbatim).
- */
+// This uses looseObject so that fields unknown to this client survive the
+// round trip through the local database and remain readable by future
+// versions of the client.
export const RemoteCollection = z.looseObject({
id: z.number(),
owner: RemoteCollectionUser,
encryptedKey: z.string(),
- /**
- * The nonce to use when decrypting the {@link encryptedKey} when the album
- * is owned by the user.
- *
- * Not set for shared albums (the decryption for uses the keypair instead).
- *
- * Remote might set this to blank to indicate absence.
- */
keyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
- /**
- * Expected to be present (along with {@link nameDecryptionNonce}), but it
- * is still optional since it might not be present if {@link name} is present.
- */
encryptedName: z.string().nullish().transform(nullToUndefined),
nameDecryptionNonce: z.string().nullish().transform(nullToUndefined),
- /**
- * Not used anymore, but still might be present for very old collections.
- *
- * Before public launch, collection names were stored unencrypted. For
- * backward compatibility, client should use {@link name} if present,
- * otherwise obtain it by decrypting it from {@link encryptedName} and
- * {@link nameDecryptionNonce}.
- */
name: z.string().nullish().transform(nullToUndefined),
- /**
- * Expected to be one of {@link CollectionType}
- */
type: z.string(),
sharees: z.array(RemoteCollectionUser).nullish().transform(nullishToEmpty),
publicURLs: z.array(RemotePublicURL).nullish().transform(nullishToEmpty),
updationTime: z.number(),
- /**
- * Tombstone marker.
- *
- * This is set to `true` in the collection fetch response to indicate
- * collections which have been deleted on remote and should thus be pruned
- * by the client locally.
- */
isDeleted: z.boolean().nullish().transform(nullToUndefined),
magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),
pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),
@@ -466,25 +144,12 @@ export const RemoteCollection = z.looseObject({
export type RemoteCollection = z.infer<typeof RemoteCollection>;
-/**
- * Decrypt a remote collection using the provided {@link collectionKey}.
- *
- * @param collection The remote collection to decrypt.
- *
- * @param collectionKey The base64 encoded key to use for decrypting the various
- * encrypted fields in {@link collection}.
- *
- * @returns A decrypted collection.
- */
export const decryptRemoteCollection = async (
collection: RemoteCollection,
collectionKey: string,
): Promise<Collection> => {
- // RemoteCollection is a looseObject, and we want to retain that semantic
- // for the parsed Collection. Mention all fields that we want to explicitly
- // drop or transform, passthrough the rest unchanged in the return value.
- //
- // See: [Note: Use looseObject when parsing JSON that will get persisted].
+ // Destructure every field that gets dropped or transformed; the spread
+ // keeps the remaining (possibly unknown) fields intact in the result.
const {
owner,
encryptedKey,
@@ -500,16 +165,15 @@ export const decryptRemoteCollection = async (
...rest
} = collection;
- // We've already used them to derive the `collectionKey`.
ignore([encryptedKey, keyDecryptionNonce]);
- // Mobile specific attribute not currently used by us.
+ // The attributes field is mobile specific and unused by the web clients.
ignore(attributes);
- // The deleted flag is used during collection fetch, but not used by us
- // beyond this point.
ignore(isDeleted);
const name =
- // `||` is used because remote sets name to blank to indicate absence.
+ // The `||` is deliberate: remote sets name to blank to indicate
+ // absence. Only very old collections, created before names were
+ // encrypted, have a plaintext name.
collection.name ||
new TextDecoder().decode(
await decryptBoxBytes(
@@ -561,17 +225,8 @@ export const decryptRemoteCollection = async (
};
};
-/**
- * A no-op function to pretend that we're using some values. This is handy when
- * we want to destructure some fields so that they don't get forwarded, but
- * otherwise don't need to use them.
- */
export const ignore = (xs: unknown) => typeof xs;
-/**
- * A convenience function to discard the unused name field from the collection
- * user objects that we receive from remote.
- */
const parseRemoteCollectionUser = ({
name,
...rest
@@ -580,177 +235,52 @@ const parseRemoteCollectionUser = ({
return rest;
};
-/**
- * Additional context stored as part of the collection's magic metadata to
- * augment the {@link type} associated with a {@link Collection}.
- */
export const CollectionSubType = {
- /**
- * The default / normal value. No special semantics.
- */
default: 0,
- /**
- * The user's default hidden collection, which contains the individually
- * hidden files.
- */
defaultHidden: 1,
- /**
- * A collection created for sharing selected files.
- */
quicklink: 2,
} as const;
export type CollectionSubType =
(typeof CollectionSubType)[keyof typeof CollectionSubType];
-/**
- * Ordering of the collection - Whether it is pinned or not.
- */
-export const CollectionOrder = {
- /**
- * The default / normal value. No special semantics, behaves "unpinned" and
- * will retain its natural sort position.
- */
- default: 0,
- /**
- * The collection is "pinned" by moving to the beginning of the sort order.
- *
- * Multiple collections can be pinned, in which case they'll be sorted
- * amongst themselves under the otherwise applicable sort order.
- *
- * -- [pinned collections] -- [other collections] --
- */
- pinned: 1,
-} as const;
+export const CollectionOrder = { default: 0, pinned: 1 } as const;
export type CollectionOrder =
(typeof CollectionOrder)[keyof typeof CollectionOrder];
-/**
- * Mutable private metadata associated with a {@link Collection}.
- *
- * - Unlike {@link CollectionPublicMagicMetadataData} this is only available to
- * the owner of the file.
- *
- * See: [Note: Private magic metadata is called magic metadata on remote]
- */
export interface CollectionPrivateMagicMetadataData {
- /**
- * The subtype of the collection type (if applicable).
- *
- * Expected to be one of {@link CollectionSubType}.
- */
subType?: number;
- /**
- * The (owner specific) visibility of the collection.
- *
- * The file's visibility is user specific attribute, and thus we keep it in
- * the private magic metadata. This allows the file's owner to share a file
- * and independently edit its visibility without revealing their visibility
- * preference to the other people with whom they have shared the file.
- *
- * Expected to be one of {@link ItemVisibility}.
- *
- * See: [Note: Enums in remote objects] for why we keep it as a number
- * instead of the expected enum.
- */
visibility?: number;
- /**
- * An overrride to the sort ordering used for the collection.
- *
- * Expected to be one of {@link CollectionOrder}.
- */
order?: number;
}
-/**
- * Zod schema for {@link CollectionPrivateMagicMetadataData}.
- *
- * See: [Note: Use looseObject for metadata Zod schemas]
- */
+// Metadata Zod schemas use looseObject because unknown fields must be
+// retained verbatim: metadata edits get pushed back to remote, and dropping
+// fields written by other clients would destroy them.
export const CollectionPrivateMagicMetadataData = z.looseObject({
subType: z.number().nullish().transform(nullToUndefined),
visibility: z.number().nullish().transform(nullToUndefined),
order: z.number().nullish().transform(nullToUndefined),
});
-/**
- * Mutable public metadata associated with a {@link Collection}.
- *
- * - Unlike {@link CollectionPrivateMagicMetadataData}, this is available to all
- * people with whom the collection has been shared.
- *
- * For more details, see [Note: Metadatum].
- */
export interface CollectionPublicMagicMetadataData {
- /**
- * The ordering of the files within the collection.
- *
- * The default is desc ("Newest first").
- *
- * If true, then the files within the collection are sorted in ascending
- * order of their time ("Oldest first").
- *
- * To reset to the default, set this to false.
- */
asc?: boolean;
- /**
- * The file ID of the file to use as the cover for the collection.
- *
- * To reset to the default cover, set this to 0.
- */
coverID?: number;
- /**
- * The layout type for the public collection display.
- *
- * Expected to be one of: "masonry", "grouped", "continuous", "trip".
- */
layout?: string;
}
-/**
- * Zod schema for {@link CollectionPublicMagicMetadataData}.
- */
export const CollectionPublicMagicMetadataData = z.looseObject({
asc: z.boolean().nullish().transform(nullToUndefined),
coverID: z.number().nullish().transform(nullToUndefined),
layout: z.string().nullish().transform(nullToUndefined),
});
-/**
- * Per-sharee mutable metadata associated with a shared {@link Collection}.
- *
- * [Note: Share specific metadata]
- *
- * When a collection is shared with a particular user, then remote creates a new
- * "share" entity defined by the (collectionID, fromUserID, toUserID) tuple
- * (this entity is not exposed to us directly, but it is helpful to know the
- * underlying implementation for this discussion).
- *
- * Remote also allows us to store mutable metadata (aka "magic metadata") with
- * each such share entity. This effectively acts as a private space where each
- * user with whom a collection has been shared can store and mutate metadata
- * about this shared collection without affecting either the owner or other
- * users with whom the collection has been shared.
- */
export interface CollectionShareeMagicMetadataData {
- /**
- * The (sharee specific) visibility of the collection.
- *
- * Expected to be one of {@link ItemVisibility}.
- */
visibility?: number;
- /**
- * An override to the sort ordering used for the collection by the sharee.
- *
- * Expected to be one of {@link CollectionOrder}.
- */
order?: number;
}
-/**
- * Zod schema for {@link CollectionShareeMagicMetadataData}.
- */
export const CollectionShareeMagicMetadataData = z.looseObject({
visibility: z.number().nullish().transform(nullToUndefined),
order: z.number().nullish().transform(nullToUndefined),
diff --git a/web/packages/media/file-metadata.ts b/web/packages/media/file-metadata.ts
index 2abdaa3e03..89c89f9690 100644
--- a/web/packages/media/file-metadata.ts
+++ b/web/packages/media/file-metadata.ts
@@ -4,175 +4,31 @@ import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
import { FileType } from "./file-type";
-/**
- * Information about the file that never changes post upload.
- *
- * ---
- *
- * [Note: Metadatum]
- *
- * There are three different sources of metadata relating to a file.
- *
- * 1. Metadata
- * 2. Magic metadata
- * 3. Public magic metadata
- *
- * The names of API entities are such for historical reasons, but we can think
- * of them as:
- *
- * 1. Metadata
- * 2. Private mutable metadata
- * 3. Public mutable metadata
- *
- * Metadata is the original metadata that we attached to the file when it was
- * uploaded. It is immutable, and it never changes.
- *
- * Later on, the user might make changes to the file's metadata. Since the
- * metadata is immutable, we need a place to keep these mutations.
- *
- * Some mutations are "private" to the user who owns the file. For example, the
- * user might archive the file. Such modifications get written to (2), Private
- * Mutable Metadata.
- *
- * Other mutations are "public" across all the users with whom the file is
- * shared. For example, if the user (owner) edits the name of the file, all
- * people with whom this file is shared can see the new edited name. Such
- * modifications get written to (3), Shared Mutable Metadata.
- *
- * When the client needs to show a file, it needs to "merge" in two or three of
- * these sources (nb: remote will only send the permissible ones):
- *
- * - When showing a shared file, (1) and (3) are merged, with changes from (3)
- * taking precedence, to obtain the full metadata pertinent to the file.
- *
- * - When showing a normal (un-shared) file, (1), (2) and (3) are merged, with
- * changes from (2) and (3) taking precedence, to obtain the full metadata.
- * (2) and (3) have no intersection of keys, so they can be merged in any
- * order.
- *
- * While these sources can be conceptually merged, it is important for the
- * client to also retain the original sources unchanged. This is because the
- * metadatas (any of the three) might have keys that the current client does not
- * yet understand, so when updating some key, say filename in (3), it should
- * only edit the key it knows about but retain the rest of the source JSON
- * unchanged.
- *
- * A similar concept applies to collections, which can (like files) have
- * metadata associated with them with varying axis of mutability and access.
- *
- * Collections also have another type of metadata.
- *
- * 4. Shared magic metadata
- *
- * which in our hypothetical naming scheme can be thought of as
- *
- * 4. Per-sharee private mutable metadata
- *
- * This is "magic metadata" associated with each share. Each user with whom the
- * collection has been shared with can use it store metadata (e.g. archive
- * status) that is private to them, and can only be edited by them. For more
- * details on this type of metadata, see [Note: Share specific metadata].
- */
export interface FileMetadata {
- /**
- * The "Ente" file type - image, video or live photo.
- *
- * Expected to be one of {@link FileType}.
- *
- * See: [Note: Enums in remote objects] for why we keep it as a number
- * instead of the expected enum.
- */
+ // One of FileType. Kept as a plain number so that parsing does not break
+ // when remote adds new cases.
fileType: number;
- /**
- * The name of the file (including its extension).
- *
- * Don't use this property directly, use {@link fileFileName} instead which
- * takes into account subsequent edits too.
- */
+ // Use fileFileName instead of reading this directly; it also accounts for
+ // subsequent edits.
title: string;
- /**
- * The time when this file was created (epoch microseconds).
- *
- * This is our best attempt at detecting the time when the photo or live
- * photo or video was taken.
- *
- * - We first try to obtain this from metadata, using Exif and other
- * metadata for images and FFmpeg-extracted metadata for video.
- *
- * - If no suitable metadata is available, then we try to deduce it from
- * file name (e.g. for screenshots without any embedded metadata).
- *
- * - If nothing can be found, then it is set to the current time at the time
- * of the upload.
- */
creationTime: number;
- /**
- * The last modification time of the file (epoch microseconds).
- */
modificationTime: number;
- /**
- * The latitude where the file was taken.
- */
latitude?: number;
- /**
- * The longitude where the file was taken.
- */
longitude?: number;
- /**
- * A hash of the file's contents.
- *
- * For images and videos this is the hash of the file's contents. For live
- * photos, this is the image hash joined with video hash using a colon (i.e.
- * `${imageHash}:{videoHash}`).
- *
- * Legacy compatibility:
- *
- * - The hash might not be present for files uploaded from ancient versions
- * of Ente (Newer clients will always include it in the metadata).
- *
- * - For live photos, older version of the web and desktop client used to
- * add two separate fields - {@link imageHash} and {@link videoHash} - to
- * the file's metadata instead of setting the {@link hash}. This behaviour
- * is deprecated, and if we now see a live photo without a {@link hash},
- * we should reconstruct the hash locally from the image and video hashes
- * by combining them as `${imageHash}:{videoHash}`.
- */
+ // For live photos this is the image hash and the video hash joined by a
+ // colon, i.e. `${imageHash}:${videoHash}`.
hash?: string;
- /**
- * The hash of the image component of a live photo.
- *
- * This is a legacy field, and should not be added by us anymore. It is
- * retained to allow us to reconstruct the hash for live photos uploaded by
- * older clients.
- */
+ // imageHash and videoHash are legacy fields. Old clients set them for live
+ // photos instead of hash; new clients must not add them.
imageHash?: string;
- /**
- * The hash of the video component of a live photo.
- *
- * This is a legacy field, and should not be added by us anymore. It is
- * retained to allow us to reconstruct the hash for live photos uploaded by
- * older clients.
- */
videoHash?: string;
- /**
- * The duration (in integral seconds) of the video.
- *
- * Only present for videos (`fileType == FileType.video`). For compatibility
- * with other clients, this must be a integer number of seconds, without any
- * sub-second fraction.
- */
+ // Integral seconds. Other clients expect no sub-second fraction.
duration?: number;
- /**
- * `true` if the uploading client was unable to generate a thumbnail for the
- * file when uploading it (e.g. unsupported format), and so instead a
- * placeholder thumbnail was used.
- */
hasStaticThumbnail?: boolean;
}
-/**
- * Zod schema for {@link FileMetadata}.
- */
+// looseObject, here and in the other metadata schemas, so that fields written
+// by newer clients are retained instead of being dropped on the next write.
export const FileMetadata = z.looseObject({
fileType: z.number(),
title: z.string(),
@@ -187,221 +43,48 @@ export const FileMetadata = z.looseObject({
hasStaticThumbnail: z.boolean().nullish().transform(nullToUndefined),
});
-/**
- * Mutable private metadata associated with an {@link EnteFile}.
- *
- * - Unlike {@link FileMetadata}, this can change after the file has been
- * uploaded.
- *
- * - Unlike {@link PublicMagicMetadata}, this is only available to the owner of
- * the file.
- *
- * [Note: Private magic metadata is called magic metadata on remote]
- *
- * For historical reasons, the unqualified phrase "magic metadata" in various
- * APIs refers to the (this) private metadata, even though the mutable public
- * metadata is the much more frequently used of the two. See: [Note: Metadatum].
- */
export interface FilePrivateMagicMetadataData {
- /**
- * The visibility of the file.
- *
- * The file's visibility is user specific attribute, and thus we keep it in
- * the private magic metadata. This allows the file's owner to share a file
- * and independently edit its visibility without revealing their visibility
- * preference to the other people with whom they have shared the file.
- *
- * Expected to be one of {@link ItemVisibility}.
- */
+ // One of ItemVisibility. Kept in the private metadata so that people with
+ // whom the file is shared never see the owner's visibility preference.
visibility?: number;
}
-/**
- * Zod schema for {@link FilePrivateMagicMetadataData}.
- *
- * See: [Note: Use looseObject for metadata Zod schemas]
- */
export const FilePrivateMagicMetadataData = z.looseObject({
visibility: z.number().nullish().transform(nullToUndefined),
});
-/**
- * The visibility of an Ente file or collection.
- */
-export const ItemVisibility = {
- /**
- * The normal state - The item is visible.
- */
- visible: 0,
- /**
- * The item has been archived.
- */
- archived: 1,
- /**
- * The item has been hidden.
- */
- hidden: 2,
-} as const;
-
-/**
- * The visibility of an Ente file or collection.
- *
- * This is the erasable type. See the {@link ItemVisibility} object for the
- * possible values and their symbolic constants.
- */
+export const ItemVisibility = { visible: 0, archived: 1, hidden: 2 } as const;
+
export type ItemVisibility =
(typeof ItemVisibility)[keyof typeof ItemVisibility];
-/**
- * Mutable public metadata associated with an {@link EnteFile}.
- *
- * - Unlike {@link FileMetadata}, this can change after the file has been
- * uploaded.
- *
- * - Unlike {@link FilePrivateMagicMetadataData}, this is available to all the
- * people with whom the file has been shared.
- *
- * For more details, see [Note: Metadatum].
- *
- * ---
- *
- * [Note: Optional magic metadata keys]
- *
- * Remote does not support nullish (`undefined` or `null`) values for the keys
- * in the magic metadata associated with a file. All of the keys themselves are
- * optional though.
- *
- * That is, all magic metadata properties are of the form:
- *
- * foo?: T
- *
- * And never like:
- *
- * foo: T | undefined
- */
export interface FilePublicMagicMetadataData {
- /**
- * A ISO 8601 date time string without a timezone, indicating the local time
- * where the photo (or video) was taken.
- *
- * e.g. "2022-01-26T13:08:20".
- *
- * See: [Note: Photos are always in local date/time].
- */
+ // An ISO 8601 date/time string without a timezone, in the local time of
+ // the place where the photo was taken. e.g. "2022-01-26T13:08:20".
dateTime?: string;
- /**
- * When available, a "±HH:mm" string indicating the UTC offset of the place
- * where the photo was taken.
- *
- * e.g. "+02:00".
- */
+ // UTC offset of the place where the photo was taken. e.g. "+02:00".
offsetTime?: string;
- /**
- * Modified value of the date time associated with an {@link EnteFile}.
- *
- * Epoch microseconds.
- *
- * This field stores edits to the {@link creationTime} {@link FileMetadata}
- * field.
- */
+ // Edits to the creationTime metadata field.
editedTime?: number;
- /**
- * Modified file name of the {@link EnteFile}.
- *
- * This field stores edits to the {@link title} {@link FileMetadata} field.
- */
+ // Edits to the title metadata field.
editedName?: string;
- /**
- * The width of the photo (or video) in pixels.
- *
- * While this should usually be present, it is not guaranteed to be.
- */
w?: number;
- /**
- * The height of the photo (or video) in pixels, if available.
- *
- * While this should usually be present, it is not guaranteed to be.
- */
h?: number;
- /**
- * An arbitrary caption / description string that the user has added to the
- * file.
- *
- * The length of this field is capped to some arbitrary maximum by client
- * side checks.
- */
caption?: string;
- /**
- * The name provided by the person who uploaded the file using an otherwise
- * anonymous public link upload.
- *
- * When sharing an album using a public link, the owner of the collection
- * can enable public uploads. When uploading files this way, the public
- * albums app asks the person doing the upload their name, and that gets
- * persisted here in the file's public magic metadata so that it can be
- * shown to the Ente users who are participants in the collection.
- *
- * (The owner of such files will be the owner of the collection)
- */
+ // The name given by an anonymous person who uploaded the file via a
+ // public link. Such files are owned by the collection owner.
uploaderName?: string;
- /** Camera make (manufacturer) extracted from metadata. */
cameraMake?: string;
- /** Camera model extracted from metadata. */
cameraModel?: string;
- /**
- * Edited latitude of the file
- *
- * If the user edits the location (latitude and longitude) of a file within
- * Ente, then the edits will be stored as the {@link lat} and {@link long}
- * properties in the file's public magic metadata.
- */
+ // lat and long are location edits made within Ente; they take precedence
+ // over the latitude and longitude in FileMetadata.
lat?: number;
- /**
- * Edited longitude of the file.
- *
- * See {@link long}.
- */
long?: number;
- /**
- * An arbitrary integer set to indicate that this file should be skipped for
- * the purpose of HLS generation.
- *
- * Current semantics:
- *
- * - if 1, skip this file
- * - otherwise attempt processing
- *
- * [Note: Marking files which do not need video processing]
- *
- * Some video files do not require generation of a HLS stream. The current
- * logic is H.264 files less than 10 MB, but this might change in future
- * clients.
- *
- * For such skipped files, there thus won't be a HLS playlist generated.
- * However, we still need a way to indicate to other clients that this file
- * has already been looked at.
- *
- * To that end, we add a flag to the public magic metadata for the file. To
- * allow future flexibility, this flag is an integer "streaming version".
- * Currently it is set to 1 by a client who recognizes that this file does
- * not need processing, and other clients can ignore this file if they find
- * sv == 1. In the future, there might be other values for sv (e.g. if the
- * skip logic changes).
- */
+ // Streaming version. A client that decides a video does not need an HLS
+ // stream sets this to 1, and other clients then skip processing it.
sv?: number;
}
-/**
- * Zod schema for the {@link PublicMagicMetadata} type.
- *
- * [Note: Use looseObject for metadata Zod schemas]
- *
- * It is important to (recursively) use the {@link looseObject} option when
- * defining Zod schemas for the various metadata types (the plaintext JSON
- * objects) because we want to retain all the fields we get from remote. There
- * might be other, newer, clients out there adding fields that the current
- * client might not we aware of, and we don't want to overwrite them.
- */
export const FilePublicMagicMetadataData = z.looseObject({
dateTime: z.string().nullish().transform(nullToUndefined),
offsetTime: z.string().nullish().transform(nullToUndefined),
@@ -422,19 +105,10 @@ export const FilePublicMagicMetadataData = z.looseObject({
sv: z.number().nullish().transform(nullToUndefined),
});
-/**
- * Return the hash of the file by reading it from its metadata.
- *
- * This is a convenience function that directly reads the information from the
- * metadata in the happy path, but also has branches to handle the legacy format
- * that older clients used to upload. For more details, see the note in the
- * documentation for {@link hash} in {@link FileMetadata}.
- */
export const metadataHash = (metadata: FileMetadata) => {
const hash = metadata.hash;
if (hash) return hash;
- // Handle past live photos upload from web client.
if (
metadata.fileType == FileType.livePhoto &&
metadata.imageHash &&
@@ -443,51 +117,20 @@ export const metadataHash = (metadata: FileMetadata) => {
return `${metadata.imageHash}:${metadata.videoHash}`;
}
- // Items uploaded by very old clients might not have a hash, so this is not
- // necessarily an error even if rare.
+ // Files uploaded by very old clients might not have a hash, so a missing
+ // hash is not an error.
return undefined;
};
-/**
- * Return `true` if the {@link ItemVisibility} of the given {@link file} is
- * archived.
- */
export const isArchivedFile = (file: EnteFile) =>
file.magicMetadata?.data.visibility == ItemVisibility.archived;
-/**
- * Return the file name of the file (including both the name and the extension).
- *
- * This function handles files with edited names. It will first look into the
- * public magic metadata of a file to see if the file has an edited name, and if
- * so, return that. Otherwise it will return the original name of the file
- * stored in its metadata.
- *
- * @returns The provided {@link EnteFile}'s filename, including the extension.
- * e.g. "flower.png".
- */
export const fileFileName = (file: EnteFile) =>
file.pubMagicMetadata?.data.editedName ?? file.metadata.title;
-/**
- * Return the file's creation timestamp (epoch microseconds).
- *
- * This function handles files with edited dates.
- *
- * While sometimes the epoch timestamp is the correct value to use, it is also
- * possible that {@link fileCreationPhotoDate} or
- * {@link fileCreationPhotoSortTime} might be more appropriate.
- */
export const fileCreationTime = (file: EnteFile) =>
file.pubMagicMetadata?.data.editedTime ?? file.metadata.creationTime;
-/**
- * Return the file's creation date as a Date in the hypothetical "timezone of
- * the photo".
- *
- * This function handles files with edited dates. For all the details and
- * nuance, see {@link createPhotoDate}.
- */
export const fileCreationPhotoDate = (file: EnteFile) =>
createPhotoDate(
file.pubMagicMetadata?.data.dateTime ??
@@ -495,20 +138,11 @@ export const fileCreationPhotoDate = (file: EnteFile) =>
file.metadata.creationTime,
);
-/**
- * Return a millisecond sort key for the file's creation date in the
- * hypothetical "timezone of the photo".
- *
- * This is a photo-local comparable value, not an absolute UTC timestamp.
- */
+// The result is a comparable photo-local value in milliseconds, not an
+// absolute UTC timestamp.
export const fileCreationPhotoSortTime = (file: EnteFile) =>
fileCreationPhotoDate(file).getTime();
-/**
- * Return the GPS coordinates (if any) present in the given {@link EnteFile}.
- *
- * This function handles files with edited locations.
- */
export const fileLocation = (file: EnteFile): Location | undefined => {
const { lat, long } = file.pubMagicMetadata?.data ?? {};
// Use (lat, long) only if both are present and nonzero.
@@ -524,9 +158,6 @@ export const fileLocation = (file: EnteFile): Location | undefined => {
return { latitude, longitude };
};
-/**
- * Return the camera make (manufacturer) for the file.
- */
export const fileCameraMake = (file: EnteFile): string | undefined => {
const rawMake = file.pubMagicMetadata?.data.cameraMake;
if (!rawMake) return undefined;
@@ -535,9 +166,6 @@ export const fileCameraMake = (file: EnteFile): string | undefined => {
return make;
};
-/**
- * Return the camera model for the file.
- */
export const fileCameraModel = (file: EnteFile): string | undefined => {
const rawModel = file.pubMagicMetadata?.data.cameraModel;
if (!rawModel) return undefined;
@@ -546,9 +174,6 @@ export const fileCameraModel = (file: EnteFile): string | undefined => {
return model;
};
-/**
- * Return a user-friendly string describing the camera used for the file.
- */
export const fileCameraLabel = (file: EnteFile): string | undefined => {
const make = fileCameraMake(file);
const model = fileCameraModel(file);
@@ -557,27 +182,6 @@ export const fileCameraLabel = (file: EnteFile): string | undefined => {
return model ?? make;
};
-/**
- * Return the duration of the video as a formatted "HH:mm:ss" string (when
- * present) for the given {@link EnteFile}.
- *
- * Only files with type `FileType.video` are expected to have a duration.
- *
- * @returns The duration of the video as a string of the form "HH:mm:ss". The
- * underlying duration present in the file's metadata is guaranteed to be
- * integral, so there will never be a subsecond component.
- *
- * - If the hour component is all zeroes, it will be omitted.
- *
- * - Leading zeros in the minutes component will be trimmed off if an hour
- * component is not present. If minutes is all zeros, then "0" will be used.
- *
- * - For example, an underlying duration of 595 seconds will result in a
- * formatted string of the form "9:55". While an underlying duration of 9
- * seconds will be returned as a string "0:09".
- *
- * - A zero duration will be treated as undefined.
- */
export const fileDurationString = (file: EnteFile): string | undefined => {
const d = file.metadata.duration;
if (!d) return undefined;
@@ -595,171 +199,45 @@ export const fileDurationString = (file: EnteFile): string | undefined => {
}
};
-/**
- * Metadata about a file extracted from various sources (like Exif) when
- * uploading it into Ente.
- *
- * Depending on the file type and the upload sequence, this data can come from
- * various places:
- *
- * - For images it comes from the Exif and other forms of metadata (XMP, IPTC)
- * embedded in the file.
- *
- * - For videos, similarly it is extracted from the metadata embedded in the
- * file using ffmpeg.
- *
- * - From various sidecar files (like metadata JSONs) that might be sitting next
- * to the original during an import.
- *
- * These bits then get distributed and saved in the various metadata fields
- * associated with an {@link EnteFile} (See: [Note: Metadatum]).
- *
- * The advantage of having them be attached to an {@link EnteFile} is that it
- * allows us to perform operations using these attributes without needing to
- * re-download the original image.
- *
- * The disadvantage is that it increases the network payload (anything attached
- * to an {@link EnteFile} comes back in the diff response), and thus latency and
- * local storage costs for all clients. Thus, we need to curate what gets
- * preserved within the {@link EnteFile}'s metadatum.
- */
export interface ParsedMetadata {
- /** The width of the image, in pixels. */
width?: number;
- /** The height of the image, in pixels. */
height?: number;
- /**
- * The date/time when this photo was taken.
- *
- * Logically this is a date in local timezone of the place where the photo
- * was taken. See: [Note: Photos are always in local date/time].
- */
creationDate?: ParsedMetadataDate | undefined;
- /** The GPS coordinates where the photo was taken. */
location?: Location;
- /**
- * A caption / description attached by the user to the photo.
- */
description?: string;
- /** Camera make (manufacturer) extracted from metadata (e.g. Apple, Canon). */
cameraMake?: string;
- /** Camera model extracted from metadata (e.g. iPhone 15 Pro). */
cameraModel?: string;
}
-/**
- * [Note: Photos are always in local date/time]
- *
- * Photos out in the wild frequently do not have associated timezone offsets for
- * the date/time embedded in their metadata. This is a artifact of an era where
- * cameras didn't know often even know their date/time correctly, let alone the
- * UTC offset of their local data/time.
- *
- * This is beginning to change with smartphone cameras, and is even reflected in
- * the standards. e.g. Exif metadata now has auxiliary "OffsetTime*" tags for
- * indicating the UTC offset of the local date/time in the existing Exif tags
- * (See: [Note: Exif dates]).
- *
- * So a photos app needs to deal with a mixture of photos whose dates may or may
- * not have UTC offsets. This is fact #1.
- *
- * Users expect to see the time they took the photo, not the time in the place
- * they are currently. People expect a New Year's Eve photo from a vacation to
- * show up as midnight, not as (e.g.) 19:30 IST. This is fact #2.
- *
- * Combine these two facts, and if you ponder a bit, you'll find that there is
- * only one way for a photos app to show / sort / label the date – by using the
- * local date/time without the attached UTC offset, **even if it is present**.
- *
- * The UTC offset is still useful though, and we don't want to lose that
- * information. The number of photos with a UTC offset will only increase. And
- * whenever it is present, it provides additional context for the user.
- *
- * So we keep both the local date/time string (an ISO 8601 string guaranteed to
- * be without an associated UTC offset), and an (optional) UTC offset string.
- *
- * It is important to NOT think of the local date/time string as an instant of
- * time that can be converted to a UTC timestamp. It cannot be converted to a
- * UTC timestamp because while it itself might have the optional associated UTC
- * offset, its siblings photos might not. The only way to retain their
- * comparability is to treat them all the "time zone where the photo was taken".
- *
- * All this is good, but we still need to retain the existing `creationTime` UTC
- * epoch timestamp because in some cases when importing photos from other
- * providers, that's all we get. We could try and convert that to a date/time
- * string too, but since we anyways need to handle existing code that deals with
- * epoch timestamps, we retain them as they were provided.
- */
+// Photos in the wild frequently have no UTC offset attached to their embedded
+// date/time, and users expect to see the time of the place where the photo was
+// taken (a New Year's Eve photo should show midnight regardless of the
+// viewer's timezone). So dates are kept as local date/time strings and must
+// not be treated as UTC instants, even when an offset is available; the offset
+// is retained only as extra context.
export interface ParsedMetadataDate {
- /**
- * A local date/time.
- *
- * This is a partial ISO 8601 date/time string guaranteed not to have a
- * timezone offset. e.g. "2023-08-23T18:03:00.000".
- */
+ // A partial ISO 8601 date/time string guaranteed not to have a timezone
+ // offset. e.g. "2023-08-23T18:03:00.000".
dateTime: string;
- /**
- * An optional offset from UTC.
- *
- * This is an optional UTC offset string of the form "±HH:mm" or "Z",
- * specifying the timezone offset for {@link dateTime} when available.
- */
+ // A UTC offset of the form "±HH:mm" or "Z", when available.
offset: string | undefined;
- /**
- * UTC epoch microseconds derived from {@link dateTime} and
- * {@link offset}.
- *
- * When the {@link offset} is present, this will accurately reflect a
- * UTC timestamp. When the {@link offset} is not present it convert to a
- * UTC timestamp by assuming that the given {@link dateTime} is in the local
- * time where this code is running. This is a good assumption but not always
- * correct (e.g. vacation photos).
- */
+ // Epoch microseconds derived from dateTime and offset. When offset is
+ // absent, dateTime is assumed to be in the timezone where this code runs,
+ // which is not always correct (e.g. vacation photos).
timestamp: number;
}
-/**
- * Parse a partial or full ISO 8601 string into a {@link ParsedMetadataDate}.
- *
- * @param s A partial or full ISO 8601 string. That is, it is a string of the
- * form "2023-08-23T18:03:00.000+05:30" or "2023-08-23T12:33:00.000Z" with all
- * components except the year potentially missing.
- *
- * @return A {@link ParsedMetadataDate}, or `undefined` if {@link s} cannot be
- * parsed.
- *
- * ---
- * Some examples:
- *
- * - "2023" => ("2023-01-01T00:00:00.000", undefined)
- * - "2023-08" => ("2023-08-01T00:00:00.000", undefined)
- * - "2023-08-23" => ("2023-08-23T00:00:00.000", undefined)
- * - "2023-08-23T18:03:00" => ("2023-08-23T18:03:00.000", undefined)
- * - "2023-08-23T18:03:00+05:30" => ("2023-08-23T18:03:00.000', "+05:30")
- * - "2023-08-23T18:03:00.000+05:30" => ("2023-08-23T18:03:00.000", "+05:30")
- * - "2023-08-23T12:33:00.000Z" => ("2023-08-23T12:33:00.000", "Z")
- */
export const parseMetadataDate = (
s: string,
): ParsedMetadataDate | undefined => {
- // Construct the timestamp using the original string itself. If s is
- // parseable as a date, then this'll be give us the correct UTC timestamp.
- // If the UTC offset is not present, then this will be in the local
- // (current) time.
+ // Milliseconds to epoch microseconds. Without an offset in s, Date parses
+ // it in the current timezone.
const timestamp = new Date(s).getTime() * 1000;
- if (isNaN(timestamp)) {
- // s in not a well formed ISO 8601 date time string.
- return undefined;
- }
-
- // Now we try to massage s into two parts - the local date/time string, and
- // an UTC offset string.
+ if (isNaN(timestamp)) return undefined;
let offset: string | undefined;
let sWithoutOffset: string;
- // Check to see if there is a time-zone descriptor of the form "Z" or
- // "±05:30" or "±0530" at the end of s.
const m = /Z|[+-]\d\d:?\d\d$/.exec(s);
if (m?.index) {
sWithoutOffset = s.substring(0, m.index);
@@ -768,39 +246,18 @@ export const parseMetadataDate = (
sWithoutOffset = s;
}
- // Convert sWithoutOffset - a potentially partial ISO 8601 string - to a
- // canonical ISO 8601 string.
- //
- // In its full generality, this is non-trivial. The approach we take is:
- //
- // 1. Rely on the browser to be able to partial ISO 8601 string. This relies
- // on non-standard behaviour but works in practice seemingly.
- //
- // 2. Get an ISO 8601 representation of it. This is standard.
- //
- // A thing to watch out for is that browsers treat date only and date time
- // strings differently when the offset is not present (as would be for us).
- //
- // > When the time zone offset is absent, date-only forms are interpreted as
- // > a UTC time and date-time forms are interpreted as local time.
- // >
- // > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format
- //
- // For our purpose, we want to always interpret them as UTC time. This way,
- // when we later gets back its string representation for step 2, we will get
- // back the same numerical value, and can just chop off the "Z".
- //
- // So if the length of the string is less than or equal to yyyy-mm-dd (10),
- // then we use it verbatim, otherwise we append a "Z".
-
+ // Browsers parse partial ISO 8601 strings even though that is not
+ // standard. When the offset is absent, they parse date-only forms as UTC
+ // but date-time forms as local time; see
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format
+ // Appending "Z" to strings longer than "yyyy-mm-dd" (10 characters) forces
+ // UTC for both forms, so toISOString below returns the same value back.
const date = new Date(
sWithoutOffset + (sWithoutOffset.length <= 10 ? "" : "Z"),
);
- // The string returned by `toISOString` is guaranteed to be UTC and denoted
- // by the suffix "Z". If we chop that off, we get back a canonical
- // representation we wish for: A otherwise well-formed ISO 9601 string but
- // any time zone descriptor.
+ // toISOString is always UTC with a trailing "Z"; dropping the "Z" gives
+ // the canonical offset-less form.
const dateTime = dropLast(date.toISOString());
return { dateTime, offset, timestamp };
@@ -808,42 +265,16 @@ export const parseMetadataDate = (
const dropLast = (s: string) => (s ? s.substring(0, s.length - 1) : s);
-/**
- * Return a date that can be used on the represent a photo on the UI, by
- * constructing it from a {@link ParsedMetadataDate}, or its {@link dateTime}
- * component, or a UTC epoch timestamp.
- *
- * These dates are all hypothetically in the timezone of the place where the
- * photo was taken. Different photos might've been taken in different timezones,
- * which is why it is hypothetical, so concretely these are all mapped to the
- * current timezone.
- *
- * The difference is subtle, but we should not think of these as absolute points
- * on the UTC timeline. They are instead better thought of as dates without an
- * associated timezone. For the purpose of mapping them all to a comparable
- * dimension them we all contingently use the current timezone - this makes it
- * easy to use JavaScript Date constructor which assumes that any date/time
- * string without an associated timezone is in the current timezone.
- *
- * Whenever we're surfacing them in the UI, or using them for grouping (say by
- * day), we should use their current timezone representation, not the UTC one.
- *
- * See also: [Note: Photos are always in local date/time].
- */
export const createPhotoDate = (
dateLike: ParsedMetadataDate | string | number,
) => {
switch (typeof dateLike) {
case "object":
- // A ISO 8601 string without a timezone. The Date constructor will
- // assume the timezone to be the current timezone.
return new Date(dateLike.dateTime);
case "string":
- // This is expected to be a string with the same meaning as
- // `ParsedMetadataDate.dateTime`.
return new Date(dateLike);
case "number":
- // A UTC epoch microseconds value.
+ // Epoch microseconds to milliseconds.
return new Date(dateLike / 1000);
}
};
diff --git a/web/packages/media/file-type.ts b/web/packages/media/file-type.ts
index c0deee74bb..e55618b62c 100644
--- a/web/packages/media/file-type.ts
+++ b/web/packages/media/file-type.ts
@@ -1,49 +1,15 @@
-/**
- * The type of an {@link EnteFile}.
- *
- * This is an object containing symbolic constant. There is also an eraseable
- * TypeScript type type with the same name, {@link FileType}.
- */
-export const FileType = {
- /**
- * An image (e.g. JPEG).
- */
- image: 0,
- /**
- * A video (e.g. MP4).
- */
- video: 1,
- /**
- * A live photo, aka motion photo.
- *
- * This is a combination of an image and a (short) video capturing the
- * before and after when the image was taken. We preserve it as a zip
- * containing both the parts.
- */
- livePhoto: 2,
-} as const;
+export const FileType = { image: 0, video: 1, livePhoto: 2 } as const;
-/**
- * The type of an {@link EnteFile}.
- *
- * This is an eraseable TypeScript type. There is also a {@link FileType} object
- * with the same name that contains the corresponding symbolic constants.
- */
export type FileType = (typeof FileType)[keyof typeof FileType];
export interface FileTypeInfo {
fileType: FileType;
- /**
- * A lowercased, standardized extension for files of the current type.
- *
- * For live photos, this is set to the extension of the image component of
- * the live photo.
- */
extension: string;
mimeType?: string;
}
-// list of format that were missed by type-detection for some files.
+// These are formats that automatic file type detection misses for some files
+// found in the wild.
export const KnownFileTypeInfos: FileTypeInfo[] = [
{ fileType: FileType.image, extension: "jpeg", mimeType: "image/jpeg" },
{ fileType: FileType.image, extension: "jpg", mimeType: "image/jpeg" },
diff --git a/web/packages/media/file.ts b/web/packages/media/file.ts
index 04f2e004c7..cac2db49e1 100644
--- a/web/packages/media/file.ts
+++ b/web/packages/media/file.ts
@@ -16,207 +16,35 @@ import {
type MagicMetadata,
} from "./magic-metadata";
-/**
- * A File.
- *
- * An EnteFile represents a file in Ente. It does not contain the actual data.
- *
- * It is named with an "Ente" prefix to disambiguate it from the web's native
- * {@link File} type.
- *
- * All files have an id (numeric) that is unique across all the files stored by
- * an Ente instance. Each file is also always associated with a collection, and
- * has an owner (both of these linkages are stored as the corresponding numeric
- * IDs within the EnteFile structure).
- *
- * > For shared files, the owner of the file is not necessarily the owner of all
- * > the collections to which the file belongs.
- *
- * While the file ID is unique, we'd can still have multiple entries for each
- * file ID in our local state, one for each {@link Collection} to which the file
- * belongs. That is, the uniqueness is across the (fileID, collectionID) pairs.
- * See [Note: Collection file].
- *
- * [Note: File lifecycle]
- *
- * 1. **Normal**: A file starts off by belonging to at least one collection. It
- * can then be added to additional collections, each of which will be an
- * EnteFile with a distinct (fileID, collectionID) pair.
- *
- * 2. **Trash**: If the user deletes the file, then the file moves to trash.
- * Such files will have {@link isDeleted} `true` in their
- * {@link RemoteEnteFile} entries when we perform a collection diff to let
- * the client know that the corresponding file is no longer part of the
- * collection.
- *
- * Such files will now be returned as part of the trash diff, with both
- * {@link isDeleted} and {@link isRestored} set to `false` for their trash
- * entry.
- *
- * 3. **Restore**: If the the user were to restore the file before permanent
- * deletion, then it effectively works as moving a normal file to an normal
- * collection. In particular, if we were to restore the file back to one of
- * the collections it was part of pre-trash, and then fetch the collection
- * diff for that collection, we would get back the same file object, except
- * with {@link isDeleted} will now be `false`.
- *
- * The trash entry for restored files will have {@link isRestored} set to
- * `true` to notify clients that an item that was previously in trash is no
- * longer there because it has been restored.
- *
- * 4. **Permanent deletion**: If the file remains in trash for 30 days, or if
- * the user explictly permanently deletes it from the trash, or if the user
- * explicitly clears the trash, then it will get permanently deleted.
- *
- * The trash entry for such permanently deleted files will have
- * {@link isDeleted} set to `true` to notify clients that an item that was
- * previously in trash is no longer there because it has been permanently
- * deleted.
- *
- * When a file is permanently deleted, remote will scrub off data from its
- * fields. See: [Note: Optionality of remote file fields].
- */
export interface EnteFile {
- /**
- * The file's globally unique ID.
- *
- * The file's ID is a integer assigned by remote as the identifier for an
- * {@link EnteFile} when it is created. It is globally unique across all
- * files stored by an Ente instance, and is not scoped to the current user.
- */
id: number;
- /**
- * The ID of the collection with which this file as associated.
- *
- * The same file (ID) may be associated with multiple collectionID, each of
- * which will come and stay as distinct {@link EnteFile} instances - all of
- * which will have the same {@link id} but distinct {@link collectionID}.
- *
- * So the ({@link id}, {@link collectionID}) pair is a primary key, not the
- * {@link id} on its own. See: [Note: Collection file].
- */
+ // The same file id can appear in multiple collections, as a distinct
+ // EnteFile instance per collection. The (id, collectionID) pair is the
+ // primary key, not id on its own.
collectionID: number;
- /**
- * The ID of the Ente user who owns the file.
- *
- * Files uploaded by non users on public links belong to the owner of the
- * collection who created the public link (See {@link uploaderName} in
- * {@link FilePublicMagicMetadataData}).
- */
ownerID: number;
- /**
- * The file's key.
- *
- * This is the base64 representation of the decrypted encryption key
- * associated with this file. When we get the file from remote (as a
- * {@link RemoteEnteFile}), the file key itself would have been encrypted by
- * the key of the {@link Collection} to which this file belongs.
- *
- * This key is used to encrypt both the file's contents, and any associated
- * data (e.g., metadatum, thumbnail) for the file.
- */
key: string;
- /**
- * Information pertaining to the encrypted S3 object that has the file's
- * contents.
- */
file: FileObjectAttributes;
- /**
- * Information pertaining to the encrypted S3 object that has the contents
- * of the file's thumbnail.
- */
thumbnail: FileObjectAttributes;
- /**
- * Static, remote visible, information associated with a file.
- *
- * This is information about storage used by the file and its thumbnail.
- * Unlike {@link metadata} which is E2EE, the {@link FileInfo} is remote
- * visible for bookkeeping purposes.
- *
- * Files uploaded by very old versions of Ente might not have this field.
- */
info?: FileInfo;
- /**
- * The last time the file was updated (epoch microseconds).
- *
- * (e.g. magic metadata updates).
- */
updationTime: number;
- /**
- * Public static metadata associated with a file.
- *
- * This is the immutable metadata that gets associated with a file when it
- * is uploaded, and there after cannot be changed.
- *
- * It is visible to all users with whom the file gets shared.
- *
- * > {@link pubMagicMetadata} contains fields that override fields present
- * > in the metadata. Clients overlay those atop the metadata fields, and
- * > thus they can be used to implement edits.
- *
- * See: [Note: Metadatum].
- */
metadata: FileMetadata;
- /**
- * Private mutable metadata associated with the file that is only visible to
- * the owner of the file.
- *
- * See: [Note: Metadatum]
- */
+ // Private to the owner; never visible to sharees.
magicMetadata?: MagicMetadata<FilePrivateMagicMetadataData>;
- /**
- * Public mutable metadata associated with the file that is visible to all
- * users with whom the file has been shared.
- *
- * While in almost all cases, files will have associated public magic
- * metadata since newer clients have something or the other they need to add
- * to it, its presence is not guaranteed.
- *
- * See: [Note: Metadatum]
- */
+ // Visible to everyone with whom the file is shared.
pubMagicMetadata?: MagicMetadata<FilePublicMagicMetadataData>;
}
-/**
- * Attributes about an object related to an {@link EnteFile}.
- *
- * - The file's contents,
- *
- * - The file's thumbnail's contents.
- */
export interface FileObjectAttributes {
- /**
- * The decryption header that was used when encrypting the objects's
- * contents (with the file's key) before uploading them to S3 remote.
- */
decryptionHeader: string;
}
export const RemoteFileObjectAttributes = z.looseObject({
- /**
- * The decryption header (base64 string) used when encrypting the object.
- *
- * For permanently deleted files, this will still be present, but remote may
- * scrub it to a blank string or a placeholder.
- */
decryptionHeader: z.string(),
});
-/**
- * Static information associated with a file.
- */
export interface FileInfo {
- /**
- * The size of the file (in bytes).
- *
- * This will not be present for files with zero length.
- */
fileSize?: number;
- /**
- * The size of the thumbnail associated with the file (in bytes).
- *
- * This will not be present for files that don't have thumbnails (an old Locker issue)
- */
thumbSize?: number;
}
@@ -226,93 +54,26 @@ export const RemoteFileInfo = z.looseObject({
});
const RemoteFileMetadata = z.object({
- /**
- * The metadata JSON object associated with the file, encrypted using the
- * file's key.
- *
- * Base64 encoded.
- *
- * There is one case when this will be not be present - for permanently
- * deleted files when we get them as part of a trash diff (see the longer
- * note about this below):
- *
- * [Note: Optionality of remote file fields]
- *
- * When a file is permanently deleted, remote will scrub off data from its
- * fields (either by nulling them outright, or inserting placeholders,
- * depending on the remote schema).
- *
- * So a {@link RemoteEnteFile} object present in the trash item of a
- * permanently deleted file in the trash diff response (i.e. a trash item
- * with {@link isDeleted} is set to `true`) may not have the fields which we
- * normally would expect to always be there for files.
- *
- * This is not a problem in code flow since the client will not even attempt
- * to decrypt or use such file entries, so the absence of these fields has
- * no impact. However, it does impact JSON validation, which might
- * preemptively (and unnecessarily) fail for such {@link RemoteEnteFile}s.
- *
- * Luckily, this is simple to handle since most of the data in a
- * {@link RemoteEnteFile} is already optional. The only tweak we require is
- * handling missing {@link encryptedData} of the {@link RemoteEnteFile}'s
- * {@link metadata} field in such cases. We could mark it as a optional too,
- * but since we anyways shouldn't be using this field, so for convenience of
- * the upstream types, we transform such missing values to a blank string.
- */
+ // Remote scrubs the fields of permanently deleted files in trash diff
+ // responses, so this can be missing there. Such entries are never
+ // decrypted, so transform missing values to a blank string instead of
+ // failing the parse.
encryptedData: z.string().nullish().transform(nullishToBlank),
- /**
- * The base64 encoded decryption header that was used during encryption of
- * {@link encryptedData}.
- *
- * For permanently deleted files, this will still be present, but remote may
- * scrub it to a blank string or a placeholder.
- */
decryptionHeader: z.string(),
});
export type RemoteFileMetadata = z.infer<typeof RemoteFileMetadata>;
-/**
- * Zod schema for a {@link EnteFile} as represented in our interactions with
- * remote.
- *
- * The contents of the fields are encrypted by the file's key (which itself is
- * encrypted by the key of the collection that contains the file). EnteFile is
- * the decrypted local representation.
- *
- * See: [Note: Use looseObject when parsing JSON that will get persisted]
- */
export const RemoteEnteFile = z.looseObject({
id: z.number(),
collectionID: z.number(),
ownerID: z.number(),
- /**
- * The file's key, encrypted using the key of the collection that contains
- * the file.
- *
- * Base64 encoded.
- */
encryptedKey: z.string(),
- /**
- * The nonce to use when decrypting {@link encryptedKey}.
- *
- * Base64 encoded.
- */
keyDecryptionNonce: z.string(),
file: RemoteFileObjectAttributes,
thumbnail: RemoteFileObjectAttributes,
info: RemoteFileInfo.nullish().transform(nullToUndefined),
updationTime: z.number(),
- /**
- * Removal marker in diff responses.
- *
- * This is set to `true` in the collection diff response to indicate files
- * that are no longer part of the collection.
- *
- * - They may have been removed from the collection.
- *
- * - They have been deleted (either moved to trash, or permanently deleted).
- */
isDeleted: z.boolean().nullish().transform(nullToUndefined),
metadata: RemoteFileMetadata,
magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),
@@ -321,49 +82,17 @@ export const RemoteEnteFile = z.looseObject({
export type RemoteEnteFile = z.infer<typeof RemoteEnteFile>;
-/**
- * Zod schema for a response for various "/diff" APIs that return changes since
- * a provided timestamp.
- *
- * - "/collections/v2/diff"
- * - "/public-collection/diff"
- * - "/cast/diff"
- */
export const FileDiffResponse = z.object({
- /**
- * A batch of changes (upserts or deletions).
- *
- * See also: [Note: Diff response will have at most one entry for an id].
- */
diff: RemoteEnteFile.array(),
- /**
- * If `true`, then there are more changes that can be fetched by doing
- * another of the same API call, this time passing it the latest from
- * amongst the timestamps of entries in {@link diff}.
- */
hasMore: z.boolean(),
});
-/**
- * Decrypt a remote file using the provided {@link collectionKey}.
- *
- * @param file The remote file to decrypt.
- *
- * @param collectionKey The base64 encoded key of the collection to which this
- * file belongs. It is needed to decrypt the file's key (which in turn is needed
- * to decrypt the file's contents and other encrypted fields).
- *
- * @returns A decrypted {@link EnteFile}.
- */
export const decryptRemoteFile = async (
remoteFile: RemoteEnteFile,
collectionKey: string,
): Promise<EnteFile> => {
- // RemoteEnteFile is a looseObject, and we want to retain that semantic for
- // the parsed EnteFile. Mention all fields that we want to explicitly drop
- // or transform, passthrough the rest unchanged in the return value.
- //
- // See: [Note: Use looseObject when parsing JSON that will get persisted].
+ // Destructure and spread so that unknown fields from the loose remote
+ // schema pass through into the persisted EnteFile.
const {
id,
encryptedKey,
@@ -375,9 +104,8 @@ export const decryptRemoteFile = async (
...rest
} = remoteFile;
- // This flag is relevant only in the diff response, where it indicates that
- // the file should be removed from the corresponding collection. We would've
- // already acted on that information, so drop it from our local state.
+ // isDeleted only matters in the diff response, and it has already been
+ // acted on before we get here.
ignore(isDeleted);
const key = await decryptBox(
@@ -413,28 +141,19 @@ export const decryptRemoteFile = async (
return { ...rest, id, key, metadata, magicMetadata, pubMagicMetadata };
};
-/**
- * Apply some transforms to gracefully handle metadata from old clients.
- *
- * @param metadataJSON The decrypted and parsed metadata JSON. Since TypeScript
- * does not have a native JSON type, this is typed as an `unknown`.
- *
- * @returns A JSON object with any transformations applied, if needed.
- */
export const transformDecryptedMetadataJSON = (
fileID: number,
metadataJSON: unknown,
) => {
- // The file ID threshold is an arbitrary cutoff so that this graceful
- // handling does not mask new issues.
+ // The threshold is an arbitrary cutoff so that these patches for old files
+ // do not mask new issues.
if (fileID > 100000000) return metadataJSON;
if (typeof metadataJSON != "object") return metadataJSON;
if (!metadataJSON) return metadataJSON;
- // In very rare cases (have found only one so far, a very old file in
- // Vishnu's account, uploaded by an initial dev version of Ente) the photo
- // has no modification time. Gracefully handle such cases.
+ // A few very old files, uploaded by initial dev builds of Ente, have no
+ // modification time.
if (
!("modificationTime" in metadataJSON) ||
!metadataJSON.modificationTime
@@ -446,9 +165,8 @@ export const transformDecryptedMetadataJSON = (
}
}
- // In very rare cases (again, some files shared with Vishnu's account,
- // uploaded by dev builds) the photo might not have a file type. Gracefully
- // handle these too.
+ // Similarly, a few very old files uploaded by dev builds have no file
+ // type.
if (
!("fileType" in metadataJSON) ||
typeof metadataJSON.fileType != "number"
@@ -460,14 +178,5 @@ export const transformDecryptedMetadataJSON = (
return metadataJSON;
};
-/**
- * A short identifier for a file in log messages.
- *
- * e.g. "file flower.png (827233681)"
- *
- * @returns a string to use as an identifier when logging information about the
- * given {@link file}. The returned string contains the file name (for ease of
- * debugging) and the file ID (for exactness).
- */
export const fileLogID = (file: EnteFile) =>
`file ${fileFileName(file)} (${file.id})`;
diff --git a/web/packages/media/formats.ts b/web/packages/media/formats.ts
index c2a98ca635..29ae0ae898 100644
--- a/web/packages/media/formats.ts
+++ b/web/packages/media/formats.ts
@@ -1,6 +1,6 @@
-/**
- * List used by {@link needsJPEGConversion}.
- */
+// Image extensions that the browser is unlikely to be able to render, but
+// which our desktop app should be able to convert to JPEG. Both conditions
+// must hold for an extension to be in this list.
const needsJPEGConversionExtensions = [
"arw",
"cr2",
@@ -15,20 +15,9 @@ const needsJPEGConversionExtensions = [
"tiff",
];
-/**
- * Return `true` if {@link extension} is from amongst a known set of image file
- * extensions that (a) we know that the browser is unlikely to support, and (b)
- * which we should be able to convert to JPEG when running in our desktop app.
- *
- * These two are independent constraints, but we only return true if we satisfy
- * both of them instead of having two disjoint lists.
- */
export const needsJPEGConversion = (extension: string) =>
needsJPEGConversionExtensions.includes(extension.toLowerCase());
-/**
- * Return `true` if {@link extension} in for an HEIC-like file.
- */
export const isHEICExtension = (extension: string) => {
const ext = extension.toLowerCase();
return ext == "heic" || ext == "heif";
diff --git a/web/packages/media/heic-convert.ts b/web/packages/media/heic-convert.ts
index 2eb561a6cb..eb34046141 100644
--- a/web/packages/media/heic-convert.ts
+++ b/web/packages/media/heic-convert.ts
@@ -1,23 +1,12 @@
import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import type { HEICConvertWorker } from "./heic-convert.worker";
-/**
- * Convert a HEIC image to a JPEG.
- *
- * Behind the scenes, it uses a web worker to do the conversion using a Wasm
- * HEIC conversion package.
- *
- * @param heicBlob The HEIC blob to convert.
- *
- * @returns The JPEG blob.
- */
+// The conversion runs in a web worker, using a Wasm HEIC conversion package.
export const heicToJPEG = async (heicBlob: Blob) =>
worker().then((w) => w.heicToJPEG(heicBlob));
-/** Cached instance of the {@link ComlinkWorker} that wraps our web worker. */
let _comlinkWorker: ComlinkWorker<typeof HEICConvertWorker> | undefined;
-/** Lazily created, cached, instance of our web worker. */
const worker = async () => (_comlinkWorker ??= createComlinkWorker()).remote;
const createComlinkWorker = () =>
diff --git a/web/packages/media/heic-convert.worker.ts b/web/packages/media/heic-convert.worker.ts
index 6ab4283fe7..1cc558a951 100644
--- a/web/packages/media/heic-convert.worker.ts
+++ b/web/packages/media/heic-convert.worker.ts
@@ -4,11 +4,6 @@ import { wait } from "ente-utils/promise";
import HeicConvert from "heic-convert";
export class HEICConvertWorker {
- /**
- * Convert a HEIC file to a JPEG file.
- *
- * Both the input and output are blobs.
- */
async heicToJPEG(heicBlob: Blob) {
const output = await heicToJPEG(heicBlob);
// I'm told this library used to have big memory spikes, and adding
@@ -24,11 +19,8 @@ logUnhandledErrorsAndRejectionsInWorker();
const heicToJPEG = async (heicBlob: Blob): Promise<Blob> => {
const buffer = new Uint8Array(await heicBlob.arrayBuffer());
- // [Note: Revisit some Node.js types errors post 22 upgrade]
- //
- // Going beyond "typescript" "5.6.3" we start seeing a type error here. This
- // is possibly fixed in the newer Node.js types, but we're at 20 currently.
- //
+ // TypeScript versions after 5.6.3 report a type error here, possibly fixed
+ // by newer Node.js types.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const result = await HeicConvert({ buffer, format: "JPEG" });
diff --git a/web/packages/media/image.ts b/web/packages/media/image.ts
index 2912af02a4..7be022ce36 100644
--- a/web/packages/media/image.ts
+++ b/web/packages/media/image.ts
@@ -1,19 +1,3 @@
-/**
- * Compute optimal dimensions for a resized version of an image while
- * maintaining aspect ratio of the source image.
- *
- * @param width The width of the source image.
- *
- * @param height The height of the source image.
- *
- * @param maxDimension The maximum width of height of the resized image.
- *
- * This function returns a new size limiting it to maximum width and height
- * (both specified by {@link maxDimension}), while maintaining aspect ratio of
- * the source {@link width} and {@link height}.
- *
- * It returns `{0, 0}` for invalid inputs.
- */
export const scaledImageDimensions = (
width: number,
height: number,
diff --git a/web/packages/media/live-photo.ts b/web/packages/media/live-photo.ts
index 35baac80d6..81e7c9fc6b 100644
--- a/web/packages/media/live-photo.ts
+++ b/web/packages/media/live-photo.ts
@@ -36,10 +36,6 @@ const potentialVideoExtensions = [
"mp",
];
-/**
- * Use the file extension of the given {@link fileName} to deduce if is is
- * potentially the image or the video part of a Live Photo.
- */
export const potentialFileTypeFromExtension = (
fileName: string,
): FileType | undefined => {
@@ -51,9 +47,6 @@ export const potentialFileTypeFromExtension = (
else return undefined;
};
-/**
- * An in-memory representation of a live photo.
- */
interface LivePhoto {
imageFileName: string;
imageData: Uint8Array<ArrayBuffer>;
@@ -61,21 +54,6 @@ interface LivePhoto {
videoData: Uint8Array<ArrayBuffer>;
}
-/**
- * Convert a binary serialized representation of a live photo to an in-memory
- * {@link LivePhoto}.
- *
- * A live photo is a zip file containing two files - an image and a video. This
- * functions reads that zip file (blob), and return separate bytes (and
- * filenames) for the image and video parts.
- *
- * @param fileName The name of the overall live photo. Both the image and video
- * parts of the decompressed live photo use this as their name, combined with
- * their original extensions.
- *
- * @param zipBlob A blob contained the zipped data (i.e. the binary serialized
- * live photo).
- */
export const decodeLivePhoto = async (
fileName: string,
zipBlob: Blob,
@@ -111,7 +89,6 @@ export const decodeLivePhoto = async (
return { imageFileName, imageData, videoFileName, videoData };
};
-/** Variant of {@link LivePhoto}, but one that allows files and data. */
interface EncodeLivePhotoInput {
imageFileName: string;
imageFileOrData: File | Uint8Array;
@@ -119,16 +96,6 @@ interface EncodeLivePhotoInput {
videoFileOrData: File | Uint8Array;
}
-/**
- * Return a binary serialized representation of a live photo.
- *
- * This function takes the (in-memory) image and video data from the
- * {@link livePhoto} object, writes them to a zip file (using the respective
- * filenames), and returns the {@link Uint8Array} that represent the bytes of
- * this zip file.
- *
- * @param livePhoto The in-mem photo to serialized.
- */
export const encodeLivePhoto = async ({
imageFileName,
imageFileOrData,
diff --git a/web/packages/media/magic-metadata.ts b/web/packages/media/magic-metadata.ts
index 74bc85219d..00d0d952c8 100644
--- a/web/packages/media/magic-metadata.ts
+++ b/web/packages/media/magic-metadata.ts
@@ -2,13 +2,6 @@ import { decryptMetadataJSON, encryptMetadataJSON } from "ente-base/crypto";
import { nullishToZero } from "ente-utils/transform";
import { z } from "zod";
-/**
- * Zod schema of the mutable metadatum objects that we send to or receive from
- * remote. It contains an encrypted metadata JSON object with some bookkeeping
- * information attached.
- *
- * See {@link RemoteMagicMetadata} for the corresponding type.
- */
export const RemoteMagicMetadata = z.object({
version: z.number(),
count: z.number().nullish().transform(nullishToZero),
@@ -16,134 +9,21 @@ export const RemoteMagicMetadata = z.object({
header: z.string(),
});
-/**
- * The type of the mutable metadata fields, as represented by remote.
- *
- * See: [Note: Metadatum]
- *
- * This is the magic metadata that we send to and receive from remote. It
- * contains an encrypted JSON object, and a version + count of entries to ensure
- * that clients do not overwrite already applied updates with stale objects.
- *
- * When decrypt these into specific local {@link MagicMetadata} instantiations
- * before using and storing them on the client.
- */
export interface RemoteMagicMetadata {
- /**
- * Monotonically increasing iteration of this metadata object.
- *
- * The version starts at 1. Remote increments this version number each time
- * a client updates the corresponding magic metadata field.
- */
version: number;
- /**
- * The number of keys with non-nullish (i.e. not null and not undefined)
- * values in the encrypted JSON object that the encrypted metadata blob
- * contains.
- *
- * [Note: Magic metadata data cannot have nullish values]
- *
- * Clients are expected to retain the magic metadata verbatim so that they
- * don't accidentally overwrite fields that they might not understand. See:
- * [Note: Use looseObject for metadata Zod schemas]
- *
- * Remote enforces this by requiring that during edits and updates, this
- * number should be greater than or equal to the previous version.
- *
- * Locally we enforce this in the {@link createMagicMetadata} function
- * (which is used for both creation and updates), which trims off any
- * entries in the data object whose value is `null` or `undefined` before
- * arriving at the final object to use.
- *
- * This has the side effect that metadata entries cannot be deleted by
- * setting their value to nullish. However usually the specific field
- * semantics allow a reset to default behaviour by setting the value of the
- * entry to the corresponding empty primitive (e.g. 0).
- */
+ // This is the number of non-nullish entries in the JSON object that
+ // `data` encrypts.
count: number;
- /**
- * The encrypted data.
- *
- * This are the base64 encoded bytes of the encrypted magic metadata JSON
- * object.
- *
- * The encryption will happen using the "key" associated with the object
- * whose magic metadata field this is. For example, if this is the
- * {@link pubMagicMetadata} of an {@link EnteFile}, then the file's key will
- * be used for encryption and decryption.
- */
data: string;
- /**
- * The base64 encoded decryption header that will be needed for the client
- * for decrypting {@link data}.
- */
header: string;
}
-/**
- * The decrypted form of {@link RemoteMagicMetadata} used and locally persisted
- * by the client.
- *
- * The bookkeeping fields ({@link version} and {@link count}) are copied over
- * from the remote object ({@link RemoteMagicMetadata}), while the encrypted
- * contents ({@link data} and {@link header} of {@link RemoteMagicMetadata}) are
- * decrypted into a JSON object that is stored as {@link data}.
- *
- * Since different types of magic metadata fields are expected to contain
- * different JSON objects as {@link data}, the type is generic, with the generic
- * parameter `T` standing for the type of the JSON object.
- *
- * > Since TypeScript does not currently have a native JSON type, this T doesn't
- * > have other constraints enforced by the type system, but it is meant to be a
- * > JSON object.
- *
- * The word "magic metadata" by itself ambiguous. It refers to both the specific
- * "magicMetadata" fields present in, say, the file and collection objects, and
- * also to the shape of the structure this field shares with other semantically
- * similar fields (e.g. public magic metadata). This type uses it in the second
- * sense - to describe the shape of any of the magic metadata like fields used
- * in various types. See: [Note: Metadatum].
- */
export interface MagicMetadata<T = unknown> {
version: number;
count: number;
- /**
- * The "metadata" itself.
- *
- * This is expected to be a JSON object, whose exact schema depends on the
- * magic metadata field in the parent object.
- */
data: T;
}
-/**
- * Encrypt the provided magic metadata into a form that can be used in
- * communication with remote, trimming the JSON object and updating the count.
- *
- * @param magicMetadata The decrypted {@link MagicMetadata} that is being used
- * by the client.
- *
- * Any entries in {@link magicMetadata}'s {@link data} that are `null` or
- * `undefined` are discarded before obtaining the final object that will be
- * encrypted (and whose count will be used).
- *
- * So in particular, it is okay for the count in the {@link magicMetadata} to be
- * out of sync with the count in the `data` JSON object because this function
- * will recompute the count using the trimmed JSON object.
- *
- * @param key The base64 encoded key to use for encrypting the {@link data}
- * contents of {@link magicMetadata}.
- *
- * The specific key used depends on the object whose magic metadata field this
- * is meant for. For example, if this were the {@link pubMagicMetadata}
- * associated with an {@link EnteFile}, then this would be the file's key.
- *
- * @returns a {@link RemoteMagicMetadata} object that contains the encrypted
- * contents of the {@link data} present in the provided {@link magicMetadata}.
- * The {@link version} is copied over from the provided {@link magicMetadata},
- * while the {@link count} is obtained from the number of entries in the trimmed
- * JSON object that was encrypted.
- */
export const encryptMagicMetadata = async (
magicMetadata: MagicMetadata,
key: string,
@@ -159,37 +39,11 @@ export const encryptMagicMetadata = async (
return { version, count, data, header };
};
-/**
- * A function to wrap an arbitrary JSON object in the {@link MagicMetadata}
- * envelope used for the various magic metadata fields.
- *
- * A trimmed JSON object is obtained from the provided JSON object by removing
- * any entries whose values is nullish (`null` or `undefined`).
- *
- * Then,
- *
- * - The `version` is set to provided value (or 1).
- * - The `count` is set to the number of entries in the trimmed JSON object.
- * - The `data` is set to the trimmed JSON object.
- *
- * {@link encryptMagicMetadata} internally uses this function to obtain an
- * trimmed `data` and its corresponding `count`. This function is also exported
- * for use in places where we just have a JSON object and would like to a new
- * {@link MagicMetadata} object to house it from scratch.
- *
- * @param data A JSON object. Since TypeScript does not have a JSON type, this
- * uses the `unknown` type.
- *
- * @param version An optional version number to use. This is useful when
- * updating existing magic metadata, where the version in the update that we
- * send to remote must match the existing version.
- *
- * If not provided, the 1 is used as the version.
- */
export const createMagicMetadata = (data: unknown, version?: number) => {
- // Discard any entries that with nullish (`null` or `undefined`) values.
- //
- // See: [Note: Magic metadata data cannot have nullish values]
+ // Remote rejects metadata updates whose entry count decreases, so nullish
+ // entries are trimmed instead of being sent. A consequence is that an
+ // entry cannot be deleted by setting it to null; reset it to its empty
+ // primitive (e.g. 0) instead.
const jsonObject = Object.fromEntries(
Object.entries(data ?? {}).filter(
([, v]) => v !== null && v !== undefined,
@@ -201,13 +55,6 @@ export const createMagicMetadata = (data: unknown, version?: number) => {
return { version: version ?? 1, count, data: jsonObject };
};
-/**
- * Decrypt the magic metadata received from remote into an object suitable for
- * use and persistence by the client.
- *
- * This is meant as the inverse of {@link encryptMagicMetadata}, see that
- * function's documentation for details.
- */
export const decryptMagicMetadata = async (
remoteMagicMetadata: RemoteMagicMetadata,
key: string,