Skip to content

armgit / ente

Public Imported from GitHub
0

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

migrated setup 2fa

Abhinav10cfc1702704
diff --git a/apps/photos/src/pages/two-factor/setup/index.tsx b/apps/photos/src/pages/two-factor/setup/index.tsx
index 8eaa5ff616..aac9c9a249 100644
--- a/apps/photos/src/pages/two-factor/setup/index.tsx
+++ b/apps/photos/src/pages/two-factor/setup/index.tsx
@@ -1,84 +1,17 @@
-import React, { useEffect, useState } from 'react';
-import { enableTwoFactor, setupTwoFactor } from 'services/userService';
-import { t } from 'i18next';
-
-import { VerticallyCentered } from 'components/Container';
+import TwoFactorSetupPage from '@ente/accounts/pages/two-factor/setup';
import { useRouter } from 'next/router';
-import VerifyTwoFactor, {
- VerifyTwoFactorCallback,
-} from 'components/TwoFactor/VerifyForm';
-import { encryptWithRecoveryKey } from 'utils/crypto';
-import { setData, LS_KEYS, getData } from 'utils/storage/localStorage';
-import { PAGES } from 'constants/pages';
-import { TwoFactorSecret } from 'types/user';
-import Card from '@mui/material/Card';
-import { Box, CardContent, Typography } from '@mui/material';
-import { TwoFactorSetup } from 'components/TwoFactor/Setup';
-import LinkButton from 'components/pages/gallery/LinkButton';
-import { logError } from 'utils/sentry';
-
-export enum SetupMode {
- QR_CODE,
- MANUAL_CODE,
-}
-
-export default function SetupTwoFactor() {
- const [twoFactorSecret, setTwoFactorSecret] =
- useState<TwoFactorSecret>(null);
+import { AppContext } from 'pages/_app';
+import { useContext } from 'react';
+import { APPS } from '@ente/shared/apps/constants';
+export default function TwoFactorSetup() {
+ const appContext = useContext(AppContext);
const router = useRouter();
- useEffect(() => {
- if (twoFactorSecret) {
- return;
- }
- const main = async () => {
- try {
- const twoFactorSecret = await setupTwoFactor();
- setTwoFactorSecret(twoFactorSecret);
- } catch (e) {
- logError(e, 'failed to get two factor setup code');
- }
- };
- main();
- }, []);
-
- const onSubmit: VerifyTwoFactorCallback = async (
- otp: string,
- markSuccessful
- ) => {
- const recoveryEncryptedTwoFactorSecret = await encryptWithRecoveryKey(
- twoFactorSecret.secretCode
- );
- await enableTwoFactor(otp, recoveryEncryptedTwoFactorSecret);
- await markSuccessful();
- setData(LS_KEYS.USER, {
- ...getData(LS_KEYS.USER),
- isTwoFactorEnabled: true,
- });
- router.push(PAGES.GALLERY);
- };
-
return (
- <VerticallyCentered>
- <Card>
- <CardContent>
- <VerticallyCentered sx={{ p: 3 }}>
- <Box mb={4}>
- <Typography variant="h2">
- {t('TWO_FACTOR')}
- </Typography>
- </Box>
- <TwoFactorSetup twoFactorSecret={twoFactorSecret} />
- <VerifyTwoFactor
- onSubmit={onSubmit}
- buttonText={t('ENABLE')}
- />
- <LinkButton sx={{ mt: 2 }} onClick={router.back}>
- {t('GO_BACK')}
- </LinkButton>
- </VerticallyCentered>
- </CardContent>
- </Card>
- </VerticallyCentered>
+ <TwoFactorSetupPage
+ appContext={appContext}
+ router={router}
+ appName={APPS.PHOTOS}
+ />
);
}
diff --git a/packages/accounts/api/user.ts b/packages/accounts/api/user.ts
index 2b39775236..8bc91430fb 100644
--- a/packages/accounts/api/user.ts
+++ b/packages/accounts/api/user.ts
@@ -9,7 +9,10 @@ import {
UserVerificationResponse,
TwoFactorRecoveryResponse,
TwoFactorVerificationResponse,
+ TwoFactorSecret,
+ RecoveryKey,
} from '@ente/accounts/types/user';
+import { B64EncryptionResult } from '@ente/shared/crypto/types';
const ENDPOINT = getEndpoint();
@@ -110,3 +113,40 @@ export const sendOTTForEmailChange = async (email: string) => {
purpose: 'change',
});
};
+
+export const setupTwoFactor = async () => {
+ const resp = await HTTPService.post(
+ `${ENDPOINT}/users/two-factor/setup`,
+ null,
+ null,
+ {
+ 'X-Auth-Token': getToken(),
+ }
+ );
+ return resp.data as TwoFactorSecret;
+};
+
+export const enableTwoFactor = async (
+ code: string,
+ recoveryEncryptedTwoFactorSecret: B64EncryptionResult
+) => {
+ await HTTPService.post(
+ `${ENDPOINT}/users/two-factor/enable`,
+ {
+ code,
+ encryptedTwoFactorSecret:
+ recoveryEncryptedTwoFactorSecret.encryptedData,
+ twoFactorSecretDecryptionNonce:
+ recoveryEncryptedTwoFactorSecret.nonce,
+ },
+ null,
+ {
+ 'X-Auth-Token': getToken(),
+ }
+ );
+};
+
+export const setRecoveryKey = (token: string, recoveryKey: RecoveryKey) =>
+ HTTPService.put(`${ENDPOINT}/users/recovery-key`, recoveryKey, null, {
+ 'X-Auth-Token': token,
+ });
diff --git a/packages/accounts/components/TwoFactor/Setup.tsx b/packages/accounts/components/TwoFactor/Setup.tsx
new file mode 100644
index 0000000000..7ea2025db1
--- /dev/null
+++ b/packages/accounts/components/TwoFactor/Setup.tsx
@@ -0,0 +1,33 @@
+import { VerticallyCentered } from 'components/Container';
+import { SetupMode } from 'pages/two-factor/setup';
+import SetupManualMode from 'pages/two-factor/setup/ManualMode';
+import SetupQRMode from 'pages/two-factor/setup/QRMode';
+import React, { useState } from 'react';
+import { TwoFactorSecret } from 'types/user';
+
+interface Iprops {
+ twoFactorSecret: TwoFactorSecret;
+}
+export function TwoFactorSetup({ twoFactorSecret }: Iprops) {
+ const [setupMode, setSetupMode] = useState<SetupMode>(SetupMode.QR_CODE);
+
+ const changeToManualMode = () => setSetupMode(SetupMode.MANUAL_CODE);
+
+ const changeToQRMode = () => setSetupMode(SetupMode.QR_CODE);
+
+ return (
+ <VerticallyCentered sx={{ mb: 3 }}>
+ {setupMode === SetupMode.QR_CODE ? (
+ <SetupQRMode
+ twoFactorSecret={twoFactorSecret}
+ changeToManualMode={changeToManualMode}
+ />
+ ) : (
+ <SetupManualMode
+ twoFactorSecret={twoFactorSecret}
+ changeToQRMode={changeToQRMode}
+ />
+ )}
+ </VerticallyCentered>
+ );
+}
diff --git a/packages/accounts/pages/two-factor/setup.tsx b/packages/accounts/pages/two-factor/setup.tsx
new file mode 100644
index 0000000000..90c88ed8d0
--- /dev/null
+++ b/packages/accounts/pages/two-factor/setup.tsx
@@ -0,0 +1,84 @@
+import React, { useEffect, useState } from 'react';
+import { enableTwoFactor, setupTwoFactor } from '@ente/accounts/api/user';
+import { t } from 'i18next';
+
+import { VerticallyCentered } from '@ente/shared/components/Container';
+import VerifyTwoFactor, {
+ VerifyTwoFactorCallback,
+} from '@ente/accounts/components/TwoFactor/VerifyForm';
+import { encryptWithRecoveryKey } from '@ente/shared/crypto/helpers';
+import { setData, LS_KEYS, getData } from '@ente/shared/storage/localStorage';
+import { PAGES } from '@ente/accounts/constants/pages';
+import { TwoFactorSecret } from '@ente/accounts/types/user';
+import Card from '@mui/material/Card';
+import { Box, CardContent, Typography } from '@mui/material';
+import { TwoFactorSetup } from '@ente/accounts/components/TwoFactor/Setup';
+import LinkButton from '@ente/shared/components/LinkButton';
+import { PageProps } from '@ente/shared/apps/types';
+// import { logError } from 'utils/sentry';
+
+export enum SetupMode {
+ QR_CODE,
+ MANUAL_CODE,
+}
+
+export default function SetupTwoFactor({ router }: PageProps) {
+ const [twoFactorSecret, setTwoFactorSecret] =
+ useState<TwoFactorSecret>(null);
+
+ useEffect(() => {
+ if (twoFactorSecret) {
+ return;
+ }
+ const main = async () => {
+ try {
+ const twoFactorSecret = await setupTwoFactor();
+ setTwoFactorSecret(twoFactorSecret);
+ } catch (e) {
+ console.log(e);
+ // logError(e, 'failed to get two factor setup code');
+ }
+ };
+ main();
+ }, []);
+
+ const onSubmit: VerifyTwoFactorCallback = async (
+ otp: string,
+ markSuccessful
+ ) => {
+ const recoveryEncryptedTwoFactorSecret = await encryptWithRecoveryKey(
+ twoFactorSecret.secretCode
+ );
+ await enableTwoFactor(otp, recoveryEncryptedTwoFactorSecret);
+ await markSuccessful();
+ setData(LS_KEYS.USER, {
+ ...getData(LS_KEYS.USER),
+ isTwoFactorEnabled: true,
+ });
+ router.push(PAGES.GALLERY);
+ };
+
+ return (
+ <VerticallyCentered>
+ <Card>
+ <CardContent>
+ <VerticallyCentered sx={{ p: 3 }}>
+ <Box mb={4}>
+ <Typography variant="h2">
+ {t('TWO_FACTOR')}
+ </Typography>
+ </Box>
+ <TwoFactorSetup twoFactorSecret={twoFactorSecret} />
+ <VerifyTwoFactor
+ onSubmit={onSubmit}
+ buttonText={t('ENABLE')}
+ />
+ <LinkButton sx={{ mt: 2 }} onClick={router.back}>
+ {t('GO_BACK')}
+ </LinkButton>
+ </VerticallyCentered>
+ </CardContent>
+ </Card>
+ </VerticallyCentered>
+ );
+}
diff --git a/packages/accounts/types/user.ts b/packages/accounts/types/user.ts
index 052ed24fab..df293e3aab 100644
--- a/packages/accounts/types/user.ts
+++ b/packages/accounts/types/user.ts
@@ -33,3 +33,10 @@ export interface UpdatedKey {
memLimit: number;
opsLimit: number;
}
+
+export interface RecoveryKey {
+ masterKeyEncryptedWithRecoveryKey: string;
+ masterKeyDecryptionNonce: string;
+ recoveryKeyEncryptedWithMasterKey: string;
+ recoveryKeyDecryptionNonce: string;
+}
diff --git a/packages/shared/crypto/helpers.ts b/packages/shared/crypto/helpers.ts
index 3a1d17f7b9..da9d0bbab3 100644
--- a/packages/shared/crypto/helpers.ts
+++ b/packages/shared/crypto/helpers.ts
@@ -1,7 +1,10 @@
import ComlinkCryptoWorker from '.';
-import { LS_KEYS, getData, setData } from '../storage/localStorage';
-import { SESSION_KEYS, setKey } from '../storage/sessionStorage';
-import { KeyAttributes } from '../user/types';
+import { LS_KEYS, getData, setData } from '@ente/shared/storage/localStorage';
+import { getToken } from '@ente/shared/storage/localStorage/helpers';
+import { SESSION_KEYS, setKey } from '@ente/shared/storage/sessionStorage';
+import { getActualKey } from '@ente/shared/user';
+import { KeyAttributes } from '@ente/shared/user/types';
+import { setRecoveryKey } from '@ente/accounts/api/user';
const LOGIN_SUB_KEY_LENGTH = 32;
const LOGIN_SUB_KEY_ID = 1;
@@ -107,3 +110,74 @@ export const saveKeyInSessionStore = async (
// safeStorageService.setEncryptionKey(key);
// }
};
+
+export async function encryptWithRecoveryKey(key: string) {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const hexRecoveryKey = await getRecoveryKey();
+ const recoveryKey = await cryptoWorker.fromHex(hexRecoveryKey);
+ const encryptedKey = await cryptoWorker.encryptToB64(key, recoveryKey);
+ return encryptedKey;
+}
+
+export const getRecoveryKey = async () => {
+ let recoveryKey: string = null;
+ try {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+
+ const keyAttributes: KeyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
+ const {
+ recoveryKeyEncryptedWithMasterKey,
+ recoveryKeyDecryptionNonce,
+ } = keyAttributes;
+ const masterKey = await getActualKey();
+ if (recoveryKeyEncryptedWithMasterKey) {
+ recoveryKey = await cryptoWorker.decryptB64(
+ recoveryKeyEncryptedWithMasterKey,
+ recoveryKeyDecryptionNonce,
+ masterKey
+ );
+ } else {
+ recoveryKey = await createNewRecoveryKey();
+ }
+ recoveryKey = await cryptoWorker.toHex(recoveryKey);
+ return recoveryKey;
+ } catch (e) {
+ console.log(e);
+ // logError(e, 'getRecoveryKey failed');
+ throw e;
+ }
+};
+
+// Used only for legacy users for whom we did not generate recovery keys during
+// sign up
+async function createNewRecoveryKey() {
+ const masterKey = await getActualKey();
+ const existingAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
+
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+
+ const recoveryKey = await cryptoWorker.generateEncryptionKey();
+ const encryptedMasterKey = await cryptoWorker.encryptToB64(
+ masterKey,
+ recoveryKey
+ );
+ const encryptedRecoveryKey = await cryptoWorker.encryptToB64(
+ recoveryKey,
+ masterKey
+ );
+ const recoveryKeyAttributes = {
+ masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,
+ masterKeyDecryptionNonce: encryptedMasterKey.nonce,
+ recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,
+ recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,
+ };
+ await setRecoveryKey(getToken(), recoveryKeyAttributes);
+
+ const updatedKeyAttributes = Object.assign(
+ existingAttributes,
+ recoveryKeyAttributes
+ );
+ setData(LS_KEYS.KEY_ATTRIBUTES, updatedKeyAttributes);
+
+ return recoveryKey;
+}