π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
migrating verify page part 1
Abhinava85e199fb064
diff --git a/apps/photos/src/pages/verify/index.tsx b/apps/photos/src/pages/verify/index.tsxindex 9d8dc9ea9c..695575725f 100644--- a/apps/photos/src/pages/verify/index.tsx+++ b/apps/photos/src/pages/verify/index.tsx@@ -1,192 +1,10 @@-import React, { useState, useEffect, useContext } from 'react';-import { Trans } from 'react-i18next';-import { t } from 'i18next';--import { LS_KEYS, getData, setData } from 'utils/storage/localStorage';+import VerifyPage from '@ente/accounts/pages/verify';import { useRouter } from 'next/router';-import {- verifyOtt,- sendOtt,- logoutUser,- clearFiles,- putAttributes,- configureSRP,-} from 'services/userService';-import { setIsFirstLogin } from 'utils/storage';-import { clearKeys } from 'utils/storage/sessionStorage';import { AppContext } from 'pages/_app';-import { PAGES } from 'constants/pages';-import {- KeyAttributes,- UserVerificationResponse,- User,- SRPSetupAttributes,-} from 'types/user';-import { Box, Typography } from '@mui/material';-import FormPaperTitle from 'components/Form/FormPaper/Title';-import FormPaper from 'components/Form/FormPaper';-import FormPaperFooter from 'components/Form/FormPaper/Footer';-import LinkButton from 'components/pages/gallery/LinkButton';-import SingleInputForm, {- SingleInputFormProps,-} from 'components/SingleInputForm';-import EnteSpinner from 'components/EnteSpinner';-import { VerticallyCentered } from 'components/Container';-import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';-import { ApiError } from 'utils/error';-import { HttpStatusCode } from 'axios';+import { useContext } from 'react';export default function Verify() {- const [email, setEmail] = useState('');- const [resend, setResend] = useState(0);- const router = useRouter();const appContext = useContext(AppContext);-- useEffect(() => {- const main = async () => {- router.prefetch(PAGES.TWO_FACTOR_VERIFY);- router.prefetch(PAGES.CREDENTIALS);- router.prefetch(PAGES.GENERATE);- const user: User = getData(LS_KEYS.USER);- const keyAttributes: KeyAttributes = getData(- LS_KEYS.KEY_ATTRIBUTES- );- if (!user?.email) {- router.push(PAGES.ROOT);- } else if (- keyAttributes?.encryptedKey &&- (user.token || user.encryptedToken)- ) {- router.push(PAGES.CREDENTIALS);- } else {- setEmail(user.email);- }- };- main();- appContext.showNavBar(true);- }, []);-- const onSubmit: SingleInputFormProps['callback'] = async (- ott,- setFieldError- ) => {- try {- const resp = await verifyOtt(email, ott);- const {- keyAttributes,- encryptedToken,- token,- id,- twoFactorSessionID,- } = resp.data as UserVerificationResponse;- if (twoFactorSessionID) {- setData(LS_KEYS.USER, {- email,- twoFactorSessionID,- isTwoFactorEnabled: true,- });- setIsFirstLogin(true);- router.push(PAGES.TWO_FACTOR_VERIFY);- } else {- setData(LS_KEYS.USER, {- email,- token,- encryptedToken,- id,- isTwoFactorEnabled: false,- });- if (keyAttributes) {- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);- setData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES, keyAttributes);- } else {- if (getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES)) {- await putAttributes(- token,- getData(LS_KEYS.ORIGINAL_KEY_ATTRIBUTES)- );- }- if (getData(LS_KEYS.SRP_SETUP_ATTRIBUTES)) {- const srpSetupAttributes: SRPSetupAttributes = getData(- LS_KEYS.SRP_SETUP_ATTRIBUTES- );- await configureSRP(srpSetupAttributes);- }- }- clearFiles();- setIsFirstLogin(true);- const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);- InMemoryStore.delete(MS_KEYS.REDIRECT_URL);- if (keyAttributes?.encryptedKey) {- clearKeys();- router.push(redirectURL ?? PAGES.CREDENTIALS);- } else {- router.push(redirectURL ?? PAGES.GENERATE);- }- }- } catch (e) {- if (e instanceof ApiError) {- if (e?.httpStatusCode === HttpStatusCode.Unauthorized) {- setFieldError(t('INVALID_CODE'));- } else if (e?.httpStatusCode === HttpStatusCode.Gone) {- setFieldError(t('EXPIRED_CODE'));- }- } else {- setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);- }- }- };-- const resendEmail = async () => {- setResend(1);- await sendOtt(email);- setResend(2);- setTimeout(() => setResend(0), 3000);- };-- if (!email) {- return (- <VerticallyCentered>- <EnteSpinner />- </VerticallyCentered>- );- }-- return (- <VerticallyCentered>- <FormPaper>- <FormPaperTitle sx={{ mb: 14, wordBreak: 'break-word' }}>- <Trans- i18nKey="EMAIL_SENT"- components={{- a: <Box color="text.muted" component={'span'} />,- }}- values={{ email }}- />- </FormPaperTitle>- <Typography color={'text.muted'} mb={2} variant="small">- {t('CHECK_INBOX')}- </Typography>- <SingleInputForm- fieldType="text"- autoComplete="one-time-code"- placeholder={t('ENTER_OTT')}- buttonText={t('VERIFY')}- callback={onSubmit}- />-- <FormPaperFooter style={{ justifyContent: 'space-between' }}>- {resend === 0 && (- <LinkButton onClick={resendEmail}>- {t('RESEND_MAIL')}- </LinkButton>- )}- {resend === 1 && <span>{t('SENDING')}</span>}- {resend === 2 && <span>{t('SENT')}</span>}- <LinkButton onClick={logoutUser}>- {t('CHANGE_EMAIL')}- </LinkButton>- </FormPaperFooter>- </FormPaper>- </VerticallyCentered>- );+ const router = useRouter();+ return <VerifyPage appContext={appContext} router={router} />;}diff --git a/packages/accounts/components/Login.tsx b/packages/accounts/components/Login.tsxindex 9add329ebb..b4e413d10e 100644--- a/packages/accounts/components/Login.tsx+++ b/packages/accounts/components/Login.tsx@@ -1,5 +1,5 @@import { useRouter } from 'next/router';-import { getSRPAttributes, sendOtt } from '../services/user';+import { getSRPAttributes, sendOtt } from '../services/srp';import { setData, LS_KEYS } from '@ente/shared/storage/localStorage';import { PAGES } from '../constants/pages';import FormPaperTitle from '@ente/shared/components/Form/FormPaper/Title';diff --git a/packages/accounts/constants/pages.ts b/packages/accounts/constants/pages.tsindex 470026af32..f4bc3614c9 100644--- a/packages/accounts/constants/pages.ts+++ b/packages/accounts/constants/pages.ts@@ -1,4 +1,5 @@export enum PAGES {+ ROOT = '/',CHANGE_EMAIL = '/change-email',CHANGE_PASSWORD = '/change-password',CREDENTIALS = '/credentials',diff --git a/packages/accounts/services/user.ts b/packages/accounts/services/srp.tssimilarity index 89%rename from packages/accounts/services/user.tsrename to packages/accounts/services/srp.tsindex e2337b5322..4443e886c2 100644--- a/packages/accounts/services/user.ts+++ b/packages/accounts/services/srp.ts@@ -1,4 +1,5 @@-// import { PAGES } from 'constants/pages';+import { PAGES } from '../constants/pages';+import { NextRouter } from 'next/router';import {getEndpoint,// getFamilyPortalURL,@@ -8,7 +9,7 @@ import {// import router from 'next/router';// import { clearData, getData, LS_KEYS } from 'utils/storage/localStorage';// import localForage from 'utils/storage/localForage';-// import { getToken } from 'utils/common/key';+import { getToken } from '@ente/shared/storage/localStorage/helper';import HTTPService from '@ente/shared/network/HTTPService';// import {// computeVerifierHelper,@@ -19,7 +20,6 @@ import HTTPService from '@ente/shared/network/HTTPService';// import { logError } from 'utils/sentry';// import { eventBus, Events } from './events';import {- // KeyAttributes,// RecoveryKey,// TwoFactorSecret,// TwoFactorVerificationResponse,@@ -39,7 +39,8 @@ import {// UpdateSRPAndKeysRequest,// UpdateSRPAndKeysResponse,GetSRPAttributesResponse,-} from '../types/user';+} from '../types/srp';+import { KeyAttributes } from '@ente/shared/user/types';// import { ApiError, CustomError } from 'utils/error';// import isElectron from 'is-electron';// import safeStorageService from './electron/safeStorage';@@ -127,69 +128,74 @@ export const sendOtt = (appName: string, email: string) => {// }// };-// export const verifyOtt = (email: string, ott: string) =>-// HTTPService.post(`${ENDPOINT}/users/verify-email`, { email, ott });+export const verifyOtt = (email: string, ott: string) =>+ HTTPService.post(`${ENDPOINT}/users/verify-email`, { email, ott });-// export const putAttributes = (token: string, keyAttributes: KeyAttributes) =>-// HTTPService.put(`${ENDPOINT}/users/attributes`, { keyAttributes }, null, {-// 'X-Auth-Token': token,-// });+export const putAttributes = (token: string, keyAttributes: KeyAttributes) =>+ HTTPService.put(+ `${ENDPOINT}/users/attributes`,+ { keyAttributes },+ undefined,+ {+ 'X-Auth-Token': token,+ }+ );// export const setRecoveryKey = (token: string, recoveryKey: RecoveryKey) =>// HTTPService.put(`${ENDPOINT}/users/recovery-key`, recoveryKey, null, {// 'X-Auth-Token': token,// });-// export const logoutUser = async () => {-// try {-// try {-// // ignore server logout result as logoutUser can be triggered before sign up or on token expiry-// await _logout();-// } catch (e) {-// //ignore-// }-// try {-// InMemoryStore.clear();-// } catch (e) {-// logError(e, 'clear InMemoryStore failed');-// }-// try {-// clearKeys();-// } catch (e) {-// logError(e, 'clearKeys failed');-// }-// try {-// clearData();-// } catch (e) {-// logError(e, 'clearData failed');-// }-// try {-// await deleteAllCache();-// } catch (e) {-// logError(e, 'deleteAllCache failed');-// }-// try {-// await clearFiles();-// } catch (e) {-// logError(e, 'clearFiles failed');-// }-// if (isElectron()) {-// try {-// safeStorageService.clearElectronStore();-// } catch (e) {-// logError(e, 'clearElectronStore failed');-// }-// }-// try {-// eventBus.emit(Events.LOGOUT);-// } catch (e) {-// logError(e, 'Error in logout handlers');-// }-// router.push(PAGES.ROOT);-// } catch (e) {-// logError(e, 'logoutUser failed');-// }-// };+export const logoutUser = async (router: NextRouter) => {+ try {+ try {+ // ignore server logout result as logoutUser can be triggered before sign up or on token expiry+ await _logout();+ } catch (e) {+ //ignore+ }+ // try {+ // InMemoryStore.clear();+ // } catch (e) {+ // logError(e, 'clear InMemoryStore failed');+ // }+ // try {+ // clearKeys();+ // } catch (e) {+ // logError(e, 'clearKeys failed');+ // }+ // try {+ // clearData();+ // } catch (e) {+ // logError(e, 'clearData failed');+ // }+ // try {+ // await deleteAllCache();+ // } catch (e) {+ // logError(e, 'deleteAllCache failed');+ // }+ // try {+ // await clearFiles();+ // } catch (e) {+ // logError(e, 'clearFiles failed');+ // }+ // if (isElectron()) {+ // try {+ // safeStorageService.clearElectronStore();+ // } catch (e) {+ // logError(e, 'clearElectronStore failed');+ // }+ // }+ // try {+ // eventBus.emit(Events.LOGOUT);+ // } catch (e) {+ // logError(e, 'Error in logout handlers');+ // }+ router.push(PAGES.ROOT);+ } catch (e) {+ // logError(e, 'logoutUser failed');+ }+};// export const clearFiles = async () => {// await localForage.clear();@@ -311,18 +317,18 @@ export const sendOtt = (appName: string, email: string) => {// return resp.data['status'];// };-// export const _logout = async () => {-// if (!getToken()) return true;-// try {-// await HTTPService.post(`${ENDPOINT}/users/logout`, null, null, {-// 'X-Auth-Token': getToken(),-// });-// return true;-// } catch (e) {-// logError(e, '/users/logout failed');-// return false;-// }-// };+export const _logout = async () => {+ if (!getToken()) return true;+ try {+ await HTTPService.post(`${ENDPOINT}/users/logout`, null, undefined, {+ 'X-Auth-Token': getToken(),+ });+ return true;+ } catch (e) {+ // logError(e, '/users/logout failed');+ return false;+ }+};// export const sendOTTForEmailChange = async (email: string) => {// if (!getToken()) {diff --git a/packages/accounts/types/user.ts b/packages/accounts/types/srp.tssimilarity index 100%rename from packages/accounts/types/user.tsrename to packages/accounts/types/srp.tsdiff --git a/packages/shared/storage/localStorage/helper.ts b/packages/shared/storage/localStorage/helper.tsnew file mode 100644index 0000000000..574c20ad1d--- /dev/null+++ b/packages/shared/storage/localStorage/helper.ts@@ -0,0 +1,3 @@+import { LS_KEYS, getData } from '.';++export const getToken = () => getData(LS_KEYS.USER)?.token;diff --git a/packages/shared/storage/localStorage.ts b/packages/shared/storage/localStorage/index.tssimilarity index 100%rename from packages/shared/storage/localStorage.tsrename to packages/shared/storage/localStorage/index.tsdiff --git a/packages/shared/user/types.ts b/packages/shared/user/types.tsnew file mode 100644index 0000000000..af2dcd039e--- /dev/null+++ b/packages/shared/user/types.ts@@ -0,0 +1,14 @@+export interface KeyAttributes {+ kekSalt: string;+ encryptedKey: string;+ keyDecryptionNonce: string;+ opsLimit: number;+ memLimit: number;+ publicKey: string;+ encryptedSecretKey: string;+ secretKeyDecryptionNonce: string;+ masterKeyEncryptedWithRecoveryKey: string;+ masterKeyDecryptionNonce: string;+ recoveryKeyEncryptedWithMasterKey: string;+ recoveryKeyDecryptionNonce: string;+}