Skip to content

armgit / ente

Public Imported from GitHub
0

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

migrate two factor recover

Abhinav6272975a6669
diff --git a/apps/photos/src/pages/two-factor/recover/index.tsx b/apps/photos/src/pages/two-factor/recover/index.tsx
index b16cf2a65d..99635303c0 100644
--- a/apps/photos/src/pages/two-factor/recover/index.tsx
+++ b/apps/photos/src/pages/two-factor/recover/index.tsx
@@ -1,176 +1,17 @@
-import React, { useContext, useEffect, useState } from 'react';
-import { getData, LS_KEYS, setData } from 'utils/storage/localStorage';
+import TwoFactorRecoverPage from '@ente/accounts/pages/two-factor/recover';
import { useRouter } from 'next/router';
-import SingleInputForm, {
- SingleInputFormProps,
-} from 'components/SingleInputForm';
-import { VerticallyCentered } from 'components/Container';
-import { logError } from 'utils/sentry';
-import {
- logoutUser,
- recoverTwoFactor,
- removeTwoFactor,
-} from 'services/userService';
import { AppContext } from 'pages/_app';
-import { PAGES } from 'constants/pages';
-import FormPaper from 'components/Form/FormPaper';
-import FormPaperTitle from 'components/Form/FormPaper/Title';
-import FormPaperFooter from 'components/Form/FormPaper/Footer';
-import LinkButton from 'components/pages/gallery/LinkButton';
-import { B64EncryptionResult } from 'types/crypto';
-import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
-import { t } from 'i18next';
-import { Trans } from 'react-i18next';
-import { Link } from '@mui/material';
-import { SUPPORT_EMAIL } from 'constants/urls';
-import { DialogBoxAttributes } from 'types/dialogBox';
-import { ApiError } from 'utils/error';
-import { HttpStatusCode } from 'axios';
+import { useContext } from 'react';
+import { APPS } from '@ente/shared/apps/constants';
-const bip39 = require('bip39');
-// mobile client library only supports english.
-bip39.setDefaultWordlist('english');
-
-export default function Recover() {
- const router = useRouter();
- const [encryptedTwoFactorSecret, setEncryptedTwoFactorSecret] =
- useState<B64EncryptionResult>(null);
- const [sessionID, setSessionID] = useState(null);
+export default function TwoFactorRecover() {
const appContext = useContext(AppContext);
- const [doesHaveEncryptedRecoveryKey, setDoesHaveEncryptedRecoveryKey] =
- useState(false);
-
- useEffect(() => {
- router.prefetch(PAGES.GALLERY);
- const user = getData(LS_KEYS.USER);
- if (!user || !user.email || !user.twoFactorSessionID) {
- router.push(PAGES.ROOT);
- } else if (
- !user.isTwoFactorEnabled &&
- (user.encryptedToken || user.token)
- ) {
- router.push(PAGES.GENERATE);
- } else {
- setSessionID(user.twoFactorSessionID);
- }
- const main = async () => {
- try {
- const resp = await recoverTwoFactor(user.twoFactorSessionID);
- setDoesHaveEncryptedRecoveryKey(!!resp.encryptedSecret);
- if (!resp.encryptedSecret) {
- showContactSupportDialog({
- text: t('GO_BACK'),
- action: router.back,
- });
- } else {
- setEncryptedTwoFactorSecret({
- encryptedData: resp.encryptedSecret,
- nonce: resp.secretDecryptionNonce,
- key: null,
- });
- }
- } catch (e) {
- if (
- e instanceof ApiError &&
- e.httpStatusCode === HttpStatusCode.NotFound
- ) {
- logoutUser();
- } else {
- logError(e, 'two factor recovery page setup failed');
- setDoesHaveEncryptedRecoveryKey(false);
- showContactSupportDialog({
- text: t('GO_BACK'),
- action: router.back,
- });
- }
- }
- };
- main();
- }, []);
-
- const recover: SingleInputFormProps['callback'] = async (
- recoveryKey: string,
- setFieldError
- ) => {
- try {
- recoveryKey = recoveryKey
- .trim()
- .split(' ')
- .map((part) => part.trim())
- .filter((part) => !!part)
- .join(' ');
- // check if user is entering mnemonic recovery key
- if (recoveryKey.indexOf(' ') > 0) {
- if (recoveryKey.split(' ').length !== 24) {
- throw new Error('recovery code should have 24 words');
- }
- recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
- }
- const cryptoWorker = await ComlinkCryptoWorker.getInstance();
- const twoFactorSecret = await cryptoWorker.decryptB64(
- encryptedTwoFactorSecret.encryptedData,
- encryptedTwoFactorSecret.nonce,
- await cryptoWorker.fromHex(recoveryKey)
- );
- const resp = await removeTwoFactor(sessionID, twoFactorSecret);
- const { keyAttributes, encryptedToken, token, id } = resp;
- setData(LS_KEYS.USER, {
- ...getData(LS_KEYS.USER),
- token,
- encryptedToken,
- id,
- isTwoFactorEnabled: false,
- });
- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);
- router.push(PAGES.CREDENTIALS);
- } catch (e) {
- logError(e, 'two factor recovery failed');
- setFieldError(t('INCORRECT_RECOVERY_KEY'));
- }
- };
-
- const showContactSupportDialog = (
- dialogClose?: DialogBoxAttributes['close']
- ) => {
- appContext.setDialogMessage({
- title: t('CONTACT_SUPPORT'),
- close: dialogClose ?? {},
- content: (
- <Trans
- i18nKey={'NO_TWO_FACTOR_RECOVERY_KEY_MESSAGE'}
- values={{ emailID: SUPPORT_EMAIL }}
- components={{
- a: <Link href={`mailto:${SUPPORT_EMAIL}`} />,
- }}
- />
- ),
- });
- };
-
- if (!doesHaveEncryptedRecoveryKey) {
- return <></>;
- }
-
+ const router = useRouter();
return (
- <VerticallyCentered>
- <FormPaper>
- <FormPaperTitle>{t('RECOVER_TWO_FACTOR')}</FormPaperTitle>
- <SingleInputForm
- callback={recover}
- fieldType="text"
- placeholder={t('RECOVERY_KEY_HINT')}
- buttonText={t('RECOVER')}
- disableAutoComplete
- />
- <FormPaperFooter style={{ justifyContent: 'space-between' }}>
- <LinkButton onClick={() => showContactSupportDialog()}>
- {t('NO_RECOVERY_KEY')}
- </LinkButton>
- <LinkButton onClick={router.back}>
- {t('GO_BACK')}
- </LinkButton>
- </FormPaperFooter>
- </FormPaper>
- </VerticallyCentered>
+ <TwoFactorRecoverPage
+ appContext={appContext}
+ router={router}
+ appName={APPS.PHOTOS}
+ />
);
}
diff --git a/packages/accounts/api/user.ts b/packages/accounts/api/user.ts
index c0f263163e..9d3fc46def 100644
--- a/packages/accounts/api/user.ts
+++ b/packages/accounts/api/user.ts
@@ -2,13 +2,14 @@ import HTTPService from '@ente/shared/network/HTTPService';
import { getEndpoint } from '@ente/shared/network/api';
import { getToken } from '@ente/shared/storage/localStorage/helpers';
-
-import {
- KeyAttributes,
- UserVerificationResponse,
-} from '@ente/shared/user/types';
+import { KeyAttributes } from '@ente/shared/user/types';
import { ApiError } from '@ente/shared/error';
import { HttpStatusCode } from 'axios';
+import {
+ UserVerificationResponse,
+ TwoFactorRecoveryResponse,
+ TwoFactorVerificationResponse,
+} from '@ente/accounts/types/user';
const ENDPOINT = getEndpoint();
@@ -66,3 +67,18 @@ export const verifyTwoFactor = async (code: string, sessionID: string) => {
);
return resp.data as UserVerificationResponse;
};
+
+export const recoverTwoFactor = async (sessionID: string) => {
+ const resp = await HTTPService.get(`${ENDPOINT}/users/two-factor/recover`, {
+ sessionID,
+ });
+ return resp.data as TwoFactorRecoveryResponse;
+};
+
+export const removeTwoFactor = async (sessionID: string, secret: string) => {
+ const resp = await HTTPService.post(`${ENDPOINT}/users/two-factor/remove`, {
+ sessionID,
+ secret,
+ });
+ return resp.data as TwoFactorVerificationResponse;
+};
diff --git a/packages/accounts/pages/two-factor/recover.tsx b/packages/accounts/pages/two-factor/recover.tsx
new file mode 100644
index 0000000000..1aa38dd2b3
--- /dev/null
+++ b/packages/accounts/pages/two-factor/recover.tsx
@@ -0,0 +1,170 @@
+import React, { useEffect, useState } from 'react';
+import { getData, LS_KEYS, setData } from '@ente/shared/storage/localStorage';
+import SingleInputForm, {
+ SingleInputFormProps,
+} from '@ente/shared/components/SingleInputForm';
+import { VerticallyCentered } from '@ente/shared/components/Container';
+// import { logError } from 'utils/sentry';
+import { logoutUser } from '@ente/accounts/services/user';
+import { recoverTwoFactor, removeTwoFactor } from '@ente/accounts/api/user';
+import { PAGES } from '@ente/accounts/constants/pages';
+import FormPaper from '@ente/shared/components/Form/FormPaper';
+import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';
+import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';
+import LinkButton from '@ente/shared/components/LinkButton';
+import { B64EncryptionResult } from '@ente/shared/crypto/types';
+import ComlinkCryptoWorker from '@ente/shared/crypto';
+import { t } from 'i18next';
+import { Trans } from 'react-i18next';
+import { Link } from '@mui/material';
+import { SUPPORT_EMAIL } from '@ente/shared/constants/urls';
+import { DialogBoxAttributesV2 } from '@ente/shared/components/DialogBoxV2';
+import { ApiError } from '@ente/shared/error';
+import { HttpStatusCode } from 'axios';
+import { PageProps } from '@ente/shared/apps/types';
+
+const bip39 = require('bip39');
+// mobile client library only supports english.
+bip39.setDefaultWordlist('english');
+
+export default function Recover({ router, appContext }: PageProps) {
+ const [encryptedTwoFactorSecret, setEncryptedTwoFactorSecret] =
+ useState<B64EncryptionResult>(null);
+ const [sessionID, setSessionID] = useState(null);
+ const [doesHaveEncryptedRecoveryKey, setDoesHaveEncryptedRecoveryKey] =
+ useState(false);
+
+ useEffect(() => {
+ router.prefetch(PAGES.GALLERY);
+ const user = getData(LS_KEYS.USER);
+ if (!user || !user.email || !user.twoFactorSessionID) {
+ router.push(PAGES.ROOT);
+ } else if (
+ !user.isTwoFactorEnabled &&
+ (user.encryptedToken || user.token)
+ ) {
+ router.push(PAGES.GENERATE);
+ } else {
+ setSessionID(user.twoFactorSessionID);
+ }
+ const main = async () => {
+ try {
+ const resp = await recoverTwoFactor(user.twoFactorSessionID);
+ setDoesHaveEncryptedRecoveryKey(!!resp.encryptedSecret);
+ if (!resp.encryptedSecret) {
+ showContactSupportDialog({
+ text: t('GO_BACK'),
+ action: router.back,
+ });
+ } else {
+ setEncryptedTwoFactorSecret({
+ encryptedData: resp.encryptedSecret,
+ nonce: resp.secretDecryptionNonce,
+ key: null,
+ });
+ }
+ } catch (e) {
+ if (
+ e instanceof ApiError &&
+ e.httpStatusCode === HttpStatusCode.NotFound
+ ) {
+ logoutUser(router);
+ } else {
+ // logError(e, 'two factor recovery page setup failed');
+ setDoesHaveEncryptedRecoveryKey(false);
+ showContactSupportDialog({
+ text: t('GO_BACK'),
+ action: router.back,
+ });
+ }
+ }
+ };
+ main();
+ }, []);
+
+ const recover: SingleInputFormProps['callback'] = async (
+ recoveryKey: string,
+ setFieldError
+ ) => {
+ try {
+ recoveryKey = recoveryKey
+ .trim()
+ .split(' ')
+ .map((part) => part.trim())
+ .filter((part) => !!part)
+ .join(' ');
+ // check if user is entering mnemonic recovery key
+ if (recoveryKey.indexOf(' ') > 0) {
+ if (recoveryKey.split(' ').length !== 24) {
+ throw new Error('recovery code should have 24 words');
+ }
+ recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
+ }
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const twoFactorSecret = await cryptoWorker.decryptB64(
+ encryptedTwoFactorSecret.encryptedData,
+ encryptedTwoFactorSecret.nonce,
+ await cryptoWorker.fromHex(recoveryKey)
+ );
+ const resp = await removeTwoFactor(sessionID, twoFactorSecret);
+ const { keyAttributes, encryptedToken, token, id } = resp;
+ setData(LS_KEYS.USER, {
+ ...getData(LS_KEYS.USER),
+ token,
+ encryptedToken,
+ id,
+ isTwoFactorEnabled: false,
+ });
+ setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);
+ router.push(PAGES.CREDENTIALS);
+ } catch (e) {
+ // logError(e, 'two factor recovery failed');
+ setFieldError(t('INCORRECT_RECOVERY_KEY'));
+ }
+ };
+
+ const showContactSupportDialog = (
+ dialogClose?: DialogBoxAttributesV2['close']
+ ) => {
+ appContext.setDialogBoxAttributesV2({
+ title: t('CONTACT_SUPPORT'),
+ close: dialogClose ?? {},
+ content: (
+ <Trans
+ i18nKey={'NO_TWO_FACTOR_RECOVERY_KEY_MESSAGE'}
+ values={{ emailID: SUPPORT_EMAIL }}
+ components={{
+ a: <Link href={`mailto:${SUPPORT_EMAIL}`} />,
+ }}
+ />
+ ),
+ });
+ };
+
+ if (!doesHaveEncryptedRecoveryKey) {
+ return <></>;
+ }
+
+ return (
+ <VerticallyCentered>
+ <FormPaper>
+ <FormPaperTitle>{t('RECOVER_TWO_FACTOR')}</FormPaperTitle>
+ <SingleInputForm
+ callback={recover}
+ fieldType="text"
+ placeholder={t('RECOVERY_KEY_HINT')}
+ buttonText={t('RECOVER')}
+ disableAutoComplete
+ />
+ <FormPaperFooter style={{ justifyContent: 'space-between' }}>
+ <LinkButton onClick={() => showContactSupportDialog()}>
+ {t('NO_RECOVERY_KEY')}
+ </LinkButton>
+ <LinkButton onClick={router.back}>
+ {t('GO_BACK')}
+ </LinkButton>
+ </FormPaperFooter>
+ </FormPaper>
+ </VerticallyCentered>
+ );
+}
diff --git a/packages/accounts/pages/two-factor/verify/index.tsx b/packages/accounts/pages/two-factor/verify.tsx
similarity index 100%
rename from packages/accounts/pages/two-factor/verify/index.tsx
rename to packages/accounts/pages/two-factor/verify.tsx
diff --git a/packages/accounts/types/user.ts b/packages/accounts/types/user.ts
new file mode 100644
index 0000000000..144e7b149d
--- /dev/null
+++ b/packages/accounts/types/user.ts
@@ -0,0 +1,27 @@
+import { KeyAttributes } from '@ente/shared/user/types';
+
+export interface UserVerificationResponse {
+ id: number;
+ keyAttributes?: KeyAttributes;
+ encryptedToken?: string;
+ token?: string;
+ twoFactorSessionID: string;
+ srpM2?: string;
+}
+
+export interface TwoFactorVerificationResponse {
+ id: number;
+ keyAttributes: KeyAttributes;
+ encryptedToken?: string;
+ token?: string;
+}
+
+export interface TwoFactorSecret {
+ secretCode: string;
+ qrCode: string;
+}
+
+export interface TwoFactorRecoveryResponse {
+ encryptedSecret: string;
+ secretDecryptionNonce: string;
+}
diff --git a/packages/shared/constants/urls.ts b/packages/shared/constants/urls.ts
new file mode 100644
index 0000000000..291704e98f
--- /dev/null
+++ b/packages/shared/constants/urls.ts
@@ -0,0 +1,19 @@
+export const ENTE_WEBSITE_LINK = 'https://ente.io';
+
+export const ML_BLOG_LINK = 'https://ente.io/blog/desktop-ml-beta';
+
+export const FACE_SEARCH_PRIVACY_POLICY_LINK =
+ 'https://ente.io/privacy#8-biometric-information-privacy-policy';
+
+export const SUPPORT_EMAIL = '[email protected]';
+
+export const APP_DOWNLOAD_URL = 'https://ente.io/download/desktop';
+
+export const FEEDBACK_EMAIL = '[email protected]';
+
+export const DELETE_ACCOUNT_EMAIL = '[email protected]';
+
+export const WEB_ROADMAP_URL = 'https://github.com/ente-io/photos-web/issues';
+
+export const DESKTOP_ROADMAP_URL =
+ 'https://github.com/ente-io/photos-desktop/issues';
diff --git a/packages/shared/user/types.ts b/packages/shared/user/types.ts
index c7d2bcaaeb..2c5d02c8d1 100644
--- a/packages/shared/user/types.ts
+++ b/packages/shared/user/types.ts
@@ -21,11 +21,3 @@ export interface User {
isTwoFactorEnabled: boolean;
twoFactorSessionID: string;
}
-export interface UserVerificationResponse {
- id: number;
- keyAttributes?: KeyAttributes;
- encryptedToken?: string;
- token?: string;
- twoFactorSessionID: string;
- srpM2?: string;
-}