diff --git a/lib/components/prekeys-handler.react.js b/lib/components/prekeys-handler.react.js new file mode 100644 index 000000000..871a48fbb --- /dev/null +++ b/lib/components/prekeys-handler.react.js @@ -0,0 +1,40 @@ +// @flow + +import invariant from 'invariant'; +import * as React from 'react'; + +import { isLoggedIn } from '../selectors/user-selectors.js'; +import { IdentityClientContext } from '../shared/identity-client-context.js'; +import { getConfig } from '../utils/config.js'; +import { useSelector } from '../utils/redux-utils.js'; + +// Time after which rotation is started +const PREKEY_ROTATION_TIMEOUT = 3 * 1000; // in milliseconds + +function PrekeysHandler(): null { + const loggedIn = useSelector(isLoggedIn); + + const identityContext = React.useContext(IdentityClientContext); + invariant(identityContext, 'Identity context should be set'); + + React.useEffect(() => { + if (!loggedIn) { + return undefined; + } + + const timeoutID = setTimeout(async () => { + try { + const { olmAPI } = getConfig(); + await olmAPI.validateAndUploadPrekeys(identityContext); + } catch (e) { + console.log('Prekey validation error: ', e.message); + } + }, PREKEY_ROTATION_TIMEOUT); + + return () => clearTimeout(timeoutID); + }, [identityContext, loggedIn]); + + return null; +} + +export default PrekeysHandler; diff --git a/lib/types/crypto-types.js b/lib/types/crypto-types.js index 783b29958..a9761df80 100644 --- a/lib/types/crypto-types.js +++ b/lib/types/crypto-types.js @@ -1,134 +1,138 @@ // @flow import t, { type TInterface } from 'tcomb'; +import { type IdentityClientContextType } from '../shared/identity-client-context.js'; import { tShape } from '../utils/validation-utils.js'; export type OLMIdentityKeys = { +ed25519: string, +curve25519: string, }; const olmIdentityKeysValidator: TInterface = tShape({ ed25519: t.String, curve25519: t.String, }); export type OLMPrekey = { +curve25519: { +id: string, +key: string, }, }; export type SignedPrekeys = { +contentPrekey: string, +contentPrekeySignature: string, +notifPrekey: string, +notifPrekeySignature: string, }; export const signedPrekeysValidator: TInterface = tShape({ contentPrekey: t.String, contentPrekeySignature: t.String, notifPrekey: t.String, notifPrekeySignature: t.String, }); export type OLMOneTimeKeys = { +curve25519: { +[string]: string }, }; export type OneTimeKeysResult = { +contentOneTimeKeys: OLMOneTimeKeys, +notificationsOneTimeKeys: OLMOneTimeKeys, }; export type OneTimeKeysResultValues = { +contentOneTimeKeys: $ReadOnlyArray, +notificationsOneTimeKeys: $ReadOnlyArray, }; export type PickledOLMAccount = { +picklingKey: string, +pickledAccount: string, }; export type CryptoStore = { +primaryAccount: PickledOLMAccount, +primaryIdentityKeys: OLMIdentityKeys, +notificationAccount: PickledOLMAccount, +notificationIdentityKeys: OLMIdentityKeys, }; export type CryptoStoreContextType = { +getInitializedCryptoStore: () => Promise, }; export type NotificationsOlmDataType = { +mainSession: string, +picklingKey: string, +pendingSessionUpdate: string, +updateCreationTimestamp: number, }; export type IdentityKeysBlob = { +primaryIdentityPublicKeys: OLMIdentityKeys, +notificationIdentityPublicKeys: OLMIdentityKeys, }; export const identityKeysBlobValidator: TInterface = tShape({ primaryIdentityPublicKeys: olmIdentityKeysValidator, notificationIdentityPublicKeys: olmIdentityKeysValidator, }); export type SignedIdentityKeysBlob = { +payload: string, +signature: string, }; export const signedIdentityKeysBlobValidator: TInterface = tShape({ payload: t.String, signature: t.String, }); export type UserDetail = { +username: string, +userID: string, }; // This type should not be changed without making equivalent changes to // `Message` in Identity service's `reserved_users` module export type ReservedUsernameMessage = | { +statement: 'Add the following usernames to reserved list', +payload: $ReadOnlyArray, +issuedAt: string, } | { +statement: 'Remove the following username from reserved list', +payload: string, +issuedAt: string, } | { +statement: 'This user is the owner of the following username and user ID', +payload: UserDetail, +issuedAt: string, }; export const olmEncryptedMessageTypes = Object.freeze({ PREKEY: 0, TEXT: 1, }); export type OlmAPI = { +initializeCryptoAccount: () => Promise, +encrypt: (content: string, deviceID: string) => Promise, +decrypt: (encryptedContent: string, deviceID: string) => Promise, +contentInboundSessionCreator: ( contentIdentityKeys: OLMIdentityKeys, initialEncryptedContent: string, ) => Promise, +getOneTimeKeys: (numberOfKeys: number) => Promise, + +validateAndUploadPrekeys: ( + identityContext: IdentityClientContextType, + ) => Promise, }; diff --git a/native/components/prekeys-handler.react.js b/native/components/prekeys-handler.react.js deleted file mode 100644 index 3f20b4040..000000000 --- a/native/components/prekeys-handler.react.js +++ /dev/null @@ -1,46 +0,0 @@ -// @flow - -import * as React from 'react'; - -import { isLoggedIn } from 'lib/selectors/user-selectors.js'; -import { useSelector } from 'lib/utils/redux-utils.js'; - -import { commCoreModule } from '../native-modules.js'; - -// Time after which rotation is started -const PREKEY_ROTATION_TIMEOUT = 3 * 1000; // in milliseconds - -function PrekeysHandler(): null { - const loggedIn = useSelector(isLoggedIn); - - React.useEffect(() => { - if (!loggedIn) { - return undefined; - } - - const timeoutID = setTimeout(async () => { - const authMetadata = await commCoreModule.getCommServicesAuthMetadata(); - const { userID, deviceID, accessToken } = authMetadata; - if (!userID || !deviceID || !accessToken) { - return; - } - - try { - await commCoreModule.initializeCryptoAccount(); - await commCoreModule.validateAndUploadPrekeys( - userID, - deviceID, - accessToken, - ); - } catch (e) { - console.log('Prekey validation error: ', e.message); - } - }, PREKEY_ROTATION_TIMEOUT); - - return () => clearTimeout(timeoutID); - }, [loggedIn]); - - return null; -} - -export default PrekeysHandler; diff --git a/native/crypto/olm-api.js b/native/crypto/olm-api.js index 4ea57349f..5b3e433a4 100644 --- a/native/crypto/olm-api.js +++ b/native/crypto/olm-api.js @@ -1,42 +1,62 @@ // @flow import { getOneTimeKeyValues } from 'lib/shared/crypto-utils.js'; +import { type IdentityClientContextType } from 'lib/shared/identity-client-context.js'; import type { OneTimeKeysResultValues, OlmAPI, OLMIdentityKeys, } from 'lib/types/crypto-types'; import { commCoreModule } from '../native-modules.js'; const olmAPI: OlmAPI = { async initializeCryptoAccount(): Promise { await commCoreModule.initializeCryptoAccount(); }, encrypt: commCoreModule.encrypt, decrypt: commCoreModule.decrypt, async contentInboundSessionCreator( contentIdentityKeys: OLMIdentityKeys, initialEncryptedContent: string, ): Promise { const identityKeys = JSON.stringify({ curve25519: contentIdentityKeys.curve25519, ed25519: contentIdentityKeys.ed25519, }); return commCoreModule.initializeContentInboundSession( identityKeys, initialEncryptedContent, contentIdentityKeys.ed25519, ); }, async getOneTimeKeys(numberOfKeys: number): Promise { const { contentOneTimeKeys, notificationsOneTimeKeys } = await commCoreModule.getOneTimeKeys(numberOfKeys); return { contentOneTimeKeys: getOneTimeKeyValues(contentOneTimeKeys), notificationsOneTimeKeys: getOneTimeKeyValues(notificationsOneTimeKeys), }; }, + async validateAndUploadPrekeys( + identityContext: IdentityClientContextType, + ): Promise { + let authMetadata; + try { + authMetadata = await identityContext.getAuthMetadata(); + } catch (e) { + return; + } + const { userID, deviceID, accessToken } = authMetadata; + if (!userID || !deviceID || !accessToken) { + return; + } + await commCoreModule.validateAndUploadPrekeys( + userID, + deviceID, + accessToken, + ); + }, }; export { olmAPI }; diff --git a/native/root.react.js b/native/root.react.js index b91ca19ed..ea1737873 100644 --- a/native/root.react.js +++ b/native/root.react.js @@ -1,383 +1,383 @@ // @flow import { ActionSheetProvider } from '@expo/react-native-action-sheet'; import { BottomSheetModalProvider } from '@gorhom/bottom-sheet'; import AsyncStorage from '@react-native-async-storage/async-storage'; import type { PossiblyStaleNavigationState, UnsafeContainerActionEvent, GenericNavigationAction, } from '@react-navigation/core'; import { useReduxDevToolsExtension } from '@react-navigation/devtools'; import { NavigationContainer } from '@react-navigation/native'; import * as SplashScreen from 'expo-splash-screen'; import invariant from 'invariant'; import * as React from 'react'; import { Platform, UIManager, StyleSheet } from 'react-native'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; 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/es/integration/react.js'; import { ChatMentionContextProvider } from 'lib/components/chat-mention-provider.react.js'; import { EditUserAvatarProvider } from 'lib/components/edit-user-avatar-provider.react.js'; import { ENSCacheProvider } from 'lib/components/ens-cache-provider.react.js'; import IntegrityHandler from 'lib/components/integrity-handler.react.js'; import KeyserverConnectionsHandler from 'lib/components/keyserver-connections-handler.js'; import { MediaCacheProvider } from 'lib/components/media-cache-provider.react.js'; +import PrekeysHandler from 'lib/components/prekeys-handler.react.js'; import { StaffContextProvider } from 'lib/components/staff-provider.react.js'; import { CallKeyserverEndpointProvider } from 'lib/keyserver-conn/call-keyserver-endpoint-provider.react.js'; import { TunnelbrokerProvider } from 'lib/tunnelbroker/tunnelbroker-context.js'; import { actionLogger } from 'lib/utils/action-logger.js'; import { OlmSessionCreatorProvider } from './account/account-hooks.js'; import { RegistrationContextProvider } from './account/registration/registration-context-provider.react.js'; import NativeEditThreadAvatarProvider from './avatars/native-edit-thread-avatar-provider.react.js'; import BackupHandler from './backup/backup-handler.js'; import { BottomSheetProvider } from './bottom-sheet/bottom-sheet-provider.react.js'; import ChatContextProvider from './chat/chat-context-provider.react.js'; import MessageEditingContextProvider from './chat/message-editing-context-provider.react.js'; import AccessTokenHandler from './components/access-token-handler.react.js'; import { FeatureFlagsProvider } from './components/feature-flags-provider.react.js'; import PersistedStateGate from './components/persisted-state-gate.js'; -import PrekeysHandler from './components/prekeys-handler.react.js'; import VersionSupportedChecker from './components/version-supported.react.js'; import ConnectedStatusBar from './connected-status-bar.react.js'; import { SQLiteDataHandler } from './data/sqlite-data-handler.js'; import ErrorBoundary from './error-boundary.react.js'; import IdentityServiceContextProvider from './identity-service/identity-service-context-provider.react.js'; import InputStateContainer from './input/input-state-container.react.js'; import LifecycleHandler from './lifecycle/lifecycle-handler.react.js'; import MarkdownContextProvider from './markdown/markdown-context-provider.react.js'; import { filesystemMediaCache } from './media/media-cache.js'; import { DeepLinksContextProvider } from './navigation/deep-links-context-provider.react.js'; import { defaultNavigationState } from './navigation/default-state.js'; import { setGlobalNavContext } from './navigation/icky-global.js'; import KeyserverReachabilityHandler from './navigation/keyserver-reachability-handler.js'; import { NavContext, type NavContextType, } from './navigation/navigation-context.js'; import NavigationHandler from './navigation/navigation-handler.react.js'; import { validNavState } from './navigation/navigation-utils.js'; import OrientationHandler from './navigation/orientation-handler.react.js'; import { navStateAsyncStorageKey } from './navigation/persistance.js'; import RootNavigator from './navigation/root-navigator.react.js'; import ConnectivityUpdater from './redux/connectivity-updater.react.js'; import { DimensionsUpdater } from './redux/dimensions-updater.react.js'; import { getPersistor } from './redux/persist.js'; import { store } from './redux/redux-setup.js'; import { useSelector } from './redux/redux-utils.js'; import { RootContext } from './root-context.js'; import { MessageSearchProvider } from './search/search-provider.react.js'; import Socket from './socket.react.js'; import { useLoadCommFonts } from './themes/fonts.js'; import { DarkTheme, LightTheme } from './themes/navigation.js'; import ThemeHandler from './themes/theme-handler.react.js'; import { provider } from './utils/ethers-utils.js'; import { useTunnelbrokerInitMessage } from './utils/tunnelbroker-utils.js'; // Add custom items to expo-dev-menu import './dev-menu.js'; import './types/message-types-validator.js'; 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 GenericNavigationAction), ) => void>(); const navStateInitializedRef = React.useRef(false); // We call this here to start the loading process // We gate the UI on the fonts loading in AppNavigator useLoadCommFonts(); 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(); void (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; } void (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 undefined; } return navContainer.addListener( '__unsafe_action__', (event: { +data: UnsafeContainerActionEvent, ... }) => { 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 tunnelbrokerInitMessage = useTunnelbrokerInitMessage(); 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; diff --git a/web/crypto/olm-api.js b/web/crypto/olm-api.js index 9b73a73c3..4a84aa86f 100644 --- a/web/crypto/olm-api.js +++ b/web/crypto/olm-api.js @@ -1,92 +1,142 @@ // @flow import olm from '@commapp/olm'; import type { Account, Session } from '@commapp/olm'; +import { type IdentityClientContextType } from 'lib/shared/identity-client-context.js'; import { type OlmAPI, olmEncryptedMessageTypes, type OLMIdentityKeys, type OneTimeKeysResultValues, } from 'lib/types/crypto-types.js'; -import { getAccountOneTimeKeys } from 'lib/utils/olm-utils.js'; +import { + getAccountOneTimeKeys, + getAccountPrekeysSet, + shouldForgetPrekey, + shouldRotatePrekey, +} from 'lib/utils/olm-utils.js'; // methods below are just mocks to SQLite API // implement proper methods tracked in ENG-6462 function getOlmAccount(): Account { const account = new olm.Account(); account.create(); return account; } // eslint-disable-next-line no-unused-vars function getOlmSession(deviceID: string): Session { return new olm.Session(); } // eslint-disable-next-line no-unused-vars function storeOlmAccount(account: Account): void {} // eslint-disable-next-line no-unused-vars function storeOlmSession(session: Session): void {} const olmAPI: OlmAPI = { async initializeCryptoAccount(): Promise { await olm.init(); }, async encrypt(content: string, deviceID: string): Promise { const session = getOlmSession(deviceID); const { body } = session.encrypt(content); storeOlmSession(session); return body; }, async decrypt(encryptedContent: string, deviceID: string): Promise { const session = getOlmSession(deviceID); const result = session.decrypt( olmEncryptedMessageTypes.TEXT, encryptedContent, ); storeOlmSession(session); return result; }, async contentInboundSessionCreator( contentIdentityKeys: OLMIdentityKeys, initialEncryptedContent: string, ): Promise { const account = getOlmAccount(); const session = new olm.Session(); session.create_inbound_from( account, contentIdentityKeys.curve25519, initialEncryptedContent, ); account.remove_one_time_keys(session); const initialEncryptedMessage = session.decrypt( olmEncryptedMessageTypes.PREKEY, initialEncryptedContent, ); storeOlmAccount(account); storeOlmSession(session); return initialEncryptedMessage; }, async getOneTimeKeys(numberOfKeys: number): Promise { const contentAccount = getOlmAccount(); const notifAccount = getOlmAccount(); const contentOneTimeKeys = getAccountOneTimeKeys( contentAccount, numberOfKeys, ); contentAccount.mark_keys_as_published(); storeOlmAccount(contentAccount); const notificationsOneTimeKeys = getAccountOneTimeKeys( notifAccount, numberOfKeys, ); notifAccount.mark_keys_as_published(); storeOlmAccount(notifAccount); return { contentOneTimeKeys, notificationsOneTimeKeys }; }, + async validateAndUploadPrekeys( + identityContext: IdentityClientContextType, + ): Promise { + const authMetadata = await identityContext.getAuthMetadata(); + const { userID, deviceID, accessToken } = authMetadata; + if (!userID || !deviceID || !accessToken) { + return; + } + + const contentAccount = getOlmAccount(); + if (shouldRotatePrekey(contentAccount)) { + contentAccount.generate_prekey(); + } + if (shouldForgetPrekey(contentAccount)) { + contentAccount.forget_old_prekey(); + } + await storeOlmAccount(contentAccount); + + if (!contentAccount.unpublished_prekey()) { + return; + } + + const notifAccount = getOlmAccount(); + const { prekey: notifPrekey, prekeySignature: notifPrekeySignature } = + getAccountPrekeysSet(notifAccount); + const { prekey: contentPrekey, prekeySignature: contentPrekeySignature } = + getAccountPrekeysSet(contentAccount); + + if (!notifPrekeySignature || !contentPrekeySignature) { + throw new Error('Prekey signature is missing'); + } + + if (!identityContext.identityClient.publishWebPrekeys) { + throw new Error('Publish prekeys method unimplemented'); + } + await identityContext.identityClient.publishWebPrekeys({ + contentPrekey, + contentPrekeySignature, + notifPrekey, + notifPrekeySignature, + }); + contentAccount.mark_keys_as_published(); + await storeOlmAccount(contentAccount); + }, }; export { olmAPI }; diff --git a/web/root.js b/web/root.js index c866ceb83..35de000a1 100644 --- a/web/root.js +++ b/web/root.js @@ -1,66 +1,68 @@ // @flow import localforage from 'localforage'; import * as React from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import { createStore, applyMiddleware, type Store } from 'redux'; import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction.js'; import { persistReducer, persistStore } from 'redux-persist'; import thunk from 'redux-thunk'; import IntegrityHandler from 'lib/components/integrity-handler.react.js'; import KeyserverConnectionsHandler from 'lib/components/keyserver-connections-handler.js'; +import PrekeysHandler from 'lib/components/prekeys-handler.react.js'; import { CallKeyserverEndpointProvider } from 'lib/keyserver-conn/call-keyserver-endpoint-provider.react.js'; import { reduxLoggerMiddleware } from 'lib/utils/action-logger.js'; import { GetOrCreateCryptoStoreProvider, OlmSessionCreatorProvider, } from './account/account-hooks.js'; import App from './app.react.js'; import { SQLiteDataHandler } from './database/sqlite-data-handler.js'; import { localforageConfig } from './database/utils/constants.js'; import ErrorBoundary from './error-boundary.react.js'; import IdentityServiceContextProvider from './grpc/identity-service-context-provider.react.js'; import { defaultWebState } from './redux/default-state.js'; import InitialReduxStateGate from './redux/initial-state-gate.js'; import { persistConfig } from './redux/persist.js'; import { type AppState, type Action, reducer } from './redux/redux-setup.js'; import history from './router-history.js'; import Socket from './socket.react.js'; localforage.config(localforageConfig); const persistedReducer = persistReducer(persistConfig, reducer); const store: Store = createStore( persistedReducer, defaultWebState, composeWithDevTools({})(applyMiddleware(thunk, reduxLoggerMiddleware)), ); const persistor = persistStore(store); const RootProvider = (): React.Node => ( + ); export default RootProvider;