A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: 2fa
ammarahm-ed7f5250cd86ee
diff --git a/apps/mobile/src/components/announcements/title.js b/apps/mobile/src/components/announcements/title.jsindex 4f3e89bd7..b723cfc70 100644--- a/apps/mobile/src/components/announcements/title.js+++ b/apps/mobile/src/components/announcements/title.js@@ -63,7 +63,7 @@ export const Title = ({ text, style = {}, inline }) => {style={{marginHorizontal: 12,...getStyle(style),- marginTop: style.marginTop || 12+ marginTop: style?.marginTop || 12}}>{text}diff --git a/apps/mobile/src/components/auth/login.js b/apps/mobile/src/components/auth/login.jsindex 249b632b7..6d97c70c8 100644--- a/apps/mobile/src/components/auth/login.js+++ b/apps/mobile/src/components/auth/login.js@@ -24,6 +24,8 @@ import Paragraph from '../ui/typography/paragraph';import { SVG } from './background';import { ForgotPassword } from './forgot-password';import SettingsService from '../../services/settings';+import SheetProvider from '../sheet-provider';+import TwoFactorVerification from './two-factor';export const Login = ({ changeMode }) => {const colors = useThemeStore(state => state.colors);@@ -61,12 +63,19 @@ export const Login = ({ changeMode }) => {};}, []);- const login = async () => {+ const login = async (mfa, callback) => {if (!validateInfo() || error) return;setLoading(true);let user;try {- await db.user.login(email.current.toLowerCase(), password.current);+ if (mfa) {+ console.log('mfa details', mfa);+ await db.user.mfaLogin(email.current.toLowerCase(), password.current, mfa);+ } else {+ await db.user.login(email.current.toLowerCase(), password.current);+ }+ callback && callback(true);+user = await db.user.getUser();if (!user) throw new Error('Email or password incorrect!');PremiumService.setPremiumStatus();@@ -91,14 +100,27 @@ export const Login = ({ changeMode }) => {progress: true});} catch (e) {- console.log(e.stack);- setLoading(false);- ToastEvent.show({- heading: user ? 'Failed to sync' : 'Login failed',- message: e.message,- type: 'error',- context: 'local'- });+ callback && callback(false);+ console.log('Login error', e.message, e.data);+ if (e.message === 'Multifactor authentication required.') {+ TwoFactorVerification.present(async mfa => {+ if (mfa) {+ console.log(mfa);+ await login(mfa);+ } else {+ setLoading(false);+ }+ }, e.data);+ } else {+ console.log(e.stack);+ setLoading(false);+ ToastEvent.show({+ heading: user ? 'Failed to sync' : 'Login failed',+ message: e.message,+ type: 'error',+ context: 'local'+ });+ }}};@@ -119,6 +141,7 @@ export const Login = ({ changeMode }) => {/><ForgotPassword />+ <SheetProvider context="two_factor_verify" />{loading ? <BaseDialog transparent={true} visible={true} animation="fade" /> : null}<Viewdiff --git a/apps/mobile/src/components/auth/sessionexpired.js b/apps/mobile/src/components/auth/sessionexpired.jsindex 7911cf6bd..75b8b8c3b 100644--- a/apps/mobile/src/components/auth/sessionexpired.js+++ b/apps/mobile/src/components/auth/sessionexpired.js@@ -26,6 +26,8 @@ import { Toast } from '../toast';import Heading from '../ui/typography/heading';import Paragraph from '../ui/typography/paragraph';import SettingsService from '../../services/settings';+import TwoFactorVerification from './two-factor';+import SheetProvider from '../sheet-provider';function getEmail(email) {if (!email) return null;@@ -96,12 +98,17 @@ export const SessionExpired = () => {}};- const login = async () => {+ const login = async (mfa, callback) => {if (error) return;setLoading(true);let user;try {- await db.user.login(email.current.toLowerCase(), password.current);+ if (mfa) {+ await db.user.mfaLogin(email.current.toLowerCase(), password.current, mfa);+ } else {+ await db.user.login(email.current.toLowerCase(), password.current);+ }+ callback && callback(true);user = await db.user.getUser();if (!user) throw new Error('Email or password incorrect!');PremiumService.setPremiumStatus();@@ -113,7 +120,6 @@ export const SessionExpired = () => {type: 'success',context: 'global'});- setVisible(false);await SettingsService.set({sessionExpired: false,userEmailConfirmed: user.isEmailConfirmed@@ -126,16 +132,25 @@ export const SessionExpired = () => {progress: true});} catch (e) {- setLoading(false);- ToastEvent.show({- heading: user ? 'Failed to sync' : 'Login failed',- message: e.message,- type: 'error',- context: 'local'- });+ callback && callback(true);+ if (e.message === 'MFA Required') {+ TwoFactorVerification.present(async mfa => {+ if (mfa) {+ await login(mfa);+ }+ }, e.data);+ } else {+ console.log(e.stack);+ setLoading(false);+ ToastEvent.show({+ heading: user ? 'Failed to sync' : 'Login failed',+ message: e.message,+ type: 'error',+ context: 'local'+ });+ }}};-return (visible && (<Modal@@ -146,6 +161,7 @@ export const SessionExpired = () => {}}visible={true}>+ <SheetProvider context="two_factor_verify" /><Viewstyle={{width: focused ? '100%' : '99.9%',diff --git a/apps/mobile/src/components/auth/twofactor.js b/apps/mobile/src/components/auth/twofactor.jsnew file mode 100644index 000000000..153aa91e9--- /dev/null+++ b/apps/mobile/src/components/auth/twofactor.js@@ -0,0 +1,261 @@+import React, { useRef, useState } from 'react';+import { View } from 'react-native';+import { eSendEvent, presentSheet } from '../../services/event-manager';+import { useThemeStore } from '../../stores/theme';+import { eCloseProgressDialog } from '../../utils/events';+import useTimer from '../../utils/hooks/use-timer';+import { SIZE } from '../../utils/size';+import { Button } from '../ui/button';+import { IconButton } from '../ui/icon-button';+import Input from '../ui/input';+import { PressableButton } from '../ui/pressable';+import Seperator from '../ui/seperator';+import Heading from '../ui/typography/heading';+import Paragraph from '../ui/typography/paragraph';++const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {+ const colors = useThemeStore(state => state.colors);+ const code = useRef();+ const [currentMethod, setCurrentMethod] = useState({+ method: mfaInfo?.primaryMethod,+ isPrimary: true+ });+ const { seconds, start } = useTimer(currentMethod.method);+ const [loading, setLoading] = useState(false);+ const inputRef = useRef();++ const codeHelpText = {+ app: 'Enter the 6 digit code from your authenticator app to continue logging in',+ sms: 'Enter the 6 digit code sent to your phone number to continue logging in',+ email: 'Enter the 6 digit code sent to your email to continue logging in',+ recoveryCode: 'Enter the 8 digit recovery code to continue logging in'+ };++ const secondaryMethodsText = {+ app: "I don't have access to authenticator app",+ sms: "I don't have access to my phone",+ email: "I don't have access to email",+ recoveryCode: "I don't have recovery codes"+ };++ const onNext = async () => {+ const length = currentMethod.method === 'recoveryCode' ? 8 : 6;++ if (!code.current || code.current.length !== length) return;+ console.log(currentMethod.method, code.current);+ setLoading(true);+ inputRef.current?.blur();+ await onMfaLogin(+ {+ method: currentMethod.method,+ code: code.current+ },+ result => {+ console.log('result recieved');+ if (result) {+ eSendEvent(eCloseProgressDialog, 'two_factor_verify');+ }+ setLoading(false);+ }+ );+ setLoading(false);+ };++ const onRequestSecondaryMethod = () => {+ setCurrentMethod({+ method: null,+ isPrimary: false+ });+ };++ const methods = [+ {+ id: 'sms',+ title: 'Send code via SMS',+ icon: 'message-plus-outline'+ },+ {+ id: 'email',+ title: 'Send code via email',+ icon: 'email-outline'+ },+ {+ id: 'app',+ title: 'Enter code from authenticator app',+ icon: 'cellphone-key'+ },+ {+ id: 'recoveryCode',+ title: 'I have a recovery code',+ icon: 'key'+ }+ ];++ const getMethods = () => {+ return methods.filter(+ m =>+ m.id === mfaInfo?.primaryMethod ||+ m.id === mfaInfo?.secondaryMethod ||+ m.id === 'recoveryCode'+ );+ };++ return (+ <View>+ <View+ style={{+ alignItems: 'center',+ paddingHorizontal: currentMethod.method ? 12 : 0+ }}+ >+ <IconButton+ customStyle={{+ width: 70,+ height: 70+ }}+ size={50}+ name="key"+ color={colors.accent}+ />+ <Heading+ style={{+ textAlign: 'center'+ }}+ >+ {currentMethod.method+ ? 'Two factor authentication'+ : 'Other methods for two-factor authentication'}+ </Heading>+ <Paragraph+ style={{+ width: '80%',+ textAlign: 'center'+ }}+ >+ {codeHelpText[currentMethod.method] || `Select how you would like to recieve the code`}+ </Paragraph>++ <Seperator />++ {currentMethod.method === 'sms' || currentMethod === 'email' ? (+ <Button+ onPress={() => {+ if (seconds) return;+ start(60);+ }}+ type={seconds ? 'gray' : 'transparent'}+ title={`${seconds ? `Resend code in (${seconds})` : 'Send code'}`}+ height={30}+ />+ ) : null}++ <Seperator />++ {currentMethod.method ? (+ <>+ <Input+ placeholder={currentMethod.method === 'recoveryCode' ? 'xxxxxxxx' : 'xxxxxx'}+ maxLength={currentMethod.method === 'recoveryCode' ? 8 : 6}+ fwdRef={inputRef}+ textAlign="center"+ keyboardType="numeric"+ onChangeText={value => {+ code.current = value;+ onNext();+ }}+ //@ts-ignore+ inputStyle={{+ fontSize: SIZE.lg,+ height: 60,+ textAlign: 'center',+ letterSpacing: 10,+ width: null+ }}+ containerStyle={{+ height: 60,+ borderWidth: 0,+ //@ts-ignore+ width: null,+ minWidth: '50%'+ }}+ />+ <Seperator />+ <Button+ title={loading ? null : 'Next'}+ type="accent"+ width={250}+ loading={loading}+ onPress={onNext}+ style={{+ borderRadius: 100,+ marginBottom: 10+ }}+ />++ <Button+ title={secondaryMethodsText[currentMethod.method]}+ type="gray"+ onPress={onRequestSecondaryMethod}+ height={30}+ />+ </>+ ) : (+ <>+ {getMethods().map(item => (+ <PressableButton+ key={item.title}+ onPress={() => {+ setCurrentMethod({+ method: item.id,+ isPrimary: false+ });+ }}+ customStyle={{+ paddingHorizontal: 12,+ paddingVertical: 12,+ marginTop: 0,+ flexDirection: 'row',+ borderRadius: 0,+ alignItems: 'center',+ width: '100%',+ justifyContent: 'flex-start'+ }}+ >+ <IconButton+ type="grayAccent"+ customStyle={{+ width: 40,+ height: 40,+ marginRight: 10+ }}+ size={15}+ color={colors.accent}+ name={item.icon}+ />+ <View+ style={{+ flexShrink: 1+ }}+ >+ <Paragraph size={SIZE.md}>{item.title}</Paragraph>+ </View>+ </PressableButton>+ ))}+ </>+ )}+ </View>+ </View>+ );+};++TwoFactorVerification.present = (onMfaLogin, data) => {+ presentSheet({+ component: <TwoFactorVerification onMfaLogin={onMfaLogin} mfaInfo={data} />,+ context: 'two_factor_verify',+ onClose: () => {+ onMfaLogin();+ }+ });+};++export default TwoFactorVerification;diff --git a/apps/mobile/src/components/dialog/DialogHeader.js b/apps/mobile/src/components/dialog/DialogHeader.tsxsimilarity index 81%rename from apps/mobile/src/components/dialog/DialogHeader.jsrename to apps/mobile/src/components/dialog/DialogHeader.tsxindex 96dca794d..4d79df639 100644--- a/apps/mobile/src/components/dialog/DialogHeader.js+++ b/apps/mobile/src/components/dialog/DialogHeader.tsx@@ -4,9 +4,26 @@ import { View } from 'react-native';import { useThemeStore } from '../../stores/theme';import { SIZE } from '../../utils/size';import { Button } from '../ui/button';+import { PressableButtonProps } from '../ui/pressable';import Heading from '../ui/typography/heading';import Paragraph from '../ui/typography/paragraph';+type DialogHeaderProps = {+ icon?: string;+ title?: string;+ paragraph?: string;+ button?: {+ onPress?: () => void;+ loading?: boolean;+ title?: string;+ type?: PressableButtonProps['type'];+ };+ paragraphColor?: string;+ padding?: number;+ centered?: boolean;+ titlePart?: string;+};+const DialogHeader = ({icon,title,@@ -16,7 +33,7 @@ const DialogHeader = ({padding,centered,titlePart-}) => {+}: DialogHeaderProps) => {const colors = useThemeStore(state => state.colors);return (@@ -42,7 +59,7 @@ const DialogHeader = ({alignItems: 'center'}}>- <Heading size={SIZE.xl}>+ <Heading style={{ textAlign: centered ? 'center' : 'left' }} size={SIZE.xl}>{title} {titlePart ? <Text style={{ color: colors.accent }}>{titlePart}</Text> : null}</Heading>diff --git a/apps/mobile/src/components/launcher/index.js b/apps/mobile/src/components/launcher/index.jsindex a3280a589..088f2333e 100644--- a/apps/mobile/src/components/launcher/index.js+++ b/apps/mobile/src/components/launcher/index.js@@ -179,7 +179,7 @@ const Launcher = React.memo(const checkForRateAppRequest = async () => {let rateApp = SettingsService.get().rateApp;- if (rateApp && rateApp < Date.now() && !useMessageStore.getState().message.visible) {+ if (rateApp && rateApp < Date.now() && !useMessageStore.getState().message?.visible) {setRateAppMessage();return true;}diff --git a/apps/mobile/src/components/sheets/recoverykey/index.js b/apps/mobile/src/components/sheets/recoverykey/index.jsindex cc688e090..96ad511f6 100644--- a/apps/mobile/src/components/sheets/recoverykey/index.js+++ b/apps/mobile/src/components/sheets/recoverykey/index.js@@ -8,19 +8,18 @@ import Share from 'react-native-share';import { LOGO_BASE64 } from '../../../assets/images/assets';import { eSubscribeEvent, eUnSubscribeEvent, ToastEvent } from '../../../services/event-manager';import { clearMessage } from '../../../services/message';+import SettingsService from '../../../services/settings';import { db } from '../../../utils/database';+import Storage from '../../../utils/database/storage';import { eOpenRecoveryKeyDialog } from '../../../utils/events';-import { MMKV } from '../../../utils/database/mmkv';import { sanitizeFilename } from '../../../utils/sanitizer';import { SIZE } from '../../../utils/size';-import Storage from '../../../utils/database/storage';import { sleep } from '../../../utils/time';-import { Button } from '../../ui/button';import DialogHeader from '../../dialog/dialog-header';+import { Button } from '../../ui/button';import Seperator from '../../ui/seperator';import SheetWrapper from '../../ui/sheet';import Paragraph from '../../ui/typography/paragraph';-import SettingsService from '../../../services/settings';let RNFetchBlob;diff --git a/apps/mobile/src/components/ui/input/index.tsx b/apps/mobile/src/components/ui/input/index.tsxindex 323f5eb00..2afae0645 100644--- a/apps/mobile/src/components/ui/input/index.tsx+++ b/apps/mobile/src/components/ui/input/index.tsx@@ -23,30 +23,30 @@ import { IconButton } from '../icon-button';import Paragraph from '../typography/paragraph';interface InputProps extends TextInputProps {- fwdRef: RefObject<any>;- validationType: 'password' | 'email' | 'confirmPassword' | 'username';- loading: boolean;- onSubmit: (event: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => void | undefined;- onErrorCheck: (error: boolean) => void;- errorMessage: string;- customColor: ColorValue;- customValidator: () => string;- marginBottom: number;- button: {+ fwdRef?: RefObject<any>;+ validationType?: 'password' | 'email' | 'confirmPassword' | 'username';+ loading?: boolean;+ onSubmit?: (event: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => void | undefined;+ onErrorCheck?: (error: boolean) => void;+ errorMessage?: string;+ customColor?: ColorValue;+ customValidator?: () => string;+ marginBottom?: number;+ button?: {icon: string;color: ColorValue;onPress: () => void;};- buttons: React.ReactNode;+ buttons?: React.ReactNode;onBlurInput?: () => void;onPress?: () => void;- height: number;- fontSize: number;+ height?: number;+ fontSize?: number;onFocusInput?: () => void;- marginRight: number;- buttonLeft: React.ReactNode;- inputStyle: TextInputProps['style'];- containerStyle: ViewStyle;+ marginRight?: number;+ buttonLeft?: React.ReactNode;+ inputStyle?: TextInputProps['style'];+ containerStyle?: ViewStyle;}const Input = ({@@ -93,7 +93,7 @@ const Input = ({if (!validationType) return;if (!value || value?.length === 0) {setError(false);- onErrorCheck(false);+ onErrorCheck && onErrorCheck(false);setErrorList({SHORT_PASS: true});@@ -112,7 +112,7 @@ const Input = ({isError = validateUsername(value);break;case 'confirmPassword':- isError = value === customValidator();+ isError = customValidator && value === customValidator();break;}@@ -125,11 +125,11 @@ const Input = ({}});setError(hasError);- onErrorCheck(hasError);+ onErrorCheck && onErrorCheck(hasError);setErrorList(isError);} else {setError(!isError);- onErrorCheck(!isError);+ onErrorCheck && onErrorCheck(!isError);}};diff --git a/apps/mobile/src/components/walkthroughs/index.tsx b/apps/mobile/src/components/walkthroughs/index.tsxindex 670aa4c89..b7572c4df 100644--- a/apps/mobile/src/components/walkthroughs/index.tsx+++ b/apps/mobile/src/components/walkthroughs/index.tsx@@ -130,6 +130,10 @@ Walkthrough.present = async (nopersist?: boolean) => {if (!nopersist) {+ if (!walkthroughState || Object.keys(walkthroughState).length === 0) {+ console.log('late init of walkthrough state');+ await Walkthrough.init();+ }if (walkthroughState[id]) return;//@ts-ignoreWalkthrough.update(id);diff --git a/apps/mobile/src/screens/settings/2fa.tsx b/apps/mobile/src/screens/settings/2fa.tsxnew file mode 100644index 000000000..48cb1afdd--- /dev/null+++ b/apps/mobile/src/screens/settings/2fa.tsx@@ -0,0 +1,675 @@+import Clipboard from '@react-native-clipboard/clipboard';+import React, { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react';+import { ActivityIndicator, Platform, View } from 'react-native';+import { FlatList } from 'react-native-gesture-handler';+import * as ScopedStorage from 'react-native-scoped-storage';+import RNFetchBlob from 'rn-fetch-blob';+import { sleep } from '../../../e2e/tests/utils.test';+import DialogHeader from '../../components/dialog/dialog-header';+import { Button } from '../../components/ui/button';+import { IconButton } from '../../components/ui/icon-button';+import Input from '../../components/ui/input';+import { PressableButton } from '../../components/ui/pressable';+import Seperator from '../../components/ui/seperator';+import { SvgView } from '../../components/ui/svg';+import Heading from '../../components/ui/typography/heading';+import Paragraph from '../../components/ui/typography/paragraph';+import { eSendEvent, presentSheet, ToastEvent } from '../../services/event-manager';+import { useSettingStore, useUserStore } from '../../stores/stores';+import { ThemeStore, useThemeStore } from '../../stores/theme';+import { db } from '../../utils/database';+import Storage from '../../utils/database/storage';+import { eCloseProgressDialog } from '../../utils/events';+import useTimer from '../../utils/hooks/use-timer';+import { sanitizeFilename } from '../../utils/sanitizer';+import { SIZE } from '../../utils/size';+import { CustomButton } from './button';+import { verifyUser } from './functions';+import SectionHeader from './section-header';++const TwoFactorAuth = ({ isSheet }: { isSheet: boolean }) => {+ const [collapsed, setCollapsed] = useState(isSheet ? false : true);+ const user = useUserStore(state => state.user);++ const enable2fa = () => {+ MFASheet.present();+ };++ const disable2fa = () => {+ verifyUser('global', async () => {+ await db.mfa?.disable();+ let user = await db.user?.fetchUser();+ useUserStore.getState().setUser(user);+ });+ };++ const mfaSettingsList = user?.mfa.isEnabled+ ? [+ {+ name: 'Add secondary 2FA methods',+ func: () => {+ MFASheet.present(true);+ },+ desc: 'Add alternate 2FA methods to protect your account'+ },+ {+ name: 'View recovery codes',+ func: () => {+ verifyUser('global', async () => {+ MFARecoveryCodes.present('sms');+ });+ },+ desc: 'View and save recovery codes for to recover your account'+ },+ {+ name: 'Disable Two Factor Authentication',+ func: disable2fa,+ desc: 'Increased security for your account'+ }+ ]+ : [+ {+ name: 'Enable Two Factor Authentication',+ func: enable2fa,+ desc: 'Increased security for your account'+ }+ ];++ return (+ <>+ {!isSheet && (+ <SectionHeader+ collapsed={collapsed}+ setCollapsed={setCollapsed}+ title="Two Factor Authentication"+ />+ )}++ {!collapsed && (+ <>+ {mfaSettingsList.map(item => (+ //@ts-ignore+ <CustomButton+ key={item.name}+ title={item.name}+ tagline={item.desc}+ onPress={item.func}+ />+ ))}+ </>+ )}+ </>+ );+};++export default TwoFactorAuth;++const mfaMethods: MFAMethod[] = [+ {+ id: 'app',+ title: 'Setup using an Authenticator app',+ body: 'Use an authenticator app like Google Authenticator on your phone to get authentication codes',+ icon: 'cellphone-key',+ recommended: true+ },+ {+ id: 'sms',+ title: 'Set up using SMS',+ body: 'Notesnook will send you an SMS with a 2FA code when prompted',+ icon: 'message-plus-outline'+ },+ {+ id: 'email',+ title: 'Set up using Email',+ body: 'Notesnook will send you a 2FA code on your email when prompted',+ icon: 'email-outline'+ }+];+type MFAMethod = {+ id: 'email' | 'sms' | 'app';+ title?: string;+ body?: string;+ icon?: string;+ recommended?: boolean | undefined;+};++type MFAStep = {+ id: string;+ props: { [name: string]: any };+};++type MFAStepProps = {+ recovery?: boolean;+ onSuccess?: (method?: MFAMethod) => void;+ setStep?: Dispatch<SetStateAction<MFAStep>>;+ method?: MFAMethod;+ isSetup?: boolean;+};+const MFAMethodsPickerStep = ({ recovery, onSuccess }: MFAStepProps) => {+ const colors = useThemeStore(state => state.colors);+ const user = useUserStore(state => state.user);++ const getMethods = () => {+ if (!recovery) return mfaMethods;+ return mfaMethods.filter(m => m.id !== user?.mfa.primaryMethod);+ };++ return (+ <>+ <DialogHeader+ title="Two-factor authentication"+ paragraph="Protect your notes by enabling 2 factor authentication"+ padding={12}+ />+ <Seperator />+ {getMethods().map(item => (+ <PressableButton+ key={item.title}+ onPress={() => {+ onSuccess && onSuccess(item);+ }}+ customStyle={{+ paddingHorizontal: 12,+ paddingVertical: 12,+ marginTop: 0,+ marginBottom: 12,+ flexDirection: 'row',+ borderRadius: 0,+ alignItems: 'flex-start'+ }}+ >+ <IconButton+ type="grayBg"+ customStyle={{+ width: 50,+ height: 50,+ marginRight: 10+ }}+ size={20}+ color={item.recommended ? colors.accent : colors.icon}+ name={item.icon}+ />+ <View+ style={{+ flexShrink: 1+ }}+ >+ <Heading size={SIZE.md}>{item.title}</Heading>+ <Paragraph size={SIZE.sm}>{item.body}</Paragraph>+ </View>+ </PressableButton>+ ))}+ </>+ );+};++const MFASetup = ({ method, onSuccess, setStep, recovery }: MFAStepProps) => {+ const colors = useThemeStore(state => state.colors);+ const user = useUserStore(state => state.user);+ const [authenticatorDetails, setAuthenticatorDetails] = useState({+ sharedKey: null,+ authenticatorUri: null+ });+ const code = useRef<string>();+ const phoneNumber = useRef<string>();+ const { seconds, setId, start } = useTimer(method?.id);++ const [loading, setLoading] = useState(method?.id === 'app' ? true : false);+ const [enabling, setEnabling] = useState(false);++ useEffect(() => {+ if (method?.id === 'app') {+ db.mfa?.setup('app').then(data => {+ setAuthenticatorDetails(data);+ setLoading(false);+ });+ }+ }, []);++ const codeHelpText = {+ app: 'After putting the above code in authenticator app, the app will display a code that you can enter below.',+ sms: 'You will receive a 2FA code on your phone number which you can enter below',+ email: 'You will receive a 2FA code on your email address which you can enter below'+ };++ const onNext = async () => {+ if (!code.current || code.current.length !== 6) return;+ try {+ if (!method) return;+ setEnabling(true);+ await db.mfa?.enable(method.id, code.current);+ let user = await db.user?.fetchUser();+ useUserStore.getState().setUser(user);+ onSuccess && onSuccess(method);+ setEnabling(false);+ } catch (e) {+ const error = e as Error;+ console.log('2fa submit code:', error.message);+ ToastEvent.error(error, 'Error submitting 2fa code');+ setEnabling(false);+ }+ };++ const onSendCode = async () => {+ console.log('send code');+ if (!method) return;+ if (method.id === 'app' && authenticatorDetails.sharedKey) {+ Clipboard.setString(authenticatorDetails.sharedKey);+ ToastEvent.show({+ heading: `Code copied!`,+ type: 'success',+ context: 'local'+ });+ return;+ }++ try {+ console.log('seconds', seconds);+ if (seconds) throw new Error('Please wait a few seconds before resending code');+ if (method.id === 'sms' && !phoneNumber.current) return;++ await db.mfa?.setup(method?.id, phoneNumber.current);++ if (method.id === 'sms') {+ console.log(phoneNumber.current);+ setId(method.id + phoneNumber.current);+ }+ await sleep(300);+ start(60, method.id + phoneNumber.current);+ ToastEvent.show({+ heading: `2FA code sent via ${method.id}.`,+ type: 'success',+ context: 'local'+ });+ } catch (e) {+ const error = e as Error;+ console.log('Send code:', error.message);+ ToastEvent.error(error, 'Error sending 2FA code');+ }+ };++ return !method ? null : (+ <View>+ <DialogHeader title={method?.title} paragraph={method?.body} padding={12} />+ <Seperator />++ <View+ style={{+ paddingHorizontal: 12+ }}+ >+ {loading ? (+ <View+ style={{+ justifyContent: 'center',+ alignItems: 'center',+ width: '100%',+ marginBottom: 50+ }}+ >+ <ActivityIndicator+ color={colors.accent}+ style={{+ height: 50+ }}+ />+ <Paragraph>Getting information.. please wait</Paragraph>+ </View>+ ) : (+ <>+ <Input+ loading={method?.id !== 'sms' ? true : false}+ value={+ method?.id === 'email'+ ? //@ts-ignore+ user.email+ : method?.id === 'app'+ ? authenticatorDetails?.sharedKey || ''+ : undefined+ }+ onChangeText={value => (phoneNumber.current = value)}+ placeholder={method?.id === 'email' ? 'Enter email address' : '+1234567890'}+ onSubmit={() => {+ onSendCode();+ }}+ buttons={+ <Button+ onPress={onSendCode}+ title={+ method.id === 'app'+ ? 'Copy'+ : `${seconds ? `Resend code in (${seconds})` : 'Send code'}`+ }+ />+ }+ />++ <Heading size={SIZE.md}>Enter the 6-digit code</Heading>+ <Paragraph>{codeHelpText[method?.id]}</Paragraph>+ <Seperator />+ <Input+ placeholder="xxxxxx"+ maxLength={6}+ loading={loading}+ textAlign="center"+ keyboardType="numeric"+ onChangeText={value => (code.current = value)}+ //@ts-ignore+ inputStyle={{+ fontSize: SIZE.lg,+ height: 60,+ textAlign: 'center',+ letterSpacing: 10,+ width: null+ }}+ containerStyle={{+ height: 60,+ borderWidth: 0,+ //@ts-ignore+ width: null+ }}+ />+ <Seperator />+ <Button+ title={enabling ? null : 'Next'}+ type="accent"+ width={250}+ onPress={onNext}+ loading={enabling}+ style={{+ borderRadius: 100,+ marginBottom: 10+ }}+ />++ <Button+ title="Select a different 2FA method"+ type="gray"+ height={25}+ onPress={() => {+ setStep &&+ setStep({+ id: 'mfapick',+ props: {+ recovery: recovery+ }+ });+ }}+ />+ </>+ )}+ </View>+ </View>+ );+};++const MFARecoveryCodes = ({ method, recovery, onSuccess, isSetup = true }: MFAStepProps) => {+ const colors = useThemeStore(state => state.colors);+ const [codes, setCodes] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ (async () => {+ try {+ const codes = await db.mfa?.codes(true);+ if (codes) setCodes(codes);+ setLoading(false);+ } catch (e) {+ const error = e as Error;+ ToastEvent.error(error, 'Error getting codes', 'local');+ setLoading(false);+ }+ })();+ }, []);++ return (+ <View>+ <DialogHeader+ centered={true}+ title="Save your recovery codes"+ paragraph={`If you lose access to your ${+ method?.id === 'email' ? 'email' : method?.id === 'sms' ? 'phone' : 'auth app'+ }, you can login to Notesnook using your recovery codes. Each code can only be used once.`}+ padding={12}+ />+ <Seperator />++ {loading ? (+ <View+ style={{+ justifyContent: 'center',+ alignItems: 'center',+ width: '100%',+ marginBottom: 50+ }}+ >+ <ActivityIndicator+ color={colors.accent}+ style={{+ height: 50+ }}+ />+ <Paragraph>Getting recovery codes.. please wait</Paragraph>+ </View>+ ) : (+ <>+ <FlatList+ data={codes}+ contentContainerStyle={{+ alignItems: 'center'+ }}+ numColumns={2}+ renderItem={({ item, index }) => (+ <Heading+ style={{ marginHorizontal: 15, marginVertical: 5, fontFamily: 'monospace' }}+ size={SIZE.lg}+ >+ {item}+ </Heading>+ )}+ />+ <Seperator />++ <View+ style={{+ flexDirection: 'row',+ justifyContent: 'center',+ marginBottom: 10+ }}+ >+ <Button+ title="Copy codes"+ fontSize={SIZE.md}+ onPress={() => {+ let codeString = codes.join('\n');+ Clipboard.setString(codeString);+ ToastEvent.show({+ heading: 'Recovery codes copied!',+ type: 'success',+ context: 'global'+ });+ }}+ style={{+ marginRight: 10+ }}+ />++ <Button+ title="Save to file"+ fontSize={SIZE.md}+ onPress={async () => {+ try {+ let path;+ let fileName = 'notesnook_recoverycodes';+ fileName = sanitizeFilename(fileName, { replacement: '_' });+ fileName = fileName + '.txt';+ const codeString = codes.join('\n');+ if (Platform.OS === 'android') {+ let file = await ScopedStorage.createDocument(+ fileName,+ 'text/plain',+ codeString,+ 'utf8'+ );+ if (!file) return;+ path = file.uri;+ } else {+ path = await Storage.checkAndCreateDir('/');+ await RNFetchBlob.fs.writeFile(path + fileName, codeString, 'utf8');+ path = path + fileName;+ }++ ToastEvent.show({+ heading: 'Recovery codes saved to text file',+ type: 'success',+ context: 'local'+ });+ return path;+ } catch (e) {}+ }}+ />+ </View>++ <Button+ title={isSetup ? 'Next' : 'Done'}+ type="accent"+ width={250}+ onPress={() => {+ if (isSetup) {+ onSuccess && onSuccess(method);+ } else {+ eSendEvent(eCloseProgressDialog);+ }+ }}+ style={{+ borderRadius: 100,+ marginBottom: 10+ }}+ />+ </>+ )}+ </View>+ );+};++MFARecoveryCodes.present = (methodId: MFAMethod['id']) => {+ presentSheet({+ component: <MFARecoveryCodes method={{ id: methodId }} isSetup={false} />+ });+};++const mfaSvg = (+ colors: ThemeStore['colors']+) => `<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 382.94 405.93">+<path fill="${colors.pri}" d="M192.58 405.92a75.19 75.19 0 0 1-18.64-2.41l-1.2-.33-1.12-.56c-40.24-20.18-74.19-46.83-100.9-79.21a299.86 299.86 0 0 1-50.95-90.47A348.21 348.21 0 0 1 .07 110.27l.04-2.02c0-20.29 11.26-38.09 28.7-45.35C42.13 57.34 163.24 7.6 172 4c16.48-8.26 34.06-1.36 36.87-.16 6.31 2.58 118.28 48.38 142.47 59.9 24.94 11.87 31.6 33.2 31.6 43.93 0 48.6-8.43 94-25.02 134.97a312.52 312.52 0 0 1-56.16 90.51c-45.85 51.6-91.7 69.89-92.15 70.05a50.11 50.11 0 0 1-17.04 2.72zm-10.79-26.71c3.98.89 13.13 2.22 19.1.05 7.58-2.77 45.96-22.67 81.83-63.03 49.55-55.77 74.7-125.88 74.74-208.38-.1-1.67-1.28-13.59-17.07-21.1-23.72-11.3-140.1-58.89-141.27-59.37l-.32-.14c-2.44-1.02-10.2-3.17-15.55-.37l-1.08.5c-1.3.54-129.86 53.34-143.57 59.05-9.6 4-13 13.9-13 21.83 0 .58-.02 1.43-.05 2.52-1.1 56.44 11.97 195.34 156.24 268.44z"/>+<path fill="${colors.nav}" d="M177.33 15.59S47.61 68.87 33.71 74.66c-13.9 5.79-20.85 19.7-20.85 33.6 0 13.9-10.45 195.26 164.47 282.96 0 0 15.88 4.39 27.92 0 12.04-4.39 164.96-78.52 164.96-283.55 0 0 0-20.85-24.33-32.43C321.55 63.66 203.94 15.6 203.94 15.6s-14.44-6.37-26.6 0z"/>+<path d="M191.23 57.29v284.25S60.34 278.53 61.51 112.89z" opacity=".2"/>+<path fill="${colors.icon}" d="m192.94 261.58-41.69-53.61 24.24-18.86 19.75 25.38 66.7-70.4 22.3 21.13z"/>+</svg>`;++const MFASuccess = ({ recovery }: MFAStepProps) => {+ const colors = useThemeStore(state => state.colors);+ return (+ <View+ style={{+ alignItems: 'center'+ }}+ >+ <Seperator />+ <SvgView width={150} height={150} src={mfaSvg(colors)} />+ <Seperator />+ <DialogHeader+ centered={true}+ title={recovery ? 'Secondary method for 2FA enabled' : 'Two-factor authentication enabled!'}+ paragraph="Your account is now 100% secure against unauthorized logins."+ padding={12}+ />+ <Seperator />++ <Button+ title="Done"+ type="accent"+ width={250}+ onPress={() => {+ eSendEvent(eCloseProgressDialog);+ }}+ style={{+ borderRadius: 100,+ marginBottom: 10+ }}+ />++ <Button+ title="Setup secondary 2FA method"+ type="gray"+ height={25}+ onPress={() => {+ MFASheet.present(true);+ }}+ />+ </View>+ );+};++const MFASheet = ({ recovery }: { recovery?: boolean }) => {+ const [step, setStep] = useState<MFAStep>({+ id: 'mfapick',+ props: {+ recovery: recovery+ }+ });++ const steps: { [name: string]: JSX.Element } = {+ mfapick: (+ <MFAMethodsPickerStep+ recovery={recovery}+ onSuccess={method => {+ setStep({+ id: 'setup',+ props: {+ method: method+ }+ });+ }}+ />+ ),+ setup: (+ <MFASetup+ recovery={recovery}+ setStep={setStep}+ {...step.props}+ onSuccess={method => {+ setStep({+ id: 'recoveryCodes',+ props: {+ method: method+ }+ });+ }}+ />+ ),+ recoveryCodes: (+ <MFARecoveryCodes+ recovery={recovery}+ {...step.props}+ onSuccess={method => {+ setStep({+ id: 'success',+ props: {+ method: method+ }+ });+ }}+ />+ ),+ success: <MFASuccess {...step.props} recovery={recovery} />+ };++ return <View>{steps[step.id]}</View>;+};++MFASheet.present = (recovery?: boolean) => {+ presentSheet({+ component: <MFASheet recovery={recovery} />+ });+};diff --git a/apps/mobile/src/screens/settings/index.js b/apps/mobile/src/screens/settings/index.jsindex f0c7dfdb2..e025f7f33 100644--- a/apps/mobile/src/screens/settings/index.js+++ b/apps/mobile/src/screens/settings/index.js@@ -23,6 +23,7 @@ import AccoutLogoutSection from './logout';import SettingsPrivacyAndSecurity from './privacy';import SectionHeader from './section-header';import SettingsUserSection from './user-section';+import TwoFactorAuth from './2fa';const format = ver => {let parts = ver.toString().split('');diff --git a/apps/mobile/src/screens/settings/usersection.js b/apps/mobile/src/screens/settings/usersection.jsindex 56abe4f4a..fd01765c5 100644--- a/apps/mobile/src/screens/settings/usersection.js+++ b/apps/mobile/src/screens/settings/usersection.js@@ -26,6 +26,7 @@ import {} from '../../utils/events';import { SIZE } from '../../utils/size';import { sleep } from '../../utils/time';+import TwoFactorAuth from './2fa';import { CustomButton } from './button';import { verifyUser } from './functions';@@ -335,6 +336,8 @@ const SettingsUserSection = () => {/>))}++ <TwoFactorAuth /></>) : null}</>diff --git a/apps/mobile/src/stores/interfaces.ts b/apps/mobile/src/stores/interfaces.tsindex 3a620d986..1f82a9644 100644--- a/apps/mobile/src/stores/interfaces.ts+++ b/apps/mobile/src/stores/interfaces.ts@@ -1,5 +1,6 @@import { FileType } from 'react-native-scoped-storage';import { State } from 'zustand';+import 'notes-core/types';export type Item = {id: string;@@ -38,11 +39,11 @@ export interface TrashStore extends State {}export interface UserStore extends State {- user: Object | null;+ user: User | null | undefined;premium: boolean;lastSynced: string;syncing: boolean;- setUser: (user: Object | null) => void;+ setUser: (user: User | null | undefined) => void;setPremium: (premium: boolean) => void;setSyncing: (syncing: boolean) => void;setLastSynced: (lastSynced: string) => void;diff --git a/apps/mobile/src/utils/database/index.js b/apps/mobile/src/utils/database/index.jsindex 881403f57..90ed733ce 100644--- a/apps/mobile/src/utils/database/index.js+++ b/apps/mobile/src/utils/database/index.js@@ -14,16 +14,16 @@ export const db = new Database(db.host(__DEV__? {- API_HOST: 'https://api.notesnook.com',- AUTH_HOST: 'https://auth.streetwriters.co',- SSE_HOST: 'https://events.streetwriters.co',- SUBSCRIPTIONS_HOST: 'https://subscriptions.streetwriters.co',- ISSUES_HOST: 'https://issues.streetwriters.co'- // API_HOST: 'http://192.168.10.29:5264',- // AUTH_HOST: 'http://192.168.10.29:8264',- // SSE_HOST: 'http://192.168.10.29:7264',- // SUBSCRIPTIONS_HOST: 'http://192.168.10.29:9264',- // ISSUES_HOST: 'http://192.168.10.29:2624'+ // API_HOST: 'https://api.notesnook.com',+ // AUTH_HOST: 'https://auth.streetwriters.co',+ // SSE_HOST: 'https://events.streetwriters.co',+ // SUBSCRIPTIONS_HOST: 'https://subscriptions.streetwriters.co',+ // ISSUES_HOST: 'https://issues.streetwriters.co'+ API_HOST: 'http://192.168.10.29:5264',+ AUTH_HOST: 'http://192.168.10.29:8264',+ SSE_HOST: 'http://192.168.10.29:7264',+ SUBSCRIPTIONS_HOST: 'http://192.168.10.29:9264',+ ISSUES_HOST: 'http://192.168.10.29:2624'}: {API_HOST: 'https://api.notesnook.com',diff --git a/apps/mobile/src/utils/hooks/useAppEvents.js b/apps/mobile/src/utils/hooks/useAppEvents.jsindex 668f4cfa5..17e9b1a41 100644--- a/apps/mobile/src/utils/hooks/useAppEvents.js+++ b/apps/mobile/src/utils/hooks/useAppEvents.js@@ -42,6 +42,7 @@ import {clearAllStores,initialize,useAttachmentStore,+ useMessageStore,useNoteStore,useSettingStore,useUserStore@@ -295,7 +296,9 @@ export const useAppEvents = () => {user = await db.user.getUser();await PremiumService.setPremiumStatus();if (login) {+ console.log('sync started');await Sync.run();+ console.log('hide progress dialog');eSendEvent(eCloseProgressDialog);}setLastSynced(await db.lastSynced());@@ -330,7 +333,11 @@ export const useAppEvents = () => {} catch (e) {}user = await db.user.getUser();- if (user?.isEmailConfirmed && !SettingsService.get().recoveryKeySaved) {+ if (+ user?.isEmailConfirmed &&+ !SettingsService.get().recoveryKeySaved &&+ !useMessageStore.getState().message?.visible+ ) {setRecoveryKeyMessage();}if (!user.isEmailConfirmed) setEmailVerifyMessage();diff --git a/apps/mobile/src/utils/hooks/useTimer.ts b/apps/mobile/src/utils/hooks/useTimer.tsnew file mode 100644index 000000000..c9dd2e96d--- /dev/null+++ b/apps/mobile/src/utils/hooks/useTimer.ts@@ -0,0 +1,42 @@+import { useEffect, useRef, useState } from 'react';++const timers: { [name: string]: number } = {};++function getSecondsLeft(id?: string) {+ let endTime = timers[id || ''];+ if (!endTime) return 0;+ if (endTime < Date.now()) return 0;+ console.log((endTime - Date.now()) / 1000);+ return ((endTime - Date.now()) / 1000).toFixed(0);+}++const useTimer = (initialId?: string) => {+ const [id, setId] = useState(initialId);+ const [seconds, setSeconds] = useState(getSecondsLeft(id));+ const interval = useRef<NodeJS.Timer>();++ const start = (sec: number, currentId = id) => {+ console.log('started', sec, id);+ if (!currentId) return;+ timers[currentId] = Date.now() + sec * 1000;+ console.log('timers:', timers[currentId]);+ setSeconds(getSecondsLeft(id));+ };++ useEffect(() => {+ console.log(seconds);+ interval.current = setInterval(() => {+ let timeLeft = getSecondsLeft(id);+ setSeconds(timeLeft);+ if (timeLeft === 0) interval.current && clearInterval(interval.current);+ }, 1000);++ return () => {+ interval.current && clearInterval(interval.current);+ };+ }, [seconds, id]);++ return { seconds, setId, start };+};++export default useTimer;diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.jsonindex 3f536bba7..14d3b2084 100644--- a/apps/mobile/tsconfig.json+++ b/apps/mobile/tsconfig.json@@ -13,7 +13,7 @@"allowSyntheticDefaultImports": true,"esModuleInterop": true,"skipLibCheck": false,- "maxNodeModuleJsDepth": 20,+ "maxNodeModuleJsDepth": 10,"downlevelIteration": true},"exclude": ["babel.config.js", "metro.config.js", "jest.config.js", "android", "ios", "html"]