Skip to content

armgit / ente

Public Imported from GitHub
0

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

remove(accounts):replaced-by-accounts-rs

Aswin Asok5f34d17ed75b
diff --git a/web/package-lock.json b/web/package-lock.json
index bc0949c842..c6f14663db 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -2611,18 +2611,6 @@
"node": ">= 10"
}
},
- "node_modules/@noble/hashes": {
- "version": "1.8.0",
- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
- "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
- "license": "MIT",
- "engines": {
- "node": "^14.21.3 || >=16"
- },
- "funding": {
- "url": "https://paulmillr.com/funding/"
- }
- },
"node_modules/@oxc-project/types": {
"version": "0.137.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.137.0.tgz",
@@ -4069,15 +4057,6 @@
"node": ">=6.0.0"
}
},
- "node_modules/bip39": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/bip39/-/bip39-3.1.0.tgz",
- "integrity": "sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A==",
- "license": "ISC",
- "dependencies": {
- "@noble/hashes": "^1.2.0"
- }
- },
"node_modules/brace-expansion": {
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
@@ -4739,10 +4718,6 @@
"resolved": "apps/ensu",
"link": true
},
- "node_modules/ente-accounts": {
- "resolved": "packages/accounts",
- "link": true
- },
"node_modules/ente-accounts-rs": {
"resolved": "packages/accounts-rs",
"link": true
@@ -5362,15 +5337,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/fast-srp-hap": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/fast-srp-hap/-/fast-srp-hap-2.0.4.tgz",
- "integrity": "sha512-lHRYYaaIbMrhZtsdGTwPN82UbqD9Bv8QfOlKs+Dz6YRnByZifOh93EYmf2iEWFtkOEIqR2IK8cFD0UN5wLIWBQ==",
- "license": "MIT",
- "engines": {
- "node": ">=10.17.0"
- }
- },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -11187,26 +11153,6 @@
"integrity": "sha512-Bq0B+ixT/DMyG8kgX2xWcI5jUvCwqrMxSFam7m0lAf78nf04hv6lNCsyLYdyYTrCVMqNDY/206K7eExYCeSyUQ==",
"license": "MIT"
},
- "packages/accounts": {
- "name": "ente-accounts",
- "version": "0.0.0",
- "dependencies": {
- "bip39": "3.1.0",
- "ente-base": "*",
- "fast-srp-hap": "2.0.4",
- "react": "19.2.7",
- "react-dom": "19.2.7",
- "react-otp-input": "3.1.1",
- "uuid": "13.0.2",
- "zxcvbn": "4.4.2"
- },
- "devDependencies": {
- "@types/react": "19.2.17",
- "@types/react-dom": "19.2.3",
- "@types/zxcvbn": "4.4.5",
- "ente-build-config": "*"
- }
- },
"packages/accounts-rs": {
"name": "ente-accounts-rs",
"version": "0.0.0",
diff --git a/web/packages/accounts-rs/README.md b/web/packages/accounts-rs/README.md
index 26fe76415d..d8c68101e8 100644
--- a/web/packages/accounts-rs/README.md
+++ b/web/packages/accounts-rs/README.md
@@ -1,3 +1,3 @@
## ente-accounts-rs
-Shared signup and login flows backed by Rust cryptography through `ente-wasm`. Locker, Space, Legacy, and Contacts use this package; the other account flows use the parallel `ente-accounts` implementation.
+Shared web account flows backed by Rust cryptography through `ente-wasm`.
diff --git a/web/packages/accounts/components/CodeBlock.tsx b/web/packages/accounts/components/CodeBlock.tsx
deleted file mode 100644
index b4b08b34d4..0000000000
--- a/web/packages/accounts/components/CodeBlock.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import ContentCopyIcon from "@mui/icons-material/ContentCopy";
-import DoneIcon from "@mui/icons-material/Done";
-import { Box, IconButton, Tooltip, Typography } from "@mui/material";
-import { CenteredRow } from "ente-base/components/containers";
-import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
-import { useClipboardCopy } from "ente-base/components/utils/hooks";
-import { t } from "i18next";
-import React from "react";
-
-interface CodeBlockProps {
- code: string | undefined;
-}
-
-export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {
- if (!code) {
- return (
- <CenteredRow sx={{ minHeight: "80px" }}>
- <ActivityIndicator />
- </CenteredRow>
- );
- }
-
- return (
- <Box
- sx={{
- position: "relative",
- bgcolor: "accent.dark",
- borderRadius: 1,
- }}
- >
- <Typography
- sx={{
- padding: "16px 44px 16px 16px",
- wordBreak: "break-word",
- color: "accent.contrastText",
- lineHeight: 1.5,
- }}
- >
- {code}
- </Typography>
- <Box sx={{ position: "absolute", top: 0, right: 0, mt: 1 }}>
- <CopyButton code={code} />
- </Box>
- </Box>
- );
-};
-
-interface CopyButtonProps {
- code: string;
-}
-
-export const CopyButton: React.FC<CopyButtonProps> = ({ code }) => {
- const [copied, handleClick] = useClipboardCopy(code);
-
- const Icon = copied ? DoneIcon : ContentCopyIcon;
-
- return (
- <Tooltip arrow open={copied} title={t("copied")}>
- <IconButton onClick={handleClick}>
- <Icon sx={{ color: "accent.contrastText" }} fontSize="small" />
- </IconButton>
- </Tooltip>
- );
-};
diff --git a/web/packages/accounts/components/LoginComponents.tsx b/web/packages/accounts/components/LoginComponents.tsx
deleted file mode 100644
index e432ceac63..0000000000
--- a/web/packages/accounts/components/LoginComponents.tsx
+++ /dev/null
@@ -1,196 +0,0 @@
-import { CircularProgress, Stack, Typography, styled } from "@mui/material";
-import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
-import {
- checkPasskeyVerificationStatus,
- passkeySessionExpiredErrorMessage,
- saveCredentialsAndNavigateTo,
-} from "ente-accounts/services/passkey";
-import { LinkButton } from "ente-base/components/LinkButton";
-import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import { genericErrorDialogAttributes } from "ente-base/components/utils/dialog";
-import log from "ente-base/log";
-import { customAPIHost } from "ente-base/origins";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import React, { useEffect, useState } from "react";
-import {
- AccountsPageContents,
- AccountsPageFooter,
-} from "./layouts/centered-paper";
-
-interface HeaderCaptionProps {
- caption?: string;
-}
-
-export const PasswordHeader: React.FC<HeaderCaptionProps> = (props) => (
- <AccountsPageTitleWithCaption {...props}>
- {t("password")}
- </AccountsPageTitleWithCaption>
-);
-
-const PasskeyHeader: React.FC<HeaderCaptionProps> = (props) => (
- <AccountsPageTitleWithCaption {...props}>
- {t("passkey")}
- </AccountsPageTitleWithCaption>
-);
-
-export const AccountsPageTitleWithCaption: React.FC<
- React.PropsWithChildren<HeaderCaptionProps>
-> = ({ caption, children }) => {
- return (
- <Header_>
- <Typography variant="h3">{children}</Typography>
- <Typography sx={{ color: "text.faint" }}>
- {caption ?? ""}
- </Typography>
- </Header_>
- );
-};
-
-const Header_ = styled("div")`
- margin-block-end: 24px;
- display: flex;
- flex-direction: column;
- gap: 8px;
-`;
-
-export const AccountsPageFooterWithHost: React.FC<React.PropsWithChildren> = ({
- children,
-}) => {
- const [host, setHost] = useState<string | undefined>();
-
- useEffect(() => void customAPIHost().then(setHost), []);
-
- return (
- <Stack sx={{ gap: 3 }}>
- <AccountsPageFooter>{children}</AccountsPageFooter>
- {host && (
- <Typography
- variant="small"
- sx={{ mx: "4px", color: "text.faint" }}
- >
- {host}
- </Typography>
- )}
- </Stack>
- );
-};
-
-interface VerifyingPasskeyProps {
- passkeySessionID: string;
- email: string | undefined;
- onRetry: () => void;
- logout: () => void;
- showMiniDialog: (attrs: MiniDialogAttributes) => void;
-}
-
-export const VerifyingPasskey: React.FC<VerifyingPasskeyProps> = ({
- passkeySessionID,
- email,
- onRetry,
- logout,
- showMiniDialog,
-}) => {
- type VerificationStatus = "waiting" | "checking" | "pending";
- const [verificationStatus, setVerificationStatus] =
- useState<VerificationStatus>("waiting");
-
- const router = useRouter();
-
- const handleRetry = () => {
- setVerificationStatus("waiting");
- onRetry();
- };
-
- const handleCheckStatus = async () => {
- setVerificationStatus("checking");
- try {
- const response =
- await checkPasskeyVerificationStatus(passkeySessionID);
- if (!response) setVerificationStatus("pending");
- else void router.push(await saveCredentialsAndNavigateTo(response));
- } catch (e) {
- log.error("Passkey verification status check failed", e);
- showMiniDialog(
- e instanceof Error &&
- e.message == passkeySessionExpiredErrorMessage
- ? sessionExpiredDialogAttributes(logout)
- : genericErrorDialogAttributes(),
- );
- setVerificationStatus("waiting");
- }
- };
-
- const handleRecover = () => {
- void router.push("/passkeys/recover");
- };
-
- return (
- <AccountsPageContents>
- <PasskeyHeader caption={email} />
-
- <VerifyingPasskeyMiddle>
- <VerifyingPasskeyStatus>
- {verificationStatus == "checking" ? (
- <Typography>
- <CircularProgress color="accent" size="1.5em" />
- </Typography>
- ) : (
- <Typography sx={{ color: "text.muted" }}>
- {verificationStatus == "waiting"
- ? t("waiting_for_verification")
- : t("verification_still_pending")}
- </Typography>
- )}
- </VerifyingPasskeyStatus>
-
- <ButtonStack>
- <FocusVisibleButton
- onClick={handleRetry}
- fullWidth
- color="secondary"
- >
- {t("try_again")}
- </FocusVisibleButton>
-
- <FocusVisibleButton
- onClick={handleCheckStatus}
- fullWidth
- color="accent"
- >
- {t("check_status")}
- </FocusVisibleButton>
- </ButtonStack>
- </VerifyingPasskeyMiddle>
-
- <AccountsPageFooterWithHost>
- <LinkButton onClick={handleRecover}>
- {t("recover_account")}
- </LinkButton>
- <LinkButton onClick={logout}>{t("change_email")}</LinkButton>
- </AccountsPageFooterWithHost>
- </AccountsPageContents>
- );
-};
-
-const VerifyingPasskeyMiddle = styled("div")`
- display: flex;
- flex-direction: column;
-
- padding-block: 1rem;
- gap: 4rem;
-`;
-
-const VerifyingPasskeyStatus = styled("div")`
- text-align: center;
- /* Size of the CircularProgress (+ some margin) so that there is no layout
- shift when it is shown */
- min-height: 2em;
-`;
-
-const ButtonStack = styled("div")`
- display: flex;
- flex-direction: column;
- gap: 1rem;
-`;
diff --git a/web/packages/accounts/components/LoginContents.tsx b/web/packages/accounts/components/LoginContents.tsx
deleted file mode 100644
index 49ae97692e..0000000000
--- a/web/packages/accounts/components/LoginContents.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-import { Input, Stack, TextField, Typography } from "@mui/material";
-import { AccountsPageFooter } from "ente-accounts/components/layouts/centered-paper";
-import {
- replaceSavedLocalUser,
- saveSRPAttributes,
-} from "ente-accounts/services/accounts-db";
-import { getSRPAttributes } from "ente-accounts/services/srp";
-import { sendOTT } from "ente-accounts/services/user";
-import { appName } from "ente-base/app";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { HTTPError } from "ente-base/http";
-import { JOIN_ALBUM_CONTEXT_KEY } from "ente-base/join-album";
-import log from "ente-base/log";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import React, { useCallback, useEffect, useState } from "react";
-import { z } from "zod";
-import { AccountsPageTitleWithCaption } from "./LoginComponents";
-
-interface LoginContentsProps {
- host: string | undefined;
- onSignUp: () => void;
-}
-
-export const LoginContents: React.FC<LoginContentsProps> = ({
- onSignUp,
- host,
-}) => {
- const router = useRouter();
- const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);
- const isEnsu = appName === "ensu";
-
- useEffect(() => {
- const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
- setIsJoinAlbumContext(!!joinAlbumContext);
- }, []);
-
- const loginUser = useCallback(
- async (email: string, setFieldError: (message: string) => void) => {
- const srpAttributes = await getSRPAttributes(email);
- if (!srpAttributes || srpAttributes.isEmailMFAEnabled) {
- try {
- await sendOTT(email, "login");
- } catch (e) {
- if (e instanceof HTTPError && e.res.status === 404) {
- let errorCode: string | undefined;
- try {
- errorCode = z
- .object({ code: z.string() })
- .parse(await e.res.json()).code;
- } catch (parseErr) {
- log.warn(
- "Ignoring error when parsing error payload",
- parseErr,
- );
- }
- if (errorCode === "USER_NOT_REGISTERED") {
- setFieldError(t("email_not_registered"));
- return;
- }
- if (errorCode === "USER_SIGNUP_INCOMPLETE") {
- setFieldError(
- t("account_setup_incomplete_create_account"),
- );
- return;
- }
- }
- throw e;
- }
- replaceSavedLocalUser({ email });
- void router.push("/verify");
- } else {
- replaceSavedLocalUser({ email });
- saveSRPAttributes(srpAttributes);
- void router.push("/credentials");
- }
- },
- [router],
- );
-
- const formik = useFormik({
- initialValues: { email: "" },
- onSubmit: async ({ email }, { setFieldError }) => {
- const setEmailFieldError = (message: string) =>
- setFieldError("email", message);
-
- if (!email) {
- setEmailFieldError(t("required"));
- return;
- }
-
- if (!z.email().safeParse(email).success) {
- setEmailFieldError(t("invalid_email_error"));
- return;
- }
-
- try {
- await loginUser(email, setEmailFieldError);
- } catch (e) {
- log.error("Failed to login", e);
- setEmailFieldError(t("generic_error"));
- }
- },
- });
-
- return (
- <>
- <AccountsPageTitleWithCaption>
- {isJoinAlbumContext ? t("login_to_join_album") : t("login")}
- </AccountsPageTitleWithCaption>
- <form onSubmit={formik.handleSubmit}>
- <TextField
- name="email"
- value={formik.values.email}
- onChange={formik.handleChange}
- type="email"
- autoComplete="username"
- label={t("enter_email")}
- fullWidth
- autoFocus
- margin="normal"
- disabled={formik.isSubmitting}
- error={!!formik.errors.email}
- helperText={formik.errors.email ?? " "}
- />
- <Input sx={{ display: "none" }} type="password" value="" />
- <LoadingButton
- fullWidth
- type="submit"
- loading={formik.isSubmitting}
- color="accent"
- >
- {t("login")}
- </LoadingButton>
- </form>
- <AccountsPageFooter>
- <Stack sx={{ gap: 3, textAlign: "center" }}>
- {isEnsu ? (
- <LinkButton onClick={() => void router.push("/chat")}>
- {t("cancel")}
- </LinkButton>
- ) : (
- <LinkButton onClick={onSignUp}>
- {t("no_account")}
- </LinkButton>
- )}
- <Typography
- variant="mini"
- sx={{ color: "text.faint", minHeight: "16px" }}
- >
- {host ?? ""}
- </Typography>
- </Stack>
- </AccountsPageFooter>
- </>
- );
-};
diff --git a/web/packages/accounts/components/NewPasswordForm.tsx b/web/packages/accounts/components/NewPasswordForm.tsx
deleted file mode 100644
index 561fbcbb5d..0000000000
--- a/web/packages/accounts/components/NewPasswordForm.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import { Input, TextField, Typography } from "@mui/material";
-import { isWeakPassword } from "ente-accounts/utils/password";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
-import log from "ente-base/log";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import { useCallback, useState } from "react";
-import { Trans } from "react-i18next";
-import { PasswordStrengthHint } from "./PasswordStrength";
-
-export interface NewPasswordFormProps {
- userEmail: string;
- submitButtonTitle: string;
- onSubmit: (
- password: string,
- setPasswordsFieldError: (message: string) => void,
- ) => Promise<void>;
-}
-
-export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({
- userEmail,
- submitButtonTitle,
- onSubmit,
-}) => {
- const [showPassword, setShowPassword] = useState(false);
- const [showConfirmPassword, setShowConfirmPassword] = useState(false);
-
- const handleToggleShowHidePassword = useCallback(
- () => setShowPassword((show) => !show),
- [],
- );
- const handleToggleShowHideConfirmPassword = useCallback(
- () => setShowConfirmPassword((show) => !show),
- [],
- );
-
- const formik = useFormik({
- initialValues: { password: "", confirmPassword: "" },
- onSubmit: async ({ password, confirmPassword }, { setFieldError }) => {
- const setPasswordsFieldError = (message: string) =>
- setFieldError("confirmPassword", message);
-
- if (!confirmPassword) {
- setPasswordsFieldError(t("required"));
- return;
- }
-
- if (password != confirmPassword) {
- setPasswordsFieldError(t("password_mismatch_error"));
- return;
- }
-
- try {
- await onSubmit(password, setPasswordsFieldError);
- } catch (e) {
- log.error("Could not set password", e);
- setPasswordsFieldError(t("generic_error"));
- }
- },
- });
-
- return (
- <form onSubmit={formik.handleSubmit}>
- <Typography variant="small" sx={{ mb: 2, color: "text.muted" }}>
- {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"
- type="email"
- autoComplete="username"
- value={userEmail}
- />
- <TextField
- name="password"
- autoComplete="new-password"
- type={showPassword ? "text" : "password"}
- label={t("password")}
- value={formik.values.password}
- onChange={formik.handleChange}
- disabled={formik.isSubmitting}
- fullWidth
- autoFocus
- slotProps={{
- input: {
- endAdornment: (
- <ShowHidePasswordInputAdornment
- showPassword={showPassword}
- onToggle={handleToggleShowHidePassword}
- />
- ),
- },
- }}
- />
- <TextField
- name="confirmPassword"
- autoComplete="new-password"
- type={showConfirmPassword ? "text" : "password"}
- label={t("confirm_password")}
- value={formik.values.confirmPassword}
- onChange={formik.handleChange}
- error={!!formik.errors.confirmPassword}
- helperText={formik.errors.confirmPassword ?? " "}
- disabled={formik.isSubmitting}
- fullWidth
- slotProps={{
- input: {
- endAdornment: (
- <ShowHidePasswordInputAdornment
- showPassword={showConfirmPassword}
- onToggle={handleToggleShowHideConfirmPassword}
- />
- ),
- },
- }}
- />
- <PasswordStrengthHint password={formik.values.password} />
-
- <Typography
- variant="small"
- sx={{ color: "text.muted", my: 2, mb: 4 }}
- >
- <Trans i18nKey={"pick_password_caution"} />
- </Typography>
-
- <LoadingButton
- color="accent"
- type="submit"
- loading={formik.isSubmitting}
- disabled={isWeakPassword(formik.values.password)}
- fullWidth
- >
- {submitButtonTitle}
- </LoadingButton>
- <Typography
- variant="small"
- sx={(theme) => ({
- textAlign: "center",
- mt: 1,
- color: "text.muted",
- minHeight: theme.typography.small.lineHeight,
- })}
- >
- {formik.isSubmitting ? t("key_generation_in_progress") : ""}
- </Typography>
- </form>
- );
-};
diff --git a/web/packages/accounts/components/PasswordStrength.tsx b/web/packages/accounts/components/PasswordStrength.tsx
deleted file mode 100644
index 5b106a9a05..0000000000
--- a/web/packages/accounts/components/PasswordStrength.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Typography, useTheme } from "@mui/material";
-import { t } from "i18next";
-import React, { useMemo } from "react";
-import { estimatePasswordStrength } from "../utils/password";
-
-interface PasswordStrengthHintProps {
- password: string;
-}
-
-export const PasswordStrengthHint: React.FC<PasswordStrengthHintProps> = ({
- password,
-}) => {
- const passwordStrength = useMemo(
- () => estimatePasswordStrength(password),
- [password],
- );
-
- const theme = useTheme();
- const color =
- passwordStrength == "weak"
- ? theme.vars.palette.critical.main
- : passwordStrength == "moderate"
- ? theme.vars.palette.warning.main
- : theme.vars.palette.accent.main;
-
- return (
- <Typography
- variant="small"
- sx={{
- mt: "8px",
- mx: "2px",
- alignSelf: "flex-start",
- whiteSpace: "pre",
- color: "var(--et-color)",
- }}
- style={{ "--et-color": color } as React.CSSProperties}
- >
- {password
- ? t("password_strength", { context: passwordStrength })
- : /* empty space + white-space: pre to prevent layout shift. */
- " "}
- </Typography>
- );
-};
diff --git a/web/packages/accounts/components/RecoveryKey.tsx b/web/packages/accounts/components/RecoveryKey.tsx
deleted file mode 100644
index 2cc0f9a5ae..0000000000
--- a/web/packages/accounts/components/RecoveryKey.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import {
- Dialog,
- DialogActions,
- DialogContent,
- DialogTitle,
- Stack,
- Typography,
-} from "@mui/material";
-import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
-import { SpacedRow } from "ente-base/components/containers";
-import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import { errorDialogAttributes } from "ente-base/components/utils/dialog";
-import { useIsSmallWidth } from "ente-base/components/utils/hooks";
-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
-import log from "ente-base/log";
-import { saveStringAsFile } from "ente-base/utils/web";
-import { t } from "i18next";
-import { useCallback, useEffect, useState } from "react";
-import {
- getUserRecoveryKey,
- recoveryKeyToMnemonic,
-} from "../services/recovery-key";
-import { CodeBlock } from "./CodeBlock";
-
-type RecoveryKeyProps = ModalVisibilityProps & {
- showMiniDialog: (attributes: MiniDialogAttributes) => void;
-};
-
-export const RecoveryKey: React.FC<RecoveryKeyProps> = ({
- open,
- onClose,
- showMiniDialog,
-}) => {
- const [recoveryKey, setRecoveryKey] = useState<string | undefined>();
- const fullScreen = useIsSmallWidth();
-
- const handleLoadError = useCallback(
- (e: unknown) => {
- log.error("Failed to generate recovery key", e);
- showMiniDialog(
- errorDialogAttributes(t("recovery_key_generation_failed")),
- );
- onClose();
- },
- [onClose, showMiniDialog],
- );
-
- useEffect(() => {
- if (!open) return;
-
- void getUserRecoveryKeyMnemonic()
- .then((key) => setRecoveryKey(key))
- .catch(handleLoadError);
- }, [open, handleLoadError]);
-
- const handleSaveClick = () => {
- saveRecoveryKeyMnemonicAsFile(recoveryKey!);
- onClose();
- };
-
- return (
- <Dialog
- fullScreen={fullScreen}
- open={open}
- onClose={onClose}
- // 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
- >
- <SpacedRow sx={{ p: "8px 4px 8px 0" }}>
- <DialogTitle variant="h3">{t("recovery_key")}</DialogTitle>
- <DialogCloseIconButton {...{ onClose }} />
- </SpacedRow>
- <DialogContent>
- <Typography sx={{ mb: 3 }}>
- {t("recovery_key_description")}
- </Typography>
- <Stack
- sx={{
- border: "1px dashed",
- borderColor: "stroke.muted",
- borderRadius: 1,
- }}
- >
- <CodeBlock code={recoveryKey} />
- <Typography sx={{ m: 2 }}>
- {t("key_not_stored_note")}
- </Typography>
- </Stack>
- </DialogContent>
- <DialogActions>
- <FocusVisibleButton
- color="secondary"
- fullWidth
- onClick={onClose}
- >
- {t("do_this_later")}
- </FocusVisibleButton>
- <FocusVisibleButton
- color="accent"
- fullWidth
- onClick={handleSaveClick}
- >
- {t("save_key")}
- </FocusVisibleButton>
- </DialogActions>
- </Dialog>
- );
-};
-
-const getUserRecoveryKeyMnemonic = async () =>
- recoveryKeyToMnemonic(await getUserRecoveryKey());
-
-const saveRecoveryKeyMnemonicAsFile = (key: string) =>
- saveStringAsFile(key, "ente-recovery-key.txt");
diff --git a/web/packages/accounts/components/SecondFactorChoice.tsx b/web/packages/accounts/components/SecondFactorChoice.tsx
deleted file mode 100644
index 63445b77f4..0000000000
--- a/web/packages/accounts/components/SecondFactorChoice.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { Dialog, DialogContent, DialogTitle, Stack } from "@mui/material";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
-import { t } from "i18next";
-import React from "react";
-
-export type SecondFactorType = "totp" | "passkey";
-
-type SecondFactorChoiceProps = ModalVisibilityProps & {
- onSelect: (factor: SecondFactorType) => void;
-};
-
-export const SecondFactorChoice: React.FC<SecondFactorChoiceProps> = ({
- open,
- onClose,
- onSelect,
-}) => (
- <Dialog
- open={open}
- onClose={(_, reason) => {
- if (reason != "backdropClick") onClose();
- }}
- fullWidth
- slotProps={{ paper: { sx: { maxWidth: "360px", padding: "12px" } } }}
- >
- <DialogTitle>{t("two_factor")}</DialogTitle>
- <DialogContent>
- <Stack sx={{ gap: "12px" }}>
- <FocusVisibleButton
- color="accent"
- onClick={() => {
- onClose();
- onSelect("totp");
- }}
- >
- {t("totp_login")}
- </FocusVisibleButton>
-
- <FocusVisibleButton
- color="accent"
- onClick={() => {
- onClose();
- onSelect("passkey");
- }}
- >
- {t("passkey_login")}
- </FocusVisibleButton>
- </Stack>
- </DialogContent>
- </Dialog>
-);
diff --git a/web/packages/accounts/components/SignUpContents.tsx b/web/packages/accounts/components/SignUpContents.tsx
deleted file mode 100644
index 8b0dde3935..0000000000
--- a/web/packages/accounts/components/SignUpContents.tsx
+++ /dev/null
@@ -1,337 +0,0 @@
-import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
-import {
- Checkbox,
- Divider,
- FormControlLabel,
- FormGroup,
- IconButton,
- InputAdornment,
- InputLabel,
- Link,
- Stack,
- TextField,
- Tooltip,
- Typography,
-} from "@mui/material";
-import {
- replaceSavedLocalUser,
- saveJustSignedUp,
- saveOriginalKeyAttributes,
- stashReferralSource,
- stashSRPSetupAttributes,
-} from "ente-accounts/services/accounts-db";
-import { generateSRPSetupAttributes } from "ente-accounts/services/srp";
-import {
- generateAndSaveInteractiveKeyAttributes,
- generateKeysAndAttributes,
- sendOTT,
- type GenerateKeysAndAttributesResult,
-} from "ente-accounts/services/user";
-import { isWeakPassword } from "ente-accounts/utils/password";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
-import { deriveKeyInsufficientMemoryErrorMessage } from "ente-base/crypto/types";
-import { isMuseumHTTPError } from "ente-base/http";
-import { JOIN_ALBUM_CONTEXT_KEY } from "ente-base/join-album";
-import log from "ente-base/log";
-import { saveMasterKeyInSessionAndSafeStore } from "ente-base/session";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import type { NextRouter } from "next/router";
-import React, { useCallback, useEffect, useState } from "react";
-import { Trans } from "react-i18next";
-import { z } from "zod";
-import { PasswordStrengthHint } from "./PasswordStrength";
-import {
- AccountsPageFooter,
- AccountsPageTitle,
-} from "./layouts/centered-paper";
-
-interface SignUpContentsProps {
- router: NextRouter;
- onLogin: () => void;
- host: string | undefined;
-}
-
-export const SignUpContents: React.FC<SignUpContentsProps> = ({
- router,
- onLogin,
- host,
-}) => {
- const [showPassword, setShowPassword] = useState(false);
- const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);
-
- useEffect(() => {
- const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
- setIsJoinAlbumContext(!!joinAlbumContext);
- }, []);
-
- const handleToggleShowHidePassword = useCallback(
- () => setShowPassword((show) => !show),
- [],
- );
-
- const formik = useFormik({
- initialValues: {
- email: "",
- password: "",
- confirmPassword: "",
- referral: "",
- acceptedTerms: false,
- },
- onSubmit: async (
- { email, password, confirmPassword, referral },
- { setFieldError },
- ) => {
- if (!email) {
- setFieldError("email", t("required"));
- return;
- }
-
- if (!z.email().safeParse(email).success) {
- setFieldError("email", t("invalid_email_error"));
- return;
- }
-
- if (!password) {
- setFieldError("password", t("required"));
- return;
- }
-
- if (!confirmPassword) {
- setFieldError("confirmPassword", t("required"));
- return;
- }
-
- if (password != confirmPassword) {
- setFieldError("confirmPassword", t("password_mismatch_error"));
- return;
- }
-
- try {
- const cleanedReferral = referral.trim();
- if (cleanedReferral) stashReferralSource(cleanedReferral);
-
- try {
- await sendOTT(email, "signup");
- } catch (e) {
- if (
- await isMuseumHTTPError(
- e,
- 409,
- "USER_ALREADY_REGISTERED",
- )
- ) {
- setFieldError("email", t("email_already_registered"));
- return;
- }
- throw e;
- }
-
- replaceSavedLocalUser({ email });
-
- let gkResult: GenerateKeysAndAttributesResult;
- try {
- gkResult = await generateKeysAndAttributes(password);
- } catch (e) {
- if (
- e instanceof Error &&
- e.message == deriveKeyInsufficientMemoryErrorMessage
- ) {
- setFieldError(
- "confirmPassword",
- t("password_generation_failed"),
- );
- return;
- }
- throw e;
- }
-
- const { masterKey, kek, keyAttributes } = gkResult;
- saveOriginalKeyAttributes(keyAttributes);
- stashSRPSetupAttributes(await generateSRPSetupAttributes(kek));
- await generateAndSaveInteractiveKeyAttributes(
- password,
- keyAttributes,
- masterKey,
- );
- await saveMasterKeyInSessionAndSafeStore(masterKey);
-
- saveJustSignedUp();
- void router.push("/verify");
- } catch (e) {
- log.error("Signup failed", e);
- setFieldError("confirmPassword", t("generic_error"));
- }
- },
- });
-
- const form = (
- <form onSubmit={formik.handleSubmit}>
- <TextField
- name="email"
- type="email"
- autoComplete="username"
- label={t("enter_email")}
- value={formik.values.email}
- onChange={formik.handleChange}
- error={!!formik.errors.email}
- helperText={formik.errors.email}
- disabled={formik.isSubmitting}
- fullWidth
- autoFocus
- />
- <TextField
- name="password"
- autoComplete="new-password"
- type={showPassword ? "text" : "password"}
- label={t("password")}
- value={formik.values.password}
- onChange={formik.handleChange}
- error={!!formik.errors.password}
- helperText={formik.errors.password}
- disabled={formik.isSubmitting}
- fullWidth
- slotProps={{
- input: {
- endAdornment: (
- <ShowHidePasswordInputAdornment
- showPassword={showPassword}
- onToggle={handleToggleShowHidePassword}
- />
- ),
- },
- }}
- />
- <TextField
- name="confirmPassword"
- autoComplete="new-password"
- type="password"
- label={t("confirm_password")}
- value={formik.values.confirmPassword}
- onChange={formik.handleChange}
- error={!!formik.errors.confirmPassword}
- helperText={formik.errors.confirmPassword}
- disabled={formik.isSubmitting}
- fullWidth
- />
- <PasswordStrengthHint password={formik.values.password} />
- <InputLabel
- htmlFor="referral"
- sx={{ color: "text.muted", mt: "24px", mx: "2px" }}
- >
- {t("referral_source_hint")}
- </InputLabel>
- <TextField
- hiddenLabel
- id="referral"
- type="text"
- value={formik.values.referral}
- onChange={formik.handleChange}
- error={!!formik.errors.referral}
- disabled={formik.isSubmitting}
- fullWidth
- slotProps={{
- input: {
- endAdornment: (
- <InputAdornment position="end">
- <Tooltip title={t("referral_source_info")}>
- <IconButton
- tabIndex={-1}
- color="secondary"
- edge={"end"}
- >
- <InfoOutlinedIcon />
- </IconButton>
- </Tooltip>
- </InputAdornment>
- ),
- },
- }}
- />
- <FormGroup sx={{ color: "text.muted", mt: 2, mb: 2.5, mx: "4px" }}>
- <FormControlLabel
- control={
- <Checkbox
- name="acceptedTerms"
- size="small"
- color="accent"
- checked={formik.values.acceptedTerms}
- onChange={formik.handleChange}
- disabled={formik.isSubmitting}
- />
- }
- label={
- <Typography variant="small">
- <Trans
- i18nKey={"terms_and_conditions"}
- components={{
- a: (
- <Link
- href="https://ente.com/terms"
- target="_blank"
- />
- ),
- b: (
- <Link
- href="https://ente.com/privacy"
- target="_blank"
- />
- ),
- }}
- />
- </Typography>
- }
- />
- </FormGroup>
- <LoadingButton
- fullWidth
- color="accent"
- type="submit"
- loading={formik.isSubmitting}
- disabled={
- !formik.values.acceptedTerms ||
- isWeakPassword(formik.values.password)
- }
- >
- {t("create_account")}
- </LoadingButton>
- <Typography
- variant="small"
- sx={(theme) => ({
- mt: 1,
- textAlign: "center",
- color: "text.muted",
- // The minHeight, equal to the lineHeight of the eventual
- // content, prevents layout shift.
- minHeight: theme.typography.small.lineHeight,
- })}
- >
- {formik.isSubmitting ? t("key_generation_in_progress") : ""}
- </Typography>
- </form>
- );
-
- return (
- <>
- <AccountsPageTitle>
- {isJoinAlbumContext ? t("signup_to_join_album") : t("sign_up")}
- </AccountsPageTitle>
- {form}
- <Divider sx={{ mt: 1 }} />
- <AccountsPageFooter>
- <Stack sx={{ gap: 3, textAlign: "center" }}>
- <LinkButton onClick={onLogin}>
- {t("existing_account")}
- </LinkButton>
- {host && (
- <Typography variant="mini" sx={{ color: "text.faint" }}>
- {host}
- </Typography>
- )}
- </Stack>
- </AccountsPageFooter>
- </>
- );
-};
diff --git a/web/packages/accounts/components/Verify2FACodeForm.tsx b/web/packages/accounts/components/Verify2FACodeForm.tsx
deleted file mode 100644
index 60800c5997..0000000000
--- a/web/packages/accounts/components/Verify2FACodeForm.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { Stack, styled, Typography } from "@mui/material";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { isHTTP401Error } from "ente-base/http";
-import log from "ente-base/log";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import React, { useEffect, useState } from "react";
-import OtpInput from "react-otp-input";
-
-interface Verify2FACodeFormProps {
- onSubmit: (otp: string) => Promise<void>;
- submitButtonText: string;
-}
-
-export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({
- onSubmit,
- submitButtonText,
-}) => {
- const [shouldAutoFocus, setShouldAutoFocus] = useState(true);
-
- const {
- values,
- errors,
- handleChange,
- handleSubmit,
- submitForm,
- isSubmitting,
- } = useFormik<{ otp: string }>({
- initialValues: { otp: "" },
- validateOnBlur: false,
- validateOnChange: false,
- onSubmit: async ({ otp }, { setFieldError, resetForm }) => {
- try {
- await onSubmit(otp);
- // Reset the form, otherwise the auto-submit effect below
- // resubmits.
- resetForm();
- } catch (e) {
- log.error("Failed to submit 2FA code", e);
- resetForm();
- setFieldError(
- "otp",
- isHTTP401Error(e)
- ? t("incorrect_code")
- : t("generic_error"),
- );
- // Workaround (toggling shouldAutoFocus) to reset the focus back
- // to the first input field in case of errors.
- // https://github.com/devfolioco/react-otp-input/issues/420
- setShouldAutoFocus(false);
- setTimeout(() => setShouldAutoFocus(true), 100);
- }
- },
- });
-
- useEffect(() => {
- if (values.otp.length == 6 && !isSubmitting) void submitForm();
- }, [values, isSubmitting, submitForm]);
-
- return (
- <form onSubmit={handleSubmit}>
- <Stack sx={{ gap: 3, textAlign: "center" }}>
- <Typography variant="small" sx={{ color: "text.muted" }}>
- {t("enter_two_factor_otp")}
- </Typography>
- <OtpInput
- containerStyle={{ justifyContent: "center" }}
- shouldAutoFocus={shouldAutoFocus}
- value={values.otp}
- onChange={handleChange("otp")}
- numInputs={6}
- inputType="tel"
- renderSeparator={<span>-</span>}
- renderInput={(props, index) => (
- <IndividualInput
- {...props}
- autoComplete={index === 0 ? "one-time-code" : "off"}
- name={index === 0 ? "otp" : undefined}
- pattern="[0-9]*"
- />
- )}
- />
- {errors.otp && (
- <Typography variant="mini" sx={{ color: "critical.main" }}>
- {errors.otp}
- </Typography>
- )}
- <LoadingButton
- type="submit"
- color="accent"
- fullWidth
- loading={isSubmitting}
- disabled={values.otp.length < 6}
- >
- {submitButtonText}
- </LoadingButton>
- </Stack>
- </form>
- );
-};
-
-const IndividualInput = styled("input")(
- ({ theme }) => `
- font-size: 1.5rem;
- padding: 4px;
- width: 40px !important;
- aspect-ratio: 1;
- margin-inline: 6px;
- border: 1px solid ${theme.vars.palette.accent.main};
- border-radius: 1px;
- outline-color: ${theme.vars.palette.accent.light};
- transition: 0.5s;
- ${theme.breakpoints.down("sm")} {
- font-size: 1rem;
- padding: 4px;
- width: 32px !important;
- }
-`,
-);
diff --git a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx b/web/packages/accounts/components/VerifyMasterPasswordForm.tsx
deleted file mode 100644
index c240e75cbc..0000000000
--- a/web/packages/accounts/components/VerifyMasterPasswordForm.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { Input, TextField } from "@mui/material";
-import {
- srpVerificationUnauthorizedErrorMessage,
- type SRPAttributes,
-} from "ente-accounts/services/srp";
-import type { KeyAttributes } from "ente-accounts/services/user";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
-import { decryptBox, deriveKey } from "ente-base/crypto";
-import log from "ente-base/log";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import { useCallback, useState } from "react";
-
-export interface VerifyMasterPasswordFormProps {
- userEmail: string;
- srpAttributes?: SRPAttributes;
- keyAttributes: KeyAttributes | undefined;
- getKeyAttributes?: (
- srpAttributes: SRPAttributes,
- kek: string,
- ) => Promise<KeyAttributes | "redirecting-second-factor" | undefined>;
- submitButtonTitle: string;
- onVerify: (
- key: string,
- kek: string,
- keyAttributes: KeyAttributes,
- password: string,
- ) => void;
-}
-
-export const VerifyMasterPasswordForm: React.FC<
- VerifyMasterPasswordFormProps
-> = ({
- userEmail,
- keyAttributes,
- srpAttributes,
- getKeyAttributes,
- onVerify,
- submitButtonTitle,
-}) => {
- const [showPassword, setShowPassword] = useState(false);
-
- const handleToggleShowHidePassword = useCallback(
- () => setShowPassword((show) => !show),
- [],
- );
-
- const formik = useFormik({
- initialValues: { password: "" },
- onSubmit: async ({ password }, { setFieldError }) => {
- const setPasswordFieldError = (message: string) =>
- setFieldError("password", message);
-
- if (!password) {
- setPasswordFieldError(t("required"));
- return;
- }
-
- try {
- await verifyPassword(password, setPasswordFieldError);
- } catch (e) {
- log.error("Failed to verify password", e);
- setPasswordFieldError(t("generic_error"));
- }
- },
- });
-
- const verifyPassword = async (
- password: string,
- setFieldError: (message: string) => void,
- ) => {
- let kek: string;
- if (srpAttributes) {
- try {
- kek = await deriveKey(
- password,
- srpAttributes.kekSalt,
- srpAttributes.opsLimit,
- srpAttributes.memLimit,
- );
- } catch (e) {
- log.error("Failed to derive kek", e);
- setFieldError(t("weak_device_hint"));
- return;
- }
- } else if (keyAttributes) {
- try {
- kek = await deriveKey(
- password,
- keyAttributes.kekSalt,
- keyAttributes.opsLimit,
- keyAttributes.memLimit,
- );
- } catch (e) {
- log.error("Failed to derive kek", e);
- setFieldError(t("weak_device_hint"));
- return;
- }
- } else throw new Error("Both SRP and key attributes are missing");
-
- if (!keyAttributes && getKeyAttributes && srpAttributes) {
- try {
- const result = await getKeyAttributes(srpAttributes, kek);
- if (result == "redirecting-second-factor") {
- return;
- } else {
- keyAttributes = result;
- }
- } catch (e) {
- if (
- e instanceof Error &&
- e.message == srpVerificationUnauthorizedErrorMessage
- ) {
- log.error("Incorrect password or no account", e);
- setFieldError(t("incorrect_password_or_no_account"));
- return;
- }
- throw e;
- }
- }
-
- if (!keyAttributes) throw Error("Couldn't get key attributes");
-
- let key: string;
- try {
- key = await decryptBox(
- {
- encryptedData: keyAttributes.encryptedKey,
- nonce: keyAttributes.keyDecryptionNonce,
- },
- kek,
- );
- } catch {
- setFieldError(t("incorrect_password"));
- return;
- }
-
- onVerify(key, kek, keyAttributes, password);
- };
-
- return (
- <form onSubmit={formik.handleSubmit}>
- <Input
- sx={{ display: "none" }}
- name="email"
- autoComplete="username"
- type="email"
- value={userEmail}
- />
- <TextField
- name="password"
- value={formik.values.password}
- onChange={formik.handleChange}
- type={showPassword ? "text" : "password"}
- autoComplete="current-password"
- label={t("password")}
- fullWidth
- autoFocus
- margin="normal"
- disabled={formik.isSubmitting}
- error={!!formik.errors.password}
- helperText={formik.errors.password ?? " "}
- slotProps={{
- input: {
- endAdornment: (
- <ShowHidePasswordInputAdornment
- showPassword={showPassword}
- onToggle={handleToggleShowHidePassword}
- />
- ),
- },
- }}
- />
- <LoadingButton
- fullWidth
- type="submit"
- loading={formik.isSubmitting}
- color={"accent"}
- >
- {submitButtonTitle}
- </LoadingButton>
- </form>
- );
-};
diff --git a/web/packages/accounts/components/layouts/centered-paper.tsx b/web/packages/accounts/components/layouts/centered-paper.tsx
deleted file mode 100644
index 712fedc2b7..0000000000
--- a/web/packages/accounts/components/layouts/centered-paper.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Paper, Stack, styled, Typography } from "@mui/material";
-import { CenteredFill } from "ente-base/components/containers";
-import { EnteLogo } from "ente-base/components/EnteLogo";
-import { NavbarBase } from "ente-base/components/Navbar";
-
-export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({
- children,
-}) => (
- <Stack
- sx={[
- { minHeight: "100svh", bgcolor: "secondary.main" },
- (theme) =>
- theme.applyStyles("dark", { bgcolor: "background.default" }),
- ]}
- >
- <NavbarBase
- sx={{
- boxShadow: "none",
- borderBottom: "none",
- bgcolor: "transparent",
- }}
- >
- <EnteLogo />
- </NavbarBase>
- <CenteredFill
- sx={[
- { bgcolor: "secondary.main" },
- (theme) =>
- theme.applyStyles("dark", {
- bgcolor: "background.default",
- }),
- ]}
- >
- <AccountsPagePaper>{children}</AccountsPagePaper>
- </CenteredFill>
- </Stack>
-);
-
-const AccountsPagePaper = styled(Paper)(({ theme }) => ({
- marginBlock: theme.spacing(2),
- padding: theme.spacing(5, 3),
- [theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },
- width: "min(420px, 85vw)",
- minHeight: "375px",
- display: "flex",
- flexDirection: "column",
- gap: theme.spacing(4),
- boxShadow: "none",
- borderRadius: "20px",
-}));
-
-export const AccountsPageTitle: React.FC<React.PropsWithChildren> = ({
- children,
-}) => (
- <Typography variant="h3" sx={{ flex: 1 }}>
- {children}
- </Typography>
-);
-
-export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({
- children,
-}) => (
- <Stack
- direction="row"
- sx={{
- mx: "4px",
- justifyContent: "space-between",
- "& :only-child": { marginInline: "auto" },
- }}
- >
- {children}
- </Stack>
-);
diff --git a/web/packages/accounts/components/utils/dialog.ts b/web/packages/accounts/components/utils/dialog.ts
deleted file mode 100644
index 52583614cb..0000000000
--- a/web/packages/accounts/components/utils/dialog.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
-import { t } from "i18next";
-
-export const sessionExpiredDialogAttributes = (
- onLogin: () => void,
-): MiniDialogAttributes => ({
- title: t("session_expired"),
- message: t("session_expired_message"),
- nonClosable: true,
- nonReplaceable: true,
- continue: { text: t("login"), action: onLogin },
- cancel: false,
-});
diff --git a/web/packages/accounts/components/utils/second-factor-choice.ts b/web/packages/accounts/components/utils/second-factor-choice.ts
deleted file mode 100644
index 1930a7156d..0000000000
--- a/web/packages/accounts/components/utils/second-factor-choice.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// 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";
-
-export const useSecondFactorChoiceIfNeeded = () => {
- const resolveSecondFactorChoice = useRef<
- | ((value: SecondFactorType | PromiseLike<SecondFactorType>) => void)
- | undefined
- >(undefined);
- const {
- show: showSecondFactorChoice,
- props: secondFactorChoiceVisibilityProps,
- } = useModalVisibility();
-
- const onSelect = useCallback((factor: SecondFactorType) => {
- const resolve = resolveSecondFactorChoice.current!;
- resolveSecondFactorChoice.current = undefined;
- resolve(factor);
- }, []);
-
- const secondFactorChoiceProps = useMemo(
- () => ({ ...secondFactorChoiceVisibilityProps, onSelect }),
- [secondFactorChoiceVisibilityProps, onSelect],
- );
-
- const userVerificationResultAfterResolvingSecondFactorChoice = useCallback(
- async (response: EmailOrSRPVerificationResponse) => {
- const {
- twoFactorSessionID: _twoFactorSessionIDV1,
- twoFactorSessionIDV2: _twoFactorSessionIDV2,
- passkeySessionID: _passkeySessionID,
- } = response;
-
- // 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 (_twoFactorSessionID && _passkeySessionID) {
- const choice = await new Promise<SecondFactorType>(
- (resolve) => {
- resolveSecondFactorChoice.current = resolve;
- showSecondFactorChoice();
- },
- );
- switch (choice) {
- case "passkey":
- passkeySessionID = _passkeySessionID;
- break;
- case "totp":
- twoFactorSessionID = _twoFactorSessionID;
- break;
- }
- } else {
- passkeySessionID = _passkeySessionID;
- twoFactorSessionID = _twoFactorSessionID;
- }
-
- return { ...response, passkeySessionID, twoFactorSessionID };
- },
- [showSecondFactorChoice],
- );
-
- return {
- secondFactorChoiceProps,
- userVerificationResultAfterResolvingSecondFactorChoice,
- };
-};
diff --git a/web/packages/accounts/components/utils/use-redirect.ts b/web/packages/accounts/components/utils/use-redirect.ts
deleted file mode 100644
index d682ffb789..0000000000
--- a/web/packages/accounts/components/utils/use-redirect.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { haveMasterKeyInSession } from "ente-base/session";
-import { useRouter } from "next/router";
-import { useEffect } from "react";
-import { stashRedirect } from "../../services/redirect";
-
-export const useRedirectIfNeedsCredentials = (currentPageSlug: string) => {
- const router = useRouter();
-
- useEffect(() => {
- if (!haveMasterKeyInSession()) {
- stashRedirect(currentPageSlug);
- void router.push("/");
- }
- }, [router, currentPageSlug]);
-};
diff --git a/web/packages/accounts/eslint.config.mjs b/web/packages/accounts/eslint.config.mjs
deleted file mode 100644
index 1919c2b05d..0000000000
--- a/web/packages/accounts/eslint.config.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-build-config/eslintrc-react.mjs";
diff --git a/web/packages/accounts/package.json b/web/packages/accounts/package.json
deleted file mode 100644
index 50f7ae61fa..0000000000
--- a/web/packages/accounts/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "name": "ente-accounts",
- "version": "0.0.0",
- "private": true,
- "dependencies": {
- "bip39": "3.1.0",
- "ente-base": "*",
- "fast-srp-hap": "2.0.4",
- "react": "19.2.7",
- "react-dom": "19.2.7",
- "react-otp-input": "3.1.1",
- "uuid": "13.0.2",
- "zxcvbn": "4.4.2"
- },
- "devDependencies": {
- "@types/react": "19.2.17",
- "@types/react-dom": "19.2.3",
- "@types/zxcvbn": "4.4.5",
- "ente-build-config": "*"
- }
-}
diff --git a/web/packages/accounts/pages/change-email.tsx b/web/packages/accounts/pages/change-email.tsx
deleted file mode 100644
index fa6052730c..0000000000
--- a/web/packages/accounts/pages/change-email.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import CheckIcon from "@mui/icons-material/Check";
-import { Alert, Box, TextField } from "@mui/material";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import { useRedirectIfNeedsCredentials } from "ente-accounts/components/utils/use-redirect";
-import { appHomeRoute } from "ente-accounts/services/redirect";
-import { changeEmail, sendOTT } from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import { isHTTPErrorWithStatus } from "ente-base/http";
-import log from "ente-base/log";
-import { useFormik } from "formik";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useState } from "react";
-import { Trans } from "react-i18next";
-import { z } from "zod";
-
-const Page: React.FC = () => {
- useRedirectIfNeedsCredentials("/change-email");
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>{t("change_email")}</AccountsPageTitle>
- <ChangeEmailForm />
- </AccountsPageContents>
- );
-};
-
-export default Page;
-
-const ChangeEmailForm: React.FC = () => {
- const [requestedEmail, setRequestedEmail] = useState("");
- const [showSentConfirmation, setShowSentConfirmation] = useState(false);
-
- const router = useRouter();
-
- const redirectToAppHome = useCallback(() => {
- void router.push(appHomeRoute);
- }, [router]);
-
- const formik = useFormik({
- initialValues: { email: "", ott: "" },
- onSubmit: async ({ email, ott }, { setFieldError }) => {
- if (!email) {
- setFieldError("email", t("required"));
- return;
- }
-
- if (!z.email().safeParse(email).success) {
- setFieldError("email", t("invalid_email_error"));
- return;
- }
-
- if (!requestedEmail) {
- try {
- await sendOTT(email, "change");
- } catch (e) {
- log.error("Could not send OTT for email change", e);
- setFieldError(
- "email",
- isHTTPErrorWithStatus(e, 403)
- ? t("email_already_taken")
- : t("generic_error"),
- );
- return;
- }
-
- setRequestedEmail(email);
- setShowSentConfirmation(true);
- } else {
- if (!ott) {
- setFieldError("ott", t("required"));
- return;
- }
-
- try {
- await changeEmail(email, ott);
- } catch (e) {
- log.error("Could not change email", e);
- setFieldError(
- "ott",
- isHTTPErrorWithStatus(e, 401)
- ? t("incorrect_code")
- : isHTTPErrorWithStatus(e, 410)
- ? t("expired_code_error")
- : t("generic_error"),
- );
- return;
- }
-
- redirectToAppHome();
- }
- },
- });
-
- return (
- <>
- {requestedEmail && showSentConfirmation && (
- <Alert
- icon={<CheckIcon fontSize="inherit" />}
- severity="success"
- onClose={() => setShowSentConfirmation(false)}
- >
- <Trans
- i18nKey="email_sent"
- components={{
- a: (
- <Box
- component={"span"}
- sx={{ color: "text.muted" }}
- />
- ),
- }}
- values={{ email: requestedEmail }}
- />
- </Alert>
- )}
- <form onSubmit={formik.handleSubmit}>
- <TextField
- name="email"
- type="email"
- label={t("enter_email")}
- value={formik.values.email}
- onChange={formik.handleChange}
- error={!!formik.errors.email}
- helperText={
- formik.errors.email ?? (requestedEmail ? "" : " ")
- }
- disabled={formik.isSubmitting}
- autoFocus
- fullWidth
- slotProps={{ input: { readOnly: !!requestedEmail } }}
- />
- {requestedEmail && (
- <TextField
- name="ott"
- type="text"
- label={t("verification_code")}
- value={formik.values.ott}
- onChange={formik.handleChange}
- error={!!formik.errors.ott}
- helperText={formik.errors.ott ?? " "}
- disabled={formik.isSubmitting}
- fullWidth
- />
- )}
- <LoadingButton
- type="submit"
- color="accent"
- fullWidth
- loading={formik.isSubmitting}
- sx={{ mt: 1, mb: 3 }}
- >
- {!requestedEmail ? t("send_otp") : t("verify")}
- </LoadingButton>
- </form>
- <AccountsPageFooter>
- {requestedEmail && (
- <LinkButton onClick={() => setRequestedEmail("")}>
- {t("change_email")}?
- </LinkButton>
- )}
- <LinkButton onClick={redirectToAppHome}>
- {t("go_back")}
- </LinkButton>
- </AccountsPageFooter>
- </>
- );
-};
diff --git a/web/packages/accounts/pages/change-password.tsx b/web/packages/accounts/pages/change-password.tsx
deleted file mode 100644
index 7330cd9480..0000000000
--- a/web/packages/accounts/pages/change-password.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { Divider } from "@mui/material";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import { appHomeRoute, stashRedirect } from "ente-accounts/services/redirect";
-import { changePassword, type LocalUser } from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { deriveKeyInsufficientMemoryErrorMessage } from "ente-base/crypto/types";
-import log from "ente-base/log";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import React, { useCallback, useEffect, useState } from "react";
-import {
- NewPasswordForm,
- type NewPasswordFormProps,
-} from "../components/NewPasswordForm";
-import { savedLocalUser } from "../services/accounts-db";
-
-const Page: React.FC = () => {
- const [user, setUser] = useState<LocalUser | undefined>(undefined);
-
- const router = useRouter();
-
- const isReset = router.query.op == "reset";
-
- useEffect(() => {
- const user = savedLocalUser();
- if (user) {
- setUser(user);
- } else {
- stashRedirect("/change-password");
- void router.replace("/");
- }
- }, [router]);
-
- return user ? (
- <PageContents {...{ user, isReset }} />
- ) : (
- <LoadingIndicator />
- );
-};
-
-export default Page;
-
-interface PageContentsProps {
- user: LocalUser;
- isReset: boolean;
-}
-
-const PageContents: React.FC<PageContentsProps> = ({ user, isReset }) => {
- const router = useRouter();
-
- const handleSubmit: NewPasswordFormProps["onSubmit"] = useCallback(
- async (password, setPasswordsFieldError) =>
- changePassword(password)
- .then(() => void router.push(appHomeRoute))
- .catch((e: unknown) => {
- log.error("Could not change password", e);
- setPasswordsFieldError(
- e instanceof Error &&
- e.message == deriveKeyInsufficientMemoryErrorMessage
- ? t("password_generation_failed")
- : t("generic_error"),
- );
- }),
- [router],
- );
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>{t("change_password")}</AccountsPageTitle>
- <NewPasswordForm
- userEmail={user.email}
- submitButtonTitle={t("change_password")}
- onSubmit={handleSubmit}
- />
- {!isReset && (
- <>
- <Divider sx={{ mt: 1 }} />
- <AccountsPageFooter>
- <LinkButton onClick={router.back}>
- {t("go_back")}
- </LinkButton>
- </AccountsPageFooter>
- </>
- )}
- </AccountsPageContents>
- );
-};
diff --git a/web/packages/accounts/pages/credentials.tsx b/web/packages/accounts/pages/credentials.tsx
deleted file mode 100644
index e8817716af..0000000000
--- a/web/packages/accounts/pages/credentials.tsx
+++ /dev/null
@@ -1,350 +0,0 @@
-import { AccountsPageContents } from "ente-accounts/components/layouts/centered-paper";
-import {
- AccountsPageFooterWithHost,
- PasswordHeader,
- VerifyingPasskey,
-} from "ente-accounts/components/LoginComponents";
-import { SecondFactorChoice } from "ente-accounts/components/SecondFactorChoice";
-import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
-import { useSecondFactorChoiceIfNeeded } from "ente-accounts/components/utils/second-factor-choice";
-import {
- VerifyMasterPasswordForm,
- type VerifyMasterPasswordFormProps,
-} from "ente-accounts/components/VerifyMasterPasswordForm";
-import {
- savedIsFirstLogin,
- savedKeyAttributes,
- savedPartialLocalUser,
- savedSRPAttributes,
- saveIsFirstLogin,
- saveKeyAttributes,
- saveSRPAttributes,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import {
- openPasskeyVerificationURL,
- passkeyVerificationRedirectURL,
-} from "ente-accounts/services/passkey";
-import {
- appHomeRoute,
- stashRedirect,
- unstashRedirect,
-} from "ente-accounts/services/redirect";
-import { checkSessionValidity } from "ente-accounts/services/session";
-import type { SRPAttributes } from "ente-accounts/services/srp";
-import {
- generateSRPSetupAttributes,
- getAndSaveSRPAttributes,
- getSRPAttributes,
- setupSRP,
- verifySRP,
-} from "ente-accounts/services/srp";
-import {
- decryptAndStoreTokenIfNeeded,
- generateAndSaveInteractiveKeyAttributes,
- type KeyAttributes,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { useBaseContext } from "ente-base/context";
-import { decryptBox } from "ente-base/crypto";
-import { isDevBuild } from "ente-base/env";
-import { clearLocalStorage } from "ente-base/local-storage";
-import log from "ente-base/log";
-import {
- masterKeyFromSession,
- saveMasterKeyInSessionAndSafeStore,
- stashKeyEncryptionKeyInSessionStore,
- unstashKeyEncryptionKeyFromSession,
- updateSessionFromElectronSafeStorageIfNeeded,
-} from "ente-base/session";
-import { saveAuthToken, savedAuthToken } from "ente-base/token";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useState } from "react";
-
-const Page: React.FC = () => {
- const { logout, showMiniDialog } = useBaseContext();
-
- const [userEmail, setUserEmail] = useState<string>("");
- const [keyAttributes, setKeyAttributes] = useState<
- KeyAttributes | undefined
- >(undefined);
- const [srpAttributes, setSRPAttributes] = useState<
- SRPAttributes | undefined
- >(undefined);
- const [passkeyVerificationData, setPasskeyVerificationData] = useState<
- { passkeySessionID: string; url: string } | undefined
- >(undefined);
- const [sessionValidityCheck, setSessionValidityCheck] = useState<
- Promise<void> | undefined
- >(undefined);
-
- const {
- secondFactorChoiceProps,
- userVerificationResultAfterResolvingSecondFactorChoice,
- } = useSecondFactorChoiceIfNeeded();
-
- const router = useRouter();
-
- const validateSession = useCallback(async () => {
- const showSessionExpiredDialog = () =>
- showMiniDialog(sessionExpiredDialogAttributes(logout));
-
- try {
- const session = await checkSessionValidity();
- switch (session.status) {
- case "invalid":
- showSessionExpiredDialog();
- break;
- case "valid":
- break;
- case "validButPasswordChanged":
- saveKeyAttributes(session.updatedKeyAttributes);
- saveSRPAttributes(session.updatedSRPAttributes);
- // Set a flag that causes new interactive key attributes to
- // be generated.
- saveIsFirstLogin();
- // This should be rare; instead of updating all the
- // in-memory state, just reload the page.
- window.location.reload();
- }
- } catch (e) {
- // Ignore errors; a potentially transient issue must not log the
- // user out.
- log.warn("Ignoring error when determining session validity", e);
- }
- }, [logout, showMiniDialog]);
-
- const postVerification = useCallback(
- async (
- userEmail: string,
- masterKey: string,
- kek: string,
- keyAttributes: KeyAttributes,
- ) => {
- await saveMasterKeyInSessionAndSafeStore(masterKey);
- await decryptAndStoreTokenIfNeeded(keyAttributes, masterKey);
- try {
- let srpAttributes = savedSRPAttributes();
- if (!srpAttributes) {
- srpAttributes = await getSRPAttributes(userEmail);
- if (srpAttributes) {
- saveSRPAttributes(srpAttributes);
- } else {
- await setupSRP(await generateSRPSetupAttributes(kek));
- await getAndSaveSRPAttributes(userEmail);
- }
- }
- } catch (e) {
- log.error("SRP migration failed", e);
- }
- void router.push(unstashRedirect() ?? appHomeRoute);
- },
- [router],
- );
-
- useEffect(() => {
- void (async () => {
- const user = savedPartialLocalUser();
- const userEmail = user?.email;
- if (!userEmail) {
- await router.replace("/");
- return;
- }
-
- await updateSessionFromElectronSafeStorageIfNeeded();
- if ((await masterKeyFromSession()) && (await savedAuthToken())) {
- await router.replace(appHomeRoute);
- return;
- }
-
- setUserEmail(userEmail);
- if (user.token) setSessionValidityCheck(validateSession());
-
- const kek = await unstashKeyEncryptionKeyFromSession();
- const keyAttributes = savedKeyAttributes();
-
- // 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(
- {
- encryptedData: keyAttributes.encryptedKey,
- nonce: keyAttributes.keyDecryptionNonce,
- },
- kek,
- );
- await postVerification(
- userEmail,
- masterKey,
- kek,
- keyAttributes,
- );
- return;
- }
-
- // Reauthentication in a new tab on the web app. Use previously
- // generated interactive key attributes to verify password.
- if (keyAttributes) {
- if (!user.token && !user.encryptedToken) {
- // TODO: Why? For now, add a dev mode circuit breaker.
- if (isDevBuild) throw new Error("Unexpected case reached");
- clearLocalStorage();
- void router.replace("/");
- return;
- }
- setKeyAttributes(keyAttributes);
- return;
- }
-
- // First login on a new client. `getKeyAttributes` from below will
- // be used during password verification to generate interactive key
- // attributes for subsequent reauthentications.
- const srpAttributes = savedSRPAttributes();
- if (srpAttributes) {
- setSRPAttributes(srpAttributes);
- return;
- }
-
- void router.replace("/");
- })();
- }, [router, validateSession, postVerification]);
-
- const getKeyAttributes: VerifyMasterPasswordFormProps["getKeyAttributes"] =
- useCallback(
- async (srpAttributes: SRPAttributes, kek: string) => {
- const {
- id,
- keyAttributes,
- token,
- encryptedToken,
- twoFactorSessionID,
- passkeySessionID,
- accountsUrl,
- } =
- await userVerificationResultAfterResolvingSecondFactorChoice(
- await verifySRP(srpAttributes, kek),
- );
-
- saveIsFirstLogin();
-
- if (passkeySessionID) {
- await stashKeyEncryptionKeyInSessionStore(kek);
- updateSavedLocalUser({ passkeySessionID });
- stashRedirect("/");
- const url = passkeyVerificationRedirectURL(
- accountsUrl!,
- passkeySessionID,
- );
- setPasskeyVerificationData({ passkeySessionID, url });
- openPasskeyVerificationURL({ passkeySessionID, url });
- return "redirecting-second-factor";
- } else if (twoFactorSessionID) {
- await stashKeyEncryptionKeyInSessionStore(kek);
- updateSavedLocalUser({
- isTwoFactorEnabled: true,
- twoFactorSessionID,
- });
- void router.push("/two-factor/verify");
- return "redirecting-second-factor";
- } else {
- if (token) await saveAuthToken(token);
- updateSavedLocalUser({
- id,
- token,
- encryptedToken,
- isTwoFactorEnabled: undefined,
- twoFactorSessionID: undefined,
- passkeySessionID: undefined,
- });
- if (keyAttributes) saveKeyAttributes(keyAttributes);
- return keyAttributes;
- }
- },
- [userVerificationResultAfterResolvingSecondFactorChoice, router],
- );
-
- const handleVerifyMasterPassword: VerifyMasterPasswordFormProps["onVerify"] =
- useCallback(
- (key, kek, keyAttributes, password) => {
- void (async () => {
- // 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()
- ? await generateAndSaveInteractiveKeyAttributes(
- password,
- keyAttributes,
- key,
- )
- : keyAttributes;
-
- await postVerification(
- userEmail,
- key,
- kek,
- updatedKeyAttributes,
- );
- })();
- },
- [postVerification, userEmail, sessionValidityCheck],
- );
-
- if (!userEmail) {
- return <LoadingIndicator />;
- }
-
- if (!keyAttributes && !srpAttributes) {
- return <LoadingIndicator />;
- }
-
- if (passkeyVerificationData) {
- // 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 />;
- }
-
- return (
- <VerifyingPasskey
- email={userEmail}
- passkeySessionID={passkeyVerificationData.passkeySessionID}
- onRetry={() =>
- openPasskeyVerificationURL(passkeyVerificationData)
- }
- {...{ logout, showMiniDialog }}
- />
- );
- }
-
- return (
- <AccountsPageContents>
- <PasswordHeader caption={userEmail} />
- <VerifyMasterPasswordForm
- {...{
- userEmail,
- keyAttributes,
- getKeyAttributes,
- srpAttributes,
- }}
- submitButtonTitle={t("sign_in")}
- onVerify={handleVerifyMasterPassword}
- />
- <AccountsPageFooterWithHost>
- <LinkButton onClick={() => router.push("/recover")}>
- {t("forgot_password")}
- </LinkButton>
- <LinkButton onClick={logout}>{t("change_email")}</LinkButton>
- </AccountsPageFooterWithHost>
- <SecondFactorChoice {...secondFactorChoiceProps} />
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/generate.tsx b/web/packages/accounts/pages/generate.tsx
deleted file mode 100644
index 8e7ab6e0f3..0000000000
--- a/web/packages/accounts/pages/generate.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { Divider } from "@mui/material";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import { RecoveryKey } from "ente-accounts/components/RecoveryKey";
-import {
- savedJustSignedUp,
- savedOriginalKeyAttributes,
- savedPartialLocalUser,
- saveJustSignedUp,
-} from "ente-accounts/services/accounts-db";
-import { appHomeRoute } from "ente-accounts/services/redirect";
-import {
- generateSRPSetupAttributes,
- getAndSaveSRPAttributes,
- setupSRP,
-} from "ente-accounts/services/srp";
-import {
- generateAndSaveInteractiveKeyAttributes,
- generateKeysAndAttributes,
- putUserKeyAttributes,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { useBaseContext } from "ente-base/context";
-import { deriveKeyInsufficientMemoryErrorMessage } from "ente-base/crypto/types";
-import log from "ente-base/log";
-import {
- haveMasterKeyInSession,
- saveMasterKeyInSessionAndSafeStore,
-} from "ente-base/session";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useState } from "react";
-import {
- NewPasswordForm,
- type NewPasswordFormProps,
-} from "../components/NewPasswordForm";
-
-const Page: React.FC = () => {
- const { logout, showMiniDialog } = useBaseContext();
-
- const [userEmail, setUserEmail] = useState("");
- const [openRecoveryKey, setOpenRecoveryKey] = useState(false);
-
- const router = useRouter();
-
- useEffect(() => {
- const user = savedPartialLocalUser();
- if (!user?.email || !user.token) {
- void router.replace("/");
- } else if (haveMasterKeyInSession()) {
- if (savedJustSignedUp()) {
- setOpenRecoveryKey(true);
- } else {
- void router.replace(appHomeRoute);
- }
- } else if (savedOriginalKeyAttributes()) {
- void router.replace("/credentials");
- } else {
- setUserEmail(user.email);
- }
- }, [router]);
-
- const handleSubmit: NewPasswordFormProps["onSubmit"] = useCallback(
- async (password, setPasswordsFieldError) => {
- try {
- const { masterKey, kek, keyAttributes } =
- await generateKeysAndAttributes(password);
- await putUserKeyAttributes(keyAttributes);
- await setupSRP(await generateSRPSetupAttributes(kek));
- await getAndSaveSRPAttributes(userEmail);
- await generateAndSaveInteractiveKeyAttributes(
- password,
- keyAttributes,
- masterKey,
- );
- await saveMasterKeyInSessionAndSafeStore(masterKey);
- saveJustSignedUp();
- setOpenRecoveryKey(true);
- } catch (e) {
- log.error("Could not generate key attributes from password", e);
- setPasswordsFieldError(
- e instanceof Error &&
- e.message == deriveKeyInsufficientMemoryErrorMessage
- ? t("password_generation_failed")
- : t("generic_error"),
- );
- }
- },
- [userEmail],
- );
-
- return (
- <>
- {openRecoveryKey ? (
- <RecoveryKey
- open={openRecoveryKey}
- onClose={() => void router.push(appHomeRoute)}
- showMiniDialog={showMiniDialog}
- />
- ) : userEmail ? (
- <AccountsPageContents>
- <AccountsPageTitle>{t("set_password")}</AccountsPageTitle>
- <NewPasswordForm
- userEmail={userEmail}
- submitButtonTitle={t("set_password")}
- onSubmit={handleSubmit}
- />
- <Divider sx={{ mt: 1 }} />
- <AccountsPageFooter>
- <LinkButton onClick={logout}>{t("go_back")}</LinkButton>
- </AccountsPageFooter>
- </AccountsPageContents>
- ) : (
- <LoadingIndicator />
- )}
- </>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/login.tsx b/web/packages/accounts/pages/login.tsx
deleted file mode 100644
index 5469f3fc3e..0000000000
--- a/web/packages/accounts/pages/login.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { AccountsPageContents } from "ente-accounts/components/layouts/centered-paper";
-import { LoginContents } from "ente-accounts/components/LoginContents";
-import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { customAPIHost } from "ente-base/origins";
-import { useRouter } from "next/router";
-import React, { useCallback, useEffect, useState } from "react";
-
-const Page: React.FC = () => {
- const [loading, setLoading] = useState(true);
- const [host, setHost] = useState<string | undefined>(undefined);
-
- const router = useRouter();
-
- useEffect(() => {
- void customAPIHost().then(setHost);
- if (savedPartialLocalUser()?.email) void router.replace("/verify");
- setLoading(false);
- }, [router]);
-
- const onSignUp = useCallback(() => void router.push("/signup"), [router]);
-
- return loading ? (
- <LoadingIndicator />
- ) : (
- <AccountsPageContents>
- <LoginContents {...{ host, onSignUp }} />
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/passkeys/finish.tsx b/web/packages/accounts/pages/passkeys/finish.tsx
deleted file mode 100644
index 3b34c8a0aa..0000000000
--- a/web/packages/accounts/pages/passkeys/finish.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import {
- saveKeyAttributes,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import { clearInflightPasskeySessionID } from "ente-accounts/services/passkey";
-import { unstashRedirect } from "ente-accounts/services/redirect";
-import {
- resetSavedLocalUserTokens,
- TwoFactorAuthorizationResponse,
-} from "ente-accounts/services/user";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { fromB64URLSafeNoPadding } from "ente-base/crypto";
-import log from "ente-base/log";
-import { nullToUndefined } from "ente-utils/transform";
-import { useRouter } from "next/router";
-import React, { useEffect } from "react";
-
-// 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(() => {
- const searchParams = new URLSearchParams(window.location.search);
- const passkeySessionID = searchParams.get("passkeySessionID");
- const response = searchParams.get("response");
- if (!passkeySessionID || !response) return;
-
- void saveQueryCredentialsAndNavigateTo(passkeySessionID, response).then(
- (slug) => router.replace(slug),
- );
- }, [router]);
-
- return <LoadingIndicator />;
-};
-
-export default Page;
-
-const saveQueryCredentialsAndNavigateTo = async (
- passkeySessionID: string,
- response: string,
-) => {
- const inflightPasskeySessionID = nullToUndefined(
- sessionStorage.getItem("inflightPasskeySessionID"),
- );
-
- if (
- !inflightPasskeySessionID ||
- passkeySessionID != inflightPasskeySessionID
- ) {
- // 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}`,
- );
- return "/";
- }
-
- clearInflightPasskeySessionID();
-
- const decodedResponse = TwoFactorAuthorizationResponse.parse(
- JSON.parse(
- new TextDecoder().decode(await fromB64URLSafeNoPadding(response)),
- ),
- );
-
- const { id, keyAttributes, encryptedToken } = decodedResponse;
-
- await resetSavedLocalUserTokens(id, encryptedToken);
- updateSavedLocalUser({ passkeySessionID: undefined });
- saveKeyAttributes(keyAttributes);
-
- return unstashRedirect() ?? "/credentials";
-};
diff --git a/web/packages/accounts/pages/recover.tsx b/web/packages/accounts/pages/recover.tsx
deleted file mode 100644
index 0ee6fb8a2b..0000000000
--- a/web/packages/accounts/pages/recover.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import {
- savedKeyAttributes,
- savedPartialLocalUser,
-} from "ente-accounts/services/accounts-db";
-import { recoveryKeyFromMnemonic } from "ente-accounts/services/recovery-key";
-import { appHomeRoute, stashRedirect } from "ente-accounts/services/redirect";
-import type { KeyAttributes } from "ente-accounts/services/user";
-import {
- decryptAndStoreTokenIfNeeded,
- sendOTT,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import {
- SingleInputForm,
- type SingleInputFormProps,
-} from "ente-base/components/SingleInputForm";
-import { useBaseContext } from "ente-base/context";
-import { decryptBox } from "ente-base/crypto";
-import log from "ente-base/log";
-import {
- haveMasterKeyInSession,
- saveMasterKeyInSessionAndSafeStore,
-} from "ente-base/session";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useState } from "react";
-
-const Page: React.FC = () => {
- const { showMiniDialog } = useBaseContext();
-
- const [keyAttributes, setKeyAttributes] = useState<
- KeyAttributes | undefined
- >(undefined);
-
- const router = useRouter();
-
- useEffect(() => {
- void (async () => {
- const user = savedPartialLocalUser();
- if (!user?.email) {
- await router.replace("/");
- return;
- }
-
- if (!user.encryptedToken && !user.token) {
- await sendOTT(user.email, undefined);
- stashRedirect("/recover");
- await router.replace("/verify");
- return;
- }
-
- const keyAttributes = savedKeyAttributes();
- if (!keyAttributes) {
- await router.replace("/generate");
- } else if (haveMasterKeyInSession()) {
- await router.replace(appHomeRoute);
- } else {
- setKeyAttributes(keyAttributes);
- }
- })();
- }, [router]);
-
- const handleSubmit: SingleInputFormProps["onSubmit"] = useCallback(
- async (recoveryKeyMnemonic: string, setFieldError) => {
- try {
- const keyAttr = keyAttributes!;
- const masterKey = await decryptBox(
- {
- encryptedData:
- keyAttr.masterKeyEncryptedWithRecoveryKey!,
- nonce: keyAttr.masterKeyDecryptionNonce!,
- },
- await recoveryKeyFromMnemonic(recoveryKeyMnemonic),
- );
- await saveMasterKeyInSessionAndSafeStore(masterKey);
- await decryptAndStoreTokenIfNeeded(keyAttr, masterKey);
-
- void router.push("/change-password?op=reset");
- } catch (e) {
- log.error("Master key recovery failed", e);
- setFieldError(t("incorrect_recovery_key"));
- }
- },
- [router, keyAttributes],
- );
-
- const showNoRecoveryKeyMessage = useCallback(() => {
- showMiniDialog({
- title: t("sorry"),
- message: t("no_recovery_key_message"),
- continue: { color: "secondary" },
- cancel: false,
- });
- }, [showMiniDialog]);
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>{t("recover_account")}</AccountsPageTitle>
- <SingleInputForm
- autoComplete="off"
- label={t("recovery_key")}
- submitButtonTitle={t("recover")}
- onSubmit={handleSubmit}
- />
- <AccountsPageFooter>
- <LinkButton onClick={showNoRecoveryKeyMessage}>
- {t("no_recovery_key_title")}
- </LinkButton>
- <LinkButton onClick={router.back}>{t("go_back")}</LinkButton>
- </AccountsPageFooter>
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/signup.tsx b/web/packages/accounts/pages/signup.tsx
deleted file mode 100644
index dfea7a50c7..0000000000
--- a/web/packages/accounts/pages/signup.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { AccountsPageContents } from "ente-accounts/components/layouts/centered-paper";
-import { SignUpContents } from "ente-accounts/components/SignUpContents";
-import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import { customAPIHost } from "ente-base/origins";
-import { useRouter } from "next/router";
-import React, { useCallback, useEffect, useState } from "react";
-
-const Page: React.FC = () => {
- const [loading, setLoading] = useState(true);
- const [host, setHost] = useState<string | undefined>(undefined);
-
- const router = useRouter();
-
- useEffect(() => {
- void customAPIHost().then(setHost);
- if (savedPartialLocalUser()?.email) void router.replace("/verify");
- setLoading(false);
- }, [router]);
-
- const onLogin = useCallback(() => void router.push("/login"), [router]);
-
- return loading ? (
- <LoadingIndicator />
- ) : (
- <AccountsPageContents>
- <SignUpContents {...{ router, host, onLogin }} />
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/two-factor/recover.tsx b/web/packages/accounts/pages/two-factor/recover.tsx
deleted file mode 100644
index e84ef3bec7..0000000000
--- a/web/packages/accounts/pages/two-factor/recover.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { Link } from "@mui/material";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";
-import {
- getRecoverTwoFactor,
- recoverTwoFactorFinish,
- type TwoFactorRecoveryResponse,
- type TwoFactorType,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
-import {
- SingleInputForm,
- type SingleInputFormProps,
-} from "ente-base/components/SingleInputForm";
-import { useBaseContext } from "ente-base/context";
-import { isHTTP4xxError, isHTTPErrorWithStatus } from "ente-base/http";
-import log from "ente-base/log";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import { Trans } from "react-i18next";
-
-export interface RecoverPageProps {
- twoFactorType: TwoFactorType;
-}
-
-const Page: React.FC<RecoverPageProps> = ({ twoFactorType }) => {
- const { logout, showMiniDialog, onGenericError } = useBaseContext();
-
- const [sessionID, setSessionID] = useState<string | undefined>(undefined);
- const [recoveryResponse, setRecoveryResponse] = useState<
- TwoFactorRecoveryResponse | undefined
- >(undefined);
-
- const router = useRouter();
-
- const showContactSupportDialog = useCallback(
- (dialogContinue?: MiniDialogAttributes["continue"]) =>
- showMiniDialog({
- title: t("contact_support"),
- message: (
- <Trans
- i18nKey={"no_two_factor_recovery_key_message"}
- components={{
- a: <Link href="mailto:[email protected]" />,
- }}
- values={{ emailID: "[email protected]" }}
- />
- ),
- continue: { color: "secondary", ...(dialogContinue ?? {}) },
- cancel: false,
- }),
- [showMiniDialog],
- );
-
- useEffect(() => {
- void (async () => {
- const user = savedPartialLocalUser();
- const sessionID =
- twoFactorType == "passkey"
- ? user?.passkeySessionID
- : user?.twoFactorSessionID;
- if (!user?.email || !sessionID) {
- await router.replace("/");
- } else if (user.encryptedToken || user.token) {
- await router.replace("/generate");
- } else {
- setSessionID(sessionID);
- try {
- setRecoveryResponse(
- await getRecoverTwoFactor(twoFactorType, sessionID),
- );
- } catch (e) {
- log.error("Second factor recovery page setup failed", e);
- if (isHTTPErrorWithStatus(e, 404)) {
- logout();
- } else if (isHTTP4xxError(e)) {
- showContactSupportDialog({ action: router.back });
- } else {
- onGenericError(e);
- }
- }
- }
- })();
- }, [
- twoFactorType,
- logout,
- showContactSupportDialog,
- onGenericError,
- router,
- ]);
-
- const handleSubmit: SingleInputFormProps["onSubmit"] | undefined = useMemo(
- () =>
- sessionID && recoveryResponse
- ? (recoveryKeyMnemonic, setFieldError) =>
- recoverTwoFactorFinish(
- twoFactorType,
- sessionID,
- recoveryResponse,
- recoveryKeyMnemonic,
- )
- .then(() => router.push("/credentials"))
- .catch((e: unknown) => {
- log.error("Second factor recovery failed", e);
- setFieldError(t("incorrect_recovery_key"));
- })
- : undefined,
- [twoFactorType, router, sessionID, recoveryResponse],
- );
-
- if (!handleSubmit) {
- return <LoadingIndicator />;
- }
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>{t("recover_two_factor")}</AccountsPageTitle>
- <SingleInputForm
- autoComplete="off"
- label={t("recovery_key")}
- submitButtonTitle={t("recover")}
- onSubmit={handleSubmit}
- />
- <AccountsPageFooter>
- <LinkButton onClick={() => showContactSupportDialog()}>
- {t("no_recovery_key_title")}
- </LinkButton>
- <LinkButton onClick={router.back}>{t("go_back")}</LinkButton>
- </AccountsPageFooter>
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/two-factor/setup.tsx b/web/packages/accounts/pages/two-factor/setup.tsx
deleted file mode 100644
index 59fc64305f..0000000000
--- a/web/packages/accounts/pages/two-factor/setup.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import { Paper, Stack, styled, Typography } from "@mui/material";
-import { CodeBlock } from "ente-accounts/components/CodeBlock";
-import { Verify2FACodeForm } from "ente-accounts/components/Verify2FACodeForm";
-import { appHomeRoute } from "ente-accounts/services/redirect";
-import type { TwoFactorSecret } from "ente-accounts/services/user";
-import {
- setupTwoFactor,
- setupTwoFactorFinish,
-} from "ente-accounts/services/user";
-import { CenteredFill } from "ente-base/components/containers";
-import { EnteLogo } from "ente-base/components/EnteLogo";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import { NavbarBase } from "ente-base/components/Navbar";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import React, { useEffect, useState } from "react";
-
-const Page: React.FC = () => {
- const [twoFactorSecret, setTwoFactorSecret] = useState<
- TwoFactorSecret | undefined
- >();
-
- const router = useRouter();
-
- useEffect(() => {
- void setupTwoFactor().then(setTwoFactorSecret);
- }, []);
-
- const handleSubmit = async (otp: string) => {
- await setupTwoFactorFinish(twoFactorSecret!.secretCode, otp);
- await router.push(appHomeRoute);
- };
-
- return (
- <Stack
- sx={[
- { minHeight: "100svh", bgcolor: "secondary.main" },
- (theme) =>
- theme.applyStyles("dark", {
- bgcolor: "background.default",
- }),
- ]}
- >
- <NavbarBase
- sx={{
- boxShadow: "none",
- borderBottom: "none",
- bgcolor: "transparent",
- }}
- >
- <EnteLogo />
- </NavbarBase>
- <CenteredFill>
- <ContentsPaper>
- <Typography variant="h5" sx={{ textAlign: "center" }}>
- {t("two_factor")}
- </Typography>
- <Instructions twoFactorSecret={twoFactorSecret} />
- <Verify2FACodeForm
- onSubmit={handleSubmit}
- submitButtonText={t("enable")}
- />
- <Stack sx={{ alignItems: "center" }}>
- <FocusVisibleButton
- variant="text"
- onClick={router.back}
- >
- {t("go_back")}
- </FocusVisibleButton>
- </Stack>
- </ContentsPaper>
- </CenteredFill>
- </Stack>
- );
-};
-
-export default Page;
-
-const ContentsPaper = styled(Paper)(({ theme }) => ({
- marginBlock: theme.spacing(2),
- padding: theme.spacing(5, 3),
- [theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },
- // This width fits the QR code secret in one line under default settings.
- width: "min(440px, 85vw)",
- minHeight: "375px",
- display: "flex",
- flexDirection: "column",
- gap: theme.spacing(4),
- boxShadow: "none",
- borderRadius: "20px",
-}));
-
-interface InstructionsProps {
- twoFactorSecret: TwoFactorSecret | undefined;
-}
-
-const Instructions: React.FC<InstructionsProps> = ({ twoFactorSecret }) => {
- const [setupMode, setSetupMode] = useState<"qr" | "manual">("qr");
-
- return (
- <Stack sx={{ gap: 3, alignItems: "center" }}>
- {setupMode == "qr" ? (
- <SetupQRMode
- twoFactorSecret={twoFactorSecret}
- onChangeMode={() => setSetupMode("manual")}
- />
- ) : (
- <SetupManualMode
- twoFactorSecret={twoFactorSecret}
- onChangeMode={() => setSetupMode("qr")}
- />
- )}
- </Stack>
- );
-};
-
-interface SetupManualModeProps {
- twoFactorSecret: TwoFactorSecret | undefined;
- onChangeMode: () => void;
-}
-
-const SetupManualMode: React.FC<SetupManualModeProps> = ({
- twoFactorSecret,
- onChangeMode,
-}) => (
- <>
- <Typography sx={{ color: "text.muted", textAlign: "center", px: 2 }}>
- {t("two_factor_manual_entry_message")}
- </Typography>
- <CodeBlock code={twoFactorSecret?.secretCode} />
- <LinkButton onClick={onChangeMode}>{t("scan_qr_title")}</LinkButton>
- </>
-);
-
-interface SetupQRModeProps {
- twoFactorSecret?: TwoFactorSecret;
- onChangeMode: () => void;
-}
-
-const SetupQRMode: React.FC<SetupQRModeProps> = ({
- twoFactorSecret,
- onChangeMode,
-}) => (
- <>
- <Typography sx={{ color: "text.muted", textAlign: "center" }}>
- {t("two_factor_qr_help")}
- </Typography>
- {twoFactorSecret ? (
- <QRCode src={`data:image/png;base64,${twoFactorSecret.qrCode}`} />
- ) : (
- <LoadingQRCode>
- <ActivityIndicator />
- </LoadingQRCode>
- )}
- <LinkButton onClick={onChangeMode}>
- {t("two_factor_manual_entry_title")}
- </LinkButton>
- </>
-);
-
-const QRCode = styled("img")(`
- width: 200px;
- height: 200px;
-`);
-
-const LoadingQRCode = styled(Stack)(
- ({ theme }) => `
- width: 200px;
- height: 200px;
- border: 1px solid ${theme.vars.palette.stroke.muted};
- align-items: center;
- justify-content: center;
- `,
-);
diff --git a/web/packages/accounts/pages/two-factor/verify.tsx b/web/packages/accounts/pages/two-factor/verify.tsx
deleted file mode 100644
index f2b1f920e7..0000000000
--- a/web/packages/accounts/pages/two-factor/verify.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { Verify2FACodeForm } from "ente-accounts/components/Verify2FACodeForm";
-import {
- savedPartialLocalUser,
- saveKeyAttributes,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import {
- resetSavedLocalUserTokens,
- verifyTwoFactor,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { useBaseContext } from "ente-base/context";
-import { isHTTPErrorWithStatus } from "ente-base/http";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useState } from "react";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "../../components/layouts/centered-paper";
-import { unstashRedirect } from "../../services/redirect";
-
-const Page: React.FC = () => {
- const { logout } = useBaseContext();
-
- const [twoFactorSessionID, setTwoFactorSessionID] = useState("");
-
- const router = useRouter();
-
- useEffect(() => {
- const user = savedPartialLocalUser();
- if (!user?.email || !user.twoFactorSessionID) {
- void router.replace("/");
- } else if (
- !user.isTwoFactorEnabled &&
- (user.encryptedToken || user.token)
- ) {
- void router.replace("/credentials");
- } else {
- setTwoFactorSessionID(user.twoFactorSessionID);
- }
- }, [router]);
-
- const handleSubmit = useCallback(
- async (otp: string) => {
- try {
- const { keyAttributes, encryptedToken, id } =
- await verifyTwoFactor(otp, twoFactorSessionID);
- await resetSavedLocalUserTokens(id, encryptedToken);
- updateSavedLocalUser({ twoFactorSessionID: undefined });
- saveKeyAttributes(keyAttributes);
- await router.push(unstashRedirect() ?? "/credentials");
- } catch (e) {
- if (isHTTPErrorWithStatus(e, 404)) {
- logout();
- } else {
- throw e;
- }
- }
- },
- [logout, router, twoFactorSessionID],
- );
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>{t("two_factor")}</AccountsPageTitle>
- <Verify2FACodeForm
- onSubmit={handleSubmit}
- submitButtonText={t("verify")}
- />
- <AccountsPageFooter>
- <LinkButton onClick={() => router.push("/two-factor/recover")}>
- {t("lost_2fa_device")}
- </LinkButton>
- <LinkButton onClick={logout}>{t("change_email")}</LinkButton>
- </AccountsPageFooter>
- </AccountsPageContents>
- );
-};
-
-export default Page;
diff --git a/web/packages/accounts/pages/verify.tsx b/web/packages/accounts/pages/verify.tsx
deleted file mode 100644
index cb6b367757..0000000000
--- a/web/packages/accounts/pages/verify.tsx
+++ /dev/null
@@ -1,262 +0,0 @@
-import { Box, Typography } from "@mui/material";
-import {
- AccountsPageContents,
- AccountsPageFooter,
- AccountsPageTitle,
-} from "ente-accounts/components/layouts/centered-paper";
-import { VerifyingPasskey } from "ente-accounts/components/LoginComponents";
-import { SecondFactorChoice } from "ente-accounts/components/SecondFactorChoice";
-import { useSecondFactorChoiceIfNeeded } from "ente-accounts/components/utils/second-factor-choice";
-import {
- replaceSavedLocalUser,
- savedKeyAttributes,
- savedOriginalKeyAttributes,
- savedPartialLocalUser,
- savedSRPAttributes,
- saveIsFirstLogin,
- saveKeyAttributes,
- saveOriginalKeyAttributes,
- unstashAfterUseSRPSetupAttributes,
- unstashReferralSource,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import {
- openPasskeyVerificationURL,
- passkeyVerificationRedirectURL,
-} from "ente-accounts/services/passkey";
-import {
- stashedRedirect,
- unstashRedirect,
-} from "ente-accounts/services/redirect";
-import {
- getAndSaveSRPAttributes,
- getSRPAttributes,
- setupSRP,
-} from "ente-accounts/services/srp";
-import {
- putUserKeyAttributes,
- sendOTT,
- verifyEmail,
-} from "ente-accounts/services/user";
-import { LinkButton } from "ente-base/components/LinkButton";
-import { LoadingIndicator } from "ente-base/components/loaders";
-import {
- SingleInputForm,
- type SingleInputFormProps,
-} from "ente-base/components/SingleInputForm";
-import { useBaseContext } from "ente-base/context";
-import { isHTTPErrorWithStatus } from "ente-base/http";
-import log from "ente-base/log";
-import { clearSessionStorage } from "ente-base/session";
-import { saveAuthToken } from "ente-base/token";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useState } from "react";
-import { Trans } from "react-i18next";
-
-const Page: React.FC = () => {
- const { logout, showMiniDialog } = useBaseContext();
-
- const [email, setEmail] = useState("");
- const [resend, setResend] = useState<"enable" | "sending" | "sent">(
- "enable",
- );
- const [passkeyVerificationData, setPasskeyVerificationData] = useState<
- { passkeySessionID: string; url: string } | undefined
- >();
-
- const {
- secondFactorChoiceProps,
- userVerificationResultAfterResolvingSecondFactorChoice,
- } = useSecondFactorChoiceIfNeeded();
-
- const router = useRouter();
-
- useEffect(() => {
- void redirectionIfNeededOrEmail().then((redirectOrEmail) => {
- if (typeof redirectOrEmail == "string") {
- void router.replace(redirectOrEmail);
- } else {
- setEmail(redirectOrEmail.email);
- }
- });
- }, [router]);
-
- const onSubmit: SingleInputFormProps["onSubmit"] = async (
- ott,
- setFieldError,
- ) => {
- try {
- const referralSource = unstashReferralSource();
- const cleanedReferral = referralSource
- ? `web:${referralSource}`
- : undefined;
- const {
- keyAttributes,
- encryptedToken,
- token,
- id,
- twoFactorSessionID,
- passkeySessionID,
- accountsUrl,
- } = await userVerificationResultAfterResolvingSecondFactorChoice(
- await verifyEmail(email, ott, cleanedReferral),
- );
-
- if (passkeySessionID) {
- updateSavedLocalUser({ passkeySessionID });
- saveIsFirstLogin();
- const url = passkeyVerificationRedirectURL(
- accountsUrl!,
- passkeySessionID,
- );
- setPasskeyVerificationData({ passkeySessionID, url });
- openPasskeyVerificationURL({ passkeySessionID, url });
- } else if (twoFactorSessionID) {
- updateSavedLocalUser({
- isTwoFactorEnabled: true,
- twoFactorSessionID,
- });
- saveIsFirstLogin();
- void router.push("/two-factor/verify");
- } else {
- if (token) await saveAuthToken(token);
- replaceSavedLocalUser({ id, email, token, encryptedToken });
- if (keyAttributes) {
- saveKeyAttributes(keyAttributes);
- saveOriginalKeyAttributes(keyAttributes);
- } else {
- const originalKeyAttributes = savedOriginalKeyAttributes();
- if (originalKeyAttributes) {
- await putUserKeyAttributes(originalKeyAttributes);
- }
- await unstashAfterUseSRPSetupAttributes(setupSRP);
- await getAndSaveSRPAttributes(email);
- }
- saveIsFirstLogin();
- if (keyAttributes) {
- clearSessionStorage();
- void router.push(unstashRedirect() ?? "/credentials");
- } else {
- void router.push(unstashRedirect() ?? "/generate");
- }
- }
- } catch (e) {
- if (isHTTPErrorWithStatus(e, 401)) {
- setFieldError(t("invalid_code_error"));
- } else if (isHTTPErrorWithStatus(e, 410)) {
- setFieldError(t("expired_code_error"));
- } else {
- log.error("OTT verification failed", e);
- throw e;
- }
- }
- };
-
- const resendEmail = useCallback(async () => {
- setResend("sending");
- await sendOTT(email, undefined);
- setResend("sent");
- setTimeout(() => setResend("enable"), 3000);
- }, [email]);
-
- if (!email) {
- return <LoadingIndicator />;
- }
-
- if (passkeyVerificationData) {
- // 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 />;
- }
-
- return (
- <VerifyingPasskey
- email={email}
- passkeySessionID={passkeyVerificationData.passkeySessionID}
- onRetry={() =>
- openPasskeyVerificationURL(passkeyVerificationData)
- }
- {...{ logout, showMiniDialog }}
- />
- );
- }
-
- return (
- <AccountsPageContents>
- <AccountsPageTitle>
- <Trans
- i18nKey="email_sent"
- components={{
- a: (
- <Box
- component={"span"}
- sx={{
- color: "text.muted",
- wordBreak: "break-word",
- }}
- />
- ),
- }}
- values={{ email }}
- />
- </AccountsPageTitle>
-
- <Typography variant="small" sx={{ color: "text.muted", mb: 2 }}>
- {t("check_inbox_hint")}
- </Typography>
- <SingleInputForm
- autoComplete="one-time-code"
- label={t("verification_code")}
- submitButtonTitle={t("verify")}
- onSubmit={onSubmit}
- />
-
- <AccountsPageFooter>
- {resend == "enable" && (
- <LinkButton onClick={resendEmail}>
- {t("resend_code")}
- </LinkButton>
- )}
- {resend == "sending" && <span>{t("status_sending")}</span>}
- {resend == "sent" && <span>{t("status_sent")}</span>}
- <LinkButton onClick={logout}>{t("change_email")}</LinkButton>
- </AccountsPageFooter>
-
- <SecondFactorChoice {...secondFactorChoiceProps} />
- </AccountsPageContents>
- );
-};
-
-export default Page;
-
-const redirectionIfNeededOrEmail = async () => {
- const user = savedPartialLocalUser();
-
- const email = user?.email;
- if (!email) {
- return "/";
- }
-
- if (savedKeyAttributes() && (user.token || user.encryptedToken)) {
- return "/credentials";
- }
-
- if (stashedRedirect() == "/recover") return { email };
-
- const srpAttributes = savedSRPAttributes();
- if (srpAttributes && !srpAttributes.isEmailMFAEnabled) {
- // 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";
- }
- }
-
- return { email };
-};
diff --git a/web/packages/accounts/services/accounts-db.ts b/web/packages/accounts/services/accounts-db.ts
deleted file mode 100644
index af92957c0b..0000000000
--- a/web/packages/accounts/services/accounts-db.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-// 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";
-import { z } from "zod";
-import {
- RemoteSRPAttributes,
- SRPSetupAttributes,
- type SRPAttributes,
-} from "./srp";
-import {
- RemoteKeyAttributes,
- type KeyAttributes,
- type LocalUser,
-} from "./user";
-
-export interface PartialLocalUser {
- id?: number;
- email?: string;
- token?: string;
- encryptedToken?: string;
- isTwoFactorEnabled?: boolean;
- twoFactorSessionID?: string;
- passkeySessionID?: string;
-}
-
-const PartialLocalUser = z.object({
- id: z.number().nullish().transform(nullToUndefined),
- email: z.string().nullish().transform(nullToUndefined),
- token: z.string().nullish().transform(nullToUndefined),
- encryptedToken: z.string().nullish().transform(nullToUndefined),
- isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
- twoFactorSessionID: z.string().nullish().transform(nullToUndefined),
- passkeySessionID: z.string().nullish().transform(nullToUndefined),
-});
-
-const LocalUser = z.object({
- id: z.number(),
- email: z.string(),
- token: z.string(),
- isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
-});
-
-export const savedPartialLocalUser = (): PartialLocalUser | undefined => {
- const jsonString = localStorage.getItem("user");
- if (!jsonString) return undefined;
- return PartialLocalUser.parse(JSON.parse(jsonString));
-};
-
-export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>
- localStorage.setItem("user", JSON.stringify(partialLocalUser));
-
-export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>
- replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });
-
-export const savedLocalUser = (): LocalUser | undefined => {
- const jsonString = localStorage.getItem("user");
- if (!jsonString) return undefined;
- // 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;
-};
-
-export const isLocalStorageAndIndexedDBMismatch = async () =>
- savedPartialLocalUser()?.token && !(await savedAuthToken());
-
-export const savedKeyAttributes = (): KeyAttributes | undefined => {
- const jsonString = localStorage.getItem("keyAttributes");
- if (!jsonString) return undefined;
- return RemoteKeyAttributes.parse(JSON.parse(jsonString));
-};
-
-export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>
- localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));
-
-// 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));
-};
-
-export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>
- localStorage.setItem(
- "originalKeyAttributes",
- JSON.stringify(keyAttributes),
- );
-
-export const savedSRPAttributes = (): SRPAttributes | undefined => {
- const jsonString = localStorage.getItem("srpAttributes");
- if (!jsonString) return undefined;
- return RemoteSRPAttributes.parse(JSON.parse(jsonString));
-};
-
-export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>
- localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));
-
-export const stashSRPSetupAttributes = (
- srpSetupAttributes: SRPSetupAttributes,
-) =>
- localStorage.setItem(
- "srpSetupAttributes",
- JSON.stringify(srpSetupAttributes),
- );
-
-export const unstashAfterUseSRPSetupAttributes = async (
- cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,
-) => {
- const jsonString = localStorage.getItem("srpSetupAttributes");
- if (!jsonString) return;
- const srpSetupAttributes = SRPSetupAttributes.parse(JSON.parse(jsonString));
- await cb(srpSetupAttributes);
- localStorage.removeItem("srpSetupAttributes");
-};
-
-// 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),
-});
-
-export const savedIsFirstLogin = () => {
- const jsonString = localStorage.getItem("isFirstLogin");
- if (!jsonString) return false;
- try {
- return z.boolean().parse(JSON.parse(jsonString));
- } catch {
- return (
- LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false
- );
- }
-};
-
-export const saveIsFirstLogin = () => {
- localStorage.setItem("isFirstLogin", JSON.stringify(true));
-};
-
-export const getAndClearIsFirstLogin = () => {
- const result = savedIsFirstLogin();
- localStorage.removeItem("isFirstLogin");
- return result;
-};
-
-export const savedJustSignedUp = () => {
- const jsonString = localStorage.getItem("justSignedUp");
- if (!jsonString) return false;
- try {
- return z.boolean().parse(JSON.parse(jsonString));
- } catch {
- return (
- LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false
- );
- }
-};
-
-export const saveJustSignedUp = () => {
- localStorage.setItem("justSignedUp", JSON.stringify(true));
-};
-
-export const getAndClearJustSignedUp = () => {
- const result = savedJustSignedUp();
- localStorage.removeItem("justSignedUp");
- return result;
-};
-
-export const stashReferralSource = (referralSource: string) => {
- localStorage.setItem("referralSource", referralSource);
-};
-
-export const unstashReferralSource = () => {
- const referralSource = localStorage.getItem("referralSource");
- if (!referralSource) return undefined;
- localStorage.removeItem("referralSource");
- return referralSource;
-};
diff --git a/web/packages/accounts/services/logout.ts b/web/packages/accounts/services/logout.ts
deleted file mode 100644
index 014ecab9f6..0000000000
--- a/web/packages/accounts/services/logout.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { clearBlobCaches } from "ente-base/blob-cache";
-import { clearKVDB } from "ente-base/kv";
-import { clearLocalStorage } from "ente-base/local-storage";
-import log from "ente-base/log";
-import { clearSessionStorage } from "ente-base/session";
-import { clearStashedRedirect } from "./redirect";
-import { remoteLogoutIfNeeded } from "./user";
-
-// 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);
-
- log.info("logout (account)");
-
- try {
- await remoteLogoutIfNeeded();
- } catch (e) {
- ignoreError("Remote", e);
- }
- try {
- clearStashedRedirect();
- } catch (e) {
- ignoreError("In-memory store", e);
- }
- try {
- clearSessionStorage();
- } catch (e) {
- ignoreError("Session storage", e);
- }
- try {
- clearLocalStorage();
- } catch (e) {
- ignoreError("Local storage", e);
- }
- try {
- await clearBlobCaches();
- } catch (e) {
- ignoreError("Blob cache", e);
- }
- try {
- await clearKVDB();
- } catch (e) {
- ignoreError("KV DB", e);
- }
-};
-
-// 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);
-
- log.info("logout (sweep)");
-
- try {
- clearLocalStorage();
- } catch (e) {
- ignoreError("Local storage", e);
- }
- try {
- await clearKVDB();
- } catch (e) {
- ignoreError("KV DB", e);
- }
-};
diff --git a/web/packages/accounts/services/passkey.ts b/web/packages/accounts/services/passkey.ts
deleted file mode 100644
index c2e478cdc4..0000000000
--- a/web/packages/accounts/services/passkey.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import {
- saveKeyAttributes,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import {
- resetSavedLocalUserTokens,
- TwoFactorAuthorizationResponse,
-} from "ente-accounts/services/user";
-import { clientPackageName, isDesktop } from "ente-base/app";
-import { encryptBox, generateKey } from "ente-base/crypto";
-import {
- authenticatedRequestHeaders,
- ensureOk,
- HTTPError,
- publicRequestHeaders,
-} from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { z } from "zod";
-import { getUserRecoveryKey } from "./recovery-key";
-import { unstashRedirect } from "./redirect";
-
-export const passkeyVerificationRedirectURL = (
- accountsURL: string,
- passkeySessionID: string,
-) => {
- // 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`;
- // 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` };
- const params = new URLSearchParams({
- clientPackage: clientPackageName,
- passkeySessionID,
- redirect,
- ...recoverOption,
- });
- return `${accountsURL}/passkeys/verify?${params.toString()}`;
-};
-
-interface OpenPasskeyVerificationURLOptions {
- passkeySessionID: string;
- url: string;
-}
-
-// Passkeys do not work on the desktop app's custom protocol.
-// Complete the flow in the system browser and return through a deep link.
-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;
-};
-
-export const openAccountsManagePasskeysPage = async () => {
- const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();
- if (!isPasskeyRecoveryEnabled) {
- const resetSecret = await generateKey();
- const { encryptedData, nonce } = await encryptBox(
- resetSecret,
- await getUserRecoveryKey(),
- );
- await configurePasskeyRecovery(resetSecret, encryptedData, nonce);
- }
-
- const { accountsToken: token, accountsUrl: accountsURL } =
- await getAccountsTokenAndURL();
- const params = new URLSearchParams({ token });
-
- window.open(`${accountsURL}/passkeys?${params.toString()}`);
-};
-
-const TwoFactorRecoveryStatus = z.object({
- isPasskeyRecoveryEnabled: z.boolean(),
-});
-
-export const getTwoFactorRecoveryStatus = async () => {
- const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return TwoFactorRecoveryStatus.parse(await res.json());
-};
-
-const configurePasskeyRecovery = async (
- secret: string,
- userSecretCipher: string,
- userSecretNonce: string,
-) =>
- ensureOk(
- await fetch(
- await apiURL("/users/two-factor/passkeys/configure-recovery"),
- {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({
- secret,
- userSecretCipher,
- userSecretNonce,
- }),
- },
- ),
- );
-
-const getAccountsTokenAndURL = async () => {
- const res = await fetch(await apiURL("/users/accounts-token"), {
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return z
- .object({ accountsUrl: z.string(), accountsToken: z.string() })
- .parse(await res.json());
-};
-
-export const passkeySessionExpiredErrorMessage = "Passkey session has expired";
-
-export const checkPasskeyVerificationStatus = async (
- sessionID: string,
-): Promise<TwoFactorAuthorizationResponse | undefined> => {
- const res = await fetch(
- await apiURL("/users/two-factor/passkeys/get-token", { sessionID }),
- { headers: publicRequestHeaders() },
- );
- if (!res.ok) {
- if (res.status == 404 || res.status == 410)
- throw new Error(passkeySessionExpiredErrorMessage);
- // 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());
-};
-
-export const saveCredentialsAndNavigateTo = async (
- response: TwoFactorAuthorizationResponse,
-) => {
- clearInflightPasskeySessionID();
-
- const { id, encryptedToken, keyAttributes } = response;
-
- await resetSavedLocalUserTokens(id, encryptedToken);
- updateSavedLocalUser({ passkeySessionID: undefined });
- saveKeyAttributes(keyAttributes);
-
- return unstashRedirect() ?? "/credentials";
-};
-
-export const clearInflightPasskeySessionID = () => {
- sessionStorage.removeItem("inflightPasskeySessionID");
-};
diff --git a/web/packages/accounts/services/recovery-key.ts b/web/packages/accounts/services/recovery-key.ts
deleted file mode 100644
index dff29f9006..0000000000
--- a/web/packages/accounts/services/recovery-key.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import * as bip39 from "bip39";
-import { savedKeyAttributes } from "ente-accounts/services/accounts-db";
-import {
- decryptBox,
- encryptBox,
- fromHex,
- generateKey,
- toHex,
-} from "ente-base/crypto";
-import { ensureMasterKeyFromSession } from "ente-base/session";
-import { saveKeyAttributes } from "./accounts-db";
-import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";
-
-// The wordlist must stay English since the BIP-39 library used by the mobile
-// clients only supports English.
-bip39.setDefaultWordlist("english");
-
-// 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()
- .split(" ")
- .map((part) => part.trim())
- .filter((part) => !!part)
- .join(" ");
-
- let recoveryKeyHex: string;
- if (trimmedInput.indexOf(" ") > 0) {
- if (trimmedInput.split(" ").length != 24) {
- throw new Error("recovery code should have 24 words");
- }
- recoveryKeyHex = bip39.mnemonicToEntropy(trimmedInput);
- } else {
- recoveryKeyHex = trimmedInput;
- }
-
- return fromHex(recoveryKeyHex);
-};
-
-export const recoveryKeyToMnemonic = async (recoveryKey: string) =>
- bip39.entropyToMnemonic(await toHex(recoveryKey));
-
-export const getUserRecoveryKey = async () => {
- const masterKey = await ensureMasterKeyFromSession();
-
- const keyAttributes = savedKeyAttributes()!;
- const { recoveryKeyEncryptedWithMasterKey, recoveryKeyDecryptionNonce } =
- keyAttributes;
-
- if (recoveryKeyEncryptedWithMasterKey && recoveryKeyDecryptionNonce) {
- return decryptBox(
- {
- encryptedData: recoveryKeyEncryptedWithMasterKey,
- nonce: recoveryKeyDecryptionNonce,
- },
- masterKey,
- );
- } else {
- return createNewRecoveryKey(masterKey, keyAttributes);
- }
-};
-
-// 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,
-) => {
- const recoveryKey = await generateKey();
- const encryptedMasterKey = await encryptBox(masterKey, recoveryKey);
- const encryptedRecoveryKey = await encryptBox(recoveryKey, masterKey);
-
- const recoveryKeyAttributes = {
- masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,
- masterKeyDecryptionNonce: encryptedMasterKey.nonce,
- recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,
- recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,
- };
-
- await putUserRecoveryKeyAttributes(recoveryKeyAttributes);
-
- saveKeyAttributes({ ...existingKeyAttributes, ...recoveryKeyAttributes });
-
- return recoveryKey;
-};
diff --git a/web/packages/accounts/services/redirect.ts b/web/packages/accounts/services/redirect.ts
deleted file mode 100644
index 878617c9cc..0000000000
--- a/web/packages/accounts/services/redirect.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { appName } from "ente-base/app";
-
-// 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: "/",
- embed: "/",
- share: "/",
- photos: "/gallery",
- ensu: "/",
- locker: "/locker",
- legacy: "/",
- space: "/app",
-}[appName];
-
-let _stashedRedirect: string | undefined;
-
-export const stashedRedirect = () => _stashedRedirect;
-
-export const stashRedirect = (r: string) => (_stashedRedirect = r);
-
-export const unstashRedirect = () => {
- const r = _stashedRedirect;
- _stashedRedirect = undefined;
- return r;
-};
-
-export const clearStashedRedirect = () => (_stashedRedirect = undefined);
diff --git a/web/packages/accounts/services/session.ts b/web/packages/accounts/services/session.ts
deleted file mode 100644
index faf4e5191b..0000000000
--- a/web/packages/accounts/services/session.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import {
- savedOriginalKeyAttributes,
- savedSRPAttributes,
-} from "ente-accounts/services/accounts-db";
-import type { KeyAttributes } from "ente-accounts/services/user";
-import { authenticatedRequestHeaders, HTTPError } from "ente-base/http";
-import log from "ente-base/log";
-import { apiURL } from "ente-base/origins";
-import { savedAuthToken } from "ente-base/token";
-import { nullToUndefined } from "ente-utils/transform";
-import { z } from "zod";
-import { getSRPAttributes, type SRPAttributes } from "./srp";
-import {
- ensureLocalUser,
- putUserKeyAttributes,
- RemoteKeyAttributes,
-} from "./user";
-
-type SessionValidity =
- | { status: "invalid" }
- | { status: "valid" }
- | {
- status: "validButPasswordChanged";
- updatedKeyAttributes: KeyAttributes;
- updatedSRPAttributes: SRPAttributes;
- };
-
-const SessionValidityResponse = z.object({
- hasSetKeys: z.boolean(),
- keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
-});
-
-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" };
- else throw new HTTPError(res);
- }
-
- const { keyAttributes } = SessionValidityResponse.parse(await res.json());
- if (keyAttributes) {
- const remoteKeyAttributes = keyAttributes;
-
- // We should have these values locally if we reach here.
- const email = ensureLocalUser().email;
- const localSRPAttributes = savedSRPAttributes()!;
-
- // 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 (remoteSRPAttributes) {
- // 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) {
- return {
- status: "validButPasswordChanged",
- updatedKeyAttributes: remoteKeyAttributes,
- updatedSRPAttributes: remoteSRPAttributes,
- };
- }
- }
- }
-
- return { status: "valid" };
-};
-
-export const isSessionInvalid = async (): Promise<boolean> => {
- const token = await savedAuthToken();
- if (!token) {
- return true;
- }
-
- try {
- const res = await fetch(await apiURL("/users/session-validity/v2"), {
- headers: await authenticatedRequestHeaders(),
- });
- if (!res.ok) {
- if (res.status == 401) return true;
- else throw new HTTPError(res);
- }
-
- const { hasSetKeys } = SessionValidityResponse.parse(await res.json());
- if (!hasSetKeys) {
- const originalKeyAttributes = savedOriginalKeyAttributes();
- if (originalKeyAttributes)
- await putUserKeyAttributes(originalKeyAttributes);
- }
- } catch (e) {
- log.warn("Failed to check session validity", e);
- // Returning true would log the user out, so do not do that on
- // potentially transient errors.
- return false;
- }
-
- return false;
-};
diff --git a/web/packages/accounts/services/sessions.ts b/web/packages/accounts/services/sessions.ts
deleted file mode 100644
index f0bec949bf..0000000000
--- a/web/packages/accounts/services/sessions.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { z } from "zod";
-
-const Session = z.object({
- token: z.string(),
- creationTime: z.number(),
- ip: z.string(),
- ua: z.string(),
- prettyUA: z.string(),
- lastUsedTime: z.number(),
-});
-
-export type Session = z.infer<typeof Session>;
-
-const SessionsResponse = z.object({ sessions: z.array(Session) });
-
-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());
- return sessions.sort((a, b) => b.lastUsedTime - a.lastUsedTime);
-};
-
-export const terminateSession = async (token: string): Promise<void> => {
- const url = await apiURL("/users/session");
- const res = await fetch(`${url}?token=${encodeURIComponent(token)}`, {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
-};
diff --git a/web/packages/accounts/services/srp.ts b/web/packages/accounts/services/srp.ts
deleted file mode 100644
index 0865b31765..0000000000
--- a/web/packages/accounts/services/srp.ts
+++ /dev/null
@@ -1,323 +0,0 @@
-import {
- deriveSubKeyBytes,
- generateDeriveKeySalt,
- toB64,
-} from "ente-base/crypto";
-import {
- authenticatedRequestHeaders,
- ensureOk,
- publicRequestHeaders,
-} from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { ensure } from "ente-utils/ensure";
-import { SRP, SrpClient } from "fast-srp-hap";
-import { v4 as uuidv4 } from "uuid";
-import { z } from "zod";
-import { saveSRPAttributes } from "./accounts-db";
-import {
- RemoteSRPVerificationResponse,
- type EmailOrSRPVerificationResponse,
-} from "./user";
-
-export interface SRPAttributes {
- srpUserID: string;
- srpSalt: string;
- memLimit: number;
- opsLimit: number;
- kekSalt: string;
- isEmailMFAEnabled: boolean;
-}
-
-export const RemoteSRPAttributes = z.object({
- srpUserID: z.string(),
- srpSalt: z.string(),
- memLimit: z.number(),
- opsLimit: z.number(),
- kekSalt: z.string(),
- isEmailMFAEnabled: z.boolean(),
-});
-
-export const getSRPAttributes = async (
- email: string,
-): Promise<SRPAttributes | undefined> => {
- const res = await fetch(await apiURL("/users/srp/attributes", { email }), {
- headers: publicRequestHeaders(),
- });
- if (res.status == 404) return undefined;
- ensureOk(res);
- return z.object({ attributes: RemoteSRPAttributes }).parse(await res.json())
- .attributes;
-};
-
-// 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(),
- srpVerifier: z.string(),
- loginSubKey: z.string(),
-});
-
-export type SRPSetupAttributes = z.infer<typeof SRPSetupAttributes>;
-
-export const generateSRPSetupAttributes = async (
- kek: string,
-): Promise<SRPSetupAttributes> => {
- const loginSubKey = await deriveSRPLoginSubKey(kek);
-
- // Museum schema requires this to be a UUID.
- const srpUserID = uuidv4();
- const srpSalt = await generateDeriveKeySalt();
-
- const srpVerifier = bufferToB64(
- SRP.computeVerifier(
- SRP.params["4096"],
- b64ToBuffer(srpSalt),
- Buffer.from(srpUserID),
- b64ToBuffer(loginSubKey),
- ),
- );
-
- return { srpUserID, srpSalt, srpVerifier, loginSubKey };
-};
-
-const deriveSRPLoginSubKey = async (kek: string) => {
- const kekSubKeyBytes = await deriveSubKeyBytes(kek, 32, 1, "loginctx");
- // 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));
-};
-
-const b64ToBuffer = (base64: string) => Buffer.from(base64, "base64");
-
-const bufferToB64 = (buffer: Buffer) => buffer.toString("base64");
-
-export const setupSRP = async (srpSetupAttributes: SRPSetupAttributes) =>
- srpSetupOrReconfigure(srpSetupAttributes, completeSRPSetup);
-
-type SRPSetupOrReconfigureExchangeCallback = ({
- setupID,
- srpM1,
-}: {
- setupID: string;
- srpM1: string;
-}) => Promise<{ srpM2: string }>;
-
-const srpSetupOrReconfigure = async (
- { srpSalt, srpUserID, srpVerifier, loginSubKey }: SRPSetupAttributes,
- exchangeCB: SRPSetupOrReconfigureExchangeCallback,
-) => {
- const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);
-
- const srpA = bufferToB64(srpClient.computeA());
-
- const { setupID, srpB } = await startSRPSetup({
- srpUserID,
- srpSalt,
- srpVerifier,
- srpA,
- });
-
- srpClient.setB(b64ToBuffer(srpB));
-
- const srpM1 = bufferToB64(srpClient.computeM1());
-
- const { srpM2 } = await exchangeCB({ srpM1, setupID });
-
- srpClient.checkM2(b64ToBuffer(srpM2));
-};
-
-const generateSRPClient = async (
- srpSalt: string,
- srpUserID: string,
- loginSubKey: string,
-) =>
- new Promise<SrpClient>((resolve, reject) => {
- SRP.genKey((err, clientKey) => {
- if (err) {
- reject(err);
- return;
- }
- resolve(
- new SrpClient(
- SRP.params["4096"],
- b64ToBuffer(srpSalt),
- Buffer.from(srpUserID),
- b64ToBuffer(loginSubKey),
- clientKey!,
- false,
- ),
- );
- });
- });
-
-interface SetupSRPRequest {
- srpUserID: string;
- srpSalt: string;
- srpVerifier: string;
- srpA: string;
-}
-
-const SetupSRPResponse = z.object({ setupID: z.string(), srpB: z.string() });
-
-type SetupSRPResponse = z.infer<typeof SetupSRPResponse>;
-
-const startSRPSetup = async (
- setupSRPRequest: SetupSRPRequest,
-): Promise<SetupSRPResponse> => {
- const res = await fetch(await apiURL("/users/srp/setup"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(setupSRPRequest),
- });
- ensureOk(res);
- return SetupSRPResponse.parse(await res.json());
-};
-
-interface CompleteSRPSetupRequest {
- setupID: string;
- srpM1: string;
-}
-
-const CompleteSRPSetupResponse = z.object({
- setupID: z.string(),
- srpM2: z.string(),
-});
-
-type CompleteSRPSetupResponse = z.infer<typeof CompleteSRPSetupResponse>;
-
-const completeSRPSetup = async (
- completeSRPSetupRequest: CompleteSRPSetupRequest,
-) => {
- const res = await fetch(await apiURL("/users/srp/complete"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(completeSRPSetupRequest),
- });
- ensureOk(res);
- return CompleteSRPSetupResponse.parse(await res.json());
-};
-
-export const getAndSaveSRPAttributes = async (userEmail: string) =>
- saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));
-
-export interface UpdatedKeyAttr {
- kekSalt: string;
- encryptedKey: string;
- keyDecryptionNonce: string;
- opsLimit: number;
- memLimit: number;
-}
-
-export const updateSRPAndKeyAttributes = (
- srpSetupAttributes: SRPSetupAttributes,
- updatedKeyAttr: UpdatedKeyAttr,
-) =>
- srpSetupOrReconfigure(srpSetupAttributes, ({ setupID, srpM1 }) =>
- updateSRPAndKeys({ setupID, srpM1, updatedKeyAttr }),
- );
-
-export interface UpdateSRPAndKeysRequest {
- setupID: string;
- srpM1: string;
- updatedKeyAttr: UpdatedKeyAttr;
- // Remote treats an omitted value as true, invalidating all other sessions
- // of the user.
- logOutOtherDevices?: boolean;
-}
-
-const UpdateSRPAndKeysResponse = z.object({
- srpM2: z.string(),
- setupID: z.string(),
-});
-
-type UpdateSRPAndKeysResponse = z.infer<typeof UpdateSRPAndKeysResponse>;
-
-const updateSRPAndKeys = async (
- updateSRPAndKeysRequest: UpdateSRPAndKeysRequest,
-): Promise<UpdateSRPAndKeysResponse> => {
- const res = await fetch(await apiURL("/users/srp/update"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(updateSRPAndKeysRequest),
- });
- ensureOk(res);
- return UpdateSRPAndKeysResponse.parse(await res.json());
-};
-
-export const srpVerificationUnauthorizedErrorMessage =
- "SRP verification failed (HTTP 401 Unauthorized)";
-
-export const verifySRP = async (
- { srpUserID, srpSalt }: SRPAttributes,
- kek: string,
-): Promise<EmailOrSRPVerificationResponse> => {
- const loginSubKey = await deriveSRPLoginSubKey(kek);
- const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);
-
- const { srpB, sessionID } = await createSRPSession({
- srpUserID,
- srpA: bufferToB64(srpClient.computeA()),
- });
-
- srpClient.setB(b64ToBuffer(srpB));
-
- const { srpM2, ...rest } = await verifySRPSession({
- sessionID,
- srpUserID,
- srpM1: bufferToB64(srpClient.computeM1()),
- });
-
- srpClient.checkM2(b64ToBuffer(srpM2));
-
- return rest;
-};
-
-interface CreateSRPSessionRequest {
- srpUserID: string;
- srpA: string;
-}
-
-const CreateSRPSessionResponse = z.object({
- sessionID: z.string(),
- srpB: z.string(),
-});
-
-type CreateSRPSessionResponse = z.infer<typeof CreateSRPSessionResponse>;
-
-const createSRPSession = async (
- createSRPSessionRequest: CreateSRPSessionRequest,
-): Promise<CreateSRPSessionResponse> => {
- const res = await fetch(await apiURL("/users/srp/create-session"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify(createSRPSessionRequest),
- });
- ensureOk(res);
- return CreateSRPSessionResponse.parse(await res.json());
-};
-
-interface VerifySRPSessionRequest {
- sessionID: string;
- srpUserID: string;
- srpM1: string;
-}
-
-type SRPVerificationResponse = z.infer<typeof RemoteSRPVerificationResponse>;
-
-const verifySRPSession = async (
- verifySRPSessionRequest: VerifySRPSessionRequest,
-): Promise<SRPVerificationResponse> => {
- const res = await fetch(await apiURL("/users/srp/verify-session"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify(verifySRPSessionRequest),
- });
- if (res.status == 401) {
- throw new Error(srpVerificationUnauthorizedErrorMessage);
- }
- ensureOk(res);
- return RemoteSRPVerificationResponse.parse(await res.json());
-};
diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.ts
deleted file mode 100644
index 71cb39d70f..0000000000
--- a/web/packages/accounts/services/user.ts
+++ /dev/null
@@ -1,523 +0,0 @@
-import {
- replaceSavedLocalUser,
- savedKeyAttributes,
- savedLocalUser,
- savedPartialLocalUser,
- saveKeyAttributes,
- updateSavedLocalUser,
-} from "ente-accounts/services/accounts-db";
-import {
- generateSRPSetupAttributes,
- getAndSaveSRPAttributes,
- updateSRPAndKeyAttributes,
- type UpdatedKeyAttr,
-} from "ente-accounts/services/srp";
-import {
- boxSealOpenBytes,
- decryptBox,
- deriveInteractiveKey,
- deriveSensitiveKey,
- encryptBox,
- generateKey,
- generateKeyPair,
- toB64URLSafe,
-} from "ente-base/crypto";
-import {
- authenticatedRequestHeaders,
- ensureOk,
- publicRequestHeaders,
-} from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { ensureMasterKeyFromSession } from "ente-base/session";
-import {
- removeAuthToken,
- saveAuthToken,
- savedAuthToken,
-} from "ente-base/token";
-import { nullToUndefined } from "ente-utils/transform";
-import { z } from "zod";
-import { clearInflightPasskeySessionID } from "./passkey";
-import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";
-
-export interface LocalUser {
- id: number;
- email: string;
- // 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;
- isTwoFactorEnabled?: boolean;
-}
-
-export const ensureLocalUser = (): LocalUser =>
- ensureExpectedLoggedInValue(savedLocalUser());
-
-export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {
- if (!t) throw new Error("Not logged in");
- return t;
-};
-
-export interface KeyAttributes {
- encryptedKey: string;
- keyDecryptionNonce: string;
- kekSalt: string;
- opsLimit: number;
- memLimit: number;
- publicKey: string;
- // 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;
- secretKeyDecryptionNonce: string;
- masterKeyEncryptedWithRecoveryKey?: string;
- masterKeyDecryptionNonce?: string;
- recoveryKeyEncryptedWithMasterKey?: string;
- recoveryKeyDecryptionNonce?: string;
-}
-
-export const RemoteKeyAttributes = z.object({
- kekSalt: z.string(),
- encryptedKey: z.string(),
- keyDecryptionNonce: z.string(),
- publicKey: z.string(),
- encryptedSecretKey: z.string(),
- secretKeyDecryptionNonce: z.string(),
- memLimit: z.number(),
- opsLimit: z.number(),
- masterKeyEncryptedWithRecoveryKey: z
- .string()
- .nullish()
- .transform(nullToUndefined),
- masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
- recoveryKeyEncryptedWithMasterKey: z
- .string()
- .nullish()
- .transform(nullToUndefined),
- recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),
-});
-
-export const ensureSavedKeyAttributes = (): KeyAttributes =>
- ensureExpectedLoggedInValue(savedKeyAttributes());
-
-export interface GenerateKeysAndAttributesResult {
- masterKey: string;
- kek: string;
- keyAttributes: KeyAttributes;
-}
-
-export async function generateKeysAndAttributes(
- password: string,
-): Promise<GenerateKeysAndAttributesResult> {
- const masterKey = await generateKey();
- const recoveryKey = await generateKey();
- const {
- key: kek,
- salt: kekSalt,
- opsLimit,
- memLimit,
- } = await deriveSensitiveKey(password);
-
- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
- await encryptBox(masterKey, kek);
- const {
- encryptedData: masterKeyEncryptedWithRecoveryKey,
- nonce: masterKeyDecryptionNonce,
- } = await encryptBox(masterKey, recoveryKey);
- const {
- encryptedData: recoveryKeyEncryptedWithMasterKey,
- nonce: recoveryKeyDecryptionNonce,
- } = await encryptBox(recoveryKey, masterKey);
-
- const keyPair = await generateKeyPair();
- const {
- encryptedData: encryptedSecretKey,
- nonce: secretKeyDecryptionNonce,
- } = await encryptBox(keyPair.privateKey, masterKey);
-
- const keyAttributes: KeyAttributes = {
- encryptedKey,
- keyDecryptionNonce,
- kekSalt,
- opsLimit,
- memLimit,
- publicKey: keyPair.publicKey,
- encryptedSecretKey,
- secretKeyDecryptionNonce,
- masterKeyEncryptedWithRecoveryKey,
- masterKeyDecryptionNonce,
- recoveryKeyEncryptedWithMasterKey,
- recoveryKeyDecryptionNonce,
- };
-
- return { masterKey, kek, keyAttributes };
-}
-
-export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>
- ensureOk(
- await fetch(await apiURL("/users/attributes"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ keyAttributes }),
- }),
- );
-
-export interface RecoveryKeyAttributes {
- masterKeyEncryptedWithRecoveryKey: string;
- masterKeyDecryptionNonce: string;
- recoveryKeyEncryptedWithMasterKey: string;
- recoveryKeyDecryptionNonce: string;
-}
-
-// 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,
-) =>
- ensureOk(
- await fetch(await apiURL("/users/recovery-key"), {
- method: "PUT",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(recoveryKeyAttributes),
- }),
- );
-
-export const sendOTT = async (
- email: string,
- purpose: "change" | "signup" | "login" | undefined,
-) =>
- ensureOk(
- await fetch(await apiURL("/users/ott"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify({ email, purpose }),
- }),
- );
-
-export interface EmailOrSRPVerificationResponse {
- id: number;
- keyAttributes?: KeyAttributes;
- encryptedToken?: string;
- token?: string;
- twoFactorSessionID?: string;
- passkeySessionID?: string;
- accountsUrl?: string;
- twoFactorSessionIDV2?: string;
-}
-
-const RemoteEmailOrSRPVerificationResponseBase = z.object({
- id: z.number(),
- keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),
- encryptedToken: z.string().nullish().transform(nullToUndefined),
- token: z.string().nullish().transform(nullToUndefined),
- twoFactorSessionID: z.string().nullish().transform(nullToUndefined),
- passkeySessionID: z.string().nullish().transform(nullToUndefined),
- accountsUrl: z.string().nullish().transform(nullToUndefined),
- twoFactorSessionIDV2: z.string().nullish().transform(nullToUndefined),
-});
-
-const requireAccountsUrlForPasskey = (response: {
- passkeySessionID?: string;
- accountsUrl?: string;
-}) => (response.passkeySessionID ? !!response.accountsUrl : true);
-
-const accountsUrlForPasskeyRefinement = {
- path: ["accountsUrl"],
- message: "accountsUrl is required when passkeySessionID is present",
-};
-
-const RemoteEmailOrSRPVerificationResponse =
- RemoteEmailOrSRPVerificationResponseBase.refine(
- requireAccountsUrlForPasskey,
- accountsUrlForPasskeyRefinement,
- );
-
-// This declaration conceptually belongs to srp.ts, but lives here to avoid a
-// cyclic dependency.
-export const RemoteSRPVerificationResponse =
- RemoteEmailOrSRPVerificationResponseBase.extend({
- srpM2: z.string(),
- }).refine(requireAccountsUrlForPasskey, accountsUrlForPasskeyRefinement);
-
-export const verifyEmail = async (
- email: string,
- ott: string,
- source: string | undefined,
-): Promise<EmailOrSRPVerificationResponse> => {
- const res = await fetch(await apiURL("/users/verify-email"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify({ email, ott, ...(source && { source }) }),
- });
- ensureOk(res);
- return RemoteEmailOrSRPVerificationResponse.parse(await res.json());
-};
-
-export const remoteLogoutIfNeeded = async () => {
- if (!(await savedAuthToken())) {
- // 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;
- }
-
- const res = await fetch(await apiURL("/users/logout"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- });
- if (res.status == 401) {
- // A 401 is expected when the token has already expired; ignore it.
- return;
- }
-
- ensureOk(res);
-};
-
-// 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,
- key: string,
-): Promise<KeyAttributes> => {
- const {
- key: interactiveKEK,
- salt: kekSalt,
- opsLimit,
- memLimit,
- } = await deriveInteractiveKey(password);
-
- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
- await encryptBox(key, interactiveKEK);
-
- const interactiveKeyAttributes = {
- ...keyAttributes,
- encryptedKey,
- keyDecryptionNonce,
- kekSalt,
- opsLimit,
- memLimit,
- };
- saveKeyAttributes(interactiveKeyAttributes);
- return interactiveKeyAttributes;
-};
-
-export const changeEmail = async (email: string, ott: string) => {
- await postChangeEmail(email, ott);
- updateSavedLocalUser({ email });
-};
-
-const postChangeEmail = async (email: string, ott: string) =>
- ensureOk(
- await fetch(await apiURL("/users/change-email"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify({ email, ott }),
- }),
- );
-
-export const changePassword = async (password: string) => {
- const user = ensureLocalUser();
- const masterKey = await ensureMasterKeyFromSession();
- const keyAttributes = ensureSavedKeyAttributes();
-
- const {
- key: kek,
- salt: kekSalt,
- opsLimit,
- memLimit,
- } = await deriveSensitiveKey(password);
-
- const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =
- await encryptBox(masterKey, kek);
- const updatedKeyAttr: UpdatedKeyAttr = {
- encryptedKey,
- keyDecryptionNonce,
- kekSalt,
- opsLimit,
- memLimit,
- };
-
- await updateSRPAndKeyAttributes(
- await generateSRPSetupAttributes(kek),
- updatedKeyAttr,
- );
-
- await getAndSaveSRPAttributes(user.email);
-
- await generateAndSaveInteractiveKeyAttributes(
- password,
- { ...keyAttributes, ...updatedKeyAttr },
- masterKey,
- );
-};
-
-export const resetSavedLocalUserTokens = async (
- userID: number,
- encryptedToken: string,
-) => {
- const user = savedPartialLocalUser();
- if (user?.id && user.id != userID) {
- throw new Error(`User ID mismatch (${user.id}, ${userID})`);
- }
- replaceSavedLocalUser({
- ...user,
- id: userID,
- token: undefined,
- encryptedToken,
- });
- return removeAuthToken();
-};
-
-export const decryptAndStoreTokenIfNeeded = async (
- keyAttributes: KeyAttributes,
- masterKey: string,
-) => {
- const { encryptedToken } = savedPartialLocalUser() ?? {};
- if (!encryptedToken) return;
-
- const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =
- keyAttributes;
- const privateKey = await decryptBox(
- { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },
- masterKey,
- );
-
- const token = await toB64URLSafe(
- await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),
- );
-
- updateSavedLocalUser({ token, encryptedToken: undefined });
- return saveAuthToken(token);
-};
-
-const TwoFactorSecret = z.object({
- secretCode: z.string(),
- // The value is a base64 encoded PNG image.
- qrCode: z.string(),
-});
-
-export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;
-
-export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {
- const res = await fetch(await apiURL("/users/two-factor/setup"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- });
- ensureOk(res);
- return TwoFactorSecret.parse(await res.json());
-};
-
-export const setupTwoFactorFinish = async (
- secretCode: string,
- totp: string,
-) => {
- const box = await encryptBox(secretCode, await getUserRecoveryKey());
- await enableTwoFactor({
- code: totp,
- encryptedTwoFactorSecret: box.encryptedData,
- twoFactorSecretDecryptionNonce: box.nonce,
- });
- updateSavedLocalUser({ isTwoFactorEnabled: true });
-};
-
-interface EnableTwoFactorRequest {
- code: string;
- encryptedTwoFactorSecret: string;
- twoFactorSecretDecryptionNonce: string;
-}
-
-const enableTwoFactor = async (req: EnableTwoFactorRequest) =>
- ensureOk(
- await fetch(await apiURL("/users/two-factor/enable"), {
- method: "POST",
- headers: await authenticatedRequestHeaders(),
- body: JSON.stringify(req),
- }),
- );
-
-export const TwoFactorAuthorizationResponse = z.object({
- id: z.number(),
- keyAttributes: RemoteKeyAttributes,
- encryptedToken: z.string(),
-});
-
-export type TwoFactorAuthorizationResponse = z.infer<
- typeof TwoFactorAuthorizationResponse
->;
-
-export const verifyTwoFactor = async (
- code: string,
- sessionID: string,
-): Promise<TwoFactorAuthorizationResponse> => {
- const res = await fetch(await apiURL("/users/two-factor/verify"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify({ code, sessionID }),
- });
- ensureOk(res);
- return TwoFactorAuthorizationResponse.parse(await res.json());
-};
-
-export type TwoFactorType = "totp" | "passkey";
-
-const TwoFactorRecoveryResponse = z.object({
- encryptedSecret: z.string(),
- secretDecryptionNonce: z.string(),
-});
-
-export type TwoFactorRecoveryResponse = z.infer<
- typeof TwoFactorRecoveryResponse
->;
-
-export const getRecoverTwoFactor = async (
- twoFactorType: TwoFactorType,
- sessionID: string,
-): Promise<TwoFactorRecoveryResponse> => {
- const res = await fetch(
- await apiURL("/users/two-factor/recover", { twoFactorType, sessionID }),
- { headers: publicRequestHeaders() },
- );
- ensureOk(res);
- return TwoFactorRecoveryResponse.parse(await res.json());
-};
-
-export const recoverTwoFactorFinish = async (
- twoFactorType: TwoFactorType,
- sessionID: string,
- recoveryResponse: TwoFactorRecoveryResponse,
- recoveryKeyMnemonic: string,
-) => {
- const { encryptedSecret: encryptedData, secretDecryptionNonce: nonce } =
- recoveryResponse;
- const twoFactorSecret = await decryptBox(
- { encryptedData, nonce },
- await recoveryKeyFromMnemonic(recoveryKeyMnemonic),
- );
- const { id, keyAttributes, encryptedToken } = await removeTwoFactor(
- twoFactorType,
- sessionID,
- twoFactorSecret,
- );
- await resetSavedLocalUserTokens(id, encryptedToken);
- updateSavedLocalUser({
- isTwoFactorEnabled: undefined,
- twoFactorSessionID: undefined,
- passkeySessionID: undefined,
- });
- if (twoFactorType == "passkey") clearInflightPasskeySessionID();
- saveKeyAttributes(keyAttributes);
-};
-
-const removeTwoFactor = async (
- twoFactorType: TwoFactorType,
- sessionID: string,
- secret: string,
-): Promise<TwoFactorAuthorizationResponse> => {
- const res = await fetch(await apiURL("/users/two-factor/remove"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify({ twoFactorType, sessionID, secret }),
- });
- ensureOk(res);
- return TwoFactorAuthorizationResponse.parse(await res.json());
-};
diff --git a/web/packages/accounts/tsconfig.json b/web/packages/accounts/tsconfig.json
deleted file mode 100644
index 15dcfedc2b..0000000000
--- a/web/packages/accounts/tsconfig.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": "ente-build-config/tsconfig-next.json",
- "include": [
- ".",
- "../base/global-electron.d.ts",
- "../base/components/utils/mui-theme.d.ts"
- ]
-}
diff --git a/web/packages/accounts/utils/password.ts b/web/packages/accounts/utils/password.ts
deleted file mode 100644
index 6b80dd76ed..0000000000
--- a/web/packages/accounts/utils/password.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import zxcvbn from "zxcvbn";
-
-export type PasswordStrength = "weak" | "moderate" | "strong";
-
-export const estimatePasswordStrength = (
- password: string,
-): PasswordStrength => {
- if (!password) {
- return "weak";
- }
-
- const zxcvbnResult = zxcvbn(password);
- if (zxcvbnResult.score < 2) {
- return "weak";
- } else if (zxcvbnResult.score < 3) {
- return "moderate";
- } else {
- return "strong";
- }
-};
-
-export const isWeakPassword = (password: string) =>
- estimatePasswordStrength(password) == "weak";