π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use
Manav Rathi989708cf58f7
diff --git a/web/packages/accounts/components/Verify2FACodeForm.tsx b/web/packages/accounts/components/Verify2FACodeForm.tsxnew file mode 100644index 0000000000..bc3d8a2a71--- /dev/null+++ b/web/packages/accounts/components/Verify2FACodeForm.tsx@@ -0,0 +1,166 @@+import { LoadingButton } from "@/base/components/mui/LoadingButton";+import {+ CenteredFlex,+ VerticallyCentered,+} from "@ente/shared/components/Container";+import { Box, styled, Typography } from "@mui/material";+import { Formik, type FormikHelpers } from "formik";+import { t } from "i18next";+import React, { useState } from "react";+import OtpInput from "react-otp-input";++interface FormValues {+ otp: string;+}++interface Verify2FACodeFormProps {+ /**+ * Called when the user submits the OTP.+ *+ * The submission can happen in two ways:+ * 1. The fill-in all the required 6 digits, or+ * 2. They press the "Enable" button.+ *+ * The form will stay in a waiting state until this callback returns.+ *+ * @param otp The OTP that the user entered.+ */+ onSubmit: (otp: string) => Promise<void>;+ /**+ * Called when the process was completed successfully.+ *+ * This will be called immediately after onSubmit fulfills, but having two+ * separate callbacks allows the form to indicate the success state in the+ * interim.+ */+ onSuccess: () => void;+ /**+ * The label for the submit button.+ */+ submitButtonText: string;+}++/**+ * A form that can be used to ask the user to fill in a 6 digit OTP that their+ * authenticator app is providing them with.+ */+export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({+ onSubmit,+ onSuccess,+ submitButtonText,+}) => {+ const [waiting, setWaiting] = useState(false);+ const [shouldAutoFocus, setShouldAutoFocus] = useState(true);++ const submitForm = async (+ { otp }: FormValues,+ { setFieldError, resetForm }: FormikHelpers<FormValues>,+ ) => {+ try {+ setWaiting(true);+ await onSubmit(otp);+ setWaiting(false);+ onSuccess();+ } catch (e) {+ resetForm();+ const message = e instanceof Error ? e.message : "";+ setFieldError("otp", `${t("generic_error_retry")} (${message})`);+ // 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);+ }+ setWaiting(false);+ };++ const onChange =+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type+ (callback: Function, triggerSubmit: Function) => (otp: string) => {+ callback(otp);+ if (otp.length === 6) {+ triggerSubmit(otp);+ }+ };+ return (+ <Formik<FormValues>+ initialValues={{ otp: "" }}+ validateOnChange={false}+ validateOnBlur={false}+ onSubmit={submitForm}+ >+ {({ values, errors, handleChange, handleSubmit, submitForm }) => (+ <VerticallyCentered>+ <form noValidate onSubmit={handleSubmit}>+ <Typography+ variant="small"+ sx={{ mb: 2, color: "text.muted" }}+ >+ {t("enter_two_factor_otp")}+ </Typography>+ <Box sx={{ my: 2 }}>+ <OtpInput+ containerStyle={{ justifyContent: "center" }}+ shouldAutoFocus={shouldAutoFocus}+ value={values.otp}+ onChange={onChange(+ handleChange("otp"),+ submitForm,+ )}+ numInputs={6}+ renderSeparator={<span>-</span>}+ renderInput={(props) => (+ <IndividualInput {...props} />+ )}+ />+ {errors.otp && (+ <CenteredFlex sx={{ mt: 1 }}>+ <InvalidInputMessage>+ {t("incorrect_code")}+ </InvalidInputMessage>+ </CenteredFlex>+ )}+ </Box>+ <LoadingButton+ type="submit"+ color="accent"+ fullWidth+ sx={{ my: 4 }}+ loading={waiting}+ disabled={values.otp.length < 6}+ >+ {submitButtonText}+ </LoadingButton>+ </form>+ </VerticallyCentered>+ )}+ </Formik>+ );+};++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;+ }+`,+);++const InvalidInputMessage: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Typography variant="mini" sx={{ color: "critical.main" }}>+ {children}+ </Typography>+);diff --git a/web/packages/accounts/pages/two-factor/setup.tsx b/web/packages/accounts/pages/two-factor/setup.tsxindex 718a6c561f..168b75826f 100644--- a/web/packages/accounts/pages/two-factor/setup.tsx+++ b/web/packages/accounts/pages/two-factor/setup.tsx@@ -1,22 +1,16 @@+import { TwoFactorSetup } from "@/accounts/components/two-factor/TwoFactorSetup";+import { Verify2FACodeForm } from "@/accounts/components/Verify2FACodeForm";import { appHomeRoute } from "@/accounts/services/redirect";import type { TwoFactorSecret } from "@/accounts/services/user";import { enableTwoFactor, setupTwoFactor } from "@/accounts/services/user";import { CenteredFill } from "@/base/components/containers";import { FocusVisibleButton } from "@/base/components/mui/FocusVisibleButton";-import { LoadingButton } from "@/base/components/mui/LoadingButton";-import {- CenteredFlex,- VerticallyCentered,-} from "@ente/shared/components/Container";import { encryptWithRecoveryKey } from "@ente/shared/crypto/helpers";import { getData, LS_KEYS, setLSUser } from "@ente/shared/storage/localStorage";-import { Box, Paper, Stack, styled, Typography } from "@mui/material";-import { Formik, type FormikHelpers } from "formik";+import { Paper, Stack, styled, Typography } from "@mui/material";import { t } from "i18next";import { useRouter } from "next/router";-import React, { useEffect, useState } from "react";-import OtpInput from "react-otp-input";-import { TwoFactorSetup } from "../../components/two-factor/TwoFactorSetup";+import React, { useCallback, useEffect, useState } from "react";export type SetupMode = "qrCode" | "manualCode";@@ -32,21 +26,20 @@ const Page: React.FC = () => {void setupTwoFactor().then(setTwoFactorSecret);}, []);- const onSubmit: VerifyTwoFactorCallback = async (- otp: string,- markSuccessful,- ) => {+ const handleSubmit = useCallback(async (otp: string) => {const recoveryEncryptedTwoFactorSecret = await encryptWithRecoveryKey(twoFactorSecret!.secretCode,);await enableTwoFactor(otp, recoveryEncryptedTwoFactorSecret);- markSuccessful();await setLSUser({...getData(LS_KEYS.USER),isTwoFactorEnabled: true,});+ }, []);++ const handleSuccess = useCallback(() => {void router.push(appHomeRoute);- };+ }, [router]);return (<Stack sx={{ minHeight: "100svh" }}>@@ -57,9 +50,10 @@ const Page: React.FC = () => {</Typography><Stack><TwoFactorSetup twoFactorSecret={twoFactorSecret} />- <VerifyTwoFactor- onSubmit={onSubmit}- buttonText={t("enable")}+ <Verify2FACodeForm+ onSubmit={handleSubmit}+ onSuccess={handleSuccess}+ submitButtonText={t("enable")}/><Stack sx={{ alignItems: "center" }}><FocusVisibleButton@@ -87,133 +81,3 @@ const ContentsPaper = styled(Paper)(({ theme }) => ({flexDirection: "column",gap: theme.spacing(4),}));--interface formValues {- otp: string;-}-interface VerifyTwoFactorProps {- onSubmit: VerifyTwoFactorCallback;- buttonText: string;-}--export type VerifyTwoFactorCallback = (- otp: string,- markSuccessful: () => void,-) => Promise<void>;--const VerifyTwoFactor: React.FC<VerifyTwoFactorProps> = (props) => {- const [waiting, setWaiting] = useState(false);- const [shouldAutoFocus, setShouldAutoFocus] = useState(true);-- const markSuccessful = () => setWaiting(false);-- const submitForm = async (- { otp }: formValues,- { setFieldError, resetForm }: FormikHelpers<formValues>,- ) => {- try {- setWaiting(true);- await props.onSubmit(otp, markSuccessful);- } catch (e) {- resetForm();- const message = e instanceof Error ? e.message : "";- setFieldError("otp", `${t("generic_error_retry")} (${message})`);- // 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);- }- setWaiting(false);- };-- const onChange =- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type- (callback: Function, triggerSubmit: Function) => (otp: string) => {- callback(otp);- if (otp.length === 6) {- triggerSubmit(otp);- }- };- return (- <Formik<formValues>- initialValues={{ otp: "" }}- validateOnChange={false}- validateOnBlur={false}- onSubmit={submitForm}- >- {({ values, errors, handleChange, handleSubmit, submitForm }) => (- <VerticallyCentered>- <form noValidate onSubmit={handleSubmit}>- <Typography- variant="small"- sx={{ mb: 2, color: "text.muted" }}- >- {t("enter_two_factor_otp")}- </Typography>- <Box sx={{ my: 2 }}>- <OtpInput- containerStyle={{ justifyContent: "center" }}- shouldAutoFocus={shouldAutoFocus}- value={values.otp}- onChange={onChange(- handleChange("otp"),- submitForm,- )}- numInputs={6}- renderSeparator={<span>-</span>}- renderInput={(props) => (- <IndividualInput {...props} />- )}- />- {errors.otp && (- <CenteredFlex sx={{ mt: 1 }}>- <InvalidInputMessage>- {t("incorrect_code")}- </InvalidInputMessage>- </CenteredFlex>- )}- </Box>- <LoadingButton- type="submit"- color="accent"- fullWidth- sx={{ my: 4 }}- loading={waiting}- disabled={values.otp.length < 6}- >- {props.buttonText}- </LoadingButton>- </form>- </VerticallyCentered>- )}- </Formik>- );-};--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;- }-`,-);--const InvalidInputMessage: React.FC<React.PropsWithChildren> = ({- children,-}) => (- <Typography variant="mini" sx={{ color: "critical.main" }}>- {children}- </Typography>-);diff --git a/web/packages/accounts/pages/two-factor/verify.tsx b/web/packages/accounts/pages/two-factor/verify.tsxindex 3ea0ad6a6b..e9174d7cd6 100644--- a/web/packages/accounts/pages/two-factor/verify.tsx+++ b/web/packages/accounts/pages/two-factor/verify.tsx@@ -1,3 +1,4 @@+import { Verify2FACodeForm } from "@/accounts/components/Verify2FACodeForm";import { PAGES } from "@/accounts/constants/pages";import { verifyTwoFactor } from "@/accounts/services/user";import { LinkButton } from "@/base/components/LinkButton";@@ -13,16 +14,12 @@ import type { User } from "@ente/shared/user/types";import { HttpStatusCode } from "axios";import { t } from "i18next";import { useRouter } from "next/router";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import {AccountsPageContents,AccountsPageFooter,AccountsPageTitle,} from "../../components/layouts/centered-paper";-import {- VerifyTwoFactor,- type VerifyTwoFactorCallback,-} from "../../components/two-factor/VerifyTwoFactor";import { unstashRedirect } from "../../services/redirect";const Page: React.FC = () => {@@ -46,35 +43,45 @@ const Page: React.FC = () => {}}, []);- const onSubmit: VerifyTwoFactorCallback = async (otp) => {- try {- const resp = await verifyTwoFactor(otp, sessionID);- const { keyAttributes, encryptedToken, token, id } = resp;- await setLSUser({- ...getData(LS_KEYS.USER),- token,- encryptedToken,- id,- });- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes!);- void router.push(unstashRedirect() ?? PAGES.CREDENTIALS);- } catch (e) {- if (- e instanceof ApiError &&- // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison- e.httpStatusCode === HttpStatusCode.NotFound- ) {- logout();- } else {- throw e;+ const handleSubmit = useCallback(+ async (otp: string) => {+ try {+ const resp = await verifyTwoFactor(otp, sessionID);+ const { keyAttributes, encryptedToken, token, id } = resp;+ await setLSUser({+ ...getData(LS_KEYS.USER),+ token,+ encryptedToken,+ id,+ });+ setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes!);+ } catch (e) {+ if (+ e instanceof ApiError &&+ // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison+ e.httpStatusCode === HttpStatusCode.NotFound+ ) {+ logout();+ } else {+ throw e;+ }}- }- };+ },+ [logout],+ );++ const handleSuccess = useCallback(() => {+ void router.push(unstashRedirect() ?? PAGES.CREDENTIALS);+ }, [router]);return (<AccountsPageContents><AccountsPageTitle>{t("two_factor")}</AccountsPageTitle>- <VerifyTwoFactor onSubmit={onSubmit} buttonText={t("verify")} />+ <Verify2FACodeForm+ onSubmit={handleSubmit}+ onSuccess={handleSuccess}+ submitButtonText={t("verify")}+ /><AccountsPageFooter><LinkButtononClick={() => router.push(PAGES.TWO_FACTOR_RECOVER)}