diff --git a/native/data/sensitive-data-handler.react.js b/native/data/sensitive-data-handler.react.js deleted file mode 100644 index 3339e1a87..000000000 --- a/native/data/sensitive-data-handler.react.js +++ /dev/null @@ -1,43 +0,0 @@ -// @flow - -import * as React from 'react'; -import ExitApp from 'react-native-exit-app'; - -import { commCoreModule } from '../native-modules'; -import { useSelector } from '../redux/redux-utils'; - -function SensitiveDataHandler(): null { - const currentLoggedInUserID: ?string = useSelector(state => - state.currentUserInfo?.anonymous ? undefined : state.currentUserInfo?.id, - ); - React.useEffect(() => { - (async () => { - try { - const databaseCurrentUserInfoID = await commCoreModule.getCurrentUserID(); - if ( - databaseCurrentUserInfoID && - databaseCurrentUserInfoID !== currentLoggedInUserID - ) { - await commCoreModule.clearSensitiveData(); - } - if (currentLoggedInUserID) { - await commCoreModule.setCurrentUserID(currentLoggedInUserID); - } - const databaseDeviceID = await commCoreModule.getDeviceID(); - if (!databaseDeviceID) { - await commCoreModule.setDeviceID('MOBILE'); - } - } catch (e) { - if (__DEV__) { - throw e; - } else { - console.log(e); - ExitApp.exitApp(); - } - } - })(); - }, [currentLoggedInUserID]); - return null; -} - -export { SensitiveDataHandler }; diff --git a/native/data/sqlite-context-provider.js b/native/data/sqlite-context-provider.js index ab8951a11..e6295ca79 100644 --- a/native/data/sqlite-context-provider.js +++ b/native/data/sqlite-context-provider.js @@ -1,118 +1,153 @@ // @flow import * as React from 'react'; import { Alert } from 'react-native'; import ExitApp from 'react-native-exit-app'; import { useDispatch } from 'react-redux'; import { setMessageStoreMessages } from 'lib/actions/message-actions.js'; import { setThreadStoreActionType } from 'lib/actions/thread-actions'; import { isLoggedIn } from 'lib/selectors/user-selectors'; import { logInActionSources } from 'lib/types/account-types'; import { fetchNewCookieFromNativeCredentials } from 'lib/utils/action-utils'; import { getMessageForException } from 'lib/utils/errors'; import { convertClientDBThreadInfosToRawThreadInfos } from 'lib/utils/thread-ops-utils'; import { commCoreModule } from '../native-modules'; import { useSelector } from '../redux/redux-utils'; import { useStaffCanSee } from '../utils/staff-utils'; import { SQLiteContext } from './sqlite-context'; type Props = { +children: React.Node, }; function SQLiteContextProvider(props: Props): React.Node { const [storeLoaded, setStoreLoaded] = React.useState(false); const dispatch = useDispatch(); const rehydrateConcluded = useSelector( state => !!(state._persist && state._persist.rehydrated), ); const cookie = useSelector(state => state.cookie); const urlPrefix = useSelector(state => state.urlPrefix); const staffCanSee = useStaffCanSee(); const loggedIn = useSelector(isLoggedIn); + const currentLoggedInUserID = useSelector(state => + state.currentUserInfo?.anonymous ? undefined : state.currentUserInfo?.id, + ); + + const handleSensitiveData = React.useCallback(async () => { + try { + const databaseCurrentUserInfoID = await commCoreModule.getCurrentUserID(); + if ( + databaseCurrentUserInfoID && + databaseCurrentUserInfoID !== currentLoggedInUserID + ) { + await commCoreModule.clearSensitiveData(); + } + if (currentLoggedInUserID) { + await commCoreModule.setCurrentUserID(currentLoggedInUserID); + } + const databaseDeviceID = await commCoreModule.getDeviceID(); + if (!databaseDeviceID) { + await commCoreModule.setDeviceID('MOBILE'); + } + } catch (e) { + if (__DEV__) { + throw e; + } else { + console.log(e); + ExitApp.exitApp(); + } + } + }, [currentLoggedInUserID]); React.useEffect(() => { - if (storeLoaded || !rehydrateConcluded) { + if (!rehydrateConcluded) { + return; + } + const sensitiveDataHandled = handleSensitiveData(); + if (storeLoaded) { return; } if (!loggedIn) { setStoreLoaded(true); return; } (async () => { + await sensitiveDataHandled; try { const [threads, messages] = await Promise.all([ commCoreModule.getAllThreads(), commCoreModule.getAllMessages(), ]); const threadInfosFromDB = convertClientDBThreadInfosToRawThreadInfos( threads, ); dispatch({ type: setThreadStoreActionType, payload: { threadInfos: threadInfosFromDB }, }); dispatch({ type: setMessageStoreMessages, payload: messages, }); setStoreLoaded(true); } catch (setStoreException) { if (staffCanSee) { Alert.alert( `Error setting threadStore or messageStore: ${ getMessageForException(setStoreException) ?? '{no exception message}' }`, ); } try { await fetchNewCookieFromNativeCredentials( dispatch, cookie, urlPrefix, logInActionSources.sqliteLoadFailure, ); setStoreLoaded(true); } catch (fetchCookieException) { if (staffCanSee) { Alert.alert( `Error fetching new cookie from native credentials: ${ getMessageForException(fetchCookieException) ?? '{no exception message}' }. Please kill the app.`, ); } else { ExitApp.exitApp(); } } } })(); }, [ + handleSensitiveData, loggedIn, cookie, dispatch, rehydrateConcluded, staffCanSee, storeLoaded, urlPrefix, ]); const contextValue = React.useMemo( () => ({ storeLoaded, }), [storeLoaded], ); return ( {props.children} ); } export { SQLiteContextProvider }; diff --git a/native/root.react.js b/native/root.react.js index 444520d6d..6e2c826e9 100644 --- a/native/root.react.js +++ b/native/root.react.js @@ -1,296 +1,294 @@ // @flow import { ActionSheetProvider } from '@expo/react-native-action-sheet'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { useReduxDevToolsExtension } from '@react-navigation/devtools'; import { NavigationContainer } from '@react-navigation/native'; import type { PossiblyStaleNavigationState } from '@react-navigation/native'; import * as SplashScreen from 'expo-splash-screen'; import invariant from 'invariant'; import * as React from 'react'; import { Platform, UIManager, View, StyleSheet, LogBox } from 'react-native'; import Orientation from 'react-native-orientation-locker'; import { SafeAreaProvider, initialWindowMetrics, } from 'react-native-safe-area-context'; import { Provider } from 'react-redux'; import { PersistGate as ReduxPersistGate } from 'redux-persist/integration/react'; import { actionLogger } from 'lib/utils/action-logger'; import ChatContextProvider from './chat/chat-context-provider.react'; import PersistedStateGate from './components/persisted-state-gate'; import ConnectedStatusBar from './connected-status-bar.react'; import CoreDataProvider from './data/core-data-provider.react'; -import { SensitiveDataHandler } from './data/sensitive-data-handler.react'; import { SQLiteContextProvider } from './data/sqlite-context-provider'; import ErrorBoundary from './error-boundary.react'; import InputStateContainer from './input/input-state-container.react'; import LifecycleHandler from './lifecycle/lifecycle-handler.react'; import { defaultNavigationState } from './navigation/default-state'; import DisconnectedBarVisibilityHandler from './navigation/disconnected-bar-visibility-handler.react'; import { setGlobalNavContext } from './navigation/icky-global'; import { NavContext } from './navigation/navigation-context'; import NavigationHandler from './navigation/navigation-handler.react'; import { validNavState } from './navigation/navigation-utils'; import OrientationHandler from './navigation/orientation-handler.react'; import { navStateAsyncStorageKey } from './navigation/persistance'; import RootNavigator from './navigation/root-navigator.react'; import ConnectivityUpdater from './redux/connectivity-updater.react'; import { DimensionsUpdater } from './redux/dimensions-updater.react'; import { getPersistor } from './redux/persist'; import { store } from './redux/redux-setup'; import { useSelector } from './redux/redux-utils'; import { RootContext } from './root-context'; import Socket from './socket.react'; import { StaffContextProvider } from './staff/staff-context.provider.react'; import { DarkTheme, LightTheme } from './themes/navigation'; import ThemeHandler from './themes/theme-handler.react'; import './themes/fonts'; LogBox.ignoreLogs([ // react-native-reanimated 'Please report: Excessive number of pending callbacks', ]); if (Platform.OS === 'android') { UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true); } const navInitAction = Object.freeze({ type: 'NAV/@@INIT' }); const navUnknownAction = Object.freeze({ type: 'NAV/@@UNKNOWN' }); SplashScreen.preventAutoHideAsync().catch(console.log); function Root() { const navStateRef = React.useRef(); const navDispatchRef = React.useRef(); const navStateInitializedRef = React.useRef(false); const [navContext, setNavContext] = React.useState(null); const updateNavContext = React.useCallback(() => { if ( !navStateRef.current || !navDispatchRef.current || !navStateInitializedRef.current ) { return; } const updatedNavContext = { state: navStateRef.current, dispatch: navDispatchRef.current, }; setNavContext(updatedNavContext); setGlobalNavContext(updatedNavContext); }, []); const [initialState, setInitialState] = React.useState( __DEV__ ? undefined : defaultNavigationState, ); React.useEffect(() => { Orientation.lockToPortrait(); (async () => { let loadedState = initialState; if (__DEV__) { try { const navStateString = await AsyncStorage.getItem( navStateAsyncStorageKey, ); if (navStateString) { const savedState = JSON.parse(navStateString); if (validNavState(savedState)) { loadedState = savedState; } } } catch {} } if (!loadedState) { loadedState = defaultNavigationState; } if (loadedState !== initialState) { setInitialState(loadedState); } navStateRef.current = loadedState; updateNavContext(); actionLogger.addOtherAction('navState', navInitAction, null, loadedState); })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [updateNavContext]); const setNavStateInitialized = React.useCallback(() => { navStateInitializedRef.current = true; updateNavContext(); }, [updateNavContext]); const [rootContext, setRootContext] = React.useState(() => ({ setNavStateInitialized, })); const detectUnsupervisedBackgroundRef = React.useCallback( (detectUnsupervisedBackground: ?(alreadyClosed: boolean) => boolean) => { setRootContext(prevRootContext => ({ ...prevRootContext, detectUnsupervisedBackground, })); }, [], ); const frozen = useSelector(state => state.frozen); const queuedActionsRef = React.useRef([]); const onNavigationStateChange = React.useCallback( (state: ?PossiblyStaleNavigationState) => { invariant(state, 'nav state should be non-null'); const prevState = navStateRef.current; navStateRef.current = state; updateNavContext(); const queuedActions = queuedActionsRef.current; queuedActionsRef.current = []; if (queuedActions.length === 0) { queuedActions.push(navUnknownAction); } for (const action of queuedActions) { actionLogger.addOtherAction('navState', action, prevState, state); } if (!__DEV__ || frozen) { return; } (async () => { try { await AsyncStorage.setItem( navStateAsyncStorageKey, JSON.stringify(state), ); } catch (e) { console.log('AsyncStorage threw while trying to persist navState', e); } })(); }, [updateNavContext, frozen], ); const navContainerRef = React.useRef(); const containerRef = React.useCallback( (navContainer: ?React.ElementRef) => { navContainerRef.current = navContainer; if (navContainer && !navDispatchRef.current) { navDispatchRef.current = navContainer.dispatch; updateNavContext(); } }, [updateNavContext], ); useReduxDevToolsExtension(navContainerRef); const navContainer = navContainerRef.current; React.useEffect(() => { if (!navContainer) { return; } return navContainer.addListener('__unsafe_action__', event => { const { action, noop } = event.data; const navState = navStateRef.current; if (noop) { actionLogger.addOtherAction('navState', action, navState, navState); return; } queuedActionsRef.current.push({ ...action, type: `NAV/${action.type}`, }); }); }, [navContainer]); const activeTheme = useSelector(state => state.globalThemeInfo.activeTheme); const theme = (() => { if (activeTheme === 'light') { return LightTheme; } else if (activeTheme === 'dark') { return DarkTheme; } return undefined; })(); const gated: React.Node = ( <> - ); let navigation; if (initialState) { navigation = ( ); } return ( {gated} {navigation} ); } const styles = StyleSheet.create({ app: { flex: 1, }, }); function AppRoot(): React.Node { return ( ); } export default AppRoot;