diff --git a/lib/push/send-hooks.react.js b/lib/push/send-hooks.react.js index 6644dec8e..d69a0eced 100644 --- a/lib/push/send-hooks.react.js +++ b/lib/push/send-hooks.react.js @@ -1,337 +1,337 @@ // @flow import invariant from 'invariant'; import _groupBy from 'lodash/fp/groupBy.js'; import * as React from 'react'; import uuid from 'uuid'; import type { LargeNotifData } from './crypto.js'; import { preparePushNotifs, prepareOwnDevicesPushNotifs, type PerUserTargetedNotifications, } from './send-utils.js'; import { ENSCacheContext } from '../components/ens-cache-provider.react.js'; import { NeynarClientContext } from '../components/neynar-client-provider.react.js'; import { usePeerOlmSessionsCreatorContext } from '../components/peer-olm-session-creator-provider.react.js'; import { thickRawThreadInfosSelector } from '../selectors/thread-selectors.js'; import { IdentityClientContext } from '../shared/identity-client-context.js'; import type { AuthMetadata } from '../shared/identity-client-context.js'; import { useTunnelbroker } from '../tunnelbroker/tunnelbroker-context.js'; import type { TargetedAPNsNotification, TargetedAndroidNotification, TargetedWebNotification, TargetedWNSNotification, NotificationsCreationData, EncryptedNotifUtilsAPI, } from '../types/notif-types.js'; import { deviceToTunnelbrokerMessageTypes } from '../types/tunnelbroker/messages.js'; import type { TunnelbrokerAPNsNotif, TunnelbrokerFCMNotif, TunnelbrokerWebPushNotif, TunnelbrokerWNSNotif, } from '../types/tunnelbroker/notif-types.js'; import { uploadBlob, assignMultipleHolders } from '../utils/blob-service.js'; import { getConfig } from '../utils/config.js'; import { getMessageForException } from '../utils/errors.js'; import { values } from '../utils/objects.js'; import { useSelector } from '../utils/redux-utils.js'; import { createDefaultHTTPRequestHeaders } from '../utils/services-utils.js'; function apnsNotifToTunnelbrokerAPNsNotif( targetedNotification: TargetedAPNsNotification, ): TunnelbrokerAPNsNotif { const { deliveryID: deviceID, notification: { headers, ...payload }, } = targetedNotification; const newHeaders = { ...headers, 'apns-push-type': 'Alert', }; return { type: deviceToTunnelbrokerMessageTypes.TUNNELBROKER_APNS_NOTIF, deviceID, headers: JSON.stringify(newHeaders), payload: JSON.stringify(payload), clientMessageID: uuid.v4(), }; } function androidNotifToTunnelbrokerFCMNotif( targetedNotification: TargetedAndroidNotification, ): TunnelbrokerFCMNotif { const { deliveryID: deviceID, notification: { data }, priority, } = targetedNotification; return { type: deviceToTunnelbrokerMessageTypes.TUNNELBROKER_FCM_NOTIF, deviceID, clientMessageID: uuid.v4(), data: JSON.stringify(data), priority: priority === 'normal' ? 'NORMAL' : 'HIGH', }; } function webNotifToTunnelbrokerWebPushNotif( targetedNotification: TargetedWebNotification, ): TunnelbrokerWebPushNotif { const { deliveryID: deviceID, notification } = targetedNotification; return { type: deviceToTunnelbrokerMessageTypes.TUNNELBROKER_WEB_PUSH_NOTIF, deviceID, clientMessageID: uuid.v4(), payload: JSON.stringify(notification), }; } function wnsNotifToTunnelbrokerWNSNofif( targetedNotification: TargetedWNSNotification, ): TunnelbrokerWNSNotif { const { deliveryID: deviceID, notification } = targetedNotification; return { type: deviceToTunnelbrokerMessageTypes.TUNNELBROKER_WNS_NOTIF, deviceID, clientMessageID: uuid.v4(), payload: JSON.stringify(notification), }; } function useSendPushNotifs(): ( notifCreationData: ?NotificationsCreationData, ) => Promise { const client = React.useContext(IdentityClientContext); invariant(client, 'Identity context should be set'); const { getAuthMetadata } = client; const rawMessageInfos = useSelector(state => state.messageStore.messages); const thickRawThreadInfos = useSelector(thickRawThreadInfosSelector); const auxUserInfos = useSelector(state => state.auxUserStore.auxUserInfos); const userInfos = useSelector(state => state.userStore.userInfos); const { getENSNames } = React.useContext(ENSCacheContext); const getFCNames = React.useContext(NeynarClientContext)?.getFCNames; const { createOlmSessionsWithUser: olmSessionCreator } = usePeerOlmSessionsCreatorContext(); const { sendNotif } = useTunnelbroker(); const { encryptedNotifUtilsAPI } = getConfig(); return React.useCallback( async (notifCreationData: ?NotificationsCreationData) => { if (!notifCreationData) { return; } const authMetadata = await getAuthMetadata(); const { deviceID, userID: senderUserID } = authMetadata; if (!deviceID || !senderUserID) { return; } const senderDeviceDescriptor = { senderDeviceID: deviceID }; const senderInfo = { senderUserID, senderDeviceDescriptor, }; const { messageDatasWithMessageInfos, rescindData, badgeUpdateData } = notifCreationData; const pushNotifsPreparationInput = { encryptedNotifUtilsAPI, senderDeviceDescriptor, olmSessionCreator, messageInfos: rawMessageInfos, thickRawThreadInfos, auxUserInfos, messageDatasWithMessageInfos, userInfos, getENSNames, getFCNames, }; const ownDevicesPushNotifsPreparationInput = { encryptedNotifUtilsAPI, senderInfo, olmSessionCreator, auxUserInfos, rescindData, badgeUpdateData, }; const [preparedPushNotifs, preparedOwnDevicesPushNotifs] = await Promise.all([ preparePushNotifs(pushNotifsPreparationInput), prepareOwnDevicesPushNotifs(ownDevicesPushNotifsPreparationInput), ]); if (!preparedPushNotifs && !prepareOwnDevicesPushNotifs) { return; } let allPreparedPushNotifs: ?PerUserTargetedNotifications = preparedPushNotifs; if (preparedOwnDevicesPushNotifs && senderUserID) { allPreparedPushNotifs = { ...allPreparedPushNotifs, [senderUserID]: { targetedNotifications: preparedOwnDevicesPushNotifs, }, }; } if (preparedPushNotifs) { try { await uploadLargeNotifBlobs( preparedPushNotifs, authMetadata, encryptedNotifUtilsAPI, ); } catch (e) { console.log('Failed to upload blobs', e); } } const sendPromises = []; for (const userID in allPreparedPushNotifs) { for (const notif of allPreparedPushNotifs[userID] .targetedNotifications) { if (notif.targetedNotification.notification.encryptionFailed) { continue; } let tunnelbrokerNotif; if (notif.platform === 'ios' || notif.platform === 'macos') { tunnelbrokerNotif = apnsNotifToTunnelbrokerAPNsNotif( notif.targetedNotification, ); } else if (notif.platform === 'android') { tunnelbrokerNotif = androidNotifToTunnelbrokerFCMNotif( notif.targetedNotification, ); } else if (notif.platform === 'web') { tunnelbrokerNotif = webNotifToTunnelbrokerWebPushNotif( notif.targetedNotification, ); } else if (notif.platform === 'windows') { tunnelbrokerNotif = wnsNotifToTunnelbrokerWNSNofif( notif.targetedNotification, ); } else { continue; } sendPromises.push( (async () => { try { await sendNotif(tunnelbrokerNotif); } catch (e) { console.log( `Failed to send notification to device: ${ tunnelbrokerNotif.deviceID }. Details: ${getMessageForException(e) ?? ''}`, ); } })(), ); } } await Promise.all(sendPromises); }, [ getAuthMetadata, sendNotif, encryptedNotifUtilsAPI, olmSessionCreator, rawMessageInfos, thickRawThreadInfos, auxUserInfos, userInfos, getENSNames, getFCNames, ], ); } async function uploadLargeNotifBlobs( pushNotifs: PerUserTargetedNotifications, authMetadata: AuthMetadata, encryptedNotifUtilsAPI: EncryptedNotifUtilsAPI, ): Promise { const largeNotifArray = values(pushNotifs) .map(({ largeNotifDataArray }) => largeNotifDataArray) .flat(); if (largeNotifArray.length === 0) { return; } const largeNotifsByHash: { +[blobHash: string]: $ReadOnlyArray, } = _groupBy(largeNotifData => largeNotifData.blobHash)(largeNotifArray); const uploads = Object.entries(largeNotifsByHash).map( ([blobHash, [{ encryptedCopyWithMessageInfos }]]) => ({ blobHash, encryptedCopyWithMessageInfos, }), ); const assignments = Object.entries(largeNotifsByHash) .map(([blobHash, largeNotifs]) => largeNotifs .map(({ blobHolders }) => blobHolders) .flat() .map(holder => ({ blobHash, holder })), ) .flat(); const authHeaders = createDefaultHTTPRequestHeaders(authMetadata); const uploadPromises = uploads.map( ({ blobHash, encryptedCopyWithMessageInfos }) => uploadBlob( encryptedNotifUtilsAPI.normalizeUint8ArrayForBlobUpload( encryptedCopyWithMessageInfos, ), blobHash, authHeaders, ), ); const assignmentPromise = assignMultipleHolders(assignments, authHeaders); const [uploadResults, assignmentResult] = await Promise.all([ Promise.all(uploadPromises), assignmentPromise, ]); for (const uploadResult of uploadResults) { if (uploadResult.success) { continue; } const { reason, statusText } = uploadResult; console.log( `Failed to upload. Reason: ${reason}, status text: ${statusText}`, ); } - if (assignmentResult.success) { + if (assignmentResult.result === 'success') { return; } - if (assignmentResult.error) { + if (assignmentResult.result === 'error') { const { statusText } = assignmentResult; console.log(`Failed to assign all holders. Status text: ${statusText}`); return; } - for (const [blobHash, holder] of assignmentResult.failedAssignments) { + for (const [blobHash, holder] of assignmentResult.failedRequests) { console.log(`Assingnemt failed for holder: ${holder} and hash ${blobHash}`); } } export { useSendPushNotifs }; diff --git a/lib/utils/blob-service.js b/lib/utils/blob-service.js index ee4a8872c..5527613a4 100644 --- a/lib/utils/blob-service.js +++ b/lib/utils/blob-service.js @@ -1,208 +1,209 @@ // @flow import invariant from 'invariant'; import uuid from 'uuid'; import { toBase64URL } from './base64.js'; import { replacePathParams, type URLPathParams } from './url-utils.js'; import type { BlobServiceHTTPEndpoint } from '../facts/blob-service.js'; import blobServiceConfig from '../facts/blob-service.js'; import type { BlobHashAndHolder } from '../types/holder-types.js'; const BLOB_SERVICE_URI_PREFIX = 'comm-blob-service://'; function makeBlobServiceURI(blobHash: string): string { return `${BLOB_SERVICE_URI_PREFIX}${blobHash}`; } function isBlobServiceURI(uri: string): boolean { return uri.startsWith(BLOB_SERVICE_URI_PREFIX); } /** * Returns the base64url-encoded blob hash from a blob service URI. * Throws an error if the URI is not a blob service URI. */ function blobHashFromBlobServiceURI(uri: string): string { invariant(isBlobServiceURI(uri), 'Not a blob service URI'); return uri.slice(BLOB_SERVICE_URI_PREFIX.length); } /** * Returns the base64url-encoded blob hash from a blob service URI. * Returns null if the URI is not a blob service URI. */ function blobHashFromURI(uri: string): ?string { if (!isBlobServiceURI(uri)) { return null; } return blobHashFromBlobServiceURI(uri); } function makeBlobServiceEndpointURL( endpoint: BlobServiceHTTPEndpoint, params: URLPathParams = {}, ): string { const path = replacePathParams(endpoint.path, params); return `${blobServiceConfig.url}${path}`; } function getBlobFetchableURL(blobHash: string): string { return makeBlobServiceEndpointURL(blobServiceConfig.httpEndpoints.GET_BLOB, { blobHash, }); } /** * Generates random blob holder prefixed by current device ID if present */ function generateBlobHolder(deviceID?: ?string): string { const randomID = uuid.v4(); if (!deviceID) { return randomID; } const urlSafeDeviceID = toBase64URL(deviceID); return `${urlSafeDeviceID}:${uuid.v4()}`; } export type BlobOperationResult = | { +success: true, } | { +success: false, +reason: 'HASH_IN_USE' | 'OTHER', +status: number, +statusText: string, }; async function uploadBlob( blob: Blob | string, hash: string, headers: { [string]: string }, ): Promise { const formData = new FormData(); formData.append('blob_hash', hash); if (typeof blob === 'string') { formData.append('base64_data', blob); } else { formData.append('blob_data', blob); } const uploadBlobResponse = await fetch( makeBlobServiceEndpointURL(blobServiceConfig.httpEndpoints.UPLOAD_BLOB), { method: blobServiceConfig.httpEndpoints.UPLOAD_BLOB.method, body: formData, headers, }, ); if (!uploadBlobResponse.ok) { const { status, statusText } = uploadBlobResponse; const reason = status === 409 ? 'HASH_IN_USE' : 'OTHER'; return { success: false, reason, status, statusText, }; } return { success: true }; } async function assignMultipleHolders( holders: $ReadOnlyArray<{ +blobHash: string, +holder: string }>, headers: { [string]: string }, ): Promise< - | { +success: true } - | { +error: true, status: number, statusText: string } + | { +result: 'success' } + | { +result: 'error', +status: number, +statusText: string } | { - +failedAssignments: $ReadOnlyArray<{ + +failedRequests: $ReadOnlyArray<{ +blobHash: string, +holder: string, }>, + +result: 'failed_requests', }, > { const assignMultipleHoldersResponse = await fetch( makeBlobServiceEndpointURL( blobServiceConfig.httpEndpoints.ASSIGN_MULTIPLE_HOLDERS, ), { method: blobServiceConfig.httpEndpoints.ASSIGN_MULTIPLE_HOLDERS.method, headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ requests: holders, }), }, ); if (!assignMultipleHoldersResponse.ok) { const { status, statusText } = assignMultipleHoldersResponse; - return { error: true, status, statusText }; + return { result: 'error', status, statusText }; } const { results } = await assignMultipleHoldersResponse.json(); const failedRequests = results .filter(result => !result.success) .map(({ blobHash, holder }) => ({ blobHash, holder })); if (failedRequests.length !== 0) { - return { failedAssignments: failedRequests }; + return { result: 'failed_requests', failedRequests }; } - return { success: true }; + return { result: 'success' }; } async function removeMultipleHolders( holders: $ReadOnlyArray, headers: { [string]: string }, instantDelete?: boolean, ): Promise< | { +result: 'success' } | { +result: 'error', +status: number, +statusText: string } | { +result: 'failed_requests', +failedRequests: $ReadOnlyArray, }, > { const response = await fetch( makeBlobServiceEndpointURL( blobServiceConfig.httpEndpoints.REMOVE_MULTIPLE_HOLDERS, ), { method: blobServiceConfig.httpEndpoints.REMOVE_MULTIPLE_HOLDERS.method, headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ requests: holders, instantDelete: !!instantDelete, }), }, ); if (!response.ok) { const { status, statusText } = response; return { result: 'error', status, statusText }; } const { failedRequests } = await response.json(); if (failedRequests.length !== 0) { return { result: 'failed_requests', failedRequests }; } return { result: 'success' }; } export { makeBlobServiceURI, isBlobServiceURI, blobHashFromURI, blobHashFromBlobServiceURI, generateBlobHolder, getBlobFetchableURL, makeBlobServiceEndpointURL, uploadBlob, assignMultipleHolders, removeMultipleHolders, };