diff --git a/lib/actions/find-user-identities-actions.js b/lib/actions/find-user-identities-actions.js new file mode 100644 index 000000000..257a6d6ce --- /dev/null +++ b/lib/actions/find-user-identities-actions.js @@ -0,0 +1,19 @@ +// @flow + +import { useUserIdentityCache } from '../components/user-identity-cache.react.js'; +import type { UserIdentitiesResponse } from '../types/identity-service-types.js'; + +const findUserIdentitiesActionTypes = Object.freeze({ + started: 'FIND_USER_IDENTITIES_STARTED', + success: 'FIND_USER_IDENTITIES_SUCCESS', + failed: 'FIND_USER_IDENTITIES_FAILED', +}); + +function useFindUserIdentities(): ( + userIDs: $ReadOnlyArray, +) => Promise { + const userIdentityCache = useUserIdentityCache(); + return userIdentityCache.getUserIdentities; +} + +export { findUserIdentitiesActionTypes, useFindUserIdentities }; diff --git a/lib/actions/user-actions.js b/lib/actions/user-actions.js index 4fc6afba8..37f81a8f2 100644 --- a/lib/actions/user-actions.js +++ b/lib/actions/user-actions.js @@ -1,1465 +1,1446 @@ // @flow import invariant from 'invariant'; import * as React from 'react'; import { useClearAllHolders } from './holder-actions.js'; -import { useUserIdentityCache } from '../components/user-identity-cache.react.js'; import { useBroadcastDeviceListUpdates, useBroadcastAccountDeletion, } from '../hooks/peer-list-hooks.js'; import type { CallSingleKeyserverEndpoint, CallSingleKeyserverEndpointOptions, } from '../keyserver-conn/call-single-keyserver-endpoint.js'; import { extractKeyserverIDFromID, sortThreadIDsPerKeyserver, sortCalendarQueryPerKeyserver, } from '../keyserver-conn/keyserver-call-utils.js'; import { useKeyserverCall } from '../keyserver-conn/keyserver-call.js'; import type { CallKeyserverEndpoint } from '../keyserver-conn/keyserver-conn-types.js'; import { usePreRequestUserState } from '../selectors/account-selectors.js'; import { getForeignPeerDeviceIDs } from '../selectors/user-selectors.js'; import { getOneTimeKeyValuesFromBlob, getPrekeyValueFromBlob, } from '../shared/crypto-utils.js'; import { fetchLatestDeviceList } from '../shared/device-list-utils.js'; import type { OutboundDMOperationSpecification } from '../shared/dm-ops/dm-op-utils'; import { dmOperationSpecificationTypes } from '../shared/dm-ops/dm-op-utils.js'; import { useProcessAndSendDMOperation } from '../shared/dm-ops/process-dm-ops.js'; import { IdentityClientContext } from '../shared/identity-client-context.js'; import threadWatcher from '../shared/thread-watcher.js'; import { permissionsAndAuthRelatedRequestTimeout, callIdentityServiceTimeout, } from '../shared/timeouts.js'; import { usePeerToPeerCommunication } from '../tunnelbroker/peer-to-peer-context.js'; import type { LegacyLogInInfo, LegacyLogInResult, LegacyRegisterResult, LegacyRegisterInfo, UpdateUserSettingsRequest, PolicyAcknowledgmentRequest, ClaimUsernameRequest, ClaimUsernameResponse, LogInRequest, KeyserverAuthResult, KeyserverAuthInfo, KeyserverAuthRequest, ClientLogInResponse, KeyserverLogOutResult, LogOutResult, } from '../types/account-types.js'; import type { UpdateUserAvatarRequest, UpdateUserAvatarResponse, } from '../types/avatar-types.js'; import type { DMChangeThreadSubscriptionOperation } from '../types/dm-ops'; import type { RawEntryInfo, CalendarQuery } from '../types/entry-types.js'; -import type { - UserIdentitiesResponse, - IdentityAuthResult, -} from '../types/identity-service-types.js'; +import type { IdentityAuthResult } from '../types/identity-service-types.js'; import type { RawMessageInfo, MessageTruncationStatuses, } from '../types/message-types.js'; import type { ThreadInfo } from '../types/minimally-encoded-thread-permissions-types'; import type { GetOlmSessionInitializationDataResponse } from '../types/olm-session-types.js'; import type { UserSearchResult, ExactUserSearchResult, } from '../types/search-types.js'; import type { PreRequestUserState } from '../types/session-types.js'; import type { SubscriptionUpdateRequest, SubscriptionUpdateResult, } from '../types/subscription-types.js'; import { thickThreadTypes } from '../types/thread-types-enum.js'; import type { RawThreadInfos } from '../types/thread-types.js'; import { userActionsP2PMessageTypes, type DeviceLogoutP2PMessage, type SecondaryDeviceLogoutP2PMessage, } from '../types/tunnelbroker/user-actions-peer-to-peer-message-types.js'; import type { CurrentUserInfo, UserInfo, PasswordUpdate, LoggedOutUserInfo, } from '../types/user-types.js'; import { authoritativeKeyserverID } from '../utils/authoritative-keyserver.js'; import { getConfig } from '../utils/config.js'; import { getMessageForException } from '../utils/errors.js'; import { useSelector } from '../utils/redux-utils.js'; import { usingCommServicesAccessToken } from '../utils/services-utils.js'; import sleep from '../utils/sleep.js'; const loggedOutUserInfo: LoggedOutUserInfo = { anonymous: true, }; export type KeyserverLogOutInput = { +preRequestUserState: PreRequestUserState, +keyserverIDs?: $ReadOnlyArray, }; const logOutActionTypes = Object.freeze({ started: 'LOG_OUT_STARTED', success: 'LOG_OUT_SUCCESS', failed: 'LOG_OUT_FAILED', }); const keyserverLogOut = ( callKeyserverEndpoint: CallKeyserverEndpoint, allKeyserverIDs: $ReadOnlyArray, ): ((input: KeyserverLogOutInput) => Promise) => async input => { const { preRequestUserState } = input; const keyserverIDs = input.keyserverIDs ?? allKeyserverIDs; const requests: { [string]: {} } = {}; for (const keyserverID of keyserverIDs) { requests[keyserverID] = {}; } let response = null; try { response = await Promise.race([ callKeyserverEndpoint('log_out', requests), (async () => { await sleep(500); throw new Error('keyserver log_out took more than 500ms'); })(), ]); } catch {} const currentUserInfo = response ? loggedOutUserInfo : null; return { currentUserInfo, preRequestUserState, keyserverIDs }; }; type UseLogOutOptions = { +logOutType?: 'legacy' | 'primary_device' | 'secondary_device', +skipIdentityLogOut?: boolean, }; function useLogOut( options: UseLogOutOptions = {}, ): (keyserverIDs?: $ReadOnlyArray) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; const preRequestUserState = usePreRequestUserState(); const callKeyserverLogOut = useKeyserverCall(keyserverLogOut); const removeAllHolders = useClearAllHolders(); const commServicesAccessToken = useSelector( state => state.commServicesAccessToken, ); const { logOutType, skipIdentityLogOut } = options; return React.useCallback( async (keyserverIDs?: $ReadOnlyArray) => { const holdersPromise = (async () => { try { await removeAllHolders(); } catch {} })(); const identityPromise = (async () => { if ( skipIdentityLogOut || !usingCommServicesAccessToken || !commServicesAccessToken ) { return; } if (!identityClient) { throw new Error('Identity service client is not initialized'); } let callIdentityClientLogOut; if (logOutType === 'primary_device') { if (!identityClient.logOutPrimaryDevice) { throw new Error( 'logOutPrimaryDevice not defined. ' + 'Are you calling it on non-primary device?', ); } callIdentityClientLogOut = identityClient.logOutPrimaryDevice; } else { callIdentityClientLogOut = logOutType === 'secondary_device' ? identityClient.logOutSecondaryDevice : identityClient.logOut; } try { await Promise.race([ callIdentityClientLogOut(), (async () => { await sleep(500); throw new Error('identity log_out took more than 500ms'); })(), ]); } catch {} })(); const [{ keyserverIDs: _, ...result }] = await Promise.all([ callKeyserverLogOut({ preRequestUserState, keyserverIDs, }), holdersPromise, identityPromise, ]); return { ...result, preRequestUserState: { ...result.preRequestUserState, commServicesAccessToken, }, }; }, [ callKeyserverLogOut, commServicesAccessToken, identityClient, logOutType, preRequestUserState, removeAllHolders, skipIdentityLogOut, ], ); } function useIdentityLogOut(): () => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; const preRequestUserState = usePreRequestUserState(); const commServicesAccessToken = useSelector( state => state.commServicesAccessToken, ); return React.useCallback(async () => { invariant( usingCommServicesAccessToken, 'identityLogOut can only be called when usingCommServicesAccessToken', ); if (!identityClient) { throw new Error('Identity service client is not initialized'); } try { await Promise.race([ identityClient.logOut(), (async () => { await sleep(500); throw new Error('identity log_out took more than 500ms'); })(), ]); } catch {} return { currentUserInfo: null, preRequestUserState: { ...preRequestUserState, commServicesAccessToken, }, }; }, [commServicesAccessToken, identityClient, preRequestUserState]); } const primaryDeviceLogOutOptions = Object.freeze({ logOutType: 'primary_device', }); function usePrimaryDeviceLogOut(): () => Promise { const identityContext = React.useContext(IdentityClientContext); if (!identityContext) { throw new Error('Identity service client is not initialized'); } const broadcastDeviceListUpdates = useBroadcastDeviceListUpdates(); const { broadcastEphemeralMessage } = usePeerToPeerCommunication(); const foreignPeerDevices = useSelector(getForeignPeerDeviceIDs); const logOut = useLogOut(primaryDeviceLogOutOptions); return React.useCallback(async () => { const { identityClient, getAuthMetadata } = identityContext; const authMetadata = await getAuthMetadata(); const { userID, deviceID: thisDeviceID } = authMetadata; if (!thisDeviceID || !userID) { throw new Error('No auth metadata'); } const { devices: [primaryDeviceID, ...secondaryDevices], } = await fetchLatestDeviceList(identityClient, userID); if (thisDeviceID !== primaryDeviceID) { throw new Error('Used primary device logout on a non-primary device'); } const messageContents: DeviceLogoutP2PMessage = { type: userActionsP2PMessageTypes.LOG_OUT_DEVICE, }; const recipients = secondaryDevices.map(deviceID => ({ userID, deviceID })); await broadcastEphemeralMessage( JSON.stringify(messageContents), recipients, authMetadata, ); // - logOut() performs device list update by calling Identity RPC // - broadcastDeviceListUpdates asks peers to download it from identity // so we need to call them in this order to make sure peers have latest // device list. // We're relying on Tunnelbroker session stil existing after calling logout // and auth metadata not yet cleared at this point. const logOutResult = await logOut(); await broadcastDeviceListUpdates(foreignPeerDevices); return logOutResult; }, [ broadcastDeviceListUpdates, broadcastEphemeralMessage, foreignPeerDevices, identityContext, logOut, ]); } const secondaryDeviceLogOutOptions = Object.freeze({ logOutType: 'secondary_device', }); function useSecondaryDeviceLogOut(): () => Promise { const logOut = useLogOut(secondaryDeviceLogOutOptions); const identityContext = React.useContext(IdentityClientContext); if (!identityContext) { throw new Error('Identity service client is not initialized'); } const { broadcastEphemeralMessage } = usePeerToPeerCommunication(); return React.useCallback(async () => { const { identityClient, getAuthMetadata } = identityContext; const authMetadata = await getAuthMetadata(); const { userID, deviceID } = authMetadata; if (!deviceID || !userID) { throw new Error('No auth metadata'); } // get current device list and primary device ID const { devices } = await fetchLatestDeviceList(identityClient, userID); const primaryDeviceID = devices[0]; if (deviceID === primaryDeviceID) { throw new Error('Used secondary device logout on primary device'); } // create and send Olm Tunnelbroker message to primary device const { olmAPI } = getConfig(); await olmAPI.initializeCryptoAccount(); const messageContents: SecondaryDeviceLogoutP2PMessage = { type: userActionsP2PMessageTypes.LOG_OUT_SECONDARY_DEVICE, }; const recipient = { userID, deviceID: primaryDeviceID }; await broadcastEphemeralMessage( JSON.stringify(messageContents), [recipient], authMetadata, ); // log out of identity service, keyserver and visually return logOut(); }, [identityContext, broadcastEphemeralMessage, logOut]); } const claimUsernameActionTypes = Object.freeze({ started: 'CLAIM_USERNAME_STARTED', success: 'CLAIM_USERNAME_SUCCESS', failed: 'CLAIM_USERNAME_FAILED', }); const claimUsername = ( callKeyserverEndpoint: CallKeyserverEndpoint, ): (( claimUsernameRequest: ClaimUsernameRequest, ) => Promise) => async (claimUsernameRequest: ClaimUsernameRequest) => { const requests = { [authoritativeKeyserverID()]: claimUsernameRequest }; const responses = await callKeyserverEndpoint('claim_username', requests); const response = responses[authoritativeKeyserverID()]; return { message: response.message, signature: response.signature, }; }; function useClaimUsername(): ( claimUsernameRequest: ClaimUsernameRequest, ) => Promise { return useKeyserverCall(claimUsername); } const deleteKeyserverAccountActionTypes = Object.freeze({ started: 'DELETE_KEYSERVER_ACCOUNT_STARTED', success: 'DELETE_KEYSERVER_ACCOUNT_SUCCESS', failed: 'DELETE_KEYSERVER_ACCOUNT_FAILED', }); const deleteKeyserverAccount = ( callKeyserverEndpoint: CallKeyserverEndpoint, allKeyserverIDs: $ReadOnlyArray, ): ((input: KeyserverLogOutInput) => Promise) => async input => { const { preRequestUserState } = input; const keyserverIDs = input.keyserverIDs ?? allKeyserverIDs; const requests: { [string]: {} } = {}; for (const keyserverID of keyserverIDs) { requests[keyserverID] = {}; } await callKeyserverEndpoint('delete_account', requests); return { currentUserInfo: loggedOutUserInfo, preRequestUserState, keyserverIDs, }; }; function useDeleteKeyserverAccount(): ( keyserverIDs?: $ReadOnlyArray, ) => Promise { const preRequestUserState = usePreRequestUserState(); const callKeyserverDeleteAccount = useKeyserverCall(deleteKeyserverAccount); return React.useCallback( (keyserverIDs?: $ReadOnlyArray) => callKeyserverDeleteAccount({ preRequestUserState, keyserverIDs }), [callKeyserverDeleteAccount, preRequestUserState], ); } const deleteAccountActionTypes = Object.freeze({ started: 'DELETE_ACCOUNT_STARTED', success: 'DELETE_ACCOUNT_SUCCESS', failed: 'DELETE_ACCOUNT_FAILED', }); const accountDeletionBroadcastOptions = Object.freeze({ includeOwnDevices: true, }); function useDeleteAccount(): (password: ?string) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; const broadcastAccountDeletion = useBroadcastAccountDeletion( accountDeletionBroadcastOptions, ); const preRequestUserState = usePreRequestUserState(); const callKeyserverDeleteAccount = useKeyserverCall(deleteKeyserverAccount); const commServicesAccessToken = useSelector( state => state.commServicesAccessToken, ); return React.useCallback( async password => { if (usingCommServicesAccessToken) { if (!identityClient) { throw new Error('Identity service client is not initialized'); } const { deleteWalletUser, deletePasswordUser } = identityClient; if (!deleteWalletUser || !deletePasswordUser) { throw new Error('Delete user method unimplemented'); } await broadcastAccountDeletion(); if (password) { await deletePasswordUser(password); } else { await deleteWalletUser(); } } try { const keyserverResult = await callKeyserverDeleteAccount({ preRequestUserState, }); const { keyserverIDs: _, ...result } = keyserverResult; return { ...result, preRequestUserState: { ...result.preRequestUserState, commServicesAccessToken, }, }; } catch (e) { if (!usingCommServicesAccessToken) { throw e; } console.log( 'Failed to delete account on keyserver:', getMessageForException(e), ); } return { currentUserInfo: null, preRequestUserState: { ...preRequestUserState, commServicesAccessToken, }, }; }, [ broadcastAccountDeletion, callKeyserverDeleteAccount, commServicesAccessToken, identityClient, preRequestUserState, ], ); } // useDeleteDiscardedIdentityAccount is used in a scenario where the user is // visibly logged-out, and it's only used to reset state (eg. Redux, SQLite) to // a logged-out state. function useDeleteDiscardedIdentityAccount(): ( password: ?string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; const preRequestUserState = usePreRequestUserState(); const commServicesAccessToken = useSelector( state => state.commServicesAccessToken, ); return React.useCallback( async password => { invariant( usingCommServicesAccessToken, 'deleteDiscardedIdentityAccount can only be called when ' + 'usingCommServicesAccessToken', ); if (!identityClient) { throw new Error('Identity service client is not initialized'); } if ( !identityClient.deleteWalletUser || !identityClient.deletePasswordUser ) { throw new Error('Delete user method unimplemented'); } const deleteUserPromise = password ? identityClient.deletePasswordUser(password) : identityClient.deleteWalletUser(); await Promise.race([ deleteUserPromise, (async () => { await sleep(callIdentityServiceTimeout); throw new Error('identity delete user call took more than 500ms'); })(), ]); return { currentUserInfo: null, preRequestUserState: { ...preRequestUserState, commServicesAccessToken, }, }; }, [commServicesAccessToken, identityClient, preRequestUserState], ); } const legacyKeyserverRegisterActionTypes = Object.freeze({ started: 'LEGACY_KEYSERVER_REGISTER_STARTED', success: 'LEGACY_KEYSERVER_REGISTER_SUCCESS', failed: 'LEGACY_KEYSERVER_REGISTER_FAILED', }); const legacyKeyserverRegisterCallSingleKeyserverEndpointOptions = { timeout: permissionsAndAuthRelatedRequestTimeout, }; const legacyKeyserverRegister = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): (( registerInfo: LegacyRegisterInfo, options?: CallSingleKeyserverEndpointOptions, ) => Promise) => async (registerInfo, options) => { const deviceTokenUpdateRequest = registerInfo.deviceTokenUpdateRequest[authoritativeKeyserverID()]; const { preRequestUserInfo, ...rest } = registerInfo; const response = await callSingleKeyserverEndpoint( 'create_account', { ...rest, deviceTokenUpdateRequest, platformDetails: getConfig().platformDetails, }, { ...legacyKeyserverRegisterCallSingleKeyserverEndpointOptions, ...options, }, ); return { currentUserInfo: response.currentUserInfo, rawMessageInfos: response.rawMessageInfos, threadInfos: response.cookieChange.threadInfos, userInfos: response.cookieChange.userInfos, calendarQuery: registerInfo.calendarQuery, }; }; export type KeyserverAuthInput = $ReadOnly<{ ...KeyserverAuthInfo, +preRequestUserInfo: ?CurrentUserInfo, }>; const keyserverAuthActionTypes = Object.freeze({ started: 'KEYSERVER_AUTH_STARTED', success: 'KEYSERVER_AUTH_SUCCESS', failed: 'KEYSERVER_AUTH_FAILED', }); const keyserverAuthCallSingleKeyserverEndpointOptions = { timeout: permissionsAndAuthRelatedRequestTimeout, }; const keyserverAuth = ( callKeyserverEndpoint: CallKeyserverEndpoint, ): ((input: KeyserverAuthInput) => Promise) => async keyserverAuthInfo => { const watchedIDs = threadWatcher.getWatchedIDs(); const { authActionSource, calendarQuery, keyserverData, deviceTokenUpdateInput, preRequestUserInfo, ...restLogInInfo } = keyserverAuthInfo; const keyserverIDs = Object.keys(keyserverData); const authKeyserverID = authoritativeKeyserverID(); if (restLogInInfo.password) { invariant( keyserverIDs.length === 1 && keyserverIDs[0] === authKeyserverID, 'passing password to non-auth keyserver', ); } const watchedIDsPerKeyserver = sortThreadIDsPerKeyserver(watchedIDs); const calendarQueryPerKeyserver = sortCalendarQueryPerKeyserver( calendarQuery, keyserverIDs, ); const requests: { [string]: KeyserverAuthRequest } = {}; for (const keyserverID of keyserverIDs) { requests[keyserverID] = { ...restLogInInfo, deviceTokenUpdateRequest: deviceTokenUpdateInput[keyserverID], watchedIDs: watchedIDsPerKeyserver[keyserverID] ?? [], calendarQuery: calendarQueryPerKeyserver[keyserverID], platformDetails: getConfig().platformDetails, initialContentEncryptedMessage: keyserverData[keyserverID].initialContentEncryptedMessage, initialNotificationsEncryptedMessage: keyserverData[keyserverID].initialNotificationsEncryptedMessage, source: authActionSource, }; } const responses: { +[string]: ClientLogInResponse } = await callKeyserverEndpoint( 'keyserver_auth', requests, keyserverAuthCallSingleKeyserverEndpointOptions, ); let threadInfos: RawThreadInfos = {}; const calendarResult: WritableCalendarResult = { calendarQuery: keyserverAuthInfo.calendarQuery, rawEntryInfos: [], }; const messagesResult: WritableGenericMessagesResult = { messageInfos: [], truncationStatus: {}, watchedIDsAtRequestTime: watchedIDs, currentAsOf: {}, }; let updatesCurrentAsOf: { +[string]: number } = {}; for (const keyserverID in responses) { threadInfos = { ...responses[keyserverID].cookieChange.threadInfos, ...threadInfos, }; if (responses[keyserverID].rawEntryInfos) { calendarResult.rawEntryInfos = calendarResult.rawEntryInfos.concat( responses[keyserverID].rawEntryInfos, ); } messagesResult.messageInfos = messagesResult.messageInfos.concat( responses[keyserverID].rawMessageInfos, ); messagesResult.truncationStatus = { ...messagesResult.truncationStatus, ...responses[keyserverID].truncationStatuses, }; messagesResult.currentAsOf = { ...messagesResult.currentAsOf, [keyserverID]: responses[keyserverID].serverTime, }; updatesCurrentAsOf = { ...updatesCurrentAsOf, [keyserverID]: responses[keyserverID].serverTime, }; } let userInfos: $ReadOnlyArray = []; if (responses[authKeyserverID]) { const userInfosArrays = [ responses[authKeyserverID].userInfos, responses[authKeyserverID].cookieChange.userInfos, ]; userInfos = mergeUserInfos(...userInfosArrays); } return { threadInfos, currentUserInfo: responses[authKeyserverID]?.currentUserInfo, calendarResult, messagesResult, userInfos, updatesCurrentAsOf, authActionSource: keyserverAuthInfo.authActionSource, notAcknowledgedPolicies: responses[authKeyserverID]?.notAcknowledgedPolicies, preRequestUserInfo, }; }; const identityRegisterActionTypes = Object.freeze({ started: 'IDENTITY_REGISTER_STARTED', success: 'IDENTITY_REGISTER_SUCCESS', failed: 'IDENTITY_REGISTER_FAILED', }); function useIdentityPasswordRegister(): ( username: string, password: string, fid: ?string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); if (!identityClient.registerPasswordUser) { throw new Error('Register password user method unimplemented'); } const { registerPasswordUser } = identityClient; const { markPrekeysAsPublished } = getConfig().olmAPI; return React.useCallback( async (username: string, password: string, fid: ?string) => { const response = await registerPasswordUser(username, password, fid); try { await markPrekeysAsPublished(); } catch (e) { console.log( 'Failed to mark prekeys as published:', getMessageForException(e), ); } return response; }, [registerPasswordUser, markPrekeysAsPublished], ); } function useIdentityWalletRegister(): ( walletAddress: string, siweMessage: string, siweSignature: string, fid: ?string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); if (!identityClient.registerWalletUser) { throw new Error('Register wallet user method unimplemented'); } const { registerWalletUser } = identityClient; const { markPrekeysAsPublished } = getConfig().olmAPI; return React.useCallback( async ( walletAddress: string, siweMessage: string, siweSignature: string, fid: ?string, ) => { const response = await registerWalletUser( walletAddress, siweMessage, siweSignature, fid, ); try { await markPrekeysAsPublished(); } catch (e) { console.log( 'Failed to mark prekeys as published:', getMessageForException(e), ); } return response; }, [registerWalletUser, markPrekeysAsPublished], ); } const identityGenerateNonceActionTypes = Object.freeze({ started: 'IDENTITY_GENERATE_NONCE_STARTED', success: 'IDENTITY_GENERATE_NONCE_SUCCESS', failed: 'IDENTITY_GENERATE_NONCE_FAILED', }); function useIdentityGenerateNonce(): () => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); return identityClient.generateNonce; } function mergeUserInfos( ...userInfoArrays: Array<$ReadOnlyArray> ): UserInfo[] { const merged: { [string]: UserInfo } = {}; for (const userInfoArray of userInfoArrays) { for (const userInfo of userInfoArray) { merged[userInfo.id] = userInfo; } } const flattened = []; for (const id in merged) { flattened.push(merged[id]); } return flattened; } type WritableGenericMessagesResult = { messageInfos: RawMessageInfo[], truncationStatus: MessageTruncationStatuses, watchedIDsAtRequestTime: string[], currentAsOf: { [keyserverID: string]: number }, }; type WritableCalendarResult = { rawEntryInfos: RawEntryInfo[], calendarQuery: CalendarQuery, }; const identityLogInActionTypes = Object.freeze({ started: 'IDENTITY_LOG_IN_STARTED', success: 'IDENTITY_LOG_IN_SUCCESS', failed: 'IDENTITY_LOG_IN_FAILED', }); function useIdentityPasswordLogIn(): ( username: string, password: string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; const preRequestUserState = useSelector(state => state.currentUserInfo); const callClaimUsername = useClaimUsername(); const { markPrekeysAsPublished } = getConfig().olmAPI; return React.useCallback( (username, password) => { if (!identityClient) { throw new Error('Identity service client is not initialized'); } return (async () => { let result; try { result = await identityClient.logInPasswordUser(username, password); } catch (e) { const { registerReservedPasswordUser } = identityClient; if ( !registerReservedPasswordUser || getMessageForException(e) !== 'need_keyserver_message_to_claim_username' ) { throw e; } const { message, signature } = await callClaimUsername({ username, password, }); result = await registerReservedPasswordUser( username, password, message, signature, ); } try { await markPrekeysAsPublished(); } catch (e) { console.log( 'Failed to mark prekeys as published:', getMessageForException(e), ); } return { ...result, preRequestUserState, }; })(); }, [ identityClient, markPrekeysAsPublished, preRequestUserState, callClaimUsername, ], ); } function useIdentityWalletLogIn(): ( walletAddress: string, siweMessage: string, siweSignature: string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); const { logInWalletUser } = identityClient; const { markPrekeysAsPublished } = getConfig().olmAPI; return React.useCallback( async ( walletAddress: string, siweMessage: string, siweSignature: string, ) => { const response = await logInWalletUser( walletAddress, siweMessage, siweSignature, ); try { await markPrekeysAsPublished(); } catch (e) { console.log( 'Failed to mark prekeys as published:', getMessageForException(e), ); } return response; }, [logInWalletUser, markPrekeysAsPublished], ); } function useIdentitySecondaryDeviceLogIn(): ( userID: string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); const { generateNonce, uploadKeysForRegisteredDeviceAndLogIn } = identityClient; const { signMessage, markPrekeysAsPublished } = getConfig().olmAPI; return React.useCallback( async (userID: string) => { const nonce = await generateNonce(); const nonceSignature = await signMessage(nonce); const response = await uploadKeysForRegisteredDeviceAndLogIn(userID, { nonce, nonceSignature, }); try { await markPrekeysAsPublished(); } catch (e) { console.log( 'Failed to mark prekeys as published:', getMessageForException(e), ); } return response; }, [ generateNonce, markPrekeysAsPublished, signMessage, uploadKeysForRegisteredDeviceAndLogIn, ], ); } const legacyLogInActionTypes = Object.freeze({ started: 'LEGACY_LOG_IN_STARTED', success: 'LEGACY_LOG_IN_SUCCESS', failed: 'LEGACY_LOG_IN_FAILED', }); const legacyLogInCallSingleKeyserverEndpointOptions = { timeout: permissionsAndAuthRelatedRequestTimeout, }; const legacyLogIn = ( callKeyserverEndpoint: CallKeyserverEndpoint, ): ((input: LegacyLogInInfo) => Promise) => async logInInfo => { const watchedIDs = threadWatcher.getWatchedIDs(); const { authActionSource, calendarQuery, keyserverIDs: inputKeyserverIDs, preRequestUserInfo, ...restLogInInfo } = logInInfo; // Eventually the list of keyservers will be fetched from the // identity service const keyserverIDs = inputKeyserverIDs ?? [authoritativeKeyserverID()]; const watchedIDsPerKeyserver = sortThreadIDsPerKeyserver(watchedIDs); const calendarQueryPerKeyserver = sortCalendarQueryPerKeyserver( calendarQuery, keyserverIDs, ); const requests: { [string]: LogInRequest } = {}; for (const keyserverID of keyserverIDs) { requests[keyserverID] = { ...restLogInInfo, deviceTokenUpdateRequest: logInInfo.deviceTokenUpdateRequest[keyserverID], source: authActionSource, watchedIDs: watchedIDsPerKeyserver[keyserverID] ?? [], calendarQuery: calendarQueryPerKeyserver[keyserverID], platformDetails: getConfig().platformDetails, }; } const responses: { +[string]: ClientLogInResponse } = await callKeyserverEndpoint( 'log_in', requests, legacyLogInCallSingleKeyserverEndpointOptions, ); const userInfosArrays = []; let threadInfos: RawThreadInfos = {}; const calendarResult: WritableCalendarResult = { calendarQuery: logInInfo.calendarQuery, rawEntryInfos: [], }; const messagesResult: WritableGenericMessagesResult = { messageInfos: [], truncationStatus: {}, watchedIDsAtRequestTime: watchedIDs, currentAsOf: {}, }; let updatesCurrentAsOf: { +[string]: number } = {}; for (const keyserverID in responses) { threadInfos = { ...responses[keyserverID].cookieChange.threadInfos, ...threadInfos, }; if (responses[keyserverID].rawEntryInfos) { calendarResult.rawEntryInfos = calendarResult.rawEntryInfos.concat( responses[keyserverID].rawEntryInfos, ); } messagesResult.messageInfos = messagesResult.messageInfos.concat( responses[keyserverID].rawMessageInfos, ); messagesResult.truncationStatus = { ...messagesResult.truncationStatus, ...responses[keyserverID].truncationStatuses, }; messagesResult.currentAsOf = { ...messagesResult.currentAsOf, [keyserverID]: responses[keyserverID].serverTime, }; updatesCurrentAsOf = { ...updatesCurrentAsOf, [keyserverID]: responses[keyserverID].serverTime, }; userInfosArrays.push(responses[keyserverID].userInfos); userInfosArrays.push(responses[keyserverID].cookieChange.userInfos); } const userInfos = mergeUserInfos(...userInfosArrays); return { threadInfos, currentUserInfo: responses[authoritativeKeyserverID()].currentUserInfo, calendarResult, messagesResult, userInfos, updatesCurrentAsOf, authActionSource: logInInfo.authActionSource, notAcknowledgedPolicies: responses[authoritativeKeyserverID()].notAcknowledgedPolicies, preRequestUserInfo, }; }; function useLegacyLogIn(): ( input: LegacyLogInInfo, ) => Promise { return useKeyserverCall(legacyLogIn); } const changeKeyserverUserPasswordActionTypes = Object.freeze({ started: 'CHANGE_KEYSERVER_USER_PASSWORD_STARTED', success: 'CHANGE_KEYSERVER_USER_PASSWORD_SUCCESS', failed: 'CHANGE_KEYSERVER_USER_PASSWORD_FAILED', }); const changeKeyserverUserPassword = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): ((passwordUpdate: PasswordUpdate) => Promise) => async passwordUpdate => { await callSingleKeyserverEndpoint('update_account', passwordUpdate); }; const changeIdentityUserPasswordActionTypes = Object.freeze({ started: 'CHANGE_IDENTITY_USER_PASSWORD_STARTED', success: 'CHANGE_IDENTITY_USER_PASSWORD_SUCCESS', failed: 'CHANGE_IDENTITY_USER_PASSWORD_FAILED', }); function useChangeIdentityUserPassword(): ( oldPassword: string, newPassword: string, ) => Promise { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; return React.useCallback( (oldPassword, newPassword) => { if (!identityClient) { throw new Error('Identity service client is not initialized'); } return identityClient.changePassword(oldPassword, newPassword); }, [identityClient], ); } const searchUsersActionTypes = Object.freeze({ started: 'SEARCH_USERS_STARTED', success: 'SEARCH_USERS_SUCCESS', failed: 'SEARCH_USERS_FAILED', }); const searchUsers = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): ((usernamePrefix: string) => Promise) => async usernamePrefix => { const response = await callSingleKeyserverEndpoint('search_users', { prefix: usernamePrefix, }); return { userInfos: response.userInfos, }; }; const exactSearchUserActionTypes = Object.freeze({ started: 'EXACT_SEARCH_USER_STARTED', success: 'EXACT_SEARCH_USER_SUCCESS', failed: 'EXACT_SEARCH_USER_FAILED', }); const exactSearchUser = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): ((username: string) => Promise) => async username => { const response = await callSingleKeyserverEndpoint('exact_search_user', { username, }); return { userInfo: response.userInfo, }; }; const updateSubscriptionActionTypes = Object.freeze({ started: 'UPDATE_SUBSCRIPTION_STARTED', success: 'UPDATE_SUBSCRIPTION_SUCCESS', failed: 'UPDATE_SUBSCRIPTION_FAILED', }); const updateSubscription = ( callKeyserverEndpoint: CallKeyserverEndpoint, ): (( input: SubscriptionUpdateRequest, ) => Promise) => async input => { const keyserverID = extractKeyserverIDFromID(input.threadID); const requests = { [keyserverID]: input }; const responses = await callKeyserverEndpoint( 'update_user_subscription', requests, ); const response = responses[keyserverID]; return { threadID: input.threadID, subscription: response.threadSubscription, }; }; type UseUpdateSubscriptionInput = $ReadOnly< | { +thick: false, ...SubscriptionUpdateRequest, } | { +thick: true, +threadInfo: ThreadInfo, ...SubscriptionUpdateRequest, }, >; function useUpdateSubscription(): ( input: UseUpdateSubscriptionInput, ) => Promise { const processAndSendDMOperation = useProcessAndSendDMOperation(); const viewerID = useSelector( state => state.currentUserInfo && state.currentUserInfo.id, ); const keyserverCall = useKeyserverCall(updateSubscription); return React.useCallback( async (input: UseUpdateSubscriptionInput) => { if (!input.thick) { const { thick, ...rest } = input; return await keyserverCall({ ...rest }); } invariant(viewerID, 'viewerID must be set'); const { threadInfo, updatedFields } = input; const subscription = { ...threadInfo.currentUser.subscription, ...updatedFields, }; const op: DMChangeThreadSubscriptionOperation = { type: 'change_thread_subscription', time: Date.now(), threadID: threadInfo.id, creatorID: viewerID, subscription, }; const opSpecification: OutboundDMOperationSpecification = { type: dmOperationSpecificationTypes.OUTBOUND, op, recipients: { type: 'all_thread_members', threadID: threadInfo.type === thickThreadTypes.THICK_SIDEBAR && threadInfo.parentThreadID ? threadInfo.parentThreadID : threadInfo.id, }, }; await processAndSendDMOperation(opSpecification); return { threadID: threadInfo.id, subscription }; }, [keyserverCall, processAndSendDMOperation, viewerID], ); } const setUserSettingsActionTypes = Object.freeze({ started: 'SET_USER_SETTINGS_STARTED', success: 'SET_USER_SETTINGS_SUCCESS', failed: 'SET_USER_SETTINGS_FAILED', }); const setUserSettings = ( callKeyserverEndpoint: CallKeyserverEndpoint, allKeyserverIDs: $ReadOnlyArray, ): ((input: UpdateUserSettingsRequest) => Promise) => async input => { const requests: { [string]: UpdateUserSettingsRequest } = {}; for (const keyserverID of allKeyserverIDs) { requests[keyserverID] = input; } await callKeyserverEndpoint('update_user_settings', requests); }; function useSetUserSettings(): ( input: UpdateUserSettingsRequest, ) => Promise { return useKeyserverCall(setUserSettings); } const getOlmSessionInitializationDataActionTypes = Object.freeze({ started: 'GET_OLM_SESSION_INITIALIZATION_DATA_STARTED', success: 'GET_OLM_SESSION_INITIALIZATION_DATA_SUCCESS', failed: 'GET_OLM_SESSION_INITIALIZATION_DATA_FAILED', }); const getOlmSessionInitializationData = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): (( options?: ?CallSingleKeyserverEndpointOptions, ) => Promise) => async options => { const olmInitData = await callSingleKeyserverEndpoint( 'get_olm_session_initialization_data', {}, options, ); return { signedIdentityKeysBlob: olmInitData.signedIdentityKeysBlob, contentInitializationInfo: { ...olmInitData.contentInitializationInfo, oneTimeKey: getOneTimeKeyValuesFromBlob( olmInitData.contentInitializationInfo.oneTimeKey, )[0], prekey: getPrekeyValueFromBlob( olmInitData.contentInitializationInfo.prekey, ), }, notifInitializationInfo: { ...olmInitData.notifInitializationInfo, oneTimeKey: getOneTimeKeyValuesFromBlob( olmInitData.notifInitializationInfo.oneTimeKey, )[0], prekey: getPrekeyValueFromBlob( olmInitData.notifInitializationInfo.prekey, ), }, }; }; const policyAcknowledgmentActionTypes = Object.freeze({ started: 'POLICY_ACKNOWLEDGMENT_STARTED', success: 'POLICY_ACKNOWLEDGMENT_SUCCESS', failed: 'POLICY_ACKNOWLEDGMENT_FAILED', }); const policyAcknowledgment = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): ((policyRequest: PolicyAcknowledgmentRequest) => Promise) => async policyRequest => { await callSingleKeyserverEndpoint('policy_acknowledgment', policyRequest); }; const updateUserAvatarActionTypes = Object.freeze({ started: 'UPDATE_USER_AVATAR_STARTED', success: 'UPDATE_USER_AVATAR_SUCCESS', failed: 'UPDATE_USER_AVATAR_FAILED', }); const updateUserAvatar = ( callSingleKeyserverEndpoint: CallSingleKeyserverEndpoint, ): (( avatarDBContent: UpdateUserAvatarRequest, ) => Promise) => async avatarDBContent => { const { updates }: UpdateUserAvatarResponse = await callSingleKeyserverEndpoint('update_user_avatar', avatarDBContent); return { updates }; }; const processNewUserIDsActionType = 'PROCESS_NEW_USER_IDS'; -const findUserIdentitiesActionTypes = Object.freeze({ - started: 'FIND_USER_IDENTITIES_STARTED', - success: 'FIND_USER_IDENTITIES_SUCCESS', - failed: 'FIND_USER_IDENTITIES_FAILED', -}); - -function useFindUserIdentities(): ( - userIDs: $ReadOnlyArray, -) => Promise { - const userIdentityCache = useUserIdentityCache(); - return userIdentityCache.getUserIdentities; -} - const versionSupportedByIdentityActionTypes = Object.freeze({ started: 'VERSION_SUPPORTED_BY_IDENTITY_STARTED', success: 'VERSION_SUPPORTED_BY_IDENTITY_SUCCESS', failed: 'VERSION_SUPPORTED_BY_IDENTITY_FAILED', }); function useVersionSupportedByIdentity(): () => Promise<{ +supported: boolean, }> { const client = React.useContext(IdentityClientContext); const identityClient = client?.identityClient; invariant(identityClient, 'Identity client should be set'); return async () => { const supported = await identityClient.versionSupported(); return { supported }; }; } export { changeKeyserverUserPasswordActionTypes, changeKeyserverUserPassword, changeIdentityUserPasswordActionTypes, useChangeIdentityUserPassword, claimUsernameActionTypes, useClaimUsername, useDeleteKeyserverAccount, deleteKeyserverAccountActionTypes, getOlmSessionInitializationDataActionTypes, getOlmSessionInitializationData, mergeUserInfos, legacyLogIn as legacyLogInRawAction, identityLogInActionTypes, useIdentityPasswordLogIn, useIdentityWalletLogIn, useIdentitySecondaryDeviceLogIn, useLegacyLogIn, legacyLogInActionTypes, useLogOut, useIdentityLogOut, usePrimaryDeviceLogOut, useSecondaryDeviceLogOut, logOutActionTypes, legacyKeyserverRegister, legacyKeyserverRegisterActionTypes, searchUsers, searchUsersActionTypes, exactSearchUser, exactSearchUserActionTypes, useSetUserSettings, setUserSettingsActionTypes, useUpdateSubscription, updateSubscriptionActionTypes, policyAcknowledgment, policyAcknowledgmentActionTypes, updateUserAvatarActionTypes, updateUserAvatar, deleteAccountActionTypes, useDeleteAccount, useDeleteDiscardedIdentityAccount, keyserverAuthActionTypes, keyserverAuth as keyserverAuthRawAction, identityRegisterActionTypes, useIdentityPasswordRegister, useIdentityWalletRegister, identityGenerateNonceActionTypes, useIdentityGenerateNonce, processNewUserIDsActionType, - findUserIdentitiesActionTypes, - useFindUserIdentities, versionSupportedByIdentityActionTypes, useVersionSupportedByIdentity, }; diff --git a/lib/components/farcaster-data-handler.react.js b/lib/components/farcaster-data-handler.react.js index ab4e625cb..e96c6e755 100644 --- a/lib/components/farcaster-data-handler.react.js +++ b/lib/components/farcaster-data-handler.react.js @@ -1,229 +1,229 @@ // @flow import * as React from 'react'; import { setAuxUserFIDsActionType } from '../actions/aux-user-actions.js'; +import { useFindUserIdentities } from '../actions/find-user-identities-actions.js'; import { updateRelationshipsActionTypes } from '../actions/relationship-actions.js'; import { setSyncedMetadataEntryActionType } from '../actions/synced-metadata-actions.js'; -import { useFindUserIdentities } from '../actions/user-actions.js'; import { NeynarClientContext } from '../components/neynar-client-provider.react.js'; import { useIsLoggedInToIdentityAndAuthoritativeKeyserver } from '../hooks/account-hooks.js'; import { useUpdateRelationships } from '../hooks/relationship-hooks.js'; import { IdentityClientContext } from '../shared/identity-client-context.js'; import { relationshipActions } from '../types/relationship-types.js'; import { syncedMetadataNames } from '../types/synced-metadata-types.js'; import { useCurrentUserFID, useUnlinkFID } from '../utils/farcaster-utils.js'; import { useDispatchActionPromise } from '../utils/redux-promise-utils.js'; import { useSelector, useDispatch } from '../utils/redux-utils.js'; import { usingCommServicesAccessToken } from '../utils/services-utils.js'; type Props = { +children?: React.Node, }; function FarcasterDataHandler(props: Props): React.Node { const { children } = props; const isActive = useSelector(state => state.lifecycleState !== 'background'); const currentUserID = useSelector(state => state.currentUserInfo?.id); const loggedIn = useIsLoggedInToIdentityAndAuthoritativeKeyserver(); const neynarClient = React.useContext(NeynarClientContext)?.client; const identityServiceClient = React.useContext(IdentityClientContext); const getFarcasterUsers = identityServiceClient?.identityClient.getFarcasterUsers; const findUserIdentities = useFindUserIdentities(); const dispatch = useDispatch(); const dispatchActionPromise = useDispatchActionPromise(); const updateRelationships = useUpdateRelationships(); const createThreadsAndRobotextForFarcasterMutuals = React.useCallback( (userIDs: $ReadOnlyArray) => updateRelationships(relationshipActions.FARCASTER_MUTUAL, userIDs), [updateRelationships], ); const userInfos = useSelector(state => state.userStore.userInfos); const fid = useCurrentUserFID(); const unlinkFID = useUnlinkFID(); const prevCanQueryRef = React.useRef(); // It's possible for the user to log out while handleFarcasterMutuals below // is running. It's not a big deal, but this can lead to a useless server call // at the end. To avoid that useless server call, we want to check whether the // user is logged in beforehand, but the value of loggedIn bound in the // callback will be outdated. Instead, we can check this ref, which will be // updated on every render. const loggedInRef = React.useRef(loggedIn); loggedInRef.current = loggedIn; const handleFarcasterMutuals = React.useCallback(async () => { const canQuery = isActive && !!fid && loggedIn; if (canQuery === prevCanQueryRef.current) { return; } prevCanQueryRef.current = canQuery; if ( !loggedIn || !isActive || !fid || !neynarClient || !getFarcasterUsers || !currentUserID ) { return; } const followerFIDs = await neynarClient.fetchFriendFIDs(fid); const commFCUsers = await getFarcasterUsers(followerFIDs); const newCommUsers = commFCUsers.filter(({ userID }) => !userInfos[userID]); if (newCommUsers.length === 0) { return; } const newCommUserIDs = newCommUsers.map(({ userID }) => userID); if (!loggedInRef.current) { return; } void dispatchActionPromise( updateRelationshipsActionTypes, createThreadsAndRobotextForFarcasterMutuals(newCommUserIDs), ); }, [ isActive, fid, loggedIn, neynarClient, getFarcasterUsers, userInfos, dispatchActionPromise, createThreadsAndRobotextForFarcasterMutuals, currentUserID, ]); const handleUserStoreFIDs = React.useCallback(async () => { if (!loggedIn || !isActive) { return; } const userStoreIDs = Object.keys(userInfos); const { identities: userIdentities } = await findUserIdentities(userStoreIDs); const userStoreFarcasterUsers = Object.entries(userIdentities) .filter(([, identity]) => identity.farcasterID !== null) .map(([userID, identity]) => ({ userID, username: identity.username, farcasterID: identity.farcasterID, })); dispatch({ type: setAuxUserFIDsActionType, payload: { farcasterUsers: userStoreFarcasterUsers, }, }); }, [loggedIn, isActive, findUserIdentities, userInfos, dispatch]); const prevCanQueryHandleCurrentUserFIDRef = React.useRef(); const canQueryHandleCurrentUserFID = isActive && loggedIn; const [fidLoaded, setFIDLoaded] = React.useState(false); const handleCurrentUserFID = React.useCallback(async () => { if ( canQueryHandleCurrentUserFID === prevCanQueryHandleCurrentUserFIDRef.current ) { return; } prevCanQueryHandleCurrentUserFIDRef.current = canQueryHandleCurrentUserFID; if (!canQueryHandleCurrentUserFID || !currentUserID || !neynarClient) { return; } if (fid) { const isCurrentUserFIDValid = await neynarClient.checkIfCurrentUserFIDIsValid(fid); if (!isCurrentUserFIDValid) { await unlinkFID(); return; } return; } const { identities: userIdentities } = await findUserIdentities([ currentUserID, ]); const identityFID = userIdentities[currentUserID]?.farcasterID; if (identityFID) { dispatch({ type: setSyncedMetadataEntryActionType, payload: { name: syncedMetadataNames.CURRENT_USER_FID, data: identityFID, }, }); } setFIDLoaded(true); }, [ canQueryHandleCurrentUserFID, findUserIdentities, currentUserID, neynarClient, fid, unlinkFID, dispatch, ]); React.useEffect(() => { if (!usingCommServicesAccessToken) { return; } void handleFarcasterMutuals(); void handleUserStoreFIDs(); void handleCurrentUserFID(); }, [handleCurrentUserFID, handleFarcasterMutuals, handleUserStoreFIDs]); React.useEffect(() => { if (loggedIn) { return; } setFIDLoaded(false); }, [loggedIn]); const farcasterDataHandler = React.useMemo(() => { if (!fidLoaded) { return null; } return children; }, [children, fidLoaded]); return farcasterDataHandler; } export { FarcasterDataHandler }; diff --git a/lib/handlers/user-infos-handler.react.js b/lib/handlers/user-infos-handler.react.js index fb83c12d7..579d55487 100644 --- a/lib/handlers/user-infos-handler.react.js +++ b/lib/handlers/user-infos-handler.react.js @@ -1,190 +1,190 @@ // @flow import invariant from 'invariant'; import * as React from 'react'; -import { updateRelationshipsActionTypes } from '../actions/relationship-actions.js'; import { useFindUserIdentities, findUserIdentitiesActionTypes, -} from '../actions/user-actions.js'; +} from '../actions/find-user-identities-actions.js'; +import { updateRelationshipsActionTypes } from '../actions/relationship-actions.js'; import { useIsLoggedInToAuthoritativeKeyserver } from '../hooks/account-hooks.js'; import { useGetAndUpdateDeviceListsForUsers } from '../hooks/peer-list-hooks.js'; import { useUpdateRelationships } from '../hooks/relationship-hooks.js'; import { usersWithMissingDeviceListSelector } from '../selectors/user-selectors.js'; import { IdentityClientContext } from '../shared/identity-client-context.js'; import { useTunnelbroker } from '../tunnelbroker/tunnelbroker-context.js'; import { relationshipActions } from '../types/relationship-types.js'; import { getMessageForException, FetchTimeout } from '../utils/errors.js'; import { useDispatchActionPromise } from '../utils/redux-promise-utils.js'; import { useSelector } from '../utils/redux-utils.js'; import { relyingOnAuthoritativeKeyserver, usingCommServicesAccessToken, } from '../utils/services-utils.js'; function UserInfosHandler(): React.Node { const client = React.useContext(IdentityClientContext); invariant(client, 'Identity context should be set'); const { getAuthMetadata } = client; const userInfos = useSelector(state => state.userStore.userInfos); const userInfosWithMissingUsernames = React.useMemo(() => { const entriesWithoutUsernames = Object.entries(userInfos).filter( ([, value]) => !value.username, ); return Object.fromEntries(entriesWithoutUsernames); }, [userInfos]); const dispatchActionPromise = useDispatchActionPromise(); const findUserIdentities = useFindUserIdentities(); const requestedIDsRef = React.useRef(new Set()); const requestedAvatarsRef = React.useRef(new Set()); const updateRelationships = useUpdateRelationships(); const currentUserInfo = useSelector(state => state.currentUserInfo); const loggedInToAuthKeyserver = useIsLoggedInToAuthoritativeKeyserver(); React.useEffect(() => { if (!loggedInToAuthKeyserver) { return; } const newUserIDs = Object.keys(userInfosWithMissingUsernames).filter( id => !requestedIDsRef.current.has(id), ); if (!usingCommServicesAccessToken || newUserIDs.length === 0) { return; } void (async () => { const authMetadata = await getAuthMetadata(); if (!authMetadata) { return; } // 1. Fetch usernames from identity const promise = (async () => { newUserIDs.forEach(id => requestedIDsRef.current.add(id)); const { identities, reservedUserIdentifiers } = await findUserIdentities(newUserIDs); newUserIDs.forEach(id => requestedIDsRef.current.delete(id)); const newUserInfos = []; for (const id in identities) { newUserInfos.push({ id, username: identities[id].username, }); } for (const id in reservedUserIdentifiers) { newUserInfos.push({ id, username: reservedUserIdentifiers[id], }); } return { userInfos: newUserInfos }; })(); void dispatchActionPromise(findUserIdentitiesActionTypes, promise); // 2. Fetch avatars from auth keyserver if (relyingOnAuthoritativeKeyserver) { const userIDsWithoutOwnID = newUserIDs.filter( id => id !== currentUserInfo?.id && !requestedAvatarsRef.current.has(id), ); if (userIDsWithoutOwnID.length === 0) { return; } userIDsWithoutOwnID.forEach(id => requestedAvatarsRef.current.add(id)); const updateRelationshipsPromise = (async () => { try { return await updateRelationships( relationshipActions.ACKNOWLEDGE, userIDsWithoutOwnID, ); } catch (e) { if (e instanceof FetchTimeout) { userIDsWithoutOwnID.forEach(id => requestedAvatarsRef.current.delete(id), ); } throw e; } })(); void dispatchActionPromise( updateRelationshipsActionTypes, updateRelationshipsPromise, ); } })(); }, [ getAuthMetadata, updateRelationships, currentUserInfo?.id, dispatchActionPromise, findUserIdentities, userInfos, userInfosWithMissingUsernames, loggedInToAuthKeyserver, ]); const usersWithMissingDeviceListSelected = useSelector( usersWithMissingDeviceListSelector, ); const getAndUpdateDeviceListsForUsers = useGetAndUpdateDeviceListsForUsers(); const { socketState } = useTunnelbroker(); const requestedDeviceListsIDsRef = React.useRef(new Set()); React.useEffect(() => { const usersWithMissingDeviceList = usersWithMissingDeviceListSelected.filter( id => !requestedDeviceListsIDsRef.current.has(id), ); if ( !usingCommServicesAccessToken || usersWithMissingDeviceList.length === 0 || !socketState.isAuthorized ) { return; } void (async () => { const authMetadata = await getAuthMetadata(); if (!authMetadata) { return; } try { usersWithMissingDeviceList.forEach(id => requestedDeviceListsIDsRef.current.add(id), ); const foundDeviceListIDs = await getAndUpdateDeviceListsForUsers( usersWithMissingDeviceList, true, ); Object.keys(foundDeviceListIDs).forEach(id => requestedDeviceListsIDsRef.current.delete(id), ); } catch (e) { console.log( `Error getting and setting peer device list: ${ getMessageForException(e) ?? 'unknown' }`, ); } })(); }, [ getAndUpdateDeviceListsForUsers, getAuthMetadata, socketState.isAuthorized, usersWithMissingDeviceListSelected, ]); } export { UserInfosHandler }; diff --git a/lib/reducers/user-reducer.js b/lib/reducers/user-reducer.js index 95a8c4eaf..3d9bb042c 100644 --- a/lib/reducers/user-reducer.js +++ b/lib/reducers/user-reducer.js @@ -1,628 +1,628 @@ // @flow import _isEqual from 'lodash/fp/isEqual.js'; import _keyBy from 'lodash/fp/keyBy.js'; import { removePeerUsersActionType } from '../actions/aux-user-actions.js'; import { setClientDBStoreActionType } from '../actions/client-db-store-actions.js'; +import { findUserIdentitiesActionTypes } from '../actions/find-user-identities-actions.js'; import { legacySiweAuthActionTypes } from '../actions/siwe-actions.js'; import { joinThreadActionTypes, newThreadActionTypes, } from '../actions/thread-actions.js'; import { fetchPendingUpdatesActionTypes } from '../actions/update-actions.js'; import { - findUserIdentitiesActionTypes, processNewUserIDsActionType, identityLogInActionTypes, identityRegisterActionTypes, deleteAccountActionTypes, keyserverAuthActionTypes, logOutActionTypes, legacyLogInActionTypes, legacyKeyserverRegisterActionTypes, setUserSettingsActionTypes, updateUserAvatarActionTypes, } from '../actions/user-actions.js'; import { extractKeyserverIDFromIDOptional } from '../keyserver-conn/keyserver-call-utils.js'; import { setNewSessionActionType } from '../keyserver-conn/keyserver-conn-types.js'; import { convertUserInfosToReplaceUserOps, type UserStoreOperation, userStoreOpsHandlers, } from '../ops/user-store-ops.js'; import { stateSyncSpecs } from '../shared/state-sync/state-sync-specs.js'; import { updateSpecs } from '../shared/updates/update-specs.js'; import type { BaseAction } from '../types/redux-types.js'; import type { ClientUserInconsistencyReportCreationRequest } from '../types/report-types.js'; import { serverRequestTypes, processServerRequestsActionType, } from '../types/request-types.js'; import { fullStateSyncActionType, incrementalStateSyncActionType, stateSyncPayloadTypes, type ClientStateSyncIncrementalSocketResult, type StateSyncIncrementalActionPayload, } from '../types/socket-types.js'; import { updateTypes } from '../types/update-types-enum.js'; import { processUpdatesActionType, type ClientUpdateInfo, type ClientUpdatesResultWithUserInfos, } from '../types/update-types.js'; import type { CurrentUserInfo, UserInfos, UserStore, } from '../types/user-types.js'; import { authoritativeKeyserverID } from '../utils/authoritative-keyserver.js'; import { relyingOnAuthoritativeKeyserver, usingCommServicesAccessToken, } from '../utils/services-utils.js'; function handleCurrentUserUpdates( state: ?CurrentUserInfo, newUpdates: $ReadOnlyArray, ): ?CurrentUserInfo { return newUpdates.reduce((reducedState, update) => { const { reduceCurrentUser } = updateSpecs[update.type]; return reduceCurrentUser ? reduceCurrentUser(reducedState, update) : reducedState; }, state); } function reduceCurrentUserInfo( state: ?CurrentUserInfo, action: BaseAction, ): ?CurrentUserInfo { if ( action.type === identityLogInActionTypes.success || action.type === identityRegisterActionTypes.success ) { const newUserInfo = { id: action.payload.userID, username: action.payload.username, }; if (!_isEqual(newUserInfo)(state)) { return newUserInfo; } } else if ( action.type === legacyLogInActionTypes.success || action.type === legacySiweAuthActionTypes.success || action.type === legacyKeyserverRegisterActionTypes.success || action.type === logOutActionTypes.success || action.type === deleteAccountActionTypes.success ) { if (!_isEqual(action.payload.currentUserInfo)(state)) { return action.payload.currentUserInfo; } } else if ( action.type === setNewSessionActionType && action.payload.sessionChange.currentUserInfo && action.payload.keyserverID === authoritativeKeyserverID() && relyingOnAuthoritativeKeyserver ) { const actionUserInfo = action.payload.sessionChange.currentUserInfo; if (!actionUserInfo?.id) { return actionUserInfo; } else if (!usingCommServicesAccessToken) { if (!_isEqual(actionUserInfo)(state)) { return actionUserInfo; } } else if (!state?.id || actionUserInfo.id !== state.id) { console.log( 'keyserver auth returned a different user info than identity login', ); } else { const newUserInfo = { ...state, avatar: actionUserInfo.avatar, settings: actionUserInfo.settings, }; if (!_isEqual(newUserInfo)(state)) { return newUserInfo; } } } else if ( (action.type === fullStateSyncActionType || (action.type === fetchPendingUpdatesActionTypes.success && action.payload.type === stateSyncPayloadTypes.FULL)) && relyingOnAuthoritativeKeyserver ) { if (action.payload.keyserverID !== authoritativeKeyserverID()) { return state; } const { currentUserInfo } = action.payload; if (!_isEqual(currentUserInfo)(state)) { return currentUserInfo; } } else if ( (action.type === incrementalStateSyncActionType || action.type === processUpdatesActionType) && relyingOnAuthoritativeKeyserver ) { if (action.payload.keyserverID !== authoritativeKeyserverID()) { return state; } return handleCurrentUserUpdates( state, action.payload.updatesResult.newUpdates, ); } else if (action.type === fetchPendingUpdatesActionTypes.success) { if (!relyingOnAuthoritativeKeyserver) { return state; } const { payload } = action; if (payload.type !== stateSyncPayloadTypes.INCREMENTAL) { return state; } const { newUpdates } = payload.updatesResult; if (action.payload.keyserverID !== authoritativeKeyserverID()) { return state; } return handleCurrentUserUpdates(state, newUpdates); } else if ( action.type === processServerRequestsActionType && relyingOnAuthoritativeKeyserver ) { if (action.payload.keyserverID !== authoritativeKeyserverID()) { return state; } const checkStateRequest = action.payload.serverRequests.find( candidate => candidate.type === serverRequestTypes.CHECK_STATE, ); const newCurrentUserInfo = checkStateRequest?.stateChanges?.currentUserInfo; if (newCurrentUserInfo && !_isEqual(newCurrentUserInfo)(state)) { return newCurrentUserInfo; } } else if ( action.type === updateUserAvatarActionTypes.success && state && !state.anonymous ) { const { viewerUpdates } = action.payload.updates; for (const update of viewerUpdates) { if ( update.type === updateTypes.UPDATE_CURRENT_USER && !_isEqual(update.currentUserInfo.avatar)(state.avatar) ) { return { ...state, avatar: update.currentUserInfo.avatar, }; } } return state; } else if (action.type === setUserSettingsActionTypes.success) { if (state?.settings) { return { ...state, settings: { ...state.settings, ...action.payload, }, }; } } return state; } const { processStoreOperations: processUserStoreOps } = userStoreOpsHandlers; function generateOpsForUserUpdates(payload: { +updatesResult: { +newUpdates: $ReadOnlyArray, ... }, ... }): $ReadOnlyArray { return payload.updatesResult.newUpdates .map(update => updateSpecs[update.type].generateOpsForUserInfoUpdates?.(update), ) .filter(Boolean) .flat(); } function discardKeyserverUsernames( newUserInfos: UserInfos, stateUserInfos: UserInfos, ): UserInfos { if (!usingCommServicesAccessToken) { return newUserInfos; } let result: UserInfos = {}; for (const id in newUserInfos) { const username = stateUserInfos[id] ? stateUserInfos[id].username : null; result = { ...result, [id]: { ...newUserInfos[id], username, }, }; } return result; } type ReduceUserInfosResult = [ UserStore, $ReadOnlyArray, $ReadOnlyArray, ]; function handleUserInfoUpdates( state: UserStore, payload: | ClientStateSyncIncrementalSocketResult | StateSyncIncrementalActionPayload | ClientUpdatesResultWithUserInfos, ): ReduceUserInfosResult { if (payload.keyserverID !== authoritativeKeyserverID()) { return [state, [], []]; } const keyserverUserInfos = _keyBy(userInfo => userInfo.id)(payload.userInfos); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: $ReadOnlyArray = [ ...convertUserInfosToReplaceUserOps(newUserInfos), ...generateOpsForUserUpdates(payload), ]; const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (_isEqual(state.userInfos)(processedUserInfos)) { return [state, [], []]; } return [ { ...state, userInfos: processedUserInfos, }, [], userStoreOps, ]; } function reduceUserInfos( state: UserStore, action: BaseAction, ): ReduceUserInfosResult { if (action.type === processNewUserIDsActionType) { const filteredUserIDs = action.payload.userIDs.filter( id => !state.userInfos[id], ); if (filteredUserIDs.length === 0) { return [state, [], []]; } const newUserInfosArray = filteredUserIDs.map(id => ({ id, username: null, })); const newUserInfos: UserInfos = _keyBy(userInfo => userInfo.id)( newUserInfosArray, ); const userStoreOps: $ReadOnlyArray = convertUserInfosToReplaceUserOps(newUserInfos); const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (!_isEqual(state.userInfos)(processedUserInfos)) { return [ { ...state, userInfos: processedUserInfos, }, [], userStoreOps, ]; } } else if ( (action.type === joinThreadActionTypes.success || action.type === newThreadActionTypes.success) && relyingOnAuthoritativeKeyserver ) { let keyserverID; if (action.type === joinThreadActionTypes.success) { keyserverID = action.payload.keyserverID; } else { keyserverID = extractKeyserverIDFromIDOptional( action.payload.newThreadID, ); } if (keyserverID !== authoritativeKeyserverID()) { return [state, [], []]; } const keyserverUserInfos: UserInfos = _keyBy(userInfo => userInfo.id)( action.payload.userInfos, ); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: $ReadOnlyArray = convertUserInfosToReplaceUserOps(newUserInfos); const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (!_isEqual(state.userInfos)(processedUserInfos)) { return [ { ...state, userInfos: processedUserInfos, }, [], userStoreOps, ]; } } else if (action.type === findUserIdentitiesActionTypes.success) { const newUserInfos = action.payload.userInfos.reduce((acc, userInfo) => { const existingUserInfo = state.userInfos[userInfo.id]; if (!existingUserInfo) { return acc; } return { ...acc, [userInfo.id]: { ...existingUserInfo, username: userInfo.username, }, }; }, {}); const userStoreOps: $ReadOnlyArray = convertUserInfosToReplaceUserOps(newUserInfos); const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (!_isEqual(state.userInfos)(processedUserInfos)) { return [ { ...state, userInfos: processedUserInfos, }, [], userStoreOps, ]; } } else if ( action.type === setNewSessionActionType && action.payload.sessionChange.cookieInvalidated && action.payload.keyserverID === authoritativeKeyserverID() && relyingOnAuthoritativeKeyserver ) { const userStoreOps: $ReadOnlyArray = [ { type: 'remove_all_users' }, ]; const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (Object.keys(state.userInfos).length === 0) { return [state, [], []]; } return [ { userInfos: processedUserInfos, }, [], userStoreOps, ]; } else if ( (action.type === fullStateSyncActionType || (action.type === fetchPendingUpdatesActionTypes.success && action.payload.type === stateSyncPayloadTypes.FULL)) && relyingOnAuthoritativeKeyserver ) { if (action.payload.keyserverID !== authoritativeKeyserverID()) { return [state, [], []]; } const keyserverUserInfos = _keyBy(userInfo => userInfo.id)( action.payload.userInfos, ); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: $ReadOnlyArray = [ { type: 'remove_all_users' }, ...convertUserInfosToReplaceUserOps(newUserInfos), ]; const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (!_isEqual(state.userInfos)(processedUserInfos)) { return [ { userInfos: processedUserInfos, }, [], userStoreOps, ]; } } else if ( action.type === legacyLogInActionTypes.success || action.type === legacySiweAuthActionTypes.success || action.type === legacyKeyserverRegisterActionTypes.success ) { const newUserInfos = _keyBy(userInfo => userInfo.id)( action.payload.userInfos, ); const userStoreOps: $ReadOnlyArray = [ { type: 'remove_all_users' }, ...convertUserInfosToReplaceUserOps(newUserInfos), ]; const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); return [ { userInfos: processedUserInfos, }, [], userStoreOps, ]; } else if ( action.type === keyserverAuthActionTypes.success && relyingOnAuthoritativeKeyserver ) { const keyserverUserInfos = _keyBy(userInfo => userInfo.id)( action.payload.userInfos, ); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: $ReadOnlyArray = convertUserInfosToReplaceUserOps(newUserInfos); const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); if (!_isEqual(state.userInfos)(processedUserInfos)) { return [ { ...state, userInfos: processedUserInfos, }, [], userStoreOps, ]; } } else if ( (action.type === incrementalStateSyncActionType || action.type === processUpdatesActionType) && relyingOnAuthoritativeKeyserver ) { return handleUserInfoUpdates(state, action.payload); } else if (action.type === fetchPendingUpdatesActionTypes.success) { if (!relyingOnAuthoritativeKeyserver) { return [state, [], []]; } const { payload } = action; if (payload.type === stateSyncPayloadTypes.INCREMENTAL) { return handleUserInfoUpdates(state, payload); } } else if ( action.type === processServerRequestsActionType && relyingOnAuthoritativeKeyserver ) { if (action.payload.keyserverID !== authoritativeKeyserverID()) { return [state, [], []]; } const checkStateRequest = action.payload.serverRequests.find( candidate => candidate.type === serverRequestTypes.CHECK_STATE, ); if (!checkStateRequest || !checkStateRequest.stateChanges) { return [state, [], []]; } const { userInfos, deleteUserInfoIDs } = checkStateRequest.stateChanges; if (!userInfos && !deleteUserInfoIDs) { return [state, [], []]; } const keyserverUserInfos = _keyBy(userInfo => userInfo.id)(userInfos); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: UserStoreOperation[] = [ ...convertUserInfosToReplaceUserOps(newUserInfos), ]; if (deleteUserInfoIDs) { userStoreOps.push({ type: 'remove_users', payload: { ids: deleteUserInfoIDs }, }); } const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); const newInconsistencies = stateSyncSpecs.users.findStoreInconsistencies( action, state.userInfos, processedUserInfos, ); return [ { userInfos: processedUserInfos, }, newInconsistencies, userStoreOps, ]; } else if (action.type === removePeerUsersActionType) { const userStoreOps: UserStoreOperation[] = [ { type: 'remove_users', payload: { ids: action.payload.userIDs }, }, ]; return [ { userInfos: processUserStoreOps(state.userInfos, userStoreOps), }, [], userStoreOps, ]; } else if (action.type === updateUserAvatarActionTypes.success) { const keyserverUserInfos = _keyBy(userInfo => userInfo.id)( action.payload.updates.userInfos, ); const newUserInfos = discardKeyserverUsernames( keyserverUserInfos, state.userInfos, ); const userStoreOps: $ReadOnlyArray = convertUserInfosToReplaceUserOps(newUserInfos); const processedUserInfos: UserInfos = processUserStoreOps( state.userInfos, userStoreOps, ); const newState = !_isEqual(state.userInfos)(processedUserInfos) ? { ...state, userInfos: processedUserInfos, } : state; return [newState, [], userStoreOps]; } else if (action.type === setClientDBStoreActionType) { if (!action.payload.users) { return [state, [], []]; } return [{ userInfos: action.payload.users }, [], []]; } return [state, [], []]; } export { reduceCurrentUserInfo, reduceUserInfos }; diff --git a/lib/shared/dm-ops/dm-op-utils.js b/lib/shared/dm-ops/dm-op-utils.js index dc548b5cb..cf58387f6 100644 --- a/lib/shared/dm-ops/dm-op-utils.js +++ b/lib/shared/dm-ops/dm-op-utils.js @@ -1,488 +1,488 @@ // @flow import invariant from 'invariant'; import _groupBy from 'lodash/fp/groupBy.js'; import * as React from 'react'; import uuid from 'uuid'; import { type ProcessDMOperationUtilities, type ProcessingPossibilityCheckResult, } from './dm-op-spec.js'; import { dmOpSpecs } from './dm-op-specs.js'; import { useProcessAndSendDMOperation } from './process-dm-ops.js'; -import { useFindUserIdentities } from '../../actions/user-actions.js'; +import { useFindUserIdentities } from '../../actions/find-user-identities-actions.js'; import { useLoggedInUserInfo } from '../../hooks/account-hooks.js'; import { useGetLatestMessageEdit } from '../../hooks/latest-message-edit.js'; import { useGetAndUpdateDeviceListsForUsers } from '../../hooks/peer-list-hooks.js'; import { mergeUpdatesWithMessageInfos } from '../../reducers/message-reducer.js'; import { getAllPeerUserIDAndDeviceIDs } from '../../selectors/user-selectors.js'; import { type P2PMessageRecipient } from '../../tunnelbroker/peer-to-peer-context.js'; import type { CreateThickRawThreadInfoInput, DMAddMembersOperation, DMAddViewerToThreadMembersOperation, DMOperation, ComposableDMOperation, } from '../../types/dm-ops.js'; import type { RawMessageInfo } from '../../types/message-types.js'; import type { RawThreadInfo, ThickRawThreadInfo, ThreadInfo, } from '../../types/minimally-encoded-thread-permissions-types.js'; import type { InboundActionMetadata } from '../../types/redux-types.js'; import { outboundP2PMessageStatuses, type OutboundP2PMessage, } from '../../types/sqlite-types.js'; import { assertThickThreadType, thickThreadTypes, } from '../../types/thread-types-enum.js'; import type { LegacyRawThreadInfo } from '../../types/thread-types.js'; import { type DMOperationP2PMessage, userActionsP2PMessageTypes, } from '../../types/tunnelbroker/user-actions-peer-to-peer-message-types.js'; import { updateTypes } from '../../types/update-types-enum.js'; import type { ClientUpdateInfo } from '../../types/update-types.js'; import { getContentSigningKey } from '../../utils/crypto-utils.js'; import { useSelector } from '../../utils/redux-utils.js'; import { messageSpecs } from '../messages/message-specs.js'; import { userHasDeviceList } from '../thread-utils.js'; import { updateSpecs } from '../updates/update-specs.js'; function generateMessagesToPeers( message: DMOperation, peers: $ReadOnlyArray<{ +userID: string, +deviceID: string, }>, ): $ReadOnlyArray { const opMessage: DMOperationP2PMessage = { type: userActionsP2PMessageTypes.DM_OPERATION, op: message, }; const plaintext = JSON.stringify(opMessage); const outboundP2PMessages = []; for (const peer of peers) { const messageToPeer: OutboundP2PMessage = { messageID: uuid.v4(), deviceID: peer.deviceID, userID: peer.userID, timestamp: new Date().getTime().toString(), plaintext, ciphertext: '', status: outboundP2PMessageStatuses.persisted, supportsAutoRetry: dmOpSpecs[message.type].supportsAutoRetry, }; outboundP2PMessages.push(messageToPeer); } return outboundP2PMessages; } export const dmOperationSpecificationTypes = Object.freeze({ OUTBOUND: 'OutboundDMOperationSpecification', INBOUND: 'InboundDMOperationSpecification', }); type OutboundDMOperationSpecificationRecipients = | { +type: 'all_peer_devices' | 'self_devices' } | { +type: 'some_users', +userIDs: $ReadOnlyArray } | { +type: 'all_thread_members', +threadID: string } | { +type: 'some_devices', +deviceIDs: $ReadOnlyArray }; // The operation generated on the sending client, causes changes to // the state and broadcasting information to peers. export type OutboundDMOperationSpecification = { +type: 'OutboundDMOperationSpecification', +op: DMOperation, +recipients: OutboundDMOperationSpecificationRecipients, +sendOnly?: boolean, }; export type OutboundComposableDMOperationSpecification = { +type: 'OutboundDMOperationSpecification', +op: ComposableDMOperation, +recipients: OutboundDMOperationSpecificationRecipients, // Composable DM Ops are created only to be sent, locally we use // dedicated mechanism for updating the store. +sendOnly: true, +composableMessageID: string, }; // The operation received from other peers, causes changes to // the state and after processing, sends confirmation to the sender. export type InboundDMOperationSpecification = { +type: 'InboundDMOperationSpecification', +op: DMOperation, +metadata: ?InboundActionMetadata, }; export type DMOperationSpecification = | OutboundDMOperationSpecification | InboundDMOperationSpecification; function useCreateMessagesToPeersFromDMOp(): ( operation: DMOperation, recipients: OutboundDMOperationSpecificationRecipients, ) => Promise<$ReadOnlyArray> { const allPeerUserIDAndDeviceIDs = useSelector(getAllPeerUserIDAndDeviceIDs); const utilities = useSendDMOperationUtils(); const auxUserInfos = useSelector(state => state.auxUserStore.auxUserInfos); const getAndUpdateDeviceListsForUsers = useGetAndUpdateDeviceListsForUsers(); const getUsersWithoutDeviceList = React.useCallback( (userIDs: $ReadOnlyArray) => { const missingDeviceListsUserIDs: Array = []; for (const userID of userIDs) { const supportsThickThreads = userHasDeviceList(userID, auxUserInfos); if (!supportsThickThreads) { missingDeviceListsUserIDs.push(userID); } } return missingDeviceListsUserIDs; }, [auxUserInfos], ); const getMissingPeers = React.useCallback( async ( userIDs: $ReadOnlyArray, ): Promise<$ReadOnlyArray> => { const missingDeviceListsUserIDs = getUsersWithoutDeviceList(userIDs); if (missingDeviceListsUserIDs.length === 0) { return []; } const deviceLists = await getAndUpdateDeviceListsForUsers( missingDeviceListsUserIDs, true, ); const updatedPeers: Array = []; for (const userID of missingDeviceListsUserIDs) { if (deviceLists[userID] && deviceLists[userID].devices.length > 0) { updatedPeers.push( ...deviceLists[userID].devices.map(deviceID => ({ deviceID, userID, })), ); } } return updatedPeers; }, [getAndUpdateDeviceListsForUsers, getUsersWithoutDeviceList], ); return React.useCallback( async ( operation: DMOperation, recipients: OutboundDMOperationSpecificationRecipients, ): Promise<$ReadOnlyArray> => { const { viewerID, threadInfos } = utilities; if (!viewerID) { return []; } let peerUserIDAndDeviceIDs = allPeerUserIDAndDeviceIDs; if (recipients.type === 'self_devices') { peerUserIDAndDeviceIDs = allPeerUserIDAndDeviceIDs.filter( peer => peer.userID === viewerID, ); } else if (recipients.type === 'some_users') { const missingPeers = await getMissingPeers(recipients.userIDs); const updatedPeers = [...allPeerUserIDAndDeviceIDs, ...missingPeers]; const userIDs = new Set(recipients.userIDs); peerUserIDAndDeviceIDs = updatedPeers.filter(peer => userIDs.has(peer.userID), ); } else if (recipients.type === 'all_thread_members') { const { threadID } = recipients; if (!threadInfos[threadID]) { console.log( `all_thread_members called for threadID ${threadID}, which is ` + 'missing from the ThreadStore. if sending a message soon after ' + 'thread creation, consider some_users instead', ); } const members = threadInfos[recipients.threadID]?.members ?? []; const memberIDs = members.map(member => member.id); const missingPeers = await getMissingPeers(memberIDs); const updatedPeers = [...allPeerUserIDAndDeviceIDs, ...missingPeers]; const userIDs = new Set(memberIDs); peerUserIDAndDeviceIDs = updatedPeers.filter(peer => userIDs.has(peer.userID), ); } else if (recipients.type === 'some_devices') { const deviceIDs = new Set(recipients.deviceIDs); peerUserIDAndDeviceIDs = allPeerUserIDAndDeviceIDs.filter(peer => deviceIDs.has(peer.deviceID), ); } const thisDeviceID = await getContentSigningKey(); const targetPeers = peerUserIDAndDeviceIDs.filter( peer => peer.deviceID !== thisDeviceID, ); return generateMessagesToPeers(operation, targetPeers); }, [allPeerUserIDAndDeviceIDs, getMissingPeers, utilities], ); } function getCreateThickRawThreadInfoInputFromThreadInfo( threadInfo: ThickRawThreadInfo, ): CreateThickRawThreadInfoInput { const roleID = Object.keys(threadInfo.roles).pop(); const thickThreadType = assertThickThreadType(threadInfo.type); return { threadID: threadInfo.id, threadType: thickThreadType, creationTime: threadInfo.creationTime, parentThreadID: threadInfo.parentThreadID, allMemberIDsWithSubscriptions: threadInfo.members.map( ({ id, subscription }) => ({ id, subscription, }), ), roleID, unread: !!threadInfo.currentUser.unread, name: threadInfo.name, avatar: threadInfo.avatar, description: threadInfo.description, color: threadInfo.color, containingThreadID: threadInfo.containingThreadID, sourceMessageID: threadInfo.sourceMessageID, repliesCount: threadInfo.repliesCount, pinnedCount: threadInfo.pinnedCount, timestamps: threadInfo.timestamps, }; } function useAddDMThreadMembers(): ( newMemberIDs: $ReadOnlyArray, threadInfo: ThreadInfo, ) => Promise { const viewerID = useSelector( state => state.currentUserInfo && state.currentUserInfo.id, ); const processAndSendDMOperation = useProcessAndSendDMOperation(); const threadInfos = useSelector(state => state.threadStore.threadInfos); return React.useCallback( async (newMemberIDs: $ReadOnlyArray, threadInfo: ThreadInfo) => { const rawThreadInfo = threadInfos[threadInfo.id]; invariant(rawThreadInfo.thick, 'thread should be thick'); const existingThreadDetails = getCreateThickRawThreadInfoInputFromThreadInfo(rawThreadInfo); invariant(viewerID, 'viewerID should be set'); const addViewerToThreadMembersOperation: DMAddViewerToThreadMembersOperation = { type: 'add_viewer_to_thread_members', existingThreadDetails, editorID: viewerID, time: Date.now(), messageID: uuid.v4(), addedUserIDs: newMemberIDs, }; const viewerOperationSpecification: OutboundDMOperationSpecification = { type: dmOperationSpecificationTypes.OUTBOUND, op: addViewerToThreadMembersOperation, recipients: { type: 'some_users', userIDs: newMemberIDs, }, sendOnly: true, }; invariant(viewerID, 'viewerID should be set'); const addMembersOperation: DMAddMembersOperation = { type: 'add_members', threadID: threadInfo.id, editorID: viewerID, time: Date.now(), messageID: uuid.v4(), addedUserIDs: newMemberIDs, }; const newMemberIDsSet = new Set(newMemberIDs); const recipientsThreadID = threadInfo.type === thickThreadTypes.THICK_SIDEBAR && threadInfo.parentThreadID ? threadInfo.parentThreadID : threadInfo.id; const existingMembers = threadInfos[recipientsThreadID]?.members ?.map(member => member.id) ?.filter(memberID => !newMemberIDsSet.has(memberID)) ?? []; const addMembersOperationSpecification: OutboundDMOperationSpecification = { type: dmOperationSpecificationTypes.OUTBOUND, op: addMembersOperation, recipients: { type: 'some_users', userIDs: existingMembers, }, }; await Promise.all([ processAndSendDMOperation(viewerOperationSpecification), processAndSendDMOperation(addMembersOperationSpecification), ]); }, [processAndSendDMOperation, threadInfos, viewerID], ); } function getThreadUpdatesForNewMessages( rawMessageInfos: $ReadOnlyArray, updateInfos: $ReadOnlyArray, utilities: ProcessDMOperationUtilities, ): Array { const { threadInfos, viewerID } = utilities; const { rawMessageInfos: allNewMessageInfos } = mergeUpdatesWithMessageInfos( rawMessageInfos, updateInfos, ); const messagesByThreadID = _groupBy(message => message.threadID)( allNewMessageInfos, ); const updatedThreadInfosByThreadID: { [string]: RawThreadInfo | LegacyRawThreadInfo, } = {}; for (const threadID in messagesByThreadID) { updatedThreadInfosByThreadID[threadID] = threadInfos[threadID]; } for (const update of updateInfos) { const updatedThreadInfo = updateSpecs[update.type].getUpdatedThreadInfo?.( update, updatedThreadInfosByThreadID, ); if (updatedThreadInfo) { updatedThreadInfosByThreadID[updatedThreadInfo.id] = updatedThreadInfo; } } const newUpdateInfos: Array = []; for (const threadID in messagesByThreadID) { const repliesCountIncreasingMessages = messagesByThreadID[threadID].filter( message => messageSpecs[message.type].includedInRepliesCount, ); let threadInfo = updatedThreadInfosByThreadID[threadID]; if (repliesCountIncreasingMessages.length > 0) { const repliesCountIncreaseTime = Math.max( repliesCountIncreasingMessages.map(message => message.time), ); const newThreadInfo = { ...threadInfo, repliesCount: threadInfo.repliesCount + repliesCountIncreasingMessages.length, }; newUpdateInfos.push({ type: updateTypes.UPDATE_THREAD, id: uuid.v4(), time: repliesCountIncreaseTime, threadInfo: newThreadInfo, }); threadInfo = newThreadInfo; } const messagesFromOtherPeers = messagesByThreadID[threadID].filter( message => message.creatorID !== viewerID, ); if (messagesFromOtherPeers.length === 0) { continue; } // We take the most recent timestamp to make sure that // change_thread_read_status operation older // than it won't flip the status to read. const time = Math.max(messagesFromOtherPeers.map(message => message.time)); invariant(threadInfo.thick, 'Thread should be thick'); // We aren't checking if the unread timestamp is lower than the time. // We're doing this because we want to flip the thread to unread after // any new message from a non-viewer. newUpdateInfos.push({ type: updateTypes.UPDATE_THREAD_READ_STATUS, id: uuid.v4(), time, threadID: threadInfo.id, unread: true, }); } return newUpdateInfos; } async function checkMessageIDConflict( dmOperation: DMOperation, utilities: ProcessDMOperationUtilities, ): Promise { if (!dmOperation.messageID) { return { isProcessingPossible: true, }; } const messageID = dmOperation.messageID; const message = await utilities.fetchMessage(messageID); if (message) { console.log( `Discarded a ${dmOperation.type} operation because ` + `message with the same ID ${messageID} already exists ` + 'in the store', ); return { isProcessingPossible: false, reason: { type: 'invalid', }, }; } return { isProcessingPossible: true, }; } function useSendDMOperationUtils(): $ReadOnly<{ ...ProcessDMOperationUtilities, viewerID: ?string, }> { const fetchMessage = useGetLatestMessageEdit(); const threadInfos = useSelector(state => state.threadStore.threadInfos); const entryInfos = useSelector(state => state.entryStore.entryInfos); const findUserIdentities = useFindUserIdentities(); const loggedInUserInfo = useLoggedInUserInfo(); const viewerID = loggedInUserInfo?.id; return React.useMemo( () => ({ viewerID, fetchMessage, threadInfos, entryInfos, findUserIdentities, }), [viewerID, fetchMessage, threadInfos, entryInfos, findUserIdentities], ); } export { useCreateMessagesToPeersFromDMOp, useAddDMThreadMembers, getCreateThickRawThreadInfoInputFromThreadInfo, getThreadUpdatesForNewMessages, checkMessageIDConflict, useSendDMOperationUtils, };