From 4fd0a71dd3e917646e0bb5b8cf499d0c780c3a8f Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 18:08:45 +0530 Subject: [PATCH 1/3] Bind assisted backup to account origin and consent --- .../Backup/BackupHealthCheckList.tsx | 42 +-- src/components/ImportExportLabels/index.tsx | 6 +- src/hooks/useSettingKeeper.tsx | 36 +- src/hooks/useUSDTWallets.ts | 79 ++++- .../AppSettings/AssistedBackupStatus.tsx | 8 +- .../AppSettings/Node/NodeSelection.tsx | 17 +- src/screens/AppSettings/Node/NodeSettings.tsx | 13 +- .../BackupWallet/ViewRecoveryKeyScreen.tsx | 36 +- .../Notifications/NotificationsCenter.tsx | 4 +- .../components/Settings/keeperSettings.tsx | 4 +- src/screens/LoginScreen/Login.tsx | 14 +- src/screens/Recieve/ReceiveScreen.tsx | 6 +- src/screens/SeedScreens/ExportSeedScreen.tsx | 36 +- src/screens/Send/SendConfirmation.tsx | 8 +- .../SignTransaction/SignTransactionScreen.tsx | 4 +- src/screens/UTXOManagement/UTXOLabeling.tsx | 12 +- .../components/LabelsEditor.tsx | 6 +- src/screens/Vault/ChoosePolicyNew.tsx | 6 +- src/screens/Vault/VaultDetails.tsx | 4 +- .../ViewTransactions/TransactionDetails.tsx | 8 +- src/services/backend/Relay.ts | 4 +- src/services/backup/repair.ts | 9 +- src/services/backup/transport.ts | 17 +- src/services/electrum/node.tsx | 20 +- src/store/reducers/bhr.ts | 120 +++++-- src/store/reducers/storage.ts | 12 +- src/store/sagaActions/bhr.ts | 16 +- src/store/sagaActions/send_and_receive.ts | 11 +- src/store/sagaActions/upgrade.ts | 6 +- src/store/sagaActions/utxos.ts | 12 +- src/store/sagaActions/wallets.ts | 12 +- src/store/sagas/bhr.ts | 232 +++++++++--- src/store/sagas/login.ts | 32 +- src/store/sagas/send_and_receive.ts | 20 +- src/store/sagas/upgrade.ts | 68 +++- src/store/sagas/utxos.ts | 140 +++++--- src/store/sagas/wallets.ts | 335 +++++++++++++----- src/store/store.ts | 80 ++++- tests/recovery/accountBinding.test.cjs | 256 +++++++++++++ tests/recovery/backupFeedback.test.cjs | 7 +- tests/recovery/backupFreshness.test.cjs | 49 ++- tests/recovery/helpers.cjs | 1 + tests/recovery/labelAccount.test.cjs | 138 ++++++++ tests/recovery/manualCoinChoices.test.cjs | 14 +- tests/recovery/sagaHarness.cjs | 41 ++- tests/recovery/sagaState.test.cjs | 7 +- tests/recovery/sendLabelOrigin.test.cjs | 97 +++++ tests/recovery/usdtAccountDelete.test.cjs | 136 +++++++ tests/recovery/usdtBackup.test.cjs | 6 +- 49 files changed, 1814 insertions(+), 433 deletions(-) create mode 100644 tests/recovery/accountBinding.test.cjs create mode 100644 tests/recovery/labelAccount.test.cjs create mode 100644 tests/recovery/sendLabelOrigin.test.cjs create mode 100644 tests/recovery/usdtAccountDelete.test.cjs diff --git a/src/components/Backup/BackupHealthCheckList.tsx b/src/components/Backup/BackupHealthCheckList.tsx index f59e845194..35f43e341b 100644 --- a/src/components/Backup/BackupHealthCheckList.tsx +++ b/src/components/Backup/BackupHealthCheckList.tsx @@ -17,6 +17,7 @@ import { setBackupAllFailure, setBackupAllSuccess, setSeedConfirmed, + isAutomaticCloudBackupEnabled, } from 'src/store/reducers/bhr'; import { CommonActions, useIsFocused, useNavigation } from '@react-navigation/native'; import { useQuery } from '@realm/react'; @@ -41,7 +42,7 @@ const ContentType = { mismatch: 'mismatch', healthCheckSuccessful: 'healthCheckSuccessful', }; -function Content({ contentType, asbEnabled }: { contentType: string; asbEnabled: boolean }) { +function Content({ contentType, asbEnabled }: { contentType: string; asbEnabled?: boolean }) { const { BackupWallet } = useContext(LocalizationContext).translations; const illustrations = { [ContentType.verifying]: ( @@ -74,17 +75,21 @@ function BackupHealthCheckList({ isUaiFlow }) { const { translations } = useContext(LocalizationContext); const { BackupWallet, vault: vaultText, common } = translations; const dispatch = useAppDispatch(); - const { primaryMnemonic, backup, id } = useQuery(RealmSchema.KeeperApp).map( + const { primaryMnemonic, id } = useQuery(RealmSchema.KeeperApp).map( getJSONFromRealmObject - )[0]; + )[0] as { primaryMnemonic: string; id: string }; const { backupMethod, seedConfirmed, - automaticCloudBackup, - backupAllLoading, - backupAllFailure, - backupAllSuccess, + automaticCloudBackupByAppId, + backupAllLoadingByAppId, + backupAllFailureByAppId, + backupAllSuccessByAppId, } = useAppSelector((state) => state.bhr); + const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id); + const backupAllLoading = !!backupAllLoadingByAppId?.[id]; + const backupAllFailure = !!backupAllFailureByAppId?.[id]; + const backupAllSuccess = !!backupAllSuccessByAppId?.[id]; const [healthCheckModal, setHealthCheckModal] = useState(false); const [showConfirmSeedModal, setShowConfirmSeedModal] = useState(isUaiFlow); const [verificationModal, setVerificationModal] = useState(false); @@ -107,9 +112,9 @@ function BackupHealthCheckList({ isUaiFlow }) { useEffect(() => { if (backupAllSuccess) { if (!automaticCloudBackup) setAsbEnabled(true); - dispatch(setBackupAllSuccess(false)); - dispatch(setBackupAllFailure(false)); - dispatch(setAutomaticCloudBackup(true)); + dispatch(setBackupAllSuccess({ appId: id, status: false })); + dispatch(setBackupAllFailure({ appId: id, status: false })); + dispatch(setAutomaticCloudBackup({ appId: id, enabled: true })); setHealthCheckModal(true); } }, [backupAllSuccess, backupAllFailure]); @@ -118,12 +123,9 @@ function BackupHealthCheckList({ isUaiFlow }) { if (seedConfirmed) { setShowConfirmSeedModal(false); dispatch(setRecoveryKeyBackedUp({ appId: id as string, status: true })); - if (!automaticCloudBackup) dispatch(backupAllSignersAndVaults()); - else { - setTimeout(() => { - setHealthCheckModal(true); - }, 100); - } + setTimeout(() => { + setHealthCheckModal(true); + }, 100); } return () => { dispatch(setSeedConfirmed(false)); @@ -133,13 +135,13 @@ function BackupHealthCheckList({ isUaiFlow }) { useEffect(() => { if (backupAllFailure && isFocused) { setFailedVerificationModal(true); - dispatch(setBackupAllFailure(false)); + dispatch(setBackupAllFailure({ appId: id, status: false })); } }, [backupAllFailure]); useEffect(() => { if (backupAllSuccess && isFocused) { - dispatch(setBackupAllSuccess(false)); + dispatch(setBackupAllSuccess({ appId: id, status: false })); dispatch(seedBackedConfirmed(true)); } }, [backupAllSuccess]); @@ -192,7 +194,7 @@ function BackupHealthCheckList({ isUaiFlow }) { } else { setBackupMismatchModal(true); } - }) + }, id) ); } else { dispatch(seedBackedConfirmed(true)); @@ -288,7 +290,7 @@ function BackupHealthCheckList({ isUaiFlow }) { buttonBackground={`${colorMode}.pantoneGreen`} buttonText={'Backup Now'} buttonCallback={() => { - dispatch(backupAllSignersAndVaults()); + dispatch(backupAllSignersAndVaults(id)); setBackupMismatchModal(false); }} secondaryButtonText="Home" diff --git a/src/components/ImportExportLabels/index.tsx b/src/components/ImportExportLabels/index.tsx index 72074f47ae..91d07f13d3 100644 --- a/src/components/ImportExportLabels/index.tsx +++ b/src/components/ImportExportLabels/index.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useRef, useState } from 'react'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { StyleSheet, TouchableOpacity } from 'react-native'; import { useDispatch } from 'react-redux'; @@ -28,6 +28,8 @@ const ImportExportLabels: React.FC = ({ }) => { const { colorMode } = useColorMode(); const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const { vault: vaultText } = translations; const { syncingUTXOs } = useAppSelector((state) => state.utxos); const [isSyncingLabels, setIsSyncingLabels] = useState(false); @@ -101,7 +103,7 @@ const ImportExportLabels: React.FC = ({ origin: standardizeDescriptor(label.origin), })); - dispatch(importLabels({ labels: standardizedLabels })); + dispatch(importLabels({ labels: standardizedLabels }, originAppId)); onSuccess(`Imported ${walletLabels.length} labels successfully`); } catch (parseError) { diff --git a/src/hooks/useSettingKeeper.tsx b/src/hooks/useSettingKeeper.tsx index ae020d4cc8..b597869295 100644 --- a/src/hooks/useSettingKeeper.tsx +++ b/src/hooks/useSettingKeeper.tsx @@ -51,6 +51,7 @@ import { setAutomaticCloudBackup, setDeleteBackupSuccess, setDeleteBackupFailure, + isAutomaticCloudBackupEnabled, } from 'src/store/reducers/bhr'; import useToastMessage from './useToastMessage'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; @@ -92,12 +93,17 @@ export const useSettingKeeper = () => { }); const { id }: KeeperApp = useQuery(RealmSchema.KeeperApp).map(getJSONFromRealmObject)[0]; const { - backupAllFailure, - backupAllSuccess, - automaticCloudBackup, - deleteBackupSuccess, - deleteBackupFailure, + backupAllFailureByAppId, + backupAllSuccessByAppId, + automaticCloudBackupByAppId, + deleteBackupSuccessByAppId, + deleteBackupFailureByAppId, } = useAppSelector((state) => state.bhr); + const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id); + const backupAllFailure = !!backupAllFailureByAppId?.[id]; + const backupAllSuccess = !!backupAllSuccessByAppId?.[id]; + const deleteBackupSuccess = !!deleteBackupSuccessByAppId?.[id]; + const deleteBackupFailure = !!deleteBackupFailureByAppId?.[id]; useEffect(() => { if (isOnL4) { @@ -142,8 +148,8 @@ export const useSettingKeeper = () => { useEffect(() => { if (backupAllSuccess && isFocused) { - dispatch(setBackupAllSuccess(false)); - dispatch(setAutomaticCloudBackup(true)); + dispatch(setBackupAllSuccess({ appId: id, status: false })); + dispatch(setAutomaticCloudBackup({ appId: id, enabled: true })); setTimeout(() => { dispatch(setShowTipModal({ status: true, address: config.ADDRESS.assistServer })); }, 1000); @@ -152,28 +158,28 @@ export const useSettingKeeper = () => { useEffect(() => { if (deleteBackupSuccess && isFocused) { - dispatch(setDeleteBackupSuccess(false)); - dispatch(setAutomaticCloudBackup(false)); + dispatch(setDeleteBackupSuccess({ appId: id, status: false })); + dispatch(setAutomaticCloudBackup({ appId: id, enabled: false })); } }, [deleteBackupSuccess]); useEffect(() => { if (deleteBackupFailure && isFocused) { - dispatch(setDeleteBackupFailure(false)); + dispatch(setDeleteBackupFailure({ appId: id, status: false })); showToast(errorText.unableToDeleteAssistedServer, ); } }, [deleteBackupFailure]); useEffect(() => { if (backupAllFailure && isFocused) { - dispatch(setBackupAllFailure(false)); + dispatch(setBackupAllFailure({ appId: id, status: false })); } }, [backupAllFailure]); const toggleAutomaticBackupMode = useCallback(() => { - if (!automaticCloudBackup) dispatch(backupAllSignersAndVaults()); + if (!automaticCloudBackup) dispatch(backupAllSignersAndVaults(id)); else setShowDeleteBackup(true); - }, [automaticCloudBackup, dispatch]); + }, [automaticCloudBackup, dispatch, id]); const debouncedAutomaticBackupToggle = useCallback(() => { if (backupToggleTimeoutRef.current) { @@ -471,11 +477,11 @@ export const useSettingKeeper = () => { primaryText={settings.assistedServerDeleteBackupModalCTA} primaryCallback={() => { setShowDeleteBackup(false); - dispatch(deleteBackup()); + dispatch(deleteBackup(id)); }} secondaryCallback={() => { setShowDeleteBackup(false); - dispatch(setAutomaticCloudBackup(false)); + dispatch(setAutomaticCloudBackup({ appId: id, enabled: false })); }} secondaryText={settings.assistedServerDeleteBackupModalSecondaryCTA} /> diff --git a/src/hooks/useUSDTWallets.ts b/src/hooks/useUSDTWallets.ts index 12578e9f78..53abd4d944 100644 --- a/src/hooks/useUSDTWallets.ts +++ b/src/hooks/useUSDTWallets.ts @@ -19,13 +19,17 @@ import USDT, { DEFAULT_DEADLINE_SECONDS, USDTTransferOptions, } from '../services/wallets/operations/dollars/USDT'; -import { useDispatch } from 'react-redux'; +import { useDispatch, useStore } from 'react-redux'; import { useAppSelector } from 'src/store/hooks'; import { updateAppImage } from 'src/store/sagaActions/bhr'; import Relay from 'src/services/backend/Relay'; import { canonical, recoveryContent } from 'src/services/backup/image'; import { markBackupMutation } from 'src/services/backup/transport'; -import { invalidateBackupRepair, setPendingAllBackup } from 'src/store/reducers/bhr'; +import { + invalidateBackupRepair, + isAutomaticCloudBackupEnabled, + setPendingAllBackup, +} from 'src/store/reducers/bhr'; export interface UseUSDTWalletsOptions { getAll?: boolean; @@ -64,7 +68,14 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall const allWallets = useQuery(RealmSchema.USDTWallet); const [error, setError] = useState(null); const dispatch = useDispatch(); + const reduxStore = useStore(); const { id: appId }: any = dbManager.getObjectByIndex(RealmSchema.KeeperApp); + const isOriginCurrent = useCallback( + () => + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id === appId && + reduxStore.getState().storage.appId === appId, + [appId, reduxStore] + ); const filterByNetwork = (wallets: USDTWallet[]) => { if (bitcoinNetworkType) @@ -101,7 +112,9 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall primaryMnemonic?: string; importDetails?: USDTWalletImportDetails; }): Promise<{ newWallet?: USDTWallet; error?: string }> => { + let beganLocalWrite = false; try { + if (!isOriginCurrent()) throw new Error('Account changed'); setError(null); const walletNetworkType = USDTWalletSupportedNetwork; const allUSDTWallets: USDTWallet[] = (await dbManager.getObjectByIndex( @@ -110,6 +123,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall null, true // get all wallets )) as any; + if (!isOriginCurrent()) throw new Error('Account changed'); let lastInstanceNum = -1; allUSDTWallets.forEach((wallet) => { @@ -128,6 +142,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall instanceNum: params.type === USDTWalletType.DEFAULT ? lastInstanceNum + 1 : null, importDetails: params.importDetails, }); + if (!isOriginCurrent()) throw new Error('Account changed'); // check if a USDT wallet already exists with the same mnemonic(especially for imported wallets) const existingWallet = allUSDTWallets.find((wallet) => wallet.id === newWallet.id); @@ -135,41 +150,67 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall throw new Error('USDT wallet already exists with the same ID'); } - await dbManager.createObject(RealmSchema.USDTWallet, newWallet); + beganLocalWrite = true; + if ((await dbManager.createObject(RealmSchema.USDTWallet, newWallet)) !== true) + throw new Error('Failed to create wallet'); + if (!isOriginCurrent()) throw new Error('Account changed'); // Create usdt wallet backup - dispatch(updateAppImage({ wallets: [newWallet], signers: null, updateNodes: false })); + dispatch(updateAppImage({ wallets: [newWallet], signers: null, updateNodes: false }, appId)); return { newWallet }; } catch (err) { + if (beganLocalWrite && isAutomaticCloudBackupEnabled(reduxStore.getState().bhr, appId)) { + markBackupMutation(appId); + dispatch(invalidateBackupRepair(appId)); + dispatch(setPendingAllBackup({ appId, pending: true })); + } setError(err.message || 'Failed to create wallet'); captureError(err); return { error: err.message || 'Failed to create wallet' }; } }, - [] + [appId, dispatch, isOriginCurrent, reduxStore] ); /** * Delete a wallet */ const deleteWallet = useCallback(async (walletId: string): Promise => { + let remoteDeleted = false; + const markIncompleteDeletion = () => { + if (!remoteDeleted) return; + markBackupMutation(appId); + dispatch(invalidateBackupRepair(appId)); + dispatch(setPendingAllBackup({ appId, pending: true })); + }; try { - const response = await Relay.deleteAppImageEntity({ - appId, - signers: null, - walletIds: [walletId], - }); - if (!response.updated) throw new Error('Failed to delete wallet'); - - await dbManager.deleteObjectById(RealmSchema.USDTWallet, walletId); - return true; + if (!isOriginCurrent()) return false; + // An account without Assisted Server Backup consent still owns its local + // wallet. Only the opted-in account needs a corresponding relay delete. + if (isAutomaticCloudBackupEnabled(reduxStore.getState().bhr, appId)) { + const response = await Relay.deleteAppImageEntity({ + appId, + signers: null, + walletIds: [walletId], + }); + if (!response.updated) throw new Error('Failed to delete wallet'); + remoteDeleted = true; + } + if (!isOriginCurrent()) { + markIncompleteDeletion(); + return false; + } + const deleted = dbManager.deleteObjectById(RealmSchema.USDTWallet, walletId) === true; + if (!deleted) markIncompleteDeletion(); + return deleted; } catch (err) { + markIncompleteDeletion(); setError(err.message || 'Failed to delete wallet'); captureError(err); return false; } - }, []); + }, [appId, dispatch, isOriginCurrent, reduxStore]); /** * Update a wallet in the database @@ -178,6 +219,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall async (wallet: USDTWallet): Promise => { let recoveryChanged = false; try { + if (!isOriginCurrent()) return false; const previous = dbManager.getObjectById(RealmSchema.USDTWallet, wallet.id); if (!previous) throw new Error('Wallet not found'); const previousWallet = previous.toJSON ? previous.toJSON() : previous; @@ -191,11 +233,12 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall walletUpdateData ); // Realm updates must omit the primary key. if (!updated) throw new Error('Failed to update wallet'); + if (!isOriginCurrent()) throw new Error('Account changed'); // Metadata and visibility must survive recovery. Balance/account refreshes // are rebuildable caches and must not cause an upload on every sync. if (recoveryChanged) - dispatch(updateAppImage({ wallets: [wallet], signers: null, updateNodes: false })); + dispatch(updateAppImage({ wallets: [wallet], signers: null, updateNodes: false }, appId)); return true; } catch (err) { @@ -204,14 +247,14 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall if (recoveryChanged) { markBackupMutation(appId); dispatch(invalidateBackupRepair(appId)); - dispatch(setPendingAllBackup(true)); + dispatch(setPendingAllBackup({ appId, pending: true })); } setError(err.message || 'Failed to update wallet'); captureError(err); return false; } }, - [appId, dispatch] + [appId, dispatch, isOriginCurrent] ); /** diff --git a/src/screens/AppSettings/AssistedBackupStatus.tsx b/src/screens/AppSettings/AssistedBackupStatus.tsx index cdc54fc004..5c8d7811ac 100644 --- a/src/screens/AppSettings/AssistedBackupStatus.tsx +++ b/src/screens/AppSettings/AssistedBackupStatus.tsx @@ -6,6 +6,7 @@ import { useNavigation } from '@react-navigation/native'; import { RealmSchema } from 'src/storage/realm/enum'; import { useAppDispatch, useAppSelector } from 'src/store/hooks'; import { checkBackupFreshness, repairBackup } from 'src/store/sagaActions/bhr'; +import { isAutomaticCloudBackupEnabled } from 'src/store/reducers/bhr'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import ScreenWrapper from 'src/components/ScreenWrapper'; import WalletHeader from 'src/components/WalletHeader'; @@ -21,15 +22,16 @@ export default function AssistedBackupStatus() { const app = useQuery(RealmSchema.KeeperApp)[0] as any; const id = app?.id as string; const { - automaticCloudBackup, + automaticCloudBackupByAppId, backupRepairStateByAppId = {}, backupRepairRunningByAppId = {}, } = useAppSelector((state) => state.bhr); + const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id); const phase = backupRepairStateByAppId[id]; const running = !!backupRepairRunningByAppId[id]; const [slow, setSlow] = useState(false); useEffect(() => { - if (automaticCloudBackup) dispatch(checkBackupFreshness()); + if (automaticCloudBackup) dispatch(checkBackupFreshness(id)); }, [id]); useEffect(() => { setSlow(false); @@ -70,7 +72,7 @@ export default function AssistedBackupStatus() { fullWidth primaryText={state === 'different' ? copy.backUp : copy.check} primaryCallback={() => - dispatch(state === 'different' ? repairBackup() : checkBackupFreshness()) + dispatch(state === 'different' ? repairBackup(id) : checkBackupFreshness(id)) } /> )} diff --git a/src/screens/AppSettings/Node/NodeSelection.tsx b/src/screens/AppSettings/Node/NodeSelection.tsx index 71f7579a97..bf62444d53 100644 --- a/src/screens/AppSettings/Node/NodeSelection.tsx +++ b/src/screens/AppSettings/Node/NodeSelection.tsx @@ -96,6 +96,8 @@ const NodeSelection = () => { }, [nodes.length]); const onSaveCallback = async (nodeDetail: NodeDetail) => { + const originAppId = Node.currentAccountId(); + if (!originAppId) return; setSaveLoading(true); // Sanitize host @@ -110,11 +112,15 @@ const NodeSelection = () => { } const nodeToSave = { ...nodeDetail }; - const { saved, connectionError: nodeConnectionError } = await Node.save(nodeToSave, nodeList); + const { saved, connectionError: nodeConnectionError } = await Node.save(nodeToSave, nodeList, originAppId); + if (!Node.isAccountActive(originAppId)) { + setSaveLoading(false); + return; + } if (saved) { const updatedNodeList = Node.getAllNodes(); setNodeList(updatedNodeList); - dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true })); + dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true }, originAppId)); const newNode = updatedNodeList.find( (node) => node.host === nodeToSave.host && node.port === nodeToSave.port ); @@ -144,6 +150,8 @@ const NodeSelection = () => { }; const onConnectToNode = async (selectedNode: NodeDetail) => { + const originAppId = Node.currentAccountId(); + if (!originAppId) return; let nodes = Node.getAllNodes(); if ( currentlySelectedNode && @@ -152,6 +160,7 @@ const NodeSelection = () => { ) { // disconnect currently selected node(if connected) await Node.disconnect(currentlySelectedNode); + if (!Node.isAccountActive(originAppId)) return; currentlySelectedNode.isConnected = false; Node.update(currentlySelectedNode, { isConnected: currentlySelectedNode.isConnected }); @@ -168,6 +177,10 @@ const NodeSelection = () => { const node = { ...selectedNode }; const { connected, connectedTo, error } = await Node.connectToSelectedNode(node); + if (!Node.isAccountActive(originAppId)) { + setLoading(false); + return; + } if (connected) { node.isConnected = connected; diff --git a/src/screens/AppSettings/Node/NodeSettings.tsx b/src/screens/AppSettings/Node/NodeSettings.tsx index dc74de79ca..7ca1441fc1 100644 --- a/src/screens/AppSettings/Node/NodeSettings.tsx +++ b/src/screens/AppSettings/Node/NodeSettings.tsx @@ -64,24 +64,31 @@ function NodeSettings() { }, [nodes.length]); const onDelete = async (selectedItem: NodeDetail) => { + const originAppId = Node.currentAccountId(); + if (!originAppId) return; const isConnected = Node.nodeConnectionStatus(selectedItem); if (isConnected) await Node.disconnect(selectedItem); + if (!Node.isAccountActive(originAppId)) return; + const status = Node.delete(selectedItem); if (status) { const updatedNodes = Node.getAllNodes(); setNodeList(updatedNodes); - dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true })); + dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true }, originAppId)); } }; const onConnectToNode = async (selectedNode: NodeDetail) => { + const originAppId = Node.currentAccountId(); + if (!originAppId) return; let updatedNodes = Node.getAllNodes(); // Disconnect the currently connected node if it's not the selected one const currentlySelectedNode = updatedNodes.find((node) => node.isConnected); if (currentlySelectedNode && currentlySelectedNode.id !== selectedNode.id) { await Node.disconnect(currentlySelectedNode); + if (!Node.isAccountActive(originAppId)) return; currentlySelectedNode.isConnected = false; Node.update(currentlySelectedNode, { isConnected: currentlySelectedNode.isConnected }); updatedNodes = updatedNodes.map((node) => @@ -93,6 +100,10 @@ function NodeSettings() { setLoading(true); const { connected, connectedTo, error } = await Node.connectToSelectedNode(selectedNode); + if (!Node.isAccountActive(originAppId)) { + setLoading(false); + return; + } if (connected) { selectedNode.isConnected = connected; diff --git a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx index f5a9ef668b..38988f8ebd 100644 --- a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx +++ b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx @@ -1,4 +1,4 @@ -import React, { useContext, useEffect, useState } from 'react'; +import React, { useContext, useState } from 'react'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import ScreenWrapper from 'src/components/ScreenWrapper'; @@ -13,18 +13,11 @@ import ThemedColor from 'src/components/ThemedColor/ThemedColor'; import Buttons from 'src/components/Buttons'; import ModalWrapper from 'src/components/Modal/ModalWrapper'; import ConfirmSeedWord from 'src/components/SeedWordBackup/ConfirmSeedWord'; -import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; -import { backupAllSignersAndVaults, seedBackedUp } from 'src/store/sagaActions/bhr'; +import { seedBackedUp } from 'src/store/sagaActions/bhr'; import { useDispatch } from 'react-redux'; import { setRecoveryKeyStatus } from 'src/store/reducers/account'; -import { useAppSelector } from 'src/store/hooks'; import useToastMessage from 'src/hooks/useToastMessage'; import TickIcon from 'src/assets/images/icon_tick.svg'; -import { - setAutomaticCloudBackup, - setBackupAllFailure, - setBackupAllSuccess, -} from 'src/store/reducers/bhr'; type KeeperApp = { id: string; @@ -33,7 +26,7 @@ type KeeperApp = { export const ViewRecoveryKeyScreen = ({ navigation }) => { const { colorMode } = useColorMode(); - const { home: homeTxt, common, BackupWallet: backupTxt, recoveryBackup } = useContext(LocalizationContext).translations; + const { home: homeTxt, common, BackupWallet: backupTxt } = useContext(LocalizationContext).translations; const { primaryMnemonic, id: appId } = useQuery(RealmSchema.KeeperApp).map( getJSONFromRealmObject )[0] as KeeperApp; @@ -41,27 +34,9 @@ export const ViewRecoveryKeyScreen = ({ navigation }) => { const [showWordIndex, setShowWordIndex] = useState(''); const seedTextColor = ThemedColor({ name: 'seedTextColor' }); const [confirmSeedModal, setConfirmSeedModal] = useState(false); - const [loader, setLoader] = useState(false); const dispatch = useDispatch(); - const { backupAllFailure, backupAllSuccess } = useAppSelector((state) => state.bhr); const { showToast } = useToastMessage(); - useEffect(() => { - if (backupAllSuccess) { - dispatch(setBackupAllSuccess(false)); - dispatch(setBackupAllFailure(false)); - dispatch(setAutomaticCloudBackup(true)); - setLoader(false); - showToast(backupTxt.recoveryKeyBackedUpSuccessfully, ); - navigation.goBack(); - } - if (backupAllFailure) { - dispatch(setBackupAllFailure(false)); - setLoader(false); - showToast(recoveryBackup.unverified.title); - } - }, [backupAllSuccess, backupAllFailure]); - const SeedCard = ({ item, index }: { item; index }) => { return ( { words={words} confirmBtnPress={() => { setConfirmSeedModal(false); - setLoader(true); dispatch(seedBackedUp()); dispatch(setRecoveryKeyStatus({ appId, status: 'confirmed' })); - dispatch(backupAllSignersAndVaults()); + showToast(backupTxt.recoveryKeyBackedUpSuccessfully, ); + navigation.goBack(); }} /> - ); diff --git a/src/screens/Home/Notifications/NotificationsCenter.tsx b/src/screens/Home/Notifications/NotificationsCenter.tsx index efcca03f94..d2ee6454de 100644 --- a/src/screens/Home/Notifications/NotificationsCenter.tsx +++ b/src/screens/Home/Notifications/NotificationsCenter.tsx @@ -90,7 +90,9 @@ const Card = memo(({ uai }: CardProps) => { const [insightModal, setInsightModal] = useState(false); const { signerMap } = useSignerMap(); const snapshots = useAppSelector((state) => state.cachedTxn.snapshots); - const { backupAllLoading } = useAppSelector((state) => state.bhr); + const backupAllLoading = useAppSelector( + (state) => !!state.bhr.backupAllLoadingByAppId?.[state.storage.appId] + ); const { translations } = useContext(LocalizationContext); const { common, notification, error: errorTranslation } = translations; diff --git a/src/screens/Home/components/Settings/keeperSettings.tsx b/src/screens/Home/components/Settings/keeperSettings.tsx index 65b0c28432..0152255a72 100644 --- a/src/screens/Home/components/Settings/keeperSettings.tsx +++ b/src/screens/Home/components/Settings/keeperSettings.tsx @@ -51,7 +51,9 @@ const KeeperSettings = ({ route }) => { }; }, []); // Empty dependency array means this runs once on mount - const { backupAllLoading } = useAppSelector((state) => state.bhr); + const backupAllLoading = useAppSelector( + (state) => !!state.bhr.backupAllLoadingByAppId?.[state.storage.appId] + ); const dispatch = useDispatch(); return ( diff --git a/src/screens/LoginScreen/Login.tsx b/src/screens/LoginScreen/Login.tsx index e28e8922c3..b6970cef1a 100644 --- a/src/screens/LoginScreen/Login.tsx +++ b/src/screens/LoginScreen/Login.tsx @@ -49,7 +49,11 @@ import BounceLoader from 'src/components/BounceLoader'; import { formatCoolDownTime, PasswordTimeout } from 'src/utils/PasswordTimeout'; import Buttons from 'src/components/Buttons'; import PinDotView from 'src/components/AppPinInput/PinDotView'; -import { setAutomaticCloudBackup, setBackupType } from 'src/store/reducers/bhr'; +import { + setAutomaticCloudBackup, + setBackupType, + isAutomaticCloudBackupEnabled, +} from 'src/store/reducers/bhr'; import Relay from 'src/services/backend/Relay'; import { setAccountManagerDetails } from 'src/store/reducers/concierge'; import Fonts from 'src/constants/Fonts'; @@ -84,7 +88,9 @@ function LoginScreen({ navigation, route }) { // useAppSelector((state) => state.settings.subscription) === SubscriptionTier.L4; const isOnPleb = false; const isKeeperPrivate = false; - const { automaticCloudBackup } = useAppSelector((state) => state.bhr); + const automaticCloudBackup = useAppSelector((state) => + isAutomaticCloudBackupEnabled(state.bhr, appId) + ); const login_button_backGround = ThemedColor({ name: 'login_button_backGround' }); const slider_background = ThemedColor({ name: 'slider_background' }); @@ -413,9 +419,9 @@ function LoginScreen({ navigation, route }) { dispatch(setSubscription(updatedSubscription.name)); dispatch(setOfflineStatus(true)); // disable assisted server backup for pleb - dispatch(setAutomaticCloudBackup(false)); + dispatch(setAutomaticCloudBackup({ appId: app.id, enabled: false })); dispatch(setPlebDueToOffline(true)); - dispatch(setAutoUpdateEnabledBeforeDowngrade(automaticCloudBackup)); + dispatch(setAutoUpdateEnabledBeforeDowngrade({ appId: app.id, enabled: automaticCloudBackup })); navigation.replace('App'); } diff --git a/src/screens/Recieve/ReceiveScreen.tsx b/src/screens/Recieve/ReceiveScreen.tsx index 6befa1e08d..ab38812359 100644 --- a/src/screens/Recieve/ReceiveScreen.tsx +++ b/src/screens/Recieve/ReceiveScreen.tsx @@ -3,7 +3,7 @@ import Text from 'src/components/KeeperText'; import { Box, useColorMode, Pressable, HStack } from '@gluestack-ui/themed-native-base'; import { ScrollView, StyleSheet, Vibration, TouchableOpacity, TextInput } from 'react-native'; -import React, { useContext, useEffect, useState } from 'react'; +import React, { useContext, useEffect, useRef, useState } from 'react'; import Buttons from 'src/components/Buttons'; import ScreenWrapper from 'src/components/ScreenWrapper'; @@ -96,6 +96,8 @@ function ReceiveScreen({ route }: { route }) { const [addressUsed, setAddressUsed] = useState(false); const dispatch = useAppDispatch(); + const selectedAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(selectedAppId).current; const { showToast } = useToastMessage(); @@ -111,7 +113,7 @@ function ReceiveScreen({ route }: { route }) { const [localCurrencyKind, setLocalCurrencyKind] = useState(currentCurrency); const generateNewReceiveAddress = () => { - dispatch(generateNewAddress(wallet)); + dispatch(generateNewAddress(wallet, originAppId)); Vibration.vibrate(50); const newTotalAddressesCount = totalAddressesCount + 1; setTotalAddressesCount(newTotalAddressesCount); diff --git a/src/screens/SeedScreens/ExportSeedScreen.tsx b/src/screens/SeedScreens/ExportSeedScreen.tsx index 447e6c1741..213e674a35 100644 --- a/src/screens/SeedScreens/ExportSeedScreen.tsx +++ b/src/screens/SeedScreens/ExportSeedScreen.tsx @@ -7,7 +7,6 @@ import ConfirmSeedWord from 'src/components/SeedWordBackup/ConfirmSeedWord'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import ModalWrapper from 'src/components/Modal/ModalWrapper'; import { - backupAllSignersAndVaults, healthCheckStatusUpdate, seedBackedUp, } from 'src/store/sagaActions/bhr'; @@ -39,12 +38,6 @@ import { RealmSchema } from 'src/storage/realm/enum'; import { setRecoveryKeyBackedUp, updateOneTimeBackupStatus } from 'src/store/reducers/account'; import { setShowTipModal } from 'src/store/reducers/settings'; import config from 'src/utils/service-utilities/config'; -import { - setAutomaticCloudBackup, - setBackupAllFailure, - setBackupAllSuccess, -} from 'src/store/reducers/bhr'; -import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; function ExportSeedScreen({ route, navigation }) { const { colorMode } = useColorMode(); @@ -88,37 +81,15 @@ function ExportSeedScreen({ route, navigation }) { const [backupSuccessModal, setBackupSuccessModal] = useState(false); const [showQRVisible, setShowQRVisible] = useState(false); const [showWordIndex, setShowWordIndex] = useState(''); - const { - backupMethod, - automaticCloudBackup, - backupAllLoading, - backupAllFailure, - backupAllSuccess, - } = useAppSelector((state) => state.bhr); + const { backupMethod } = useAppSelector((state) => state.bhr); const isChangePassword = parentScreen === PRIVACYANDDISPLAY; const seedTextColor = ThemedColor({ name: 'seedTextColor' }); const { id: appId } = dbManager.getObjectByIndex(RealmSchema.KeeperApp); - const [asbEnabled, setAsbEnabled] = useState(false); useEffect(() => { if (backupMethod !== null && next && !isHealthCheck && !isInheritancePlaning) { - if (asbEnabled) dispatch(backupAllSignersAndVaults()); - else setBackupSuccessModal(true); - } - }, [backupMethod]); - - useEffect(() => { - if (backupAllSuccess) { - if (!automaticCloudBackup) setAsbEnabled(true); - dispatch(setBackupAllSuccess(false)); - dispatch(setBackupAllFailure(false)); - dispatch(setAutomaticCloudBackup(true)); setBackupSuccessModal(true); } - if (backupAllFailure) { - dispatch(setBackupAllFailure(false)); - showToast(translations.recoveryBackup.unverified.title); - } - }, [backupAllSuccess, backupAllFailure]); + }, [backupMethod]); const getNoteSubtitle = () => { @@ -328,7 +299,6 @@ function ExportSeedScreen({ route, navigation }) { }) ); } else { - if (!automaticCloudBackup) setAsbEnabled(true); dispatch(seedBackedUp()); dispatch(setRecoveryKeyBackedUp({ appId, status: true })); } @@ -361,7 +331,6 @@ function ExportSeedScreen({ route, navigation }) { {BackupWallet.backupSuccessParagraph} - {asbEnabled && {BackupWallet.assistedServerBackupEnabled}} )} @@ -387,7 +356,6 @@ function ExportSeedScreen({ route, navigation }) { )} /> - ); } diff --git a/src/screens/Send/SendConfirmation.tsx b/src/screens/Send/SendConfirmation.tsx index c142e84d6d..9b15883a9d 100644 --- a/src/screens/Send/SendConfirmation.tsx +++ b/src/screens/Send/SendConfirmation.tsx @@ -2,7 +2,7 @@ import { StyleSheet, TouchableOpacity, ScrollView } from 'react-native'; import Text from 'src/components/KeeperText'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { CommonActions, useIsFocused, useNavigation } from '@react-navigation/native'; -import React, { useCallback, useContext, useEffect, useState } from 'react'; +import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { sendPhaseTwo } from 'src/store/sagaActions/send_and_receive'; import { hp, wp } from 'src/constants/responsive'; import Share from 'react-native-share'; @@ -100,6 +100,8 @@ function SendConfirmation({ route }) { const { colorMode } = useColorMode(); const { showToast } = useToastMessage(); const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const isFocused = useIsFocused(); const { sender, @@ -328,7 +330,7 @@ function SendConfirmation({ route }) { ), }, note, - }) + }, originAppId) ); }, 200); }) @@ -1058,4 +1060,4 @@ function updateSatsAmountInMsg(message: string, newAmount) { console.log('🚀 ~ updateSatsAmountInMsg ~ error:', error); return message; } -} \ No newline at end of file +} diff --git a/src/screens/SignTransaction/SignTransactionScreen.tsx b/src/screens/SignTransaction/SignTransactionScreen.tsx index eae120b884..10e80c129f 100644 --- a/src/screens/SignTransaction/SignTransactionScreen.tsx +++ b/src/screens/SignTransaction/SignTransactionScreen.tsx @@ -172,6 +172,8 @@ function SignTransactionScreen() { const card = useRef(new CKTapCard()).current; const satochipCard = useRef(new SatochipCard()).current; const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const cachedTxn = useAppSelector((state) => state.cachedTxn); const cachedTxid = useAppSelector((state) => state.sendAndReceive.sendPhaseTwo.cachedTxid); @@ -808,7 +810,7 @@ function SignTransactionScreen() { txnPriority: tnxDetails.transactionPriority, note, miniscriptTxElements, - }) + }, originAppId) ); } else { showToast(errorText.notEnoughtSignature); diff --git a/src/screens/UTXOManagement/UTXOLabeling.tsx b/src/screens/UTXOManagement/UTXOLabeling.tsx index 2b137dd6a2..95bbe6e382 100644 --- a/src/screens/UTXOManagement/UTXOLabeling.tsx +++ b/src/screens/UTXOManagement/UTXOLabeling.tsx @@ -54,6 +54,8 @@ function UTXOLabeling() { const { transactions: txTranslations, wallet: walletTranslations, common } = translations; const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; // Live reactive wallet from Realm so spendability updates immediately after saga writes const liveWalletResult = useWallets({ walletIds: [wallet.id] }).wallets[0]; const liveVaultResult = useVault({ vaultId: wallet.id }).activeVault; @@ -127,7 +129,7 @@ function UTXOLabeling() { const finalLabels = [{ name: noteRef.current, isSystem: false }]; if (txNoteLabels[utxo.txId][0]?.name) { const labelChanges = getLabelChanges(txNoteLabels[utxo.txId], finalLabels); - dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }, originAppId)); } else { dispatch( addLabels({ @@ -135,13 +137,13 @@ function UTXOLabeling() { txId: utxo.txId, wallet, type: LabelRefType.TXN, - }) + }, originAppId) ); } } else { if (txNoteLabels[utxo.txId][0]?.name) { const labelChanges = getLabelChanges(txNoteLabels[utxo.txId], []); - dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }, originAppId)); } } } @@ -251,7 +253,7 @@ function UTXOLabeling() { { - dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'spendable' })); + dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'spendable' }, originAppId)); showToast('Coin marked spendable', ); }} > @@ -264,7 +266,7 @@ function UTXOLabeling() { { - dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'doNotSpend' })); + dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'doNotSpend' }, originAppId)); showToast('Coin marked Do Not Spend', ); }} > diff --git a/src/screens/UTXOManagement/components/LabelsEditor.tsx b/src/screens/UTXOManagement/components/LabelsEditor.tsx index 58db542da5..3f703b0a96 100644 --- a/src/screens/UTXOManagement/components/LabelsEditor.tsx +++ b/src/screens/UTXOManagement/components/LabelsEditor.tsx @@ -28,6 +28,8 @@ function LabelsEditor({ utxo = null, address = null, wallet, onLabelsSaved, read const { showToast } = useToastMessage(); const processDispatched = useRef(false); const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const labelsKey = address ? address : `${utxo.txId}:${utxo.vout}`; const getSortedNames = (labels) => @@ -106,9 +108,9 @@ function LabelsEditor({ utxo = null, address = null, wallet, onLabelsSaved, read const labelChanges = getLabelChanges(initialLabels, finalLabels); processDispatched.current = true; if (address) { - dispatch(bulkUpdateLabels({ labelChanges, address, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, address, wallet }, originAppId)); } else { - dispatch(bulkUpdateLabels({ labelChanges, UTXO: utxo, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, UTXO: utxo, wallet }, originAppId)); } }; diff --git a/src/screens/Vault/ChoosePolicyNew.tsx b/src/screens/Vault/ChoosePolicyNew.tsx index 390114b990..9d6bec45a8 100644 --- a/src/screens/Vault/ChoosePolicyNew.tsx +++ b/src/screens/Vault/ChoosePolicyNew.tsx @@ -1,7 +1,7 @@ import Text from 'src/components/KeeperText'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { StyleSheet, TouchableOpacity } from 'react-native'; -import React, { useCallback, useContext, useEffect, useState } from 'react'; +import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { DelayedPolicyUpdate, SignerPolicy, @@ -46,6 +46,8 @@ import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import ThemedColor from 'src/components/ThemedColor/ThemedColor'; function ChoosePolicyNew({ navigation, route }) { + const selectedAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(selectedAppId).current; const { colorMode } = useColorMode(); const isDarkMode = colorMode === 'dark'; const { showToast } = useToastMessage(); @@ -193,7 +195,7 @@ function ChoosePolicyNew({ navigation, route }) { restrictions: newPolicy.restrictions, signingDelay: newPolicy.signingDelay, }; - dispatch(updateSignerPolicy(signer, route.params.vaultKey, policyUpdates, verificationToken)); + dispatch(updateSignerPolicy(signer, route.params.vaultKey, policyUpdates, verificationToken, originAppId)); }; useEffect(() => { diff --git a/src/screens/Vault/VaultDetails.tsx b/src/screens/Vault/VaultDetails.tsx index 4ae46546d7..8b8dd6ff0d 100644 --- a/src/screens/Vault/VaultDetails.tsx +++ b/src/screens/Vault/VaultDetails.tsx @@ -155,6 +155,8 @@ function VaultDetails({ navigation, route }: ScreenProps) { viewTransaction = null, } = route.params || {}; const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const { showToast } = useToastMessage(); const { activeVault: vault } = useVault({ vaultId }); const [pullRefresh, setPullRefresh] = useState(false); @@ -442,7 +444,7 @@ function VaultDetails({ navigation, route }: ScreenProps) { const txid = tnx?.potentialTxId || getTnxIdFromCachedTnx(tnx); for (const broadcastedTnx of transactions) { if (broadcastedTnx.txid === txid) { - dispatch(discardBroadcastedTnx({ cachedTxid: tnx.txid, vault })); + dispatch(discardBroadcastedTnx({ cachedTxid: tnx.txid, vault }, originAppId)); } } } diff --git a/src/screens/ViewTransactions/TransactionDetails.tsx b/src/screens/ViewTransactions/TransactionDetails.tsx index 6d0bd4220a..5782fad77d 100644 --- a/src/screens/ViewTransactions/TransactionDetails.tsx +++ b/src/screens/ViewTransactions/TransactionDetails.tsx @@ -71,6 +71,8 @@ function TransactionDetails({ route }) { const close = () => setVisible(false); const noteRef = useRef(); const dispatch = useDispatch(); + const activeAppId = useAppSelector((state) => state.storage.appId); + const originAppId = useRef(activeAppId).current; const [updatingLabel, setUpdatingLabel] = React.useState(false); const { bitcoinNetworkType } = useAppSelector((state) => state.settings); const insets = useSafeAreaInsets(); @@ -88,7 +90,7 @@ function TransactionDetails({ route }) { const finalLabels = [{ name: noteRef.current, isSystem: false }]; if (labels[transaction.txid][0]?.name) { const labelChanges = getLabelChanges(labels[transaction.txid], finalLabels); - dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }, originAppId)); } else { dispatch( addLabels({ @@ -96,13 +98,13 @@ function TransactionDetails({ route }) { txId: transaction.txid, wallet, type: LabelRefType.TXN, - }) + }, originAppId) ); } } else { if (labels[transaction.txid][0]?.name) { const labelChanges = getLabelChanges(labels[transaction.txid], []); - dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet })); + dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }, originAppId)); } } } diff --git a/src/services/backend/Relay.ts b/src/services/backend/Relay.ts index d9a33502ad..24839a7fed 100644 --- a/src/services/backend/Relay.ts +++ b/src/services/backend/Relay.ts @@ -142,7 +142,7 @@ export default class Relay { err?: string; }> => { try { - const res = await RestClient.post(`${RELAY}migrateXfps`, { appId, signerChanges }); + const res = await backupPost(`${RELAY}migrateXfps`, { appId, signerChanges }); const data = res.data || res.json; return data; } catch (err) { @@ -493,7 +493,7 @@ export default class Relay { message?: string; }> => { try { - const res = await backupPost(`${RELAY}deleteBackup`, body); + const res = await backupPost(`${RELAY}deleteBackup`, body, true); const data = res.data || res.json; return data; } catch (err) { diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 2bd77a5e87..3ba77bcce6 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -14,6 +14,7 @@ import { backupQueuedRevision, backupRevision, boundedBackupPost, + canAccessBackupAccount, withBackupSession, } from './transport'; import { @@ -160,12 +161,13 @@ async function encodeImage(app: any, image: BackupImage, checkpoint = () => {}) export function inspectBackup( appId: string, repair: boolean, - onPhase: (phase: RepairPhase) => void + onPhase: (phase: RepairPhase) => void, + explicitChoice = false ): Promise { const running = inFlight.get(appId); if (running) { if (repair && !running.repair) - return running.promise.then(() => inspectBackup(appId, true, onPhase)); + return running.promise.then(() => inspectBackup(appId, true, onPhase, explicitChoice)); running.listeners.add(onPhase); if (running.phase) onPhase(running.phase); return running.promise; @@ -186,7 +188,8 @@ export function inspectBackup( const assertCurrent = () => { if ( Date.now() >= deadline || - (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId || + !canAccessBackupAccount(appId, explicitChoice) ) throw new Error('Backup changed during check'); const currentRevision = backupRevision(appId); diff --git a/src/services/backup/transport.ts b/src/services/backup/transport.ts index 6b23798c71..04e6e46c7b 100644 --- a/src/services/backup/transport.ts +++ b/src/services/backup/transport.ts @@ -4,6 +4,12 @@ import RestClient from '../rest/RestClient'; const queues = new Map>(); const revisions = new Map(); const queuedMutationRevisions = new Map(); +let mayUploadForAccount: (appId: string, explicitChoice: boolean) => boolean = () => false; +export const setBackupUploadGuard = (guard: (appId: string, explicitChoice: boolean) => boolean) => { + mayUploadForAccount = guard; +}; +export const canAccessBackupAccount = (appId: string, explicitChoice = false) => + mayUploadForAccount(appId, explicitChoice); export const backupRevision = (id: string) => revisions.get(id) || 0; export const backupQueuedRevision = (id: string) => queuedMutationRevisions.get(id) || 0; export const markBackupMutation = (id: string) => revisions.set(id, backupRevision(id) + 1); @@ -89,11 +95,18 @@ export async function boundedBackupPost( } } -export function backupPost(path: string, body: any) { +export function backupPost(path: string, body: any, explicitChoice = false) { const appId = body.appId || body.appID; if (!appId) return Promise.reject(new Error('Missing backup account')); + if (!canAccessBackupAccount(appId, explicitChoice)) + return Promise.reject(new Error('Backup account is not active or opted in')); markBackupMutation(appId); - const result = withBackupSession(appId, () => boundedBackupPost(path, body)); + const result = withBackupSession(appId, () => { + // The queued write may execute after an account switch or consent change. + if (!canAccessBackupAccount(appId, explicitChoice)) + throw new Error('Backup account is not active or opted in'); + return boundedBackupPost(path, body); + }); queuedMutationRevisions.set(appId, backupRevision(appId)); return result; } diff --git a/src/services/electrum/node.tsx b/src/services/electrum/node.tsx index 1b09f62e35..70b93b3f75 100644 --- a/src/services/electrum/node.tsx +++ b/src/services/electrum/node.tsx @@ -7,7 +7,23 @@ import { predefinedMainnetNodes, predefinedTestnetNodes } from './predefinedNode import { store } from 'src/store/store'; export default class Node { - public static async save(nodeDetail: NodeDetail, nodeList: NodeDetail[]) { + public static currentAccountId(): string | undefined { + const appId = store.getState().storage.appId; + return this.isAccountActive(appId) ? appId : undefined; + } + + public static isAccountActive(appId?: string): boolean { + try { + return !!appId && store.getState().storage.appId === appId && + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id === appId; + } catch { + return false; + } + } + + public static async save(nodeDetail: NodeDetail, nodeList: NodeDetail[], originAppId = this.currentAccountId()) { + if (!this.isAccountActive(originAppId)) + return { saved: false, connectionError: 'Account changed' }; const { bitcoinNetworkType } = store.getState().settings; if (!nodeDetail.host || !nodeDetail.port) { return { saved: false, connectionError: 'Missing node host URL or port' }; @@ -19,6 +35,8 @@ export default class Node { if (!isConnectable) { return { saved: false, connectionError }; } + if (!this.isAccountActive(originAppId)) + return { saved: false, connectionError: 'Account changed' }; const node = { ...nodeDetail }; diff --git a/src/store/reducers/bhr.ts b/src/store/reducers/bhr.ts index dcd6edd455..1effed9274 100644 --- a/src/store/reducers/bhr.ts +++ b/src/store/reducers/bhr.ts @@ -42,16 +42,24 @@ const initialState: { backupAllLoading: boolean; backupAllSuccess: boolean; backupAllFailure: boolean; + backupAllLoadingByAppId: Record; + backupAllSuccessByAppId: Record; + backupAllFailureByAppId: Record; pendingAllBackup: boolean; + pendingAllBackupByAppId: Record; backupRepairCompletedByAppId: Record; backupRepairStateByAppId: Record; backupRepairRunningByAppId: Record; + // The legacy flag is retained only until the first authenticated migration. automaticCloudBackup: boolean; + automaticCloudBackupByAppId: Record; deleteBackupSuccess: boolean; deleteBackupFailure: boolean; + deleteBackupSuccessByAppId: Record; + deleteBackupFailureByAppId: Record; homeToastMessage: homeToastMessageType; } = { backupMethod: null, @@ -86,20 +94,32 @@ const initialState: { backupAllLoading: false, backupAllFailure: false, backupAllSuccess: false, + backupAllLoadingByAppId: {}, + backupAllSuccessByAppId: {}, + backupAllFailureByAppId: {}, pendingAllBackup: false, + pendingAllBackupByAppId: {}, backupRepairCompletedByAppId: {}, backupRepairStateByAppId: {}, backupRepairRunningByAppId: {}, automaticCloudBackup: false, + automaticCloudBackupByAppId: {}, deleteBackupSuccess: false, deleteBackupFailure: false, + deleteBackupSuccessByAppId: {}, + deleteBackupFailureByAppId: {}, homeToastMessage: { message: null, isError: false }, }; +export const isAutomaticCloudBackupEnabled = ( + backup: { automaticCloudBackupByAppId?: Record }, + appId?: string +): boolean => !!appId && backup.automaticCloudBackupByAppId?.[appId] === true; + const bhrSlice = createSlice({ name: 'bhr', initialState, @@ -218,19 +238,40 @@ const bhrSlice = createSlice({ resetSeedWords: (state) => { state.seedWords = []; }, - setBackupAllLoading: (state, action: PayloadAction) => { - state.backupAllLoading = action.payload; - }, - setBackupAllSuccess: (state, action: PayloadAction) => { - state.backupAllSuccess = action.payload; - state.backupAllLoading = false; - }, - setBackupAllFailure: (state, action: PayloadAction) => { - state.backupAllFailure = action.payload; - state.backupAllLoading = false; - }, - setPendingAllBackup: (state, action: PayloadAction) => { - state.pendingAllBackup = action.payload; + setBackupAllLoading: ( + state, + action: PayloadAction<{ appId: string; status: boolean }> + ) => { + const { appId, status } = action.payload; + if (!appId) return; + (state.backupAllLoadingByAppId ??= {})[appId] = status; + }, + setBackupAllSuccess: ( + state, + action: PayloadAction<{ appId: string; status: boolean }> + ) => { + const { appId, status } = action.payload; + if (!appId) return; + (state.backupAllSuccessByAppId ??= {})[appId] = status; + (state.backupAllLoadingByAppId ??= {})[appId] = false; + }, + setBackupAllFailure: ( + state, + action: PayloadAction<{ appId: string; status: boolean }> + ) => { + const { appId, status } = action.payload; + if (!appId) return; + (state.backupAllFailureByAppId ??= {})[appId] = status; + (state.backupAllLoadingByAppId ??= {})[appId] = false; + }, + setPendingAllBackup: ( + state, + action: PayloadAction<{ appId: string; pending: boolean }> + ) => { + const { appId, pending } = action.payload; + if (!appId) return; + (state.pendingAllBackupByAppId ??= {})[appId] = pending; + state.pendingAllBackup = false; }, setBackupRepairState: (state, action: PayloadAction<{ appId: string; phase: RepairPhase }>) => { @@ -246,14 +287,45 @@ const bhrSlice = createSlice({ if (state.backupRepairStateByAppId?.[action.payload] === 'verified') state.backupRepairStateByAppId[action.payload] = 'unverified'; }, - setAutomaticCloudBackup: (state, action: PayloadAction) => { - state.automaticCloudBackup = action.payload; - }, - setDeleteBackupSuccess: (state, action: PayloadAction) => { - state.deleteBackupSuccess = action.payload; - }, - setDeleteBackupFailure: (state, action: PayloadAction) => { - state.deleteBackupFailure = action.payload; + setAutomaticCloudBackup: ( + state, + action: PayloadAction<{ appId: string; enabled: boolean }> + ) => { + const { appId, enabled } = action.payload; + if (!appId) return; + (state.automaticCloudBackupByAppId ??= {})[appId] = enabled; + if (!enabled) (state.backupAllSuccessByAppId ??= {})[appId] = false; + state.automaticCloudBackup = false; + }, + migrateLegacyAutomaticCloudBackup: ( + state, + action: PayloadAction<{ appId: string; canAttributeConsent: boolean }> + ) => { + const { appId, canAttributeConsent } = action.payload; + if (state.automaticCloudBackup && appId && canAttributeConsent) { + const byAppId = (state.automaticCloudBackupByAppId ??= {}); + if (byAppId[appId] === undefined) byAppId[appId] = true; + (state.pendingAllBackupByAppId ??= {})[appId] = true; + } + // An unbound legacy flag must never authorize uploads for another account. + state.automaticCloudBackup = false; + state.pendingAllBackup = false; + }, + setDeleteBackupSuccess: ( + state, + action: PayloadAction<{ appId: string; status: boolean }> + ) => { + const { appId, status } = action.payload; + if (!appId) return; + (state.deleteBackupSuccessByAppId ??= {})[appId] = status; + }, + setDeleteBackupFailure: ( + state, + action: PayloadAction<{ appId: string; status: boolean }> + ) => { + const { appId, status } = action.payload; + if (!appId) return; + (state.deleteBackupFailureByAppId ??= {})[appId] = status; }, setHomeToastMessage: (state, action: PayloadAction) => { state.homeToastMessage = action.payload; @@ -306,6 +378,7 @@ export const { invalidateBackupRepair, setAutomaticCloudBackup, + migrateLegacyAutomaticCloudBackup, setDeleteBackupSuccess, setDeleteBackupFailure, @@ -346,9 +419,14 @@ const bhrPersistConfig = { 'backupAllLoading', 'backupAllFailure', 'backupAllSuccess', + 'backupAllLoadingByAppId', + 'backupAllFailureByAppId', + 'backupAllSuccessByAppId', 'deleteBackupSuccess', 'deleteBackupFailure', + 'deleteBackupSuccessByAppId', + 'deleteBackupFailureByAppId', 'homeToastMessage', ], diff --git a/src/store/reducers/storage.ts b/src/store/reducers/storage.ts index ab7363fd2c..2545477d70 100644 --- a/src/store/reducers/storage.ts +++ b/src/store/reducers/storage.ts @@ -40,6 +40,7 @@ const initialState: { delayedPolicyUpdate: { [policyId: string]: DelayedPolicyUpdate }; // contains a single policy update at a time plebDueToOffline: boolean; // app downgraded to pleb due to internet issue wasAutoUpdateEnabledBeforeDowngrade: boolean; + wasAutoUpdateEnabledBeforeDowngradeByAppId: Record; defaultWalletCreated: { [NetworkType.MAINNET]: boolean; [NetworkType.TESTNET]: boolean; @@ -78,6 +79,7 @@ const initialState: { delayedPolicyUpdate: {}, plebDueToOffline: false, wasAutoUpdateEnabledBeforeDowngrade: false, + wasAutoUpdateEnabledBeforeDowngradeByAppId: {}, defaultWalletCreated: { [NetworkType.MAINNET]: false, [NetworkType.TESTNET]: false, @@ -145,8 +147,14 @@ const storageSlice = createSlice({ setPlebDueToOffline: (state, action: PayloadAction) => { state.plebDueToOffline = action.payload; }, - setAutoUpdateEnabledBeforeDowngrade: (state, action: PayloadAction) => { - state.wasAutoUpdateEnabledBeforeDowngrade = action.payload; + setAutoUpdateEnabledBeforeDowngrade: ( + state, + action: PayloadAction<{ appId: string; enabled: boolean }> + ) => { + const { appId, enabled } = action.payload; + if (!appId) return; + (state.wasAutoUpdateEnabledBeforeDowngradeByAppId ??= {})[appId] = enabled; + state.wasAutoUpdateEnabledBeforeDowngrade = false; }, setDefaultWalletCreated: ( state, diff --git a/src/store/sagaActions/bhr.ts b/src/store/sagaActions/bhr.ts index 24ed5515ad..876d8f34d9 100644 --- a/src/store/sagaActions/bhr.ts +++ b/src/store/sagaActions/bhr.ts @@ -15,8 +15,9 @@ export const SET_AUTOMATIC_CLOUD_BACKUP = 'SET_AUTOMATIC_CLOUD_BACKUP'; export const DELETE_BACKUP = 'DELETE_BACKUP'; export const VALIDATE_SERVER_BACKUP = 'VALIDATE_SERVER_BACKUP'; -export const updateAppImage = ({ wallets, signers, updateNodes }) => ({ +export const updateAppImage = ({ wallets, signers, updateNodes }, originAppId?: string) => ({ type: UPDATE_APP_IMAGE, + ...(originAppId ? { originAppId } : {}), payload: { wallets, signers, @@ -90,8 +91,9 @@ export const bsmsCloudHealthCheck = () => ({ type: BSMS_CLOUD_HEALTH_CHECK, }); -export const backupAllSignersAndVaults = () => ({ +export const backupAllSignersAndVaults = (appId: string) => ({ type: BACKUP_ALL_SIGNERS_AND_VAULTS, + appId, }); export const setAutomaticCloudBackup = (payload) => ({ @@ -99,16 +101,18 @@ export const setAutomaticCloudBackup = (payload) => ({ payload, }); -export const deleteBackup = () => ({ +export const deleteBackup = (appId: string) => ({ type: DELETE_BACKUP, + appId, }); -export const validateServerBackup = (callback) => ({ +export const validateServerBackup = (callback, originAppId: string) => ({ type: VALIDATE_SERVER_BACKUP, callback, + originAppId, }); export const CHECK_BACKUP_FRESHNESS = 'CHECK_BACKUP_FRESHNESS'; export const REPAIR_BACKUP = 'REPAIR_BACKUP'; -export const checkBackupFreshness = () => ({ type: CHECK_BACKUP_FRESHNESS }); -export const repairBackup = () => ({ type: REPAIR_BACKUP }); +export const checkBackupFreshness = (appId: string) => ({ type: CHECK_BACKUP_FRESHNESS, appId }); +export const repairBackup = (appId: string) => ({ type: REPAIR_BACKUP, appId }); diff --git a/src/store/sagaActions/send_and_receive.ts b/src/store/sagaActions/send_and_receive.ts index cb18d384af..9b475b67e2 100644 --- a/src/store/sagaActions/send_and_receive.ts +++ b/src/store/sagaActions/send_and_receive.ts @@ -54,6 +54,7 @@ export const sendPhaseOne = (payload: { export interface SendPhaseTwoAction extends Action { type: typeof SEND_PHASE_TWO; + originAppId?: string; payload: { wallet: Wallet | Vault; currentBlockHeight: number; @@ -75,13 +76,15 @@ export const sendPhaseTwo = (payload: { selectedPhase: number; selectedPaths: number[]; }; -}): SendPhaseTwoAction => ({ +}, originAppId?: string): SendPhaseTwoAction => ({ type: SEND_PHASE_TWO, payload, + originAppId, }); export interface SendPhaseThreeAction extends Action { type: typeof SEND_PHASE_THREE; + originAppId?: string; payload: { wallet: Wallet | Vault; txnPriority: TxPriority; @@ -101,9 +104,10 @@ export const sendPhaseThree = (payload: { selectedPhase: number; selectedPaths: number[]; }; -}): SendPhaseThreeAction => ({ +}, originAppId?: string): SendPhaseThreeAction => ({ type: SEND_PHASE_THREE, payload, + originAppId, }); export interface CalculateSendMaxFeeAction extends Action { @@ -164,7 +168,8 @@ export const calculateCustomFee = (payload: { payload, }); -export const discardBroadcastedTnx = ({ cachedTxid, vault }) => ({ +export const discardBroadcastedTnx = ({ cachedTxid, vault }, originAppId?: string) => ({ type: DISCARD_BROADCASTED_TNX, payload: { cachedTxid, vault }, + originAppId, }); diff --git a/src/store/sagaActions/upgrade.ts b/src/store/sagaActions/upgrade.ts index d6b6a14fc7..c6546a99ab 100644 --- a/src/store/sagaActions/upgrade.ts +++ b/src/store/sagaActions/upgrade.ts @@ -2,11 +2,13 @@ export const RESET_REDUX_STORE = 'RESET_REDUX_STORE'; export const UPDATE_VERSION_HISTORY = 'UPDATE_VERSION_HISTORY'; export const MIGRATE_LABELS_329 = 'MIGRATE_LABELS_329'; -export const updateVersionHistory = (previousVersion, newVersion, isRecovery = false) => ({ +export const updateVersionHistory = (previousVersion, newVersion, isRecovery = false, originAppId?: string) => ({ type: UPDATE_VERSION_HISTORY, payload: { previousVersion, newVersion, isRecovery }, + originAppId, }); -export const migrateLabelsToBip329 = () => ({ +export const migrateLabelsToBip329 = (originAppId?: string) => ({ type: MIGRATE_LABELS_329, + originAppId, }); diff --git a/src/store/sagaActions/utxos.ts b/src/store/sagaActions/utxos.ts index 3307b81f54..0ae52ccfac 100644 --- a/src/store/sagaActions/utxos.ts +++ b/src/store/sagaActions/utxos.ts @@ -14,9 +14,10 @@ export const addLabels = (payload: { wallet: Wallet | Vault; labels: { name: string; isSystem: boolean }[]; type; -}) => ({ +}, originAppId?: string) => ({ type: ADD_LABELS, payload, + originAppId, }); export const bulkUpdateLabels = (payload: { @@ -28,9 +29,10 @@ export const bulkUpdateLabels = (payload: { txId?: string; address?: string; wallet: Wallet; -}) => ({ +}, originAppId?: string) => ({ type: BULK_UPDATE_LABELS, payload, + originAppId, }); export const importLabels = (payload: { @@ -42,9 +44,10 @@ export const importLabels = (payload: { origin: string; } ]; -}) => ({ +}, originAppId?: string) => ({ type: IMPORT_LABELS, payload, + originAppId, }); export const markUTXOSpendability = (payload: { @@ -52,7 +55,8 @@ export const markUTXOSpendability = (payload: { txId: string; vout: number; spendability: UTXOSpendability; -}) => ({ +}, originAppId?: string) => ({ type: MARK_UTXO_SPENDABILITY, payload, + originAppId, }); diff --git a/src/store/sagaActions/wallets.ts b/src/store/sagaActions/wallets.ts index b9078e1e3e..1e19a5adcd 100644 --- a/src/store/sagaActions/wallets.ts +++ b/src/store/sagaActions/wallets.ts @@ -30,14 +30,15 @@ export const autoSyncWallets = ( syncAll?: boolean, hardRefresh?: boolean, addNotifications?: boolean, - backupCheckAppId?: string + originAppId?: string ) => ({ type: AUTO_SYNC_WALLETS, + ...(originAppId ? { originAppId } : {}), payload: { syncAll, hardRefresh, addNotifications, - backupCheckAppId, + backupCheckAppId: originAppId, }, }); @@ -48,9 +49,11 @@ export const updateSignerPolicy = ( restrictions: SignerRestriction; signingDelay: number; }, - verificationToken + verificationToken, + originAppId?: string ) => ({ type: UPDATE_SIGNER_POLICY, + originAppId, payload: { signer, signingKey, @@ -139,8 +142,9 @@ export const updateKeyDetails = (signer: VaultSigner, key: string, value: any) = }, }); -export const generateNewAddress = (wallet: Wallet | Vault) => ({ +export const generateNewAddress = (wallet: Wallet | Vault, originAppId?: string) => ({ type: GENERATE_NEW_ADDRESS, + originAppId, payload: { wallet }, }); diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 206aaceb2d..152ac95bcf 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -48,6 +48,7 @@ import { appImagerecoveryRetry, setAppImageError, setAutomaticCloudBackup, + isAutomaticCloudBackupEnabled, setBackupAllFailure, setBackupAllLoading, setBackupAllSuccess, @@ -83,7 +84,7 @@ import { import { uaiActioned, uaiChecks } from '../sagaActions/uai'; import { setAppCreated, setAppId, setDefaultWalletCreated } from '../reducers/storage'; import { applyUpgradeSequence, KEY_MANAGEMENT_VERSION } from './upgrade'; -import { RootState } from '../store'; +import { RootState, store } from '../store'; import { setupRecoveryKeySigningKey } from 'src/hardware/signerSetup'; import { addNewWalletsWorker, addSigningDeviceWorker, NewWalletInfo } from './wallets'; import { @@ -97,17 +98,33 @@ import { addAccount, saveDefaultWalletState, setRecoveryKeyStatus } from '../red import { loadConciergeTickets, loadConciergeUser } from '../reducers/concierge'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; +function currentBackupAppId(): string | undefined { + try { + const id = (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id; + return id && store.getState().storage.appId === id ? id : undefined; + } catch { + return undefined; + } +} + export function* updateAppImageWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { wallets?: Wallet[] | USDTWallet[]; signers?: Signer[]; updateNodes?: boolean; }; }) { + const appId = originAppId || currentBackupAppId(); + if (!appId || currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; try { - const backupResponse = yield call(checkBackupCondition); + const backupResponse = yield call(checkBackupCondition, appId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; if (backupResponse) return { updated: true, error: '' }; const { wallets, signers, updateNodes } = payload; @@ -115,6 +132,7 @@ export function* updateAppImageWorker({ dbManager.getObjectByIndex, RealmSchema.KeeperApp ); + if (id !== appId) return { updated: false, error: 'Backup account changed' }; const walletsObject = {}; const signersObject = {}; const nodesList = []; @@ -145,6 +163,9 @@ export function* updateAppImageWorker({ } } + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; + const response = yield call(Relay.updateAppImage, { appId: id, publicId, @@ -156,26 +177,33 @@ export function* updateAppImageWorker({ nodes: nodesList, replaceNodes: !!updateNodes, }); - if (!response?.updated) yield call(setServerBackupFailed); + if (!response?.updated) yield call(setServerBackupFailed, appId); return response; } catch (err) { console.log({ err }); console.error('App image update failed', err); - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, appId); return { updated: true, error: '' }; } } export function* updateVaultImageWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { vault: Vault; archiveVaultId?: string; isUpdate?: boolean; }; }) { - const backupResponse = yield call(checkBackupCondition); + const appId = originAppId || currentBackupAppId(); + if (!appId || currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; + const backupResponse = yield call(checkBackupCondition, appId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; if (backupResponse) return { updated: true, error: '' }; const { vault, archiveVaultId, isUpdate } = payload; @@ -183,6 +211,7 @@ export function* updateVaultImageWorker({ dbManager.getObjectByIndex, RealmSchema.KeeperApp ); + if (id !== appId) return { updated: false, error: 'Backup account changed' }; const encryptionKey = generateEncryptionKey(primarySeed); const vaultEncrypted = encrypt( encryptionKey, @@ -200,6 +229,8 @@ export function* updateVaultImageWorker({ xfpHash: hash256(signer.masterFingerprint), }); } + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; if (isUpdate) { const response = yield call(Relay.updateVaultImage, { @@ -229,7 +260,7 @@ export function* updateVaultImageWorker({ return response; } catch (err) { captureError(err); - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, appId); return { updated: true, error: '' }; } } @@ -237,18 +268,26 @@ export function* updateVaultImageWorker({ // TODO: Other functions here only handle Relay backup, but this also updates local DB, should move that part out export function* deleteAppImageEntityWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { signerIds?: string[]; walletIds?: string[]; }; }) { + const appId = originAppId || currentBackupAppId(); + if (!appId || currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; try { const { signerIds, walletIds } = payload; const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (id !== appId) return { updated: false, error: 'Backup account changed' }; let response; - const backupResponse = yield call(checkBackupCondition); + const backupResponse = yield call(checkBackupCondition, appId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; if (backupResponse) response = { updated: true, error: '' }; else { response = yield call(Relay.deleteAppImageEntity, { @@ -258,14 +297,46 @@ export function* deleteAppImageEntityWorker({ }); } + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; + if (response?.updated !== true) { + yield put(setPendingAllBackup({ appId, pending: true })); + yield call(setServerBackupFailed, appId); + return response || { updated: false, error: 'Backup deletion not confirmed' }; + } + const remoteDeleteSucceeded = !backupResponse; + if (walletIds?.length > 0) { for (const walletId of walletIds) { - yield call(dbManager.deleteObjectById, RealmSchema.Wallet, walletId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; + const deleted = yield call(dbManager.deleteObjectById, RealmSchema.Wallet, walletId); + if (deleted !== true) { + if (remoteDeleteSucceeded) { + yield put(setPendingAllBackup({ appId, pending: true })); + yield call(setServerBackupFailed, appId); + } + return { updated: false, error: 'Local wallet deletion failed' }; + } } } if (signerIds?.length > 0) { for (const signerId of signerIds) { - yield call(dbManager.deleteObjectByPrimaryKey, RealmSchema.Signer, 'id', signerId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; + const deleted = yield call( + dbManager.deleteObjectByPrimaryKey, + RealmSchema.Signer, + 'id', + signerId + ); + if (deleted !== true) { + if (remoteDeleteSucceeded) { + yield put(setPendingAllBackup({ appId, pending: true })); + yield call(setServerBackupFailed, appId); + } + return { updated: false, error: 'Local signer deletion failed' }; + } } } return response; @@ -277,16 +348,24 @@ export function* deleteAppImageEntityWorker({ export function* deleteVaultImageWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { vaultIds: string[]; }; }) { + const appId = originAppId || currentBackupAppId(); + if (!appId || currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; try { - const backupResponse = yield call(checkBackupCondition); + const backupResponse = yield call(checkBackupCondition, appId); + if (currentBackupAppId() !== appId) + return { updated: false, error: 'Backup account changed' }; if (backupResponse) return { updated: true, error: '' }; const { vaultIds } = payload; const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (id !== appId) return { updated: false, error: 'Backup account changed' }; const response = yield call(Relay.deleteVaultImage, { appId: id, vaults: vaultIds, @@ -458,7 +537,7 @@ function* getAppImageWorker({ payload }) { } } yield put(addAccount(appID)); - yield put(autoSyncWallets(true, true, false)); + yield put(autoSyncWallets(true, true, false, appID)); yield put( saveDefaultWalletState({ appId: appID, @@ -525,6 +604,7 @@ function* recoverApp( }; yield call(writeRecoveredObject, RealmSchema.KeeperApp, app); + yield put(setAppId(appID)); // Wallet recreation if (appImage.wallets) { @@ -700,7 +780,6 @@ function* recoverApp( title: 'Recovered Wallet', }); - yield put(setAppId(appID)); } function* writeRecoveredObject(schema: RealmSchema, record: any) { @@ -978,12 +1057,13 @@ export const deleteAppImageEntityWatcher = createWatcher( DELETE_APP_IMAGE_ENTITY ); -function* runBackupInspection(repair: boolean) { +function* runBackupInspection(repair: boolean, expectedAppId?: string, explicitChoice = false) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (expectedAppId && id !== expectedAppId) return false; yield put(setBackupRepairRunning({ appId: id, running: true })); let finalPhase: RepairPhase = 'unverified'; const updates = eventChannel((emit) => { - inspectBackup(id, repair, (phase) => emit(phase)).then( + inspectBackup(id, repair, (phase) => emit(phase), explicitChoice).then( () => emit(END), () => emit(END) ); @@ -997,20 +1077,26 @@ function* runBackupInspection(repair: boolean) { yield put(setBackupRepairState({ appId: id, phase })); } const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - if (current?.id === id) { - yield put(setPendingAllBackup(finalPhase !== 'verified')); + const ownerIsActive = yield select((state: RootState) => state.storage.appId === id); + if (current?.id === id && ownerIsActive) { + yield put(setPendingAllBackup({ appId: id, pending: finalPhase !== 'verified' })); if (finalPhase === 'verified') { const notifications = dbManager.getObjectByField( RealmSchema.UAI, uaiType.SERVER_BACKUP_FAILURE, 'uaiType' - ); - for (const uai of notifications) + ) as unknown as Array<{ id: string }>; + for (const uai of notifications) { + const stillActive = yield select((state: RootState) => state.storage.appId === id); + if (!stillActive || currentBackupAppId() !== id) break; yield call(uaiActionedWorker, { payload: { uaiId: uai.id, action: true } }); + } } else if ( !dbManager.getObjectByField(RealmSchema.UAI, uaiType.SERVER_BACKUP_FAILURE, 'uaiType') ?.length ) { + const stillActive = yield select((state: RootState) => state.storage.appId === id); + if (!stillActive || currentBackupAppId() !== id) return false; yield call(addToUaiStackWorker, { payload: { uaiType: uaiType.SERVER_BACKUP_FAILURE, @@ -1029,29 +1115,40 @@ function* runBackupInspection(repair: boolean) { } } -function* backupFreshnessWorker({ type }) { - const { automaticCloudBackup } = yield select((state: RootState) => state.bhr); - if (!automaticCloudBackup) return; - yield call(runBackupInspection, type === REPAIR_BACKUP); +function* backupFreshnessWorker({ type, appId }) { + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (!appId || id !== appId) return; + const enabled = yield select((state: RootState) => + state.storage.appId === appId && isAutomaticCloudBackupEnabled(state.bhr, appId) + ); + if (!enabled) return; + yield call(runBackupInspection, type === REPAIR_BACKUP, appId); } export function* backupFreshnessWatcher() { yield takeEvery([CHECK_BACKUP_FRESHNESS, REPAIR_BACKUP], backupFreshnessWorker); } -function* backupAllSignersAndVaultsWorker() { +function* backupAllSignersAndVaultsWorker({ appId }: { appId: string }) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - yield put(setBackupAllSuccess(false)); - yield put(setBackupAllFailure(false)); - yield put(setBackupAllLoading(true)); + if (!appId || appId !== id) return false; + yield put(setBackupAllSuccess({ appId, status: false })); + yield put(setBackupAllFailure({ appId, status: false })); + yield put(setBackupAllLoading({ appId, status: true })); try { - const verified = yield call(runBackupInspection, true); + const verified = yield call(runBackupInspection, true, appId, true); const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - if (current?.id === id) - yield put(verified ? setBackupAllSuccess(true) : setBackupAllFailure(true)); + if (current?.id === id) { + if (verified) yield put(setAutomaticCloudBackup({ appId, enabled: true })); + yield put( + verified + ? setBackupAllSuccess({ appId, status: true }) + : setBackupAllFailure({ appId, status: true }) + ); + } return verified; } finally { - yield put(setBackupAllLoading(false)); + yield put(setBackupAllLoading({ appId, status: false })); } } @@ -1060,37 +1157,53 @@ export const backupAllSignersAndVaultsWatcher = createWatcher( BACKUP_ALL_SIGNERS_AND_VAULTS ); -function* deleteBackupWorker() { - yield put(setBackupAllLoading(true)); +function* deleteBackupWorker({ appId }: { appId: string }) { + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (!appId || appId !== id) return false; + yield put(setBackupAllLoading({ appId, status: true })); try { - const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - - yield call(Relay.deleteBackup, { - appId: id, + const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (current?.id !== appId) return false; + const response = yield call(Relay.deleteBackup, { + appId, }); - yield put(setDeleteBackupSuccess(true)); - yield put(setPendingAllBackup(false)); + if (response?.updated !== true && response?.data?.updated !== true) + throw new Error('Backup deletion not confirmed'); + const afterDelete: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (afterDelete?.id !== appId) return false; + yield put(setAutomaticCloudBackup({ appId, enabled: false })); + yield put(setDeleteBackupSuccess({ appId, status: true })); + yield put(setPendingAllBackup({ appId, pending: false })); return true; } catch (error) { - yield put(setDeleteBackupFailure(true)); + yield put(setDeleteBackupFailure({ appId, status: true })); console.log('🚀 ~ deleteBackupWorker ~ error:', error); return false; } finally { - yield put(setBackupAllLoading(false)); + yield put(setBackupAllLoading({ appId, status: false })); } } export const deleteBackupWatcher = createWatcher(deleteBackupWorker, DELETE_BACKUP); -export function* checkBackupCondition() { - const { automaticCloudBackup } = yield select((state: RootState) => state.bhr); - if (!automaticCloudBackup) return true; +export function* checkBackupCondition(expectedAppId?: string) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (expectedAppId && expectedAppId !== id) return true; + const enabled = yield select((state: RootState) => + state.storage.appId === id && isAutomaticCloudBackupEnabled(state.bhr, id) + ); + if (!enabled) return true; markBackupMutation(id); yield put(invalidateBackupRepair(id)); const netInfo = yield call(NetInfo.fetch); + const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + const stillEnabled = yield select((state: RootState) => + state.storage.appId === id && isAutomaticCloudBackupEnabled(state.bhr, id) + ); + if (current?.id !== id || (expectedAppId && current.id !== expectedAppId) || !stillEnabled) + return true; if (!netInfo.isConnected) { - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, id); return true; } // Never suppress this incremental write or replace it with a snapshot: wallet @@ -1099,19 +1212,27 @@ export function* checkBackupCondition() { return false; } -export function* setServerBackupFailed() { +export function* setServerBackupFailed(expectedAppId?: string) { + const { id: appId }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (expectedAppId && expectedAppId !== appId) return; + const ownerIsActive = yield select((state: RootState) => state.storage.appId === appId); + if (!ownerIsActive || currentBackupAppId() !== appId) return; const uaiCollection = dbManager.getObjectByField( RealmSchema.UAI, uaiType.SERVER_BACKUP_FAILURE, 'uaiType' - ); + ) as unknown as Array<{ id: string; uaiType: uaiType }>; for (const uai of uaiCollection) { if (uai.uaiType === uaiType.SERVER_BACKUP_FAILURE) { + const stillActive = yield select((state: RootState) => state.storage.appId === appId); + if (!stillActive || currentBackupAppId() !== appId) return; yield call(uaiActionedWorker, { payload: { uaiId: uai.id, action: false }, }); } } + const stillActive = yield select((state: RootState) => state.storage.appId === appId); + if (!stillActive || currentBackupAppId() !== appId) return; yield call(addToUaiStackWorker, { payload: { uaiType: uaiType.SERVER_BACKUP_FAILURE, @@ -1121,16 +1242,27 @@ export function* setServerBackupFailed() { }, }, }); - yield put(setPendingAllBackup(true)); + const activeAfterNotice = yield select((state: RootState) => state.storage.appId === appId); + if (!activeAfterNotice || currentBackupAppId() !== appId) return; + yield put(setPendingAllBackup({ appId, pending: true })); } -function* validateServerBackupWorker({ callback }) { - const matched = yield call(runBackupInspection, false); +function* validateServerBackupWorker({ callback, originAppId }) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (!originAppId || originAppId !== id) { + callback({ status: false, error: true, message: 'Backup account changed.' }); + return; + } + const matched = yield call(runBackupInspection, false, originAppId); + const stillActive = yield select((state: RootState) => state.storage.appId === originAppId); + if (!stillActive || currentBackupAppId() !== originAppId) { + callback({ status: false, error: true, message: 'Backup account changed.' }); + return; + } const { backupRepairStateByAppId = {} } = yield select((state: RootState) => state.bhr); callback({ status: matched, - error: backupRepairStateByAppId[id] === 'unverified', + error: backupRepairStateByAppId[originAppId] === 'unverified', message: matched ? 'Backup verified successfully.' : 'Backup could not be verified.', }); } diff --git a/src/store/sagas/login.ts b/src/store/sagas/login.ts index 93465bf271..60e95eb749 100644 --- a/src/store/sagas/login.ts +++ b/src/store/sagas/login.ts @@ -57,7 +57,11 @@ import { resetSyncing } from '../reducers/wallets'; import { autoSyncWallets } from '../sagaActions/wallets'; import { connectToNode } from '../sagaActions/network'; import { fetchDelayedPolicyUpdate, fetchSignedDelayedTransaction } from '../sagaActions/storage'; -import { setAutomaticCloudBackup, setBackupType } from '../reducers/bhr'; +import { + setAutomaticCloudBackup, + setBackupType, + migrateLegacyAutomaticCloudBackup, +} from '../reducers/bhr'; import { addAccount, saveDefaultWalletState, @@ -185,11 +189,21 @@ function* credentialsAuthWorker({ payload }) { } const previousVersion = yield select((state) => state.storage.appVersion); - const { plebDueToOffline, wasAutoUpdateEnabledBeforeDowngrade, defaultWalletCreated } = - yield select((state) => state.storage); + const { defaultWalletCreated } = yield select((state) => state.storage); // setting correct app id from realm at login const keeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (keeperApp?.id) { + const onlyKnownAccount = + allAccounts.length <= 1 && + (!allAccounts.length || allAccounts[0].appId === keeperApp.id); + yield put( + migrateLegacyAutomaticCloudBackup({ + appId: keeperApp.id, + canAttributeConsent: onlyKnownAccount && appId === keeperApp.id, + }) + ); + } if (keeperApp?.id) yield put(setAppId(keeperApp.id)); // Store temporary account details @@ -292,14 +306,16 @@ async function downgradeToPleb() { subscription: updatedSubscription, }); store.dispatch(setSubscription(updatedSubscription.name)); - store.dispatch(setAutomaticCloudBackup(false)); + store.dispatch(setAutomaticCloudBackup({ appId: app.id, enabled: false })); await Relay.updateSubscription(app.id, app.publicId, { productId: SubscriptionTier.L1.toLowerCase(), }); } -async function updateSubscriptionFromRelayData(data, wasAutoUpdateEnabledBeforeDowngrade) { +async function updateSubscriptionFromRelayData(data) { const app: KeeperApp = await dbManager.getObjectByIndex(RealmSchema.KeeperApp); + const wasAutoUpdateEnabledBeforeDowngrade = + store.getState().storage.wasAutoUpdateEnabledBeforeDowngradeByAppId?.[app.id] === true; const isBtcPayment = data?.paymentType == 'btc_payment'; let updatedSubscription: SubScription; if (isBtcPayment) { @@ -322,9 +338,11 @@ async function updateSubscriptionFromRelayData(data, wasAutoUpdateEnabledBeforeD subscription: updatedSubscription, }); store.dispatch(setSubscription(updatedSubscription.name)); - store.dispatch(setAutomaticCloudBackup(wasAutoUpdateEnabledBeforeDowngrade)); + store.dispatch( + setAutomaticCloudBackup({ appId: app.id, enabled: wasAutoUpdateEnabledBeforeDowngrade }) + ); store.dispatch(setPlebDueToOffline(false)); - store.dispatch(setAutoUpdateEnabledBeforeDowngrade(false)); + store.dispatch(setAutoUpdateEnabledBeforeDowngrade({ appId: app.id, enabled: false })); } export const credentialsAuthWatcher = createWatcher(credentialsAuthWorker, CREDS_AUTH); diff --git a/src/store/sagas/send_and_receive.ts b/src/store/sagas/send_and_receive.ts index f9c988a13b..12b95f0eb8 100644 --- a/src/store/sagas/send_and_receive.ts +++ b/src/store/sagas/send_and_receive.ts @@ -129,7 +129,7 @@ function* sendPhaseOneWorker({ payload }: SendPhaseOneAction) { export const sendPhaseOneWatcher = createWatcher(sendPhaseOneWorker, SEND_PHASE_ONE); -function* sendPhaseTwoWorker({ payload }: SendPhaseTwoAction) { +function* sendPhaseTwoWorker({ payload, originAppId }: SendPhaseTwoAction & { originAppId?: string }) { if (!ELECTRUM_CLIENT.isClientConnected) { ElectrumClient.resetCurrentPeerIndex(); yield call(connectToNodeWorker); @@ -170,6 +170,7 @@ function* sendPhaseTwoWorker({ payload }: SendPhaseTwoAction) { if (!txid) throw new Error('Send failed: unable to generate txid'); if (note) { yield call(addLabelsWorker, { + originAppId, payload: { txId: txid, wallet, @@ -205,7 +206,7 @@ function* sendPhaseTwoWorker({ payload }: SendPhaseTwoAction) { } if (finalOutputs) { - yield call(handleChangeOutputLabels, finalOutputs, inputs, wallet, txid); + yield call(handleChangeOutputLabels, finalOutputs, inputs, wallet, txid, originAppId); } } catch (err) { if ([ELECTRUM_NOT_CONNECTED_ERR, ELECTRUM_NOT_CONNECTED_ERR_TOR].includes(err?.message)) { @@ -223,7 +224,7 @@ function* sendPhaseTwoWorker({ payload }: SendPhaseTwoAction) { export const sendPhaseTwoWatcher = createWatcher(sendPhaseTwoWorker, SEND_PHASE_TWO); -function* sendPhaseThreeWorker({ payload }: SendPhaseThreeAction) { +function* sendPhaseThreeWorker({ payload, originAppId }: SendPhaseThreeAction & { originAppId?: string }) { if (!ELECTRUM_CLIENT.isClientConnected) { ElectrumClient.resetCurrentPeerIndex(); yield call(connectToNodeWorker); @@ -276,6 +277,7 @@ function* sendPhaseThreeWorker({ payload }: SendPhaseThreeAction) { if (note) { yield call(addLabelsWorker, { + originAppId, payload: { txId: txid, wallet, @@ -286,7 +288,7 @@ function* sendPhaseThreeWorker({ payload }: SendPhaseThreeAction) { } if (finalOutputs) { - yield call(handleChangeOutputLabels, finalOutputs, inputs, wallet, txid); + yield call(handleChangeOutputLabels, finalOutputs, inputs, wallet, txid, originAppId); } } catch (err) { if ([ELECTRUM_NOT_CONNECTED_ERR, ELECTRUM_NOT_CONNECTED_ERR_TOR].includes(err?.message)) { @@ -304,7 +306,7 @@ function* sendPhaseThreeWorker({ payload }: SendPhaseThreeAction) { export const sendPhaseThreeWatcher = createWatcher(sendPhaseThreeWorker, SEND_PHASE_THREE); -function* handleChangeOutputLabels(finalOutputs, inputs, wallet, txid) { +function* handleChangeOutputLabels(finalOutputs, inputs, wallet, txid, originAppId?: string) { const changeOutputIndex = finalOutputs.findIndex((output) => Object.values(wallet.specs.addresses.internal).includes(output.address) ); @@ -340,6 +342,7 @@ function* handleChangeOutputLabels(finalOutputs, inputs, wallet, txid) { } yield fork(bulkUpdateLabelsWorker, { + originAppId, payload: { labelChanges, UTXO: { txId: txid, vout: changeOutputIndex }, @@ -463,7 +466,7 @@ function* calculateCustomFee({ payload }: CalculateCustomFeeAction) { export const calculateCustomFeeWatcher = createWatcher(calculateCustomFee, CALCULATE_CUSTOM_FEE); -function* discardBroadcastedTnxWorker({ payload }) { +function* discardBroadcastedTnxWorker({ payload, originAppId }) { const { cachedTxid, vault } = payload; const snapshots = yield select((state) => state.cachedTxn.snapshots); if (snapshots[cachedTxid]) { @@ -476,9 +479,10 @@ function* discardBroadcastedTnxWorker({ payload }) { }); const potentialTxId = snapshots[cachedTxid].potentialTxId; const note = snapshots[cachedTxid].routeParams.note; - yield call(handleChangeOutputLabels, finalOutputs, inputs, vault, potentialTxId); + yield call(handleChangeOutputLabels, finalOutputs, inputs, vault, potentialTxId, originAppId); if (note.length) { yield call(addLabelsWorker, { + originAppId, payload: { txId: potentialTxId, wallet: vault, @@ -512,4 +516,4 @@ const reformatExchangeRates = (rawExchangeRates) => { } }); return formattedExchangeRates; -}; \ No newline at end of file +}; diff --git a/src/store/sagas/upgrade.ts b/src/store/sagas/upgrade.ts index e7dd01185f..27055ddbfc 100644 --- a/src/store/sagas/upgrade.ts +++ b/src/store/sagas/upgrade.ts @@ -38,8 +38,8 @@ import { import { updateAppImageWorker, updateVaultImageWorker } from './bhr'; import { createWatcher } from '../utilities'; import { setAppVersion } from '../reducers/storage'; -import { setPendingAllBackup } from '../reducers/bhr'; -import { RootState } from '../store'; +import { isAutomaticCloudBackupEnabled, setPendingAllBackup } from '../reducers/bhr'; +import { RootState, store } from '../store'; export const LABELS_INTRODUCTION_VERSION = '1.0.4'; export const BIP329_INTRODUCTION_VERSION = '1.0.7'; @@ -48,6 +48,10 @@ export const APP_KEY_UPGRADE_VERSION = '1.1.12'; export const HEALTH_CHECK_TIMELINE_MIGRATION_VERSION = '1.2.6'; export const SIGNER_POLICY_MIGRATION_VERSION = '2.1.0'; +const upgradeAccountIsActive = (appId?: string) => + !!appId && store.getState().storage.appId === appId && + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id === appId; + export function* applyUpgradeSequence({ previousVersion, newVersion, @@ -58,19 +62,22 @@ export function* applyUpgradeSequence({ isRecovery?: boolean; }) { console.log(`applying upgrade sequence - from: ${previousVersion} to ${newVersion}`); + const { id: originAppId }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (!originAppId) return; if ( semver.gte(previousVersion, LABELS_INTRODUCTION_VERSION) && semver.lt(previousVersion, BIP329_INTRODUCTION_VERSION) ) { - yield put(migrateLabelsToBip329()); + yield put(migrateLabelsToBip329(originAppId)); } if (semver.lt(previousVersion, KEY_MANAGEMENT_VERSION)) { - yield call(migrateStructureforSignersInAppImage); - yield call(migrateStructureforVaultInAppImage); + yield call(migrateStructureforSignersInAppImage, originAppId); + yield call(migrateStructureforVaultInAppImage, originAppId); } - if (semver.lt(previousVersion, APP_KEY_UPGRADE_VERSION)) yield call(updateAppKeysToEnableSigning); + if (semver.lt(previousVersion, APP_KEY_UPGRADE_VERSION)) + yield call(updateAppKeysToEnableSigning, originAppId); if (semver.lt(previousVersion, HEALTH_CHECK_TIMELINE_MIGRATION_VERSION)) { yield call(healthCheckTimelineMigration); @@ -78,25 +85,36 @@ export function* applyUpgradeSequence({ if (semver.lt(previousVersion, SIGNER_POLICY_MIGRATION_VERSION)) { yield call(migrateServerKeyPolicy); - yield put(setPendingAllBackup(true)); + const app: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (app?.id === originAppId) yield put(setPendingAllBackup({ appId: originAppId, pending: true })); } + if (!upgradeAccountIsActive(originAppId)) return; yield put(setAppVersion(newVersion)); - yield put(updateVersionHistory(previousVersion, newVersion, isRecovery)); + yield put(updateVersionHistory(previousVersion, newVersion, isRecovery, originAppId)); } export function* updateVersionHistoryWorker({ payload, + originAppId, }: { payload: { previousVersion: string; newVersion: string; isRecovery?: boolean }; + originAppId?: string; }) { const { previousVersion, newVersion, isRecovery = false } = payload; try { const app: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - const response = yield call(Relay.updateAppImage, { - appId: app.id, - version: newVersion, - }); + if (!originAppId || app?.id !== originAppId) return; + const enabled = yield select((state: RootState) => + state.storage.appId === originAppId && isAutomaticCloudBackupEnabled(state.bhr, originAppId) + ); + if (enabled) { + yield call(Relay.updateAppImage, { + appId: originAppId, + version: newVersion, + }); + } + if (!upgradeAccountIsActive(originAppId)) return; yield call(dbManager.createObject, RealmSchema.VersionHistory, { version: `${newVersion}(${DeviceInfo.getBuildNumber()})`, date: new Date().toString(), @@ -116,8 +134,9 @@ export const updateVersionHistoryWatcher = createWatcher( UPDATE_VERSION_HISTORY ); -function* migrateLablesWorker() { +function* migrateLablesWorker({ originAppId }: { originAppId?: string }) { try { + if (!upgradeAccountIsActive(originAppId)) return; const UTXOLabels: UTXOInfo[] = yield call(dbManager.getCollection, RealmSchema.UTXOInfo); const tags = []; const wallets: Wallet[] = yield call(dbManager.getCollection, RealmSchema.Wallet); @@ -143,18 +162,24 @@ function* migrateLablesWorker() { }); if (tags.length) { + if (!upgradeAccountIsActive(originAppId)) return; yield call(dbManager.createObjectBulk, RealmSchema.Tags, tags); const { id, primarySeed }: KeeperApp = yield call( dbManager.getObjectByIndex, RealmSchema.KeeperApp ); + if (id !== originAppId) return; const encryptionKey = generateEncryptionKey(primarySeed); const tagsToBackup = tags.map((tag) => ({ id: hash256(hash256(encryptionKey + tag.id)), content: encrypt(encryptionKey, JSON.stringify(tag)), })); - yield call(Relay.modifyLabels, id, tagsToBackup.length ? tagsToBackup : [], []); + if (!upgradeAccountIsActive(originAppId)) return; + const enabled = yield select((state: RootState) => + state.storage.appId === originAppId && isAutomaticCloudBackupEnabled(state.bhr, originAppId) + ); + if (enabled) yield call(Relay.modifyLabels, id, tagsToBackup, []); } } catch (error) { console.log({ error }); @@ -163,11 +188,12 @@ function* migrateLablesWorker() { export const migrateLablesWatcher = createWatcher(migrateLablesWorker, MIGRATE_LABELS_329); -function* migrateStructureforSignersInAppImage() { +function* migrateStructureforSignersInAppImage(originAppId: string) { try { + if (!upgradeAccountIsActive(originAppId)) return; const wallets = yield call(dbManager.getCollection, RealmSchema.Wallet); const signers = yield call(dbManager.getCollection, RealmSchema.Signer); - const response = yield call(updateAppImageWorker, { payload: { wallets, signers } }); + const response = yield call(updateAppImageWorker, { payload: { wallets, signers }, originAppId }); if (response.updated) { console.log('Updated the Signers in app image'); } else { @@ -176,13 +202,15 @@ function* migrateStructureforSignersInAppImage() { } catch (err) {} } -function* migrateStructureforVaultInAppImage() { +function* migrateStructureforVaultInAppImage(originAppId: string) { try { + if (!upgradeAccountIsActive(originAppId)) return; const vaults: Vault[] = yield call(dbManager.getCollection, RealmSchema.Vault); const activeVault: Vault = vaults.filter((vault) => !vault.archived)[0] || null; yield call(updateVaultImageWorker, { payload: { isUpdate: true, vault: activeVault }, + originAppId, }); } catch (err) { console.log('Something went wrong in updating the vault image', err); @@ -190,8 +218,9 @@ function* migrateStructureforVaultInAppImage() { } // This function updates app keys/mobile keys to enable signing by generating and associating extended keys. -function* updateAppKeysToEnableSigning() { +function* updateAppKeysToEnableSigning(originAppId: string) { try { + if (!upgradeAccountIsActive(originAppId)) return; const wallets = yield call(dbManager.getCollection, RealmSchema.Wallet); const signers = yield call(dbManager.getCollection, RealmSchema.Signer); const keeperSigners = signers.filter( @@ -202,9 +231,10 @@ function* updateAppKeysToEnableSigning() { ); const { appKeyWalletMap, myAppKeySigners } = mapAppKeysToWallets(wallets, keeperSigners); const extendedKeyMap = generateExtendedKeysForSigners(myAppKeySigners, appKeyWalletMap); + if (!upgradeAccountIsActive(originAppId)) return; updateVaultSigners(extendedKeyMap, signers); updateSignerDetails(myAppKeySigners, extendedKeyMap); - const response = yield call(updateAppImageWorker, { payload: { signers } }); + const response = yield call(updateAppImageWorker, { payload: { signers }, originAppId }); if (response.updated) { console.log('Updated the Signers in app image'); } else { diff --git a/src/store/sagas/utxos.ts b/src/store/sagas/utxos.ts index 7f3d1addec..e08a8c83a0 100644 --- a/src/store/sagas/utxos.ts +++ b/src/store/sagas/utxos.ts @@ -1,7 +1,7 @@ import dbManager from 'src/storage/realm/dbManager'; import { RealmSchema } from 'src/storage/realm/enum'; -import { call, delay, fork, put, takeLatest } from 'redux-saga/effects'; -import { BIP329Label, UTXO, UTXOSpendability } from 'src/services/wallets/interfaces'; +import { call, delay, put } from 'redux-saga/effects'; +import { BIP329Label, UTXOSpendability } from 'src/services/wallets/interfaces'; import { EntityKind, LabelRefType } from 'src/services/wallets/enums'; import Relay from 'src/services/backend/Relay'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; @@ -10,6 +10,7 @@ import { Vault } from 'src/services/wallets/interfaces/vault'; import { KeeperApp } from 'src/models/interfaces/KeeperApp'; import { createWatcher } from '../utilities'; import { getJSONFromRealmObject } from 'src/storage/realm/utils'; +import { store } from '../store'; import { ADD_LABELS, @@ -26,8 +27,39 @@ import { } from './bhr'; import { encrypt, generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption'; +function currentOriginApp(originAppId?: string): KeeperApp | null { + if (!originAppId || store.getState().storage.appId !== originAppId) return null; + try { + const app = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp; + return app?.id === originAppId ? app : null; + } catch { + return null; + } +} + +// Keep the ownership check and local writes in one synchronous turn. An action +// created for A must never mutate B's Realm after a network or saga wait. +function persistTagsForOrigin(originAppId: string, added: BIP329Label[], deleted: string[] = []) { + if (!currentOriginApp(originAppId)) return false; + if (added.length && dbManager.createObjectBulk(RealmSchema.Tags, added) !== true) return false; + for (const id of deleted) { + if (dbManager.deleteObjectById(RealmSchema.Tags, id) !== true) return false; + } + return true; +} + +function persistSpendabilityForOrigin(originAppId: string, schema: RealmSchema, id: string, specs: any) { + if (!currentOriginApp(originAppId)) return false; + return dbManager.updateObjectById(schema, id, { specs }) === true; +} + +function originUiAction(action: T, originAppId: string): T & { originAppId: string } { + return { ...action, originAppId }; +} + export function* addLabelsWorker({ payload, + originAppId, }: { payload: { txId: string; @@ -36,9 +68,14 @@ export function* addLabelsWorker({ labels: { name: string; isSystem: boolean }[]; type; }; + originAppId?: string; }) { try { - yield put(setSyncingUTXOs(true)); + if (!originAppId) return; + const app = currentOriginApp(originAppId); + if (!app) return; + const primarySeed = app.primarySeed; + yield put(originUiAction(setSyncingUTXOs(true), originAppId)); const { txId, vout, wallet, labels, type } = payload; const origin = generateAbbreviatedOutputDescriptors(wallet); const tags = []; @@ -54,35 +91,32 @@ export function* addLabelsWorker({ }; tags.push(tag); }); - const { id, primarySeed }: KeeperApp = yield call( - dbManager.getObjectByIndex, - RealmSchema.KeeperApp - ); - yield call(dbManager.createObjectBulk, RealmSchema.Tags, tags); + if (!(yield call(persistTagsForOrigin, originAppId, tags))) return; try { - const backupResponse = yield call(checkBackupCondition); - if (!backupResponse) { + const backupResponse = yield call(checkBackupCondition, originAppId); + if (!backupResponse && currentOriginApp(originAppId)) { const encryptionKey = generateEncryptionKey(primarySeed); const tagsToBackup = tags.map((tag) => ({ id: hash256(hash256(encryptionKey + tag.id)), content: encrypt(encryptionKey, JSON.stringify(tag)), })); - yield call(Relay.modifyLabels, id, tagsToBackup, []); + yield call(Relay.modifyLabels, originAppId, tagsToBackup, []); } else yield delay(100); } catch (error) { console.log('🚀 ~ addLabelsWorker error:', error); - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, originAppId); } - yield put(resetState()); + yield put(originUiAction(resetState(), originAppId)); } catch (e) { - yield put(setSyncingUTXOError(e)); + if (originAppId) yield put(originUiAction(setSyncingUTXOError(e), originAppId)); } finally { - yield put(setSyncingUTXOs(false)); + if (originAppId) yield put(originUiAction(setSyncingUTXOs(false), originAppId)); } } export function* bulkUpdateLabelsWorker({ payload, + originAppId, }: { payload: { labelChanges: { @@ -94,9 +128,14 @@ export function* bulkUpdateLabelsWorker({ address?: string; wallet: Wallet; }; + originAppId?: string; }) { try { - yield put(setSyncingUTXOs(true)); + if (!originAppId) return; + const app = currentOriginApp(originAppId); + if (!app) return; + const primarySeed = app.primarySeed; + yield put(originUiAction(setSyncingUTXOs(true), originAppId)); const { labelChanges, wallet, UTXO, txId, address } = payload; const origin = generateAbbreviatedOutputDescriptors(wallet); let addedTags: BIP329Label[] = []; @@ -117,43 +156,37 @@ export function* bulkUpdateLabelsWorker({ if (labelChanges.deleted) { deletedTagIds = labelChanges.deleted.map((label) => `${ref}${label.name}`); } - const { primarySeed, id }: KeeperApp = yield call( - dbManager.getObjectByIndex, - RealmSchema.KeeperApp - ); - yield call(dbManager.createObjectBulk, RealmSchema.Tags, addedTags); - for (const element of deletedTagIds) { - yield call(dbManager.deleteObjectById, RealmSchema.Tags, element); - } + if (!(yield call(persistTagsForOrigin, originAppId, addedTags, deletedTagIds))) return; try { - const backupResponse = yield call(checkBackupCondition); - if (!backupResponse) { + const backupResponse = yield call(checkBackupCondition, originAppId); + if (!backupResponse && currentOriginApp(originAppId)) { const encryptionKey = generateEncryptionKey(primarySeed); const tagsToBackup = addedTags.map((tag) => ({ id: hash256(hash256(encryptionKey + tag.id)), content: encrypt(encryptionKey, JSON.stringify(tag)), })); const tagsToDelete = deletedTagIds.map((tag) => hash256(hash256(encryptionKey + tag))); - yield fork( + yield call( Relay.modifyLabels, - id, + originAppId, tagsToBackup.length ? tagsToBackup : [], tagsToDelete.length ? tagsToDelete : [] ); } else yield delay(100); } catch (error) { - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, originAppId); } - yield put(resetState()); + yield put(originUiAction(resetState(), originAppId)); } catch (e) { - yield put(setSyncingUTXOError(e)); + if (originAppId) yield put(originUiAction(setSyncingUTXOError(e), originAppId)); } finally { - yield put(setSyncingUTXOs(false)); + if (originAppId) yield put(originUiAction(setSyncingUTXOs(false), originAppId)); } } export function* importLabelsWorker({ payload, + originAppId, }: { payload: { labels: [ @@ -165,9 +198,14 @@ export function* importLabelsWorker({ } ]; }; + originAppId?: string; }) { try { - yield put(setSyncingUTXOs(true)); + if (!originAppId) return; + const app = currentOriginApp(originAppId); + if (!app) return; + const primarySeed = app.primarySeed; + yield put(originUiAction(setSyncingUTXOs(true), originAppId)); const { labels } = payload; let addedTags: BIP329Label[] = []; if (labels) { @@ -183,30 +221,26 @@ export function* importLabelsWorker({ })); } - const { primarySeed, id }: KeeperApp = yield call( - dbManager.getObjectByIndex, - RealmSchema.KeeperApp - ); - yield call(dbManager.createObjectBulk, RealmSchema.Tags, addedTags); + if (!(yield call(persistTagsForOrigin, originAppId, addedTags))) return; try { - const backupResponse = yield call(checkBackupCondition); - if (!backupResponse) { + const backupResponse = yield call(checkBackupCondition, originAppId); + if (!backupResponse && currentOriginApp(originAppId)) { const encryptionKey = generateEncryptionKey(primarySeed); const tagsToBackup = addedTags.map((tag) => ({ id: hash256(hash256(encryptionKey + tag.id)), content: encrypt(encryptionKey, JSON.stringify(tag)), })); - yield fork(Relay.modifyLabels, id, tagsToBackup.length ? tagsToBackup : [], []); + yield call(Relay.modifyLabels, originAppId, tagsToBackup.length ? tagsToBackup : [], []); } else yield delay(100); } catch (error) { - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, originAppId); } - yield put(resetState()); + yield put(originUiAction(resetState(), originAppId)); } catch (e) { - yield put(setSyncingUTXOError(e)); + if (originAppId) yield put(originUiAction(setSyncingUTXOError(e), originAppId)); } finally { - yield put(setSyncingUTXOs(false)); + if (originAppId) yield put(originUiAction(setSyncingUTXOs(false), originAppId)); } } @@ -216,6 +250,7 @@ export const importLabelsWatcher = createWatcher(importLabelsWorker, IMPORT_LABE export function* markUTXOSpendabilityWorker({ payload, + originAppId, }: { payload: { wallet: any; @@ -223,8 +258,11 @@ export function* markUTXOSpendabilityWorker({ vout: number; spendability: UTXOSpendability; }; + originAppId?: string; }) { try { + if (!originAppId) return; + if (!currentOriginApp(originAppId)) return; const { wallet, txId, vout, spendability } = payload; const schema = wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet; @@ -253,7 +291,7 @@ export function* markUTXOSpendabilityWorker({ } if (!changed) return; - const persisted = yield call(dbManager.updateObjectById, schema, wallet.id, { specs }); + const persisted = yield call(persistSpendabilityForOrigin, originAppId, schema, wallet.id, specs); if (persisted !== true) return; // Persist the user's choice first, then invalidate/refresh Assisted Server // Backup through its normal opt-in/offline-aware incremental path. @@ -262,11 +300,15 @@ export function* markUTXOSpendabilityWorker({ schema === RealmSchema.Vault ? yield call(updateVaultImageWorker, { payload: { vault: walletJSON as Vault, isUpdate: true }, + originAppId, }) - : yield call(updateAppImageWorker, { payload: { wallets: [walletJSON as Wallet] } }); - if (!response?.updated) yield call(setServerBackupFailed); + : yield call(updateAppImageWorker, { + payload: { wallets: [walletJSON as Wallet] }, + originAppId, + }); + if (!response?.updated) yield call(setServerBackupFailed, originAppId); } catch { - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, originAppId); } } catch (e) { console.log('markUTXOSpendabilityWorker error:', e); diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts index cd3d786253..c420b1bcb8 100644 --- a/src/store/sagas/wallets.ts +++ b/src/store/sagas/wallets.ts @@ -70,7 +70,7 @@ import { sanitizeSeedKeyForBackup, } from 'src/utils/utilities'; import { COLLABORATIVE_SCHEME } from 'src/screens/SigningDevices/SetupCollaborativeWallet'; -import { RootState } from '../store'; +import { RootState, store } from '../store'; import { checkBackupFreshness } from '../sagaActions/bhr'; import { @@ -131,6 +131,7 @@ import { showDeletingKeyModal, hideDeletingKeyModal, showKeyDeletedSuccessModal, + isAutomaticCloudBackupEnabled, } from '../reducers/bhr'; import { setElectrumNotConnectedErr } from '../reducers/login'; import { connectToNodeWorker } from './network'; @@ -141,6 +142,21 @@ import { accountNoFromDerivationPath } from 'src/utils/service-utilities/utils'; import { classifyDustByAddress } from 'src/services/wallets/operations/dustClassification'; import { setPendingDustToast } from '../reducers/utxos'; +const currentWalletAccountId = (): string | undefined => { + try { + return (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id; + } catch { + return undefined; + } +}; +const assertWalletAccount = (appId: string) => { + if ( + !appId || + currentWalletAccountId() !== appId || + store.getState().storage.appId !== appId + ) throw new Error('Account changed'); +}; + export interface NewVaultDetails { name?: string; description?: string; @@ -210,10 +226,18 @@ function* addNewWallet( } } -export function* addNewWalletsWorker({ payload: newWalletInfo }: { payload: NewWalletInfo[] }) { +export function* addNewWalletsWorker({ + payload: newWalletInfo, + originAppId, +}: { + payload: NewWalletInfo[]; + originAppId?: string; +}) { try { const wallets: Wallet[] = []; const app: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + const sourceAppId = originAppId || app?.id; + assertWalletAccount(sourceAppId); for (const { walletType, walletDetails, importDetails } of newWalletInfo) { const wallet: Wallet = yield call( @@ -228,8 +252,12 @@ export function* addNewWalletsWorker({ payload: newWalletInfo }: { payload: NewW if (wallets.length > 0) { yield put(setRelayWalletUpdateLoading(true)); - const response = yield call(updateAppImageWorker, { payload: { wallets } }); + const response = yield call(updateAppImageWorker, { + payload: { wallets }, + originAppId: sourceAppId, + }); if (response.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.createObjectBulk, RealmSchema.Wallet, wallets); yield put(relayWalletUpdateSuccess()); return true; @@ -260,7 +288,9 @@ export interface NewVaultInfo { export function* addNewVaultWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { newVaultInfo?: NewVaultInfo; isMigrated?: boolean; @@ -268,6 +298,8 @@ export function* addNewVaultWorker({ }; }) { try { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { newVaultInfo, isMigrated, oldVaultId } = payload; const { bitcoinNetworkType: networkType } = yield select((state: RootState) => state.settings); @@ -297,8 +329,12 @@ export function* addNewVaultWorker({ } yield put(setRelayVaultUpdateLoading(true)); - const newVaultResponse = yield call(updateVaultImageWorker, { payload: { vault } }); + const newVaultResponse = yield call(updateVaultImageWorker, { + payload: { vault }, + originAppId: sourceAppId, + }); if (newVaultResponse.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.createObject, RealmSchema.Vault, vault); yield put(uaiChecks([uaiType.SECURE_VAULT])); @@ -312,6 +348,7 @@ export function* addNewVaultWorker({ archivedId: oldVault.archivedId ? oldVault.archivedId : oldVault.id, }; const archivedVaultresponse = yield call(updateVaultImageWorker, { + originAppId: sourceAppId, payload: { vault: { ...oldVault, @@ -320,6 +357,7 @@ export function* addNewVaultWorker({ }, }); if (archivedVaultresponse.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.updateObjectById, RealmSchema.Vault, oldVaultId, updatedParams); yield put(initiateVaultMigration({ intrimVault: vault })); } @@ -355,14 +393,18 @@ export const addNewVaultWatcher = createWatcher(addNewVaultWorker, ADD_NEW_VAULT export function* addSigningDeviceWorker({ payload: { signers }, callback, + originAppId, }: { payload: { signers: Signer[] }; callback?: () => void; + originAppId?: string; }) { if (!signers.length) return; + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); for (let i = 0; i < signers.length; i++) { const signer = signers[i]; - yield call(mergeSimilarKeysWorker, { payload: { signer } }); + yield call(mergeSimilarKeysWorker, { payload: { signer }, originAppId: sourceAppId }); } try { const { bitcoinNetworkType } = yield select((state: RootState) => state.settings); @@ -484,8 +526,12 @@ export function* addSigningDeviceWorker({ id: getKeyUID(signer), })); yield put(setRelaySignersUpdateLoading(true)); - const response = yield call(updateAppImageWorker, { payload: { signers: signersToUpdate } }); + const response = yield call(updateAppImageWorker, { + payload: { signers: signersToUpdate }, + originAppId: sourceAppId, + }); if (response.updated) { + assertWalletAccount(sourceAppId); yield call( dbManager.createObjectBulk, RealmSchema.Signer, @@ -499,7 +545,7 @@ export function* addSigningDeviceWorker({ (signersToUpdate[0]?.extraData?.instanceNumber !== 1 && !signersToUpdate[0]?.hidden) ) ); - yield call(updateVaultSignerXprivWorker, { signers }); + yield call(updateVaultSignerXprivWorker, { signers, originAppId: sourceAppId }); } else { const errorMsg = response.error?.message ? response.error.message.toString() @@ -518,29 +564,46 @@ export function* addSigningDeviceWorker({ export const addSigningDeviceWatcher = createWatcher(addSigningDeviceWorker, ADD_SIGINING_DEVICE); -function* deleteSigningDeviceWorker({ payload: { signers } }: { payload: { signers: Signer[] } }) { +function* deleteSigningDeviceWorker({ + payload: { signers }, + originAppId, +}: { + payload: { signers: Signer[] }; + originAppId?: string; +}) { + const sourceAppId = originAppId || currentWalletAccountId(); try { + assertWalletAccount(sourceAppId); if (signers.length) { yield put(showDeletingKeyModal()); const signersToDeleteIds = []; for (const signer of signers) { signersToDeleteIds.push(getKeyUID(signer)); } - for (let i = 0; i < signers.length; i++) { - yield call(deleteAppImageEntityWorker, { - payload: { - signerIds: signersToDeleteIds, - }, - }); + const response = yield call(deleteAppImageEntityWorker, { + originAppId: sourceAppId, + payload: { signerIds: signersToDeleteIds }, + }); + if (!response?.updated) { + assertWalletAccount(sourceAppId); + yield put(hideDeletingKeyModal()); + yield put(relaySignersUpdateFail('An error occurred while deleting signers.')); + return false; } + assertWalletAccount(sourceAppId); yield put(uaiChecks([uaiType.SIGNING_DEVICES_HEALTH_CHECK])); yield put(hideDeletingKeyModal()); yield put(showKeyDeletedSuccessModal()); + return true; } + return false; } catch (error) { captureError(error); - yield put(hideDeletingKeyModal()); - yield put(relaySignersUpdateFail('An error occurred while deleting signers.')); + if (currentWalletAccountId() === sourceAppId && store.getState().storage.appId === sourceAppId) { + yield put(hideDeletingKeyModal()); + yield put(relaySignersUpdateFail('An error occurred while deleting signers.')); + } + return false; } } @@ -549,8 +612,16 @@ export const deleteSigningDeviceWatcher = createWatcher( DELETE_SIGINING_DEVICE ); -function* archiveSigningDeviceWorker({ payload: { signers } }: { payload: { signers: Signer[] } }) { +function* archiveSigningDeviceWorker({ + payload: { signers }, + originAppId, +}: { + payload: { signers: Signer[] }; + originAppId?: string; +}) { try { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const signersToArchiveIds = []; for (const signer of signers) { signersToArchiveIds.push(getKeyUID(signer)); @@ -558,6 +629,7 @@ function* archiveSigningDeviceWorker({ payload: { signers } }: { payload: { sign if (signers.length) { for (let i = 0; i < signers.length; i++) { yield call(updateSignerDetailsWorker, { + originAppId: sourceAppId, payload: { signer: signers[i], key: 'archived', @@ -580,12 +652,17 @@ export const archiveSigningDeviceWatcher = createWatcher( function* migrateVaultWorker({ payload, + originAppId, }: { payload: { newVaultInfo: NewVaultInfo; oldVaultId: string }; + originAppId?: string; }) { try { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { newVaultInfo, oldVaultId } = payload; const migrated = yield call(addNewVaultWorker, { + originAppId: sourceAppId, payload: { newVaultInfo, isMigrated: true, oldVaultId }, }); const migratedVault = yield select((state: RootState) => state.vault.intrimVault); @@ -613,12 +690,15 @@ export const migrateVaultWatcher = createWatcher(migrateVaultWorker, MIGRATE_VAU function* refreshWalletsWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { wallets: (Wallet | Vault)[]; options: { hardRefresh?: boolean; addNotifications?: boolean; dustScan?: boolean }; }; }) { + const sourceAppId = originAppId || currentWalletAccountId(); let { wallets, options } = payload; // Filter out pre-mix, post-mix, and bad bank wallets as they are no longer displayed or used. @@ -634,6 +714,7 @@ function* refreshWalletsWorker({ }); try { + assertWalletAccount(sourceAppId); if (!wallets || wallets.length === 0) return true; if (!ELECTRUM_CLIENT.isClientConnected) { @@ -708,6 +789,7 @@ function* refreshWalletsWorker({ } yield fork(bulkUpdateLabelsWorker, { + originAppId: sourceAppId, payload: { labelChanges, UTXO: utxo, wallet: synchedWallet as any }, }); @@ -869,6 +951,7 @@ function* refreshWalletsWorker({ } // Write updated specs (with spendability) back to Realm + assertWalletAccount(sourceAppId); if (synchedWallet.entityKind === EntityKind.VAULT) { yield call(dbManager.updateObjectById, RealmSchema.Vault, synchedWallet.id, { specs: synchedWallet.specs, @@ -909,7 +992,9 @@ export const refreshWalletsWatcher = createWatcher(refreshWalletsWorker, REFRESH export function* autoWalletsSyncWorker({ payload, + originAppId, }: { + originAppId?: string; payload: { syncAll?: boolean; hardRefresh?: boolean; @@ -917,6 +1002,8 @@ export function* autoWalletsSyncWorker({ backupCheckAppId?: string; }; }) { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { syncAll, hardRefresh, addNotifications, backupCheckAppId } = payload; const wallets: Wallet[] = yield call(dbManager.getObjectByIndex, RealmSchema.Wallet, null, true); const vaults: Vault[] = yield call(dbManager.getObjectByIndex, RealmSchema.Vault, null, true); @@ -934,6 +1021,7 @@ export function* autoWalletsSyncWorker({ let refreshSucceeded = true; if (walletsToSync.length) { refreshSucceeded = yield call(refreshWalletsWorker, { + originAppId: sourceAppId, payload: { wallets: walletsToSync, options: { @@ -945,16 +1033,25 @@ export function* autoWalletsSyncWorker({ } // Check backup freshness only after the refreshed wallet specs are persisted. // A failed refresh or account switch must not verify a stale snapshot. - if (backupCheckAppId && refreshSucceeded) { + if ( + backupCheckAppId === sourceAppId && + refreshSucceeded && + currentWalletAccountId() === sourceAppId && + store.getState().storage.appId === sourceAppId + ) { const { appId } = yield select((state: RootState) => state.storage); - const { automaticCloudBackup, pendingAllBackup, backupRepairCompletedByAppId = {} } = + const { + automaticCloudBackupByAppId, + pendingAllBackupByAppId, + backupRepairCompletedByAppId = {}, + } = yield select((state: RootState) => state.bhr); if ( appId === backupCheckAppId && - automaticCloudBackup && - (pendingAllBackup || !backupRepairCompletedByAppId[appId]) + isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, appId) && + (pendingAllBackupByAppId?.[appId] || !backupRepairCompletedByAppId[appId]) ) { - yield put(checkBackupFreshness()); + yield put(checkBackupFreshness(appId)); } } } @@ -963,6 +1060,7 @@ export const autoWalletsSyncWatcher = createWatcher(autoWalletsSyncWorker, AUTO_ export function* updateSignerPolicyWorker({ payload, + originAppId, }: { payload: { signer: Signer; @@ -973,12 +1071,14 @@ export function* updateSignerPolicyWorker({ }; verificationToken: number; }; + originAppId?: string; }) { - const fcmToken = yield select((state: RootState) => state.notifications.fcmToken); - const { bitcoinNetwork } = yield select((state: RootState) => state.settings); - + const sourceAppId = originAppId || currentWalletAccountId(); const { signer, signingKey, updates, verificationToken } = payload; try { + assertWalletAccount(sourceAppId); + const fcmToken = yield select((state: RootState) => state.notifications.fcmToken); + const { bitcoinNetwork } = yield select((state: RootState) => state.settings); const signerId = signingKey?.xfp || WalletUtilities.getFingerprintFromExtendedKey( @@ -996,6 +1096,7 @@ export function* updateSignerPolicyWorker({ updates, fcmToken ); + assertWalletAccount(sourceAppId); if (delayedPolicyUpdate) { yield put(updateDelayedPolicyUpdate(delayedPolicyUpdate)); @@ -1018,9 +1119,11 @@ export function* updateSignerPolicyWorker({ } ); } + assertWalletAccount(sourceAppId); yield put(setSignerPolicyError('success')); } catch (err) { - yield put(setSignerPolicyError('failure')); + if (currentWalletAccountId() === sourceAppId && store.getState().storage.appId === sourceAppId) + yield put(setSignerPolicyError('failure')); } } @@ -1054,7 +1157,8 @@ function* testcoinsWorker({ payload }) { export const testcoinsWatcher = createWatcher(testcoinsWorker, TEST_SATS_RECIEVE); -function* updateWalletDetailsWorker({ payload }) { +function* updateWalletDetailsWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { wallet, details, @@ -1066,6 +1170,7 @@ function* updateWalletDetailsWorker({ payload }) { }; } = payload; try { + assertWalletAccount(sourceAppId); const presentationData: WalletPresentationData = { name: details.name, description: details.description, @@ -1074,8 +1179,12 @@ function* updateWalletDetailsWorker({ payload }) { wallet.presentationData = presentationData; yield put(setRelayWalletUpdateLoading(true)); - const response = yield call(updateAppImageWorker, { payload: { wallets: [wallet] } }); + const response = yield call(updateAppImageWorker, { + payload: { wallets: [wallet] }, + originAppId: sourceAppId, + }); if (response.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.updateObjectById, RealmSchema.Wallet, wallet.id, { presentationData, }); @@ -1096,7 +1205,8 @@ export const updateWalletDetailWatcher = createWatcher( UPDATE_WALLET_DETAILS ); -function* updateVaultDetailsWorker({ payload }) { +function* updateVaultDetailsWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { vault, details, @@ -1108,6 +1218,7 @@ function* updateVaultDetailsWorker({ payload }) { }; } = payload; try { + assertWalletAccount(sourceAppId); const presentationData: VaultPresentationData = { name: details.name, description: details.description, @@ -1119,8 +1230,10 @@ function* updateVaultDetailsWorker({ payload }) { const response = yield call(updateVaultImageWorker, { payload: { vault }, + originAppId: sourceAppId, }); if (response.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.updateObjectById, RealmSchema.Vault, vault.id, { presentationData, }); @@ -1142,7 +1255,8 @@ export const updateVaultDetailsWatcher = createWatcher( UPDATE_VAULT_DETAILS ); -export function* updateSignerDetailsWorker({ payload }) { +export function* updateSignerDetailsWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { signer, key, @@ -1154,9 +1268,14 @@ export function* updateSignerDetailsWorker({ payload }) { } = payload; yield put(setRelaySignersUpdateLoading(true)); try { + assertWalletAccount(sourceAppId); signer[key] = value; - const response = yield call(updateAppImageWorker, { payload: { signers: [signer] } }); + const response = yield call(updateAppImageWorker, { + payload: { signers: [signer] }, + originAppId: sourceAppId, + }); if (response.updated) { + assertWalletAccount(sourceAppId); const signerKeyUID = getKeyUID(signer); yield call( dbManager.updateObjectByQuery, @@ -1181,7 +1300,9 @@ export function* updateSignerDetailsWorker({ payload }) { export const updateSignerDetails = createWatcher(updateSignerDetailsWorker, UPDATE_SIGNER_DETAILS); -function* updateKeyDetailsWorker({ payload }) { +function* updateKeyDetailsWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { signer, key, @@ -1207,13 +1328,15 @@ function* updateKeyDetailsWorker({ payload }) { if (!updatedFlag) { updatedRegsteredVaults.push(value); } - const saved = yield call( - dbManager.updateObjectByPrimaryId, - RealmSchema.VaultSigner, - 'xpub', - signer.xpub, - { registeredVaults: updatedRegsteredVaults } - ); + const saved = yield call(() => { + assertWalletAccount(sourceAppId); + return dbManager.updateObjectByPrimaryId( + RealmSchema.VaultSigner, + 'xpub', + signer.xpub, + { registeredVaults: updatedRegsteredVaults } + ); + }); if (saved !== true) { yield put(relaySignersUpdateFail('Key registration could not be saved')); return false; @@ -1226,37 +1349,49 @@ function* updateKeyDetailsWorker({ payload }) { if (vault.signers.some((key) => key.xpub === signer.xpub)) { const response = yield call(updateVaultImageWorker, { payload: { vault, isUpdate: true }, + originAppId: sourceAppId, }); - if (!response?.updated) yield call(setServerBackupFailed); + if (!response?.updated) yield call(setServerBackupFailed, sourceAppId); } } } catch (error) { - yield call(setServerBackupFailed); + yield call(setServerBackupFailed, sourceAppId); } return true; } - const updated = yield call( - dbManager.updateObjectByPrimaryId, - RealmSchema.VaultSigner, - 'xpub', - signer.xpub, - { + const updated = yield call(() => { + assertWalletAccount(sourceAppId); + return dbManager.updateObjectByPrimaryId(RealmSchema.VaultSigner, 'xpub', signer.xpub, { [key]: value, - } - ); + }); + }); return updated === true; } export const updateKeyDetails = createWatcher(updateKeyDetailsWorker, UPDATE_KEY_DETAILS); -function* deleteVaultWorker({ payload }) { +function* deleteVaultWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { vaultId } = payload; try { + assertWalletAccount(sourceAppId); yield put(setRelayVaultUpdateLoading(true)); - const response = yield call(deleteVaultImageWorker, { payload: { vaultIds: [vaultId] } }); + const backupEnabled = yield select((state: RootState) => + isAutomaticCloudBackupEnabled(state.bhr, sourceAppId) + ); + const response = yield call(deleteVaultImageWorker, { + payload: { vaultIds: [vaultId] }, + originAppId: sourceAppId, + }); if (response.updated) { - yield call(dbManager.deleteObjectById, RealmSchema.Vault, vaultId); + assertWalletAccount(sourceAppId); + const deleted = yield call(dbManager.deleteObjectById, RealmSchema.Vault, vaultId); + if (deleted !== true) { + if (backupEnabled) yield call(setServerBackupFailed, sourceAppId); + throw new Error('Local vault deletion failed'); + } + assertWalletAccount(sourceAppId); yield put(relayVaultUpdateSuccess()); } else { const errorMsg = response.error?.message @@ -1265,15 +1400,18 @@ function* deleteVaultWorker({ payload }) { yield put(relayVaultUpdateFail(errorMsg)); } } catch (err) { - yield put(relayVaultUpdateFail('Something went wrong while deleting the vault!')); + if (currentWalletAccountId() === sourceAppId && store.getState().storage.appId === sourceAppId) + yield put(relayVaultUpdateFail('Something went wrong while deleting the vault!')); } } export const deleteVaultyWatcher = createWatcher(deleteVaultWorker, DELETE_VAULT); -function* reinstateVaultWorker({ payload }) { +function* reinstateVaultWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { vaultId } = payload; try { + assertWalletAccount(sourceAppId); yield put(setRelayVaultUpdateLoading(true)); const vault: Vault = dbManager.getObjectById(RealmSchema.Vault, vaultId).toJSON(); const updatedParams = { @@ -1286,6 +1424,7 @@ function* reinstateVaultWorker({ payload }) { }, }; const response = yield call(updateVaultImageWorker, { + originAppId: sourceAppId, payload: { vault: { ...vault, @@ -1299,9 +1438,11 @@ function* reinstateVaultWorker({ payload }) { signingDevices.forEach((signer) => (signerMap[getKeyUID(signer)] = signer)); if (response.updated) { + assertWalletAccount(sourceAppId); yield call(dbManager.updateObjectById, RealmSchema.Vault, vaultId, updatedParams); for (let i = 0; i < vault.signers.length; i++) { yield call(updateSignerDetailsWorker, { + originAppId: sourceAppId, payload: { signer: signerMap[getKeyUID(vault.signers[i])], key: 'archived', @@ -1323,9 +1464,11 @@ function* reinstateVaultWorker({ payload }) { export const reinstateVaultWatcher = createWatcher(reinstateVaultWorker, REINSTATE_VAULT); -function* refillMobileKeyWorker({ payload }) { +function* refillMobileKeyWorker({ payload, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); const { vaultKey } = payload; try { + assertWalletAccount(sourceAppId); const { xpriv } = vaultKey; if (!xpriv) { const signer: Signer = dbManager @@ -1343,6 +1486,7 @@ function* refillMobileKeyWorker({ payload }) { if (xpub === signerXpub) { const { xpriv } = details.xpubDetails[XpubTypes.P2WSH]; yield call(updateKeyDetailsWorker, { + originAppId: sourceAppId, payload: { signer: signer.signerXpubs[XpubTypes.P2WSH][0], key: 'xpriv', value: xpriv }, }); } @@ -1354,12 +1498,15 @@ function* refillMobileKeyWorker({ payload }) { export const refillMobileKeyWatcher = createWatcher(refillMobileKeyWorker, REFILL_MOBILEKEY); -function* refreshCanaryWalletsWorker() { +function* refreshCanaryWalletsWorker({ originAppId }: { originAppId?: string } = {}) { try { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const vaults: Vault[] = yield call(dbManager.getCollection, RealmSchema.Vault); const canaryWallets = vaults.filter((vault) => vault.type === VaultType.CANARY); if (canaryWallets.length) { yield call(refreshWalletsWorker, { + originAppId: sourceAppId, payload: { wallets: canaryWallets, options: { @@ -1378,8 +1525,16 @@ export const refreshCanaryWalletsWatcher = createWatcher( REFRESH_CANARY_VAULT ); -function* mergeSimilarKeysWorker({ payload }: { payload: { signer: Signer } }) { +function* mergeSimilarKeysWorker({ + payload, + originAppId, +}: { + payload: { signer: Signer }; + originAppId?: string; +}) { try { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { signer } = payload; const signers: Signer[] = yield call(dbManager.getCollection, RealmSchema.Signer); for (let i = 0; i < signers.length; i++) { @@ -1394,14 +1549,14 @@ function* mergeSimilarKeysWorker({ payload }: { payload: { signer: Signer } }) { s.masterFingerprint !== signer.masterFingerprint ) { const signerKeyUID = getKeyUID(s); - yield call( - dbManager.updateObjectByQuery, - RealmSchema.Signer, - (realmSigner) => getKeyUID(realmSigner) === signerKeyUID, - { - masterFingerprint: signer.masterFingerprint, - } - ); + yield call(() => { + assertWalletAccount(sourceAppId); + return dbManager.updateObjectByQuery( + RealmSchema.Signer, + (realmSigner) => getKeyUID(realmSigner) === signerKeyUID, + { masterFingerprint: signer.masterFingerprint } + ); + }); // get all keys that have the same masterFingerprint const keys = yield call( dbManager.getObjectByQuery, @@ -1410,6 +1565,7 @@ function* mergeSimilarKeysWorker({ payload }: { payload: { signer: Signer } }) { true // get all matching objects ); for (let i = 0; i < keys.length; i++) { + assertWalletAccount(sourceAppId); yield call( dbManager.updateObjectByPrimaryId, RealmSchema.VaultSigner, @@ -1424,6 +1580,8 @@ function* mergeSimilarKeysWorker({ payload }: { payload: { signer: Signer } }) { dbManager.getObjectByIndex, RealmSchema.KeeperApp ); + assertWalletAccount(sourceAppId); + if (id !== sourceAppId) throw new Error('Account changed'); const encryptionKey = generateEncryptionKey(primarySeed); const encrytedSigner = encrypt( encryptionKey, @@ -1454,23 +1612,30 @@ export const mergeSimilarKeysWatcher = createWatcher(mergeSimilarKeysWorker, MER function* generateNewExternalAddressWorker({ payload, + originAppId, }: { payload: { wallet: Wallet | Vault; }; + originAppId?: string; }) { + const sourceAppId = originAppId || currentWalletAccountId(); + if ( + !sourceAppId || + currentWalletAccountId() !== sourceAppId || + store.getState().storage.appId !== sourceAppId + ) return false; const { wallet } = payload; - wallet.specs.totalExternalAddresses += 1; - - if (wallet.entityKind === EntityKind.VAULT) { - yield call(dbManager.updateObjectById, RealmSchema.Vault, wallet.id, { - specs: wallet.specs, - }); - } else { - yield call(dbManager.updateObjectById, RealmSchema.Wallet, wallet.id, { - specs: wallet.specs, - }); - } + const specs = { ...wallet.specs, totalExternalAddresses: wallet.specs.totalExternalAddresses + 1 }; + + return yield call(() => { + assertWalletAccount(sourceAppId); + return dbManager.updateObjectById( + wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet, + wallet.id, + { specs } + ); + }); } export const generateNewExternalAddressWatcher = createWatcher( @@ -1550,7 +1715,9 @@ export const fetchCollaborativeChannelWatcher = createWatcher( FETCH_COLLABORATIVE_CHANNEL ); -function* updateVaultSignerXprivWorker({ signers }) { +function* updateVaultSignerXprivWorker({ signers, originAppId }) { + const sourceAppId = originAppId || currentWalletAccountId(); + assertWalletAccount(sourceAppId); const { bitcoinNetworkType } = yield select((state: RootState) => state.settings); for (let i = 0; i < signers.length; i++) { const signer = signers[i]; @@ -1583,12 +1750,14 @@ function* updateVaultSignerXprivWorker({ signers }) { ? tXpriv : null; yield call( - dbManager.updateObjectByPrimaryId, - RealmSchema.VaultSigner, - 'xpub', - vaultSigner.xpub, - { - xpriv: uptXpriv, + () => { + assertWalletAccount(sourceAppId); + return dbManager.updateObjectByPrimaryId( + RealmSchema.VaultSigner, + 'xpub', + vaultSigner.xpub, + { xpriv: uptXpriv } + ); } ); } diff --git a/src/store/store.ts b/src/store/store.ts index bf33c248fc..9a94620c5d 100644 --- a/src/store/store.ts +++ b/src/store/store.ts @@ -25,6 +25,11 @@ import helpAiReducer from './reducers/helpAi'; import { RESET_REDUX_STORE } from './sagaActions/upgrade'; import reduxPersistMigrations from './migrations'; +import dbManager from 'src/storage/realm/dbManager'; +import { RealmSchema } from 'src/storage/realm/enum'; +import { setBackupUploadGuard } from 'src/services/backup/transport'; +import { isAutomaticCloudBackupEnabled } from './reducers/bhr'; +import { KeeperApp } from 'src/models/interfaces/KeeperApp'; const appReducer = combineReducers({ settings: settingsReducer, @@ -70,7 +75,66 @@ const persistConfig = { const persistedReducer = persistReducer(persistConfig, rootReducer); const sagaMiddleware = createSagaMiddleware(); -const middlewars = [sagaMiddleware]; +// Keep the account present at dispatch time even if a saga runs after a switch. +const accountOwnedActions = new Set([ + 'UPDATE_APP_IMAGE', + 'UPDATE_VAULT_IMAGE', + 'DELETE_APP_IMAGE_ENTITY', + 'ADD_NEW_WALLETS', + 'ADD_NEW_VAULT', + 'ADD_SIGINING_DEVICE', + 'DELETE_SIGINING_DEVICE', + 'ARCHIVE_SIGINING_DEVICE', + 'MIGRATE_VAULT', + 'DELETE_VAULT', + 'REINSTATE_VAULT', + 'REFILL_MOBILEKEY', + 'MERGER_SIMILAR_KEYS', + 'REFRESH_WALLETS', + 'AUTO_SYNC_WALLETS', + 'REFRESH_CANARY_VAULT', + 'UPDATE_WALLET_DETAILS', + 'UPDATE_VAULT_DETAILS', + 'UPDATE_SIGNER_DETAILS', + 'UPDATE_KEY_DETAILS', + 'UPDATED_VAULT_SIGNERS_XPRIV', + 'ADD_LABELS', + 'BULK_UPDATE_LABELS', + 'IMPORT_LABELS', + 'MARK_UTXO_SPENDABILITY', + 'SEND_PHASE_TWO', + 'SEND_PHASE_THREE', + 'DISCARD_BROADCASTED_TNX', + 'GENERATE_NEW_ADDRESS', + 'UPDATE_SIGNER_POLICY', +]); +const accountOwnedUtxoUiActions = new Set([ + 'utxos/setSyncingUTXOs', + 'utxos/setSyncingUTXOError', + 'utxos/resetState', +]); +const bindActionOrigin = (api) => (next) => (action) => { + const originAppId = api.getState()?.storage?.appId; + if (action?.originAppId && accountOwnedUtxoUiActions.has(action.type)) { + try { + if ( + action.originAppId !== originAppId || + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id !== originAppId + ) return action; + } catch { + return action; + } + } + if ( + originAppId && + action && + accountOwnedActions.has(action.type) && + !('originAppId' in action) + ) + return next({ ...action, originAppId }); + return next(action); +}; +const middlewars = [bindActionOrigin, sagaMiddleware]; if (__DEV__) { // const createDebugger = require('redux-flipper').default; @@ -85,5 +149,19 @@ export const store = configureStore({ }).concat(middlewars), }); +setBackupUploadGuard((appId, explicitChoice) => { + const state = store.getState(); + if ( + state.storage.appId !== appId || + (!explicitChoice && !isAutomaticCloudBackupEnabled(state.bhr, appId)) + ) + return false; + try { + return (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id === appId; + } catch { + return false; + } +}); + sagaMiddleware.run(rootSaga); export const persistor = persistStore(store); diff --git a/tests/recovery/accountBinding.test.cjs b/tests/recovery/accountBinding.test.cjs new file mode 100644 index 0000000000..b17dd2c3f2 --- /dev/null +++ b/tests/recovery/accountBinding.test.cjs @@ -0,0 +1,256 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, wallet, signer, enums, loadModule } = require('./sagaHarness.cjs'); +const { harness } = require('./helpers.cjs'); + +function switchToOptedInB(f) { + f.app.id = 'B'; + f.app.primarySeed = 'cd'.repeat(32); + f.state.storage.appId = 'B'; + f.state.bhr.automaticCloudBackupByAppId.B = true; +} + +test('A wallet and vault actions queued before B login never use B key or destination', async () => { + const f = fixture(); + const originAppId = f.app.id; + const aWallet = wallet('A-wallet', enums.NetworkType.MAINNET); + switchToOptedInB(f); + const walletResult = await f.run('updateAppImageWorker', { + originAppId, + payload: { wallets: [aWallet], updateNodes: true }, + }); + const vaultResult = await f.run('updateVaultImageWorker', { + originAppId, + payload: { vault: { id: 'A-vault', signers: [], archived: false } }, + }); + const createResult = await f.run('addNewWalletsWorker', { + originAppId, + payload: [{ walletType: enums.WalletType.DEFAULT, walletDetails: { fixture: aWallet } }], + }); + assert.equal(walletResult.updated, false); + assert.equal(vaultResult.updated, false); + assert.equal(createResult, false); + assert.equal(f.calls.length, 0, 'B must receive no A ciphertext or appId'); + assert.equal(f.collections.Wallet.length, 0, 'A wallet must not be persisted in B Realm'); +}); + +test('selected B blocks stale A writes even before Realm finishes switching', async () => { + const f = fixture(); + const originAppId = f.app.id; + const aWallet = wallet('same-wallet', enums.NetworkType.MAINNET); + f.collections.Wallet.push({ ...aWallet, specs: { totalExternalAddresses: 4 } }); + f.state.storage.appId = 'B'; + f.state.bhr.automaticCloudBackupByAppId.B = true; + const createResult = await f.run('addNewWalletsWorker', { + originAppId, + payload: [{ walletType: enums.WalletType.DEFAULT, walletDetails: { fixture: aWallet } }], + }); + const backupResult = await f.run('updateAppImageWorker', { + originAppId, + payload: { wallets: [aWallet] }, + }); + const addressResult = await f.run('generateNewExternalAddressWorker', { + originAppId, + payload: { wallet: { ...aWallet, specs: { totalExternalAddresses: 7 } } }, + }); + assert.equal(createResult, false); + assert.equal(backupResult.updated, false); + assert.equal(addressResult, false); + assert.equal(f.calls.length, 0); + assert.equal(f.collections.Wallet.length, 1); + assert.equal(f.collections.Wallet[0].specs.totalExternalAddresses, 4); +}); + +test('A to opted-in B during connectivity wait blocks upload and preserves B local wallet', async () => { + const f = fixture(); + const originAppId = f.app.id; + const sharedId = 'same-id-in-both-accounts'; + f.collections.Wallet.push(wallet(sharedId, enums.NetworkType.MAINNET)); + let resumeConnectivity; + f.scope.NetInfo.fetch = () => new Promise((resolve) => { resumeConnectivity = resolve; }); + const deleting = f.run('deleteAppImageEntityWorker', { + originAppId, + payload: { walletIds: [sharedId] }, + }); + for (let i = 0; i < 20 && !resumeConnectivity; i++) await new Promise(setImmediate); + assert.ok(resumeConnectivity, 'test must switch while the original account is waiting'); + switchToOptedInB(f); + resumeConnectivity({ isConnected: true }); + const result = await deleting; + assert.equal(result.updated, false); + assert.equal(f.calls.length, 0, 'no remote delete may target either account'); + assert.deepEqual(f.collections.Wallet.map(({ id }) => id), [sharedId]); + + let resumeSecondCheck; + f.scope.NetInfo.fetch = () => new Promise((resolve) => { resumeSecondCheck = resolve; }); + f.app.id = originAppId; + f.app.primarySeed = 'ab'.repeat(32); + f.state.storage.appId = originAppId; + const updating = f.run('updateAppImageWorker', { + originAppId, + payload: { wallets: [wallet('A-wallet', enums.NetworkType.MAINNET)], updateNodes: true }, + }); + for (let i = 0; i < 20 && !resumeSecondCheck; i++) await new Promise(setImmediate); + assert.ok(resumeSecondCheck); + switchToOptedInB(f); + resumeSecondCheck({ isConnected: true }); + assert.equal((await updating).updated, false); + assert.equal(f.calls.length, 0, 'A payload must never be encrypted with B seed or sent to B'); +}); + +test('queued A transport cannot execute after opted-in B becomes active', async () => { + const calls = []; + const transport = loadModule('src/services/backup/transport.ts', { + '../rest/RestClient': { post: async (_path, body) => { calls.push(body); return { data: { updated: true } }; } }, + }); + let active = 'A'; + const consent = { A: true, B: true }; + transport.setBackupUploadGuard((id, explicitChoice) => id === active && (consent[id] || explicitChoice)); + let release; + const busy = transport.withBackupSession('A', () => new Promise((resolve) => { release = resolve; })); + for (let i = 0; i < 20 && !release; i++) await new Promise(setImmediate); + assert.ok(release); + const pending = transport.backupPost('fixture/updateAppImage', { appId: 'A', walletsObject: { secret: 'A-ciphertext' } }); + active = 'B'; + release(); + await busy; + await assert.rejects(pending, /not active or opted in/); + assert.deepEqual(calls, [], 'the queued request must never reach the network'); +}); + +test('per-account consent starts off, survives switches, and legacy consent needs attribution', () => { + const reducer = loadModule('src/store/reducers/bhr.ts', { + 'src/models/enums/BHR': loadModule('src/models/enums/BHR.ts'), + 'src/storage': { reduxStorage: {} }, + 'redux-persist': { persistReducer: (_settings, fn) => fn }, + }); + let state = reducer.default(undefined, { type: 'init' }); + assert.equal(reducer.isAutomaticCloudBackupEnabled(state, 'A'), false); + assert.equal(reducer.isAutomaticCloudBackupEnabled(state, 'B'), false); + state = reducer.default(state, reducer.setAutomaticCloudBackup({ appId: 'A', enabled: true })); + assert.equal(reducer.isAutomaticCloudBackupEnabled(state, 'A'), true); + assert.equal(reducer.isAutomaticCloudBackupEnabled(state, 'B'), false); + state = reducer.default(state, reducer.setBackupAllSuccess({ appId: 'A', status: true })); + state = reducer.default(state, reducer.setAutomaticCloudBackup({ appId: 'A', enabled: false })); + assert.equal(state.backupAllSuccessByAppId.A, false, 'stale UI success cannot reenable A'); + assert.equal(reducer.isAutomaticCloudBackupEnabled(state, 'A'), false); + const legacy = { ...state, automaticCloudBackup: true, automaticCloudBackupByAppId: {} }; + const ambiguous = reducer.default(legacy, reducer.migrateLegacyAutomaticCloudBackup({ appId: 'A', canAttributeConsent: false })); + assert.equal(reducer.isAutomaticCloudBackupEnabled(ambiguous, 'A'), false); + assert.equal(ambiguous.automaticCloudBackup, false); + const attributable = reducer.default(legacy, reducer.migrateLegacyAutomaticCloudBackup({ appId: 'A', canAttributeConsent: true })); + assert.equal(reducer.isAutomaticCloudBackupEnabled(attributable, 'A'), true); + assert.equal(reducer.isAutomaticCloudBackupEnabled(attributable, 'B'), false); +}); + +test('explicit backup can repair an off account only while that account stays active', async () => { + const f = harness(); + f.local.Wallet.push(wallet('explicit', enums.NetworkType.MAINNET)); + f.transport.setBackupUploadGuard((id, explicitChoice) => id === f.app.id && explicitChoice); + assert.equal(await f.repair.inspectBackup(f.app.id, true, () => {}, true), 'verified'); + assert.deepEqual(f.calls, ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot']); +}); + +test('unconfirmed server deletion retains account consent and reports failure', async () => { + const f = fixture(); + f.scope.Relay.deleteBackup = async () => ({ updated: false }); + assert.equal(await f.run('deleteBackupWorker', { appId: f.app.id }), false); + assert.equal(f.state.bhr.automaticCloudBackupByAppId[f.app.id], true); + assert.ok(f.actions.some((action) => action.type === 'setDeleteBackupFailure' && + action.payload.appId === f.app.id && action.payload.status === true)); + assert.ok(!f.actions.some((action) => action.type === 'setAutomaticCloudBackup' && + action.payload.enabled === false)); +}); + +test('rejected entity deletion retains local wallet and queues an account repair', async () => { + const f = fixture(); + const id = f.app.id; + f.collections.Wallet.push(wallet('keep', enums.NetworkType.MAINNET)); + f.scope.Relay.deleteAppImageEntity = async () => ({ updated: false, error: 'rejected' }); + const result = await f.run('deleteAppImageEntityWorker', { + originAppId: id, + payload: { walletIds: ['keep'] }, + }); + assert.equal(result.updated, false); + assert.deepEqual(f.collections.Wallet.map((w) => w.id), ['keep']); + assert.equal(f.state.bhr.pendingAllBackupByAppId[id], true); +}); + +test('remote entity deletion followed by local failure reports partial deletion', async () => { + const f = fixture(); + const id = f.app.id; + f.collections.Wallet.push(wallet('keep', enums.NetworkType.MAINNET)); + f.scope.dbManager.deleteObjectById = () => false; + const result = await f.run('deleteAppImageEntityWorker', { + originAppId: id, + payload: { walletIds: ['keep'] }, + }); + assert.equal(result.updated, false); + assert.deepEqual(f.collections.Wallet.map((w) => w.id), ['keep']); + assert.equal(f.state.bhr.pendingAllBackupByAppId[id], true); +}); + +test('signer delete reports failure and never shows success after rejected remote delete', async () => { + const f = fixture(); + const key = signer('AABBCCDD', enums.NetworkType.MAINNET); + f.scope.deleteAppImageEntityWorker = function* () { return { updated: false, error: 'rejected' }; }; + const result = await f.run('deleteSigningDeviceWorker', { + originAppId: f.app.id, + payload: { signers: [key] }, + }); + assert.equal(result, false); + assert.ok(f.actions.some((action) => action.type === 'relaySignersUpdateFail')); + assert.ok(!f.actions.some((action) => action.type === 'showKeyDeletedSuccessModal')); +}); + +test('remote vault deletion followed by failed local delete reports failure and pending repair', async () => { + const f = fixture(); + f.scope.deleteVaultImageWorker = function* () { return { updated: true }; }; + f.scope.dbManager.deleteObjectById = () => false; + await f.run('deleteVaultWorker', { originAppId: f.app.id, payload: { vaultId: 'keep-vault' } }); + assert.ok(f.actions.some((action) => action.type === 'relayVaultUpdateFail')); + assert.ok(!f.actions.some((action) => action.type === 'relayVaultUpdateSuccess')); + assert.equal(f.state.bhr.pendingAllBackupByAppId[f.app.id], true); +}); + +test('queued A address action cannot change B wallet with the same ID', async () => { + const f = fixture(); + const originAppId = f.app.id; + const aWallet = { ...wallet('same-wallet', enums.NetworkType.MAINNET), + specs: { totalExternalAddresses: 7 } }; + f.collections.Wallet.push({ ...wallet('same-wallet', enums.NetworkType.MAINNET), + specs: { totalExternalAddresses: 4 } }); + switchToOptedInB(f); + assert.equal(await f.run('generateNewExternalAddressWorker', { + originAppId, payload: { wallet: aWallet }, + }), false); + assert.equal(f.collections.Wallet[0].specs.totalExternalAddresses, 4); + assert.equal(aWallet.specs.totalExternalAddresses, 7); +}); + +test('A policy response after B login cannot change B signer or policy UI state', async () => { + const f = fixture(); + const originAppId = f.app.id; + let completePolicy; + f.scope.SigningServer.updatePolicy = () => new Promise((resolve) => { completePolicy = resolve; }); + let writes = 0; + f.scope.dbManager.updateObjectByPrimaryId = () => { writes++; return true; }; + const policy = f.run('updateSignerPolicyWorker', { + originAppId, + payload: { + signer: { masterFingerprint: 'AABBCCDD', signerPolicy: {} }, + signingKey: { xfp: 'AABBCCDD' }, + updates: { restrictions: {}, signingDelay: 0 }, + verificationToken: 123456, + }, + }); + for (let i = 0; i < 20 && !completePolicy; i++) await new Promise(setImmediate); + assert.ok(completePolicy); + switchToOptedInB(f); + completePolicy({ updated: true, delayedPolicyUpdate: { id: 'A-policy' } }); + await policy; + assert.equal(writes, 0); + assert.ok(!f.actions.some((action) => + action.type === 'updateDelayedPolicyUpdate' || + (action.type === 'setSignerPolicyError' && action.payload === 'success'))); +}); diff --git a/tests/recovery/backupFeedback.test.cjs b/tests/recovery/backupFeedback.test.cjs index c94c89b29d..3deccd825e 100644 --- a/tests/recovery/backupFeedback.test.cjs +++ b/tests/recovery/backupFeedback.test.cjs @@ -39,7 +39,12 @@ for (const file of ['src/components/Backup/BackupHealthCheckList.tsx', 'src/scre if (!callback && ts.isCallExpression(node) && node.expression.getText(source)==='useEffect' && node.arguments[0]?.getText(source).includes('backupAllSuccess')) callback=node.arguments[0].getText(source); ts.forEachChild(node,visit); } - visit(source); assert.ok(callback); + visit(source); + if (!callback) { + assert.ok(!source.getFullText().includes('backupAllSignersAndVaults('), + 'Recovery Key confirmation must not start Assisted Server Backup'); + return; + } const actions=[], ui=[]; const context={ backupAllSuccess:false,backupAllFailure:true,automaticCloudBackup:false, dispatch:a=>actions.push(a),setBackupAllSuccess:v=>({type:'success',value:v}),setBackupAllFailure:v=>({type:'failure',value:v}),setAutomaticCloudBackup:v=>({type:'enabled',value:v}), diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs index e03ad47b90..90b856f479 100644 --- a/tests/recovery/backupFreshness.test.cjs +++ b/tests/recovery/backupFreshness.test.cjs @@ -1,12 +1,58 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); -const { fixture, enums, encryption, wallet, loadModule } = require('./sagaHarness.cjs'); +const { fixture, enums, encryption, wallet, loadModule, functions } = require('./sagaHarness.cjs'); +const vm = require('node:vm'); +const ts = require('typescript'); const { NetworkType, WalletType } = enums; +test('login freshness runs after successful sync only for the opted-in source account', async () => { + const scenarios = [ + { enabled: true, pending: true, success: true, switched: false, expected: true }, + { enabled: false, pending: true, success: true, switched: false, expected: false }, + { enabled: true, pending: false, verified: true, success: true, switched: false, expected: false }, + { enabled: true, pending: true, success: false, switched: false, expected: false }, + { enabled: true, pending: true, success: true, switched: true, expected: false }, + ]; + for (const scenario of scenarios) { + const f = fixture(); + const sourceAppId = f.app.id; + f.collections.Wallet.push(wallet('after-sync', NetworkType.MAINNET)); + f.state.bhr.automaticCloudBackupByAppId[sourceAppId] = scenario.enabled; + f.state.bhr.pendingAllBackupByAppId[sourceAppId] = scenario.pending; + f.state.bhr.backupRepairCompletedByAppId[sourceAppId] = !!scenario.verified; + let synced = false; + f.scope.refreshWalletsWorker = function* () { + synced = true; + if (scenario.switched) { + f.app.id = 'B'; + f.state.storage.appId = 'B'; + f.state.bhr.automaticCloudBackupByAppId.B = true; + } + return scenario.success; + }; + f.scope.checkBackupFreshness = (id) => { + assert.equal(synced, true, 'freshness cannot start before sync completes'); + return { type: 'checkBackupFreshness', appId: id }; + }; + vm.runInNewContext(ts.transpileModule( + functions('src/store/sagas/wallets.ts', ['autoWalletsSyncWorker']), + { compilerOptions: { target: ts.ScriptTarget.ES2020 } } + ).outputText, f.scope); + await f.run('autoWalletsSyncWorker', { + originAppId: sourceAppId, + payload: { syncAll: true, backupCheckAppId: sourceAppId }, + }); + const freshness = f.actions.filter((action) => action.type === 'checkBackupFreshness'); + assert.equal(freshness.length, scenario.expected ? 1 : 0, JSON.stringify(scenario)); + if (scenario.expected) assert.equal(freshness[0].appId, sourceAppId); + } +}); + test('login backup inspection waits for wallet refresh to finish', async () => { let finishSync; const syncGate = new Promise((resolve) => { finishSync = resolve; }); const f = fixture({ bhr: { pendingAllBackup: true }, syncGate }); + f.state.bhr.pendingAllBackupByAppId[f.app.id] = true; f.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); const running = f.run('autoWalletsSyncWorker', { payload: { syncAll: false, hardRefresh: false, addNotifications: true, backupCheckAppId: f.app.id }, @@ -22,6 +68,7 @@ test('login backup inspection waits for wallet refresh to finish', async () => { test('failed refresh and account switch do not verify backup freshness', async () => { for (const option of ['syncFails', 'switchAppDuringSync']) { const f = fixture({ bhr: { pendingAllBackup: true }, [option]: true }); + f.state.bhr.pendingAllBackupByAppId[f.app.id] = true; f.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); await f.run('autoWalletsSyncWorker', { payload: { backupCheckAppId: f.app.id }, diff --git a/tests/recovery/helpers.cjs b/tests/recovery/helpers.cjs index 6d0b4e8e87..c8e03d888b 100644 --- a/tests/recovery/helpers.cjs +++ b/tests/recovery/helpers.cjs @@ -43,6 +43,7 @@ function harness(options = {}) { } }; const clock = options.now ? { Date: { now: options.now } } : {}; const transport = loadModule('src/services/backup/transport.ts', { '../rest/RestClient': rest }, clock); + transport.setBackupUploadGuard(id => app.id === id); const repair = loadModule('src/services/backup/repair.ts', { 'src/storage/realm/dbManager': db, 'src/storage/realm/enum': { RealmSchema: new Proxy({}, { get: (_, name) => name }) }, diff --git a/tests/recovery/labelAccount.test.cjs b/tests/recovery/labelAccount.test.cjs new file mode 100644 index 0000000000..c6801b3a0e --- /dev/null +++ b/tests/recovery/labelAccount.test.cjs @@ -0,0 +1,138 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { runSaga } = require('redux-saga'); +const { call, delay, put } = require('redux-saga/effects'); + +const file = 'src/store/sagas/utxos.ts'; +const source = ts.createSourceFile( + file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true +); +const names = new Set([ + 'currentOriginApp', 'persistTagsForOrigin', 'persistSpendabilityForOrigin', + 'originUiAction', + 'addLabelsWorker', 'bulkUpdateLabelsWorker', 'importLabelsWorker', 'markUTXOSpendabilityWorker', +]); +const extracted = source.statements + .filter((node) => ts.isFunctionDeclaration(node) && names.has(node.name?.text)) + .map((node) => node.getText(source).replace(/^export /, '')) + .join('\n'); +const code = ts.transpileModule(extracted, { + compilerOptions: { target: ts.ScriptTarget.ES2020 }, +}).outputText; + +function fixture({ consent = true, switchDuringCheck = false, switchDuringWalletRead = false } = {}) { + const state = { active: 'A', reduxActive: 'A', saved: [], deleted: [], uploaded: [], uiActions: [], failed: 0, consent }; + const dbManager = { + getObjectByIndex: () => ({ id: state.active, primarySeed: `seed-${state.active}` }), + createObjectBulk: (_schema, tags) => { + state.saved.push({ appId: state.active, tags }); + return true; + }, + deleteObjectById: (_schema, id) => { + state.deleted.push({ appId: state.active, id }); + return true; + }, + getObjectById: () => { + if (switchDuringWalletRead) state.active = 'B'; + return { id: 'wallet', specs: { + confirmedUTXOs: [{ txId: 'tx', vout: 0, spendability: 'spendable' }], + } }; + }, + updateObjectById: () => { + state.saved.push({ appId: state.active, walletUpdated: true }); + return true; + }, + }; + const scope = { + call, delay, put, dbManager, console, + store: { getState: () => ({ storage: { appId: state.reduxActive } }) }, + RealmSchema: { KeeperApp: 'KeeperApp', Tags: 'Tags', Wallet: 'Wallet', Vault: 'Vault' }, + LabelRefType: { TXN: 'TXN', ADDR: 'ADDR', OUTPUT: 'OUTPUT' }, + EntityKind: { VAULT: 'VAULT' }, + generateAbbreviatedOutputDescriptors: () => 'disposable-origin', + generateEncryptionKey: (seed) => seed, + hash256: (value) => `hash(${value})`, + encrypt: (_key, value) => value, + getJSONFromRealmObject: (value) => value, + Relay: { modifyLabels: async (appId, added, removed) => { + state.uploaded.push({ appId, added, removed }); + return { updated: true }; + } }, + checkBackupCondition: function* (appId) { + assert.equal(appId, 'A'); + if (switchDuringCheck) { + state.active = 'B'; + state.reduxActive = 'B'; + } + return !state.consent; + }, + setServerBackupFailed: function* (appId) { + assert.equal(appId, 'A'); + state.failed++; + }, + updateAppImageWorker: function* () { throw Error('unexpected backup'); }, + updateVaultImageWorker: function* () { throw Error('unexpected backup'); }, + setSyncingUTXOs: (value) => ({ type: 'sync', value }), + setSyncingUTXOError: (value) => ({ type: 'error', value }), + resetState: () => ({ type: 'reset' }), + }; + vm.runInNewContext(code, scope); + const run = (name, payload, originAppId = 'A') => runSaga( + { dispatch: (action) => state.uiActions.push({ ...action, active: state.active }), + getState: () => ({}) }, scope[name], { payload, originAppId } + ).toPromise(); + return { state, run }; +} + +const wallet = { id: 'wallet', entityKind: 'WALLET' }; +const add = { txId: 'tx', wallet, labels: [{ name: 'note', isSystem: false }], type: 'TXN' }; + +test('an A label action starting after switch to B writes neither Realm nor relay', async () => { + const f = fixture(); + f.state.active = 'B'; + f.state.reduxActive = 'B'; + await f.run('addLabelsWorker', add); + assert.deepEqual(f.state.saved, []); + assert.deepEqual(f.state.uploaded, []); +}); + +test('Redux account B with A Realm still open cannot persist A labels', async () => { + const f = fixture(); + f.state.reduxActive = 'B'; + await f.run('addLabelsWorker', add); + assert.deepEqual(f.state.saved, []); + assert.deepEqual(f.state.uploaded, []); +}); + +test('switch during connectivity check leaves A local label and makes no B upload', async () => { + const f = fixture({ switchDuringCheck: true }); + await f.run('addLabelsWorker', add); + assert.equal(f.state.saved.length, 1); + assert.equal(f.state.saved[0].appId, 'A'); + assert.deepEqual(f.state.uploaded, []); + assert.equal(f.state.failed, 0); + assert.ok(f.state.uiActions.filter((action) => action.active === 'B').every( + (action) => action.originAppId === 'A' + )); +}); + +test('unconsented A can label locally with zero backup upload', async () => { + const f = fixture({ consent: false }); + await f.run('importLabelsWorker', { labels: [{ type: 'TX', ref: 'tx', label: 'note', origin: 'fixture' }] }); + assert.equal(f.state.saved[0].appId, 'A'); + assert.deepEqual(f.state.uploaded, []); +}); + +test('UTXO spendability cannot persist into B after an A action waits for Realm', async () => { + const f = fixture({ switchDuringWalletRead: true }); + await f.run('markUTXOSpendabilityWorker', { + wallet, txId: 'tx', vout: 0, spendability: 'doNotSpend', + }); + assert.equal(f.state.active, 'B'); + assert.deepEqual(f.state.saved, []); + assert.deepEqual(f.state.uploaded, []); +}); diff --git a/tests/recovery/manualCoinChoices.test.cjs b/tests/recovery/manualCoinChoices.test.cjs index 2f7a4ae47c..7d68e4a032 100644 --- a/tests/recovery/manualCoinChoices.test.cjs +++ b/tests/recovery/manualCoinChoices.test.cjs @@ -43,7 +43,9 @@ function sagaFixture(options = {}) { return { updated: true }; }; loadFunctions(f.scope, 'src/store/sagas/bhr.ts', ['updateVaultImageWorker']); - loadFunctions(f.scope, 'src/store/sagas/utxos.ts', ['markUTXOSpendabilityWorker']); + loadFunctions(f.scope, 'src/store/sagas/utxos.ts', [ + 'currentOriginApp', 'persistSpendabilityForOrigin', 'markUTXOSpendabilityWorker', + ]); return f; } for (const kind of ['wallets', 'vaults']) test(`${kind}: compare manual choices but ignore chain-derived UTXO fields and confirmation order`, async () => { @@ -77,7 +79,7 @@ for (const kind of ['Wallet', 'Vault']) test(`${kind}: manual choice persists be assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, 'doNotSpend'); return original(payload); }; - await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + await f.run('markUTXOSpendabilityWorker', { originAppId: f.app.id, payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); const encrypted = kind === 'Vault' ? f.remote.vault : f.remote.wallets[w.id]; const restored = JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed), encrypted)); assert.equal(restored.specs.confirmedUTXOs[0].spendability, 'doNotSpend'); @@ -88,10 +90,10 @@ for (const kind of ['Wallet', 'Vault']) for (const options of [ { bhr: { automaticCloudBackup: false } }, { online: false }, { rejectIncremental: true }, { incrementalError: true }, ]) test(`${kind}: local manual choice survives backup unavailability ${JSON.stringify(options)}`, async () => { const f = sagaFixture(options); const w = withCoins(kind); f.collections[kind].push(w); - await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + await f.run('markUTXOSpendabilityWorker', { originAppId: f.app.id, payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, 'doNotSpend'); if (options.bhr || options.online === false) assert.equal(f.calls.length, 0); - if (!options.bhr) assert.equal(f.state.bhr.pendingAllBackup, true); + if (!options.bhr) assert.equal(f.state.bhr.pendingAllBackupByAppId[f.app.id], true); assert.equal(f.remote.wallets[w.id], undefined); assert.equal(f.remote.vault, undefined); }); @@ -99,14 +101,14 @@ for (const kind of ['Wallet', 'Vault']) for (const options of [ test('missing outpoint and repeated identical choice do not upload', async () => { const f = sagaFixture(); const w = withCoins(); w.specs.confirmedUTXOs[0] = coin(); f.collections.Wallet.push(w); for (const txId of ['missing', coin().txId]) { - await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId, vout: 0, spendability: 'doNotSpend' } }); + await f.run('markUTXOSpendabilityWorker', { originAppId: f.app.id, payload: { wallet: w, txId, vout: 0, spendability: 'doNotSpend' } }); } assert.equal(f.calls.length, 0); }); test('rejected local persistence never uploads an unapplied coin choice', async () => { const f = sagaFixture({ rejectLocalWrite: true }); const w = withCoins(); f.collections.Wallet.push(w); - await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + await f.run('markUTXOSpendabilityWorker', { originAppId: f.app.id, payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); assert.equal(f.collections.Wallet[0].specs.confirmedUTXOs[0].spendability, 'spendable'); assert.equal(f.calls.length, 0); }); diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs index 37cc5412d7..9e99f72a2a 100644 --- a/tests/recovery/sagaHarness.cjs +++ b/tests/recovery/sagaHarness.cjs @@ -79,12 +79,18 @@ function fixture(options = {}) { const state = { storage: { appId }, bhr: { - automaticCloudBackup: true, + automaticCloudBackup: false, + automaticCloudBackupByAppId: { + [appId]: options.bhr?.automaticCloudBackup !== false, + ...options.bhr?.automaticCloudBackupByAppId, + }, pendingAllBackup: false, + pendingAllBackupByAppId: {}, backupRepairCompletedByAppId: { [appId]: true }, ...options.bhr, }, - settings: { bitcoinNetworkType: NetworkType.MAINNET }, + settings: { bitcoinNetworkType: NetworkType.MAINNET, bitcoinNetwork: NetworkType.MAINNET }, + notifications: { fcmToken: 'disposable-token' }, account: account.default( undefined, account.setTempDetails({ hash: 'fixture', realmId: 'fixture', accountIdentifier: '' }) @@ -115,6 +121,8 @@ function fixture(options = {}) { const scope = { ...effects, markBackupMutation: () => {}, + store: { getState: () => state }, + isAutomaticCloudBackupEnabled: (backup, id) => !!backup.automaticCloudBackupByAppId?.[id], ...encryption, ...enums, ...account, @@ -158,6 +166,10 @@ function fixture(options = {}) { collections[schema] = collections[schema].filter((row) => String(row.id) !== String(id)); return true; }, + deleteObjectByPrimaryKey: (schema, key, value) => { + collections[schema] = collections[schema].filter((row) => String(row[key]) !== String(value)); + return true; + }, updateObjectById: (schema, id, patch) => { const row = collections[schema].find((record) => String(record.id) === String(id)); if (!row) return false; @@ -207,6 +219,8 @@ function fixture(options = {}) { config: { BIP85_IMAGE_ENCRYPTIONKEY_DERIVATION_PATH: 'fixture', isDevMode: () => false }, WalletUtilities: { getFingerprintFromSeed: () => 'AAAAAAAA' }, SubscriptionTier: { L1: 'L1', L3: 'L3' }, + SigningServer: { updatePolicy: async () => ({ updated: true }) }, + Alert: { alert: () => {} }, AppSubscriptionLevel: { L1: 1, L3: 3 }, BackupType: { SEED: 'SEED' }, BackupAction: { SEED_BACKUP_CONFIRMED: 'confirmed' }, @@ -227,7 +241,10 @@ function fixture(options = {}) { 'setBackupAllSuccess', 'setBackupAllFailure', 'setBackupAllLoading', + 'setDeleteBackupSuccess', + 'setDeleteBackupFailure', 'setPendingAllBackup', + 'setAutomaticCloudBackup', 'setHomeToastMessage', 'setRelayWalletUpdateLoading', 'relayWalletUpdateSuccess', @@ -235,6 +252,14 @@ function fixture(options = {}) { 'setRelaySignersUpdateLoading', 'relaySignersUpdateSuccess', 'relaySignersUpdateFail', + 'hideDeletingKeyModal', + 'showDeletingKeyModal', + 'showKeyDeletedSuccessModal', + 'setSignerPolicyError', + 'updateDelayedPolicyUpdate', + 'setRelayVaultUpdateLoading', + 'relayVaultUpdateSuccess', + 'relayVaultUpdateFail', 'setAppImageError', 'setSeedConfirmed', 'setBackupType', @@ -259,7 +284,10 @@ function fixture(options = {}) { 'sanitizeSeedKeyForBackup', 'sanitizeVaultSignersForSeedKeyBackup', ]) + '\n' + functions('src/store/sagas/bhr.ts', [ + 'currentBackupAppId', 'deleteAppImageEntityWorker', + 'deleteVaultImageWorker', + 'deleteBackupWorker', 'checkBackupCondition', 'setServerBackupFailed', 'updateAppImageWorker', @@ -270,7 +298,10 @@ function fixture(options = {}) { ]) + '\n' + functions('src/store/sagas/wallets.ts', [ + 'currentWalletAccountId', 'assertWalletAccount', 'addNewWalletsWorker', 'addSigningDeviceWorker', 'mergeSimilarKeysWorker', + 'deleteSigningDeviceWorker', 'deleteVaultWorker', + 'generateNewExternalAddressWorker', 'updateSignerPolicyWorker', 'updateVaultSignerXprivWorker', 'updateSignerDetailsWorker', 'updateKeyDetailsWorker', 'autoWalletsSyncWorker', ]); @@ -286,7 +317,11 @@ function fixture(options = {}) { actions.push(action); if (action.type === 'setBackupRepairCompleted') state.bhr.backupRepairCompletedByAppId[action.payload] = true; - if (action.type === 'setPendingAllBackup') state.bhr.pendingAllBackup = action.payload; + if (action.type === 'setPendingAllBackup') { + const { appId: pendingAppId, pending } = action.payload; + state.bhr.pendingAllBackupByAppId[pendingAppId] = pending; + state.bhr.pendingAllBackup = pending; + } state.account = account.default(state.account, action); }, }, diff --git a/tests/recovery/sagaState.test.cjs b/tests/recovery/sagaState.test.cjs index 9285b375c1..86b9bd33a6 100644 --- a/tests/recovery/sagaState.test.cjs +++ b/tests/recovery/sagaState.test.cjs @@ -19,11 +19,12 @@ function runInspection(f, repair) { const scope = { ...saga, ...effects, ...bhr, inspectBackup:f.repair.inspectBackup, RealmSchema:{KeeperApp:'KeeperApp',UAI:'UAI'}, dbManager:{ getObjectByIndex:()=>f.app, getObjectByField:()=>[] }, + currentBackupAppId:()=>f.app.id, uaiType:{SERVER_BACKUP_FAILURE:'failure'}, uaiActionedWorker:()=>{}, addToUaiStackWorker:()=>{}, }; vm.runInNewContext(ts.transpileModule(code,{ compilerOptions:{ target:ts.ScriptTarget.ES2020 }}).outputText,scope); let state = bhr.default(undefined,{type:'init'}); const actions = []; - const task = saga.runSaga({getState:()=>({bhr:state}),dispatch:action=>{ actions.push(action); state=bhr.default(state,action); }},scope.runBackupInspection,repair).toPromise(); + const task = saga.runSaga({getState:()=>({bhr:state,storage:{appId:f.app.id}}),dispatch:action=>{ actions.push(action); state=bhr.default(state,action); }},scope.runBackupInspection,repair).toPromise(); return {task,get state(){ return state; }, actions}; } @@ -33,14 +34,14 @@ test('only verified readback sets durable per-account completion and clears pend assert.equal(run.state.backupRepairCompletedByAppId.disposable,true); assert.equal(run.state.backupRepairStateByAppId.disposable,'verified'); assert.equal(run.state.backupRepairRunningByAppId.disposable,false); - assert.equal(run.state.pendingAllBackup,false); + assert.equal(run.state.pendingAllBackupByAppId.disposable,false); const phases=run.actions.filter(a=>a.type==='bhr/setBackupRepairState').map(a=>a.payload.phase); assert.deepEqual(phases,['checking','preparing','uploading','verifying','verified']); }); test('offline/unverified remains pending and retryable, never spins indefinitely', async () => { const f=harness({readError:true}); f.local.Wallet.push(wallet()); const run=runInspection(f,true); - assert.equal(await run.task,false); assert.equal(run.state.pendingAllBackup,true); + assert.equal(await run.task,false); assert.equal(run.state.pendingAllBackupByAppId.disposable,true); assert.equal(run.state.backupRepairCompletedByAppId.disposable,false); assert.equal(run.state.backupRepairRunningByAppId.disposable,false); }); diff --git a/tests/recovery/sendLabelOrigin.test.cjs b/tests/recovery/sendLabelOrigin.test.cjs new file mode 100644 index 0000000000..de3ad46a25 --- /dev/null +++ b/tests/recovery/sendLabelOrigin.test.cjs @@ -0,0 +1,97 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const root = path.join(__dirname, '../..'); +function sourceFile(file) { + return ts.createSourceFile(file, fs.readFileSync(path.join(root, file), 'utf8'), + ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS); +} +function declarations(file, names) { + const source = sourceFile(file); + const matches = []; + const walk = (node) => { + if (ts.isVariableDeclaration(node) && names.includes(node.name.getText(source))) + matches.push(`const ${node.getText(source)};`); + ts.forEachChild(node, walk); + }; + walk(source); + return matches; +} + +const code = ts.transpileModule([ + ...declarations('src/store/store.ts', [ + 'accountOwnedActions', 'accountOwnedUtxoUiActions', 'bindActionOrigin', + ]), + ...declarations('src/store/sagaActions/send_and_receive.ts', [ + 'SEND_PHASE_TWO', 'SEND_PHASE_THREE', 'DISCARD_BROADCASTED_TNX', + 'sendPhaseTwo', 'sendPhaseThree', 'discardBroadcastedTnx', + ]), + ...declarations('src/store/sagaActions/utxos.ts', ['IMPORT_LABELS', 'importLabels']), + ...declarations('src/components/ImportExportLabels/index.tsx', ['handleImportLabels']), + 'globalThis.actions = { bindActionOrigin, sendPhaseTwo, sendPhaseThree, discardBroadcastedTnx, importLabels, handleImportLabels };', +].join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText; +const scope = { + Set, + dbManager: { getObjectByIndex: () => ({ id: 'B' }) }, + RealmSchema: { KeeperApp: 'KeeperApp' }, + originAppId: 'A', + vault: { id: 'A-vault' }, + generateAbbreviatedOutputDescriptors: () => 'descriptor', + setIsSyncingLabels: () => {}, + onError: (error) => { throw Error(error); }, + onSuccess: () => {}, + console, +}; +vm.runInNewContext(code, scope); + +test('a delayed A send action keeps A as origin when dispatched on B', () => { + const { bindActionOrigin, sendPhaseTwo, sendPhaseThree, discardBroadcastedTnx } = scope.actions; + const middleware = bindActionOrigin({ getState: () => ({ storage: { appId: 'B' } }) }); + const seen = []; + const dispatch = middleware((action) => { seen.push(action); return action; }); + dispatch(sendPhaseTwo({ wallet: { id: 'A-wallet' } }, 'A')); + dispatch(sendPhaseThree({ wallet: { id: 'A-vault' } }, 'A')); + dispatch(discardBroadcastedTnx({ cachedTxid: 'tx', vault: { id: 'A-vault' } }, 'A')); + dispatch({ type: 'utxos/setSyncingUTXOs', payload: false, originAppId: 'A' }); + assert.equal(seen.length, 3); + assert.ok(seen.every((action) => action.originAppId === 'A')); +}); + +test('send screens pass their captured owner to label-bearing actions', () => { + for (const [file, actionName] of [ + ['src/screens/Send/SendConfirmation.tsx', 'sendPhaseTwo'], + ['src/screens/SignTransaction/SignTransactionScreen.tsx', 'sendPhaseThree'], + ['src/screens/Vault/VaultDetails.tsx', 'discardBroadcastedTnx'], + ]) { + const source = sourceFile(file); + const calls = []; + const walk = (node) => { + if (ts.isCallExpression(node) && node.expression.getText(source) === actionName) + calls.push(node); + ts.forEachChild(node, walk); + }; + walk(source); + assert.ok(calls.length, `${file} should dispatch ${actionName}`); + assert.ok(calls.every((call) => call.arguments[1]?.getText(source) === 'originAppId'), + `${file} must forward its captured owner`); + } +}); + +test('a file import callback from A keeps A after the active account switches to B', async () => { + const seen = []; + const middleware = scope.actions.bindActionOrigin({ + getState: () => ({ storage: { appId: 'B' } }), + }); + scope.dispatch = middleware((action) => { seen.push(action); return action; }); + scope.importFile = async (onFile) => onFile(JSON.stringify({ + type: 'tx', ref: 'txid', label: 'note', origin: 'descriptor', + })); + await scope.actions.handleImportLabels(); + assert.equal(seen.length, 1); + assert.equal(seen[0].type, 'IMPORT_LABELS'); + assert.equal(seen[0].originAppId, 'A'); +}); diff --git a/tests/recovery/usdtAccountDelete.test.cjs b/tests/recovery/usdtAccountDelete.test.cjs new file mode 100644 index 0000000000..72ed256c75 --- /dev/null +++ b/tests/recovery/usdtAccountDelete.test.cjs @@ -0,0 +1,136 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const file = 'src/hooks/useUSDTWallets.ts'; +const source = ts.createSourceFile( + file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true +); +const declarations = new Map(); +function find(node) { + if (ts.isVariableDeclaration(node) && + ['isOriginCurrent', 'createWallet', 'deleteWallet', 'updateWallet'].includes(node.name.getText(source))) + declarations.set(node.name.getText(source), node); + ts.forEachChild(node, find); +} +find(source); +for (const name of ['isOriginCurrent', 'createWallet', 'deleteWallet', 'updateWallet']) + assert.ok(declarations.has(name), `production USDT ${name} callback must exist`); +const code = ts.transpileModule( + [...declarations.values()].map((declaration) => `const ${declaration.getText(source)};`).join('\n'), { + compilerOptions: { target: ts.ScriptTarget.ES2020 }, +}).outputText; + +function fixture({ consent = true, switchDuringRemote = false, switchDuringGeneration = false, + switchDuringUpdate = false } = {}) { + const state = { active: 'A', remote: [], local: [], errors: [], dispatched: [], invalidated: [] }; + const scope = { + appId: 'A', + useCallback: (callback) => callback, + RealmSchema: { KeeperApp: 'KeeperApp', USDTWallet: 'USDTWallet' }, + dbManager: { + getObjectByIndex: (schema) => schema === 'KeeperApp' ? { id: state.active } : [], + getObjectById: () => ({ id: 'wallet', name: 'old' }), + createObject: async (_schema, wallet) => { + state.local.push({ appId: state.active, wallet }); + return true; + }, + updateObjectById: async (_schema, _id, update) => { + state.local.push({ appId: state.active, update }); + if (switchDuringUpdate) state.active = 'B'; + return true; + }, + deleteObjectById: (_schema, walletId) => { + state.local.push({ appId: state.active, walletId }); + return true; + }, + }, + reduxStore: { getState: () => ({ + storage: { appId: state.active }, + bhr: { automaticCloudBackupByAppId: { A: consent } }, + }) }, + isAutomaticCloudBackupEnabled: (backup, appId) => backup.automaticCloudBackupByAppId[appId], + USDTWalletType: { DEFAULT: 'default' }, + USDTWalletSupportedNetwork: 'mainnet', + generateUSDTWallet: async () => { + if (switchDuringGeneration) state.active = 'B'; + return { id: 'wallet', name: 'new' }; + }, + canonical: JSON.stringify, + recoveryContent: (_kind, wallet) => wallet, + updateAppImage: (payload, originAppId) => ({ type: 'UPDATE_APP_IMAGE', payload, originAppId }), + invalidateBackupRepair: (appId) => ({ type: 'INVALIDATE_BACKUP_REPAIR', appId }), + setPendingAllBackup: (payload) => ({ type: 'SET_PENDING_ALL_BACKUP', payload }), + markBackupMutation: (appId) => state.invalidated.push(appId), + dispatch: (action) => state.dispatched.push(action), + Relay: { deleteAppImageEntity: async (body) => { + state.remote.push(body); + if (switchDuringRemote) state.active = 'B'; + return { updated: true }; + } }, + setError: (error) => state.errors.push(error), + captureError: () => {}, + }; + vm.runInNewContext(`${code}\nglobalThis.callbacks = { createWallet, deleteWallet, updateWallet };`, scope); + return { state, ...scope.callbacks }; +} + +test('unconsented USDT wallet deletes locally without a relay write', async () => { + const f = fixture({ consent: false }); + assert.equal(await f.deleteWallet('wallet'), true); + assert.deepEqual(f.state.remote, []); + assert.equal(f.state.local[0].appId, 'A'); +}); + +test('remote response after account switch cannot delete B local wallet', async () => { + const f = fixture({ switchDuringRemote: true }); + assert.equal(await f.deleteWallet('wallet'), false); + assert.equal(f.state.remote.length, 1); + assert.equal(f.state.remote[0].appId, 'A'); + assert.deepEqual(f.state.local, []); + assert.deepEqual(f.state.invalidated, ['A']); + assert.equal(f.state.dispatched.find((action) => action.type === 'SET_PENDING_ALL_BACKUP').payload.appId, 'A'); +}); + +test('a stale A callback invoked while B is active makes no write', async () => { + const f = fixture(); + f.state.active = 'B'; + assert.equal(await f.deleteWallet('wallet'), false); + assert.deepEqual(f.state.remote, []); + assert.deepEqual(f.state.local, []); +}); + +test('wallet generation after account switch cannot persist to B or dispatch backup', async () => { + const f = fixture({ switchDuringGeneration: true }); + const result = await f.createWallet({ type: 'default', name: 'new', description: '' }); + assert.equal(result.error, 'Account changed'); + assert.deepEqual(f.state.local, []); + assert.deepEqual(f.state.dispatched, []); +}); + +test('wallet create dispatches backup with captured originating account', async () => { + const f = fixture(); + const result = await f.createWallet({ type: 'default', name: 'new', description: '' }); + assert.equal(result.newWallet.id, 'wallet'); + assert.equal(f.state.local[0].appId, 'A'); + assert.equal(f.state.dispatched[0].originAppId, 'A'); +}); + +test('wallet update after account switch cannot dispatch backup for B', async () => { + const f = fixture({ switchDuringUpdate: true }); + assert.equal(await f.updateWallet({ id: 'wallet', name: 'new' }), false); + assert.equal(f.state.local[0].appId, 'A'); + assert.equal(f.state.dispatched.some((action) => action.type === 'UPDATE_APP_IMAGE'), false); + assert.deepEqual(f.state.invalidated, ['A']); +}); + +test('a stale wallet update invoked while B is active makes no write', async () => { + const f = fixture(); + f.state.active = 'B'; + assert.equal(await f.updateWallet({ id: 'wallet', name: 'new' }), false); + assert.deepEqual(f.state.local, []); + assert.deepEqual(f.state.dispatched, []); +}); diff --git a/tests/recovery/usdtBackup.test.cjs b/tests/recovery/usdtBackup.test.cjs index aedac01595..8041d14d2f 100644 --- a/tests/recovery/usdtBackup.test.cjs +++ b/tests/recovery/usdtBackup.test.cjs @@ -47,6 +47,7 @@ function hookFixture(options = {}) { canonical: image.canonical, recoveryContent: image.recoveryContent, appId: f.app.id, + isOriginCurrent: () => f.app.id === f.state.storage.appId, markBackupMutation: (id) => mutations.push(id), invalidateBackupRepair: (payload) => ({ type: 'invalidateBackupRepair', payload }), setPendingAllBackup: (payload) => ({ type: 'setPendingAllBackup', payload }), @@ -59,7 +60,10 @@ function hookFixture(options = {}) { pending.push(f.run('updateAppImageWorker', action)); } else { f.actions.push(action); - if (action.type === 'setPendingAllBackup') f.state.bhr.pendingAllBackup = action.payload; + if (action.type === 'setPendingAllBackup') { + f.state.bhr.pendingAllBackupByAppId[action.payload.appId] = action.payload.pending; + f.state.bhr.pendingAllBackup = action.payload.pending; + } } }, setError: (message) => errors.push(message), From 1e40ce7cffe63a3a568555cce1c3224ccf460251 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 22:07:49 +0530 Subject: [PATCH 2/3] test(backup): cover account switch during vault registration repair --- tests/recovery/vaultRegistration.test.cjs | 32 +++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/tests/recovery/vaultRegistration.test.cjs b/tests/recovery/vaultRegistration.test.cjs index c31762bddb..2a7e8f3efa 100644 --- a/tests/recovery/vaultRegistration.test.cjs +++ b/tests/recovery/vaultRegistration.test.cjs @@ -19,7 +19,7 @@ const vault = (id) => ({ specs: {}, }); -function registrationFixture({ incompleteReadback = false } = {}) { +function registrationFixture({ incompleteReadback = false, afterSnapshot, afterUpload } = {}) { const state = { appImage: { appId: 'disposable', wallets: {}, signers: {}, nodes: [], @@ -28,8 +28,13 @@ function registrationFixture({ incompleteReadback = false } = {}) { allVaultImages: [], labels: [], revision: 'a'.repeat(64), }; let uploads = 0; + let snapshotReads = 0; const f = harness({ adapter: async (endpoint, payload) => { - if (endpoint === 'getBackupSnapshot') return { data: clone(state) }; + if (endpoint === 'getBackupSnapshot') { + snapshotReads++; + if (afterSnapshot) await afterSnapshot(snapshotReads); + return { data: clone(state) }; + } assert.equal(endpoint, 'repairAppBackup'); assert.equal(payload.expectedRevision, state.revision); assert.equal(payload.replaceCurrentState, true); @@ -45,6 +50,7 @@ function registrationFixture({ incompleteReadback = false } = {}) { if (incompleteReadback) state.allVaultImages.pop(); state.labels = payload.labels; state.revision = 'b'.repeat(64); + if (afterUpload) await afterUpload(); return { data: { updated: true } }; } }); const cipherKey = encryption.generateEncryptionKey(f.app.primarySeed); @@ -92,6 +98,28 @@ test('an incomplete registration repair readback cannot be marked verified', asy assert.deepEqual(f.calls, ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot']); }); +test('account switch after registration snapshot prevents an upload for the old account', async () => { + let fixture; + fixture = registrationFixture({ afterSnapshot: (read) => { + if (read === 1) fixture.f.app.id = 'other-disposable-account'; + } }); + assert.equal(await fixture.f.run(true), 'unverified'); + assert.equal(fixture.uploads(), 0); + assert.deepEqual(fixture.f.calls, ['getBackupSnapshot']); + assert.ok(!fixture.f.phases.includes('verified')); +}); + +test('account switch after registration upload cannot claim a verified repair', async () => { + let fixture; + fixture = registrationFixture({ afterUpload: () => { + fixture.f.app.id = 'other-disposable-account'; + } }); + assert.equal(await fixture.f.run(true), 'unverified'); + assert.equal(fixture.uploads(), 1, 'the upload was for the original account'); + assert.deepEqual(fixture.f.calls, ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot']); + assert.ok(!fixture.f.phases.includes('verified')); +}); + test('registration-only drift is a difference while vault key and policy drift remain conflicts', async () => { const local = makeImage(), remote = makeImage(); local.vaults.first = vault('first'); From 81bc417cb42372a4eb7dc918db073684f8bf2687 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 15:09:40 +0530 Subject: [PATCH 3/3] Guard backup consent completion across account switches --- src/store/sagas/bhr.ts | 18 ++++---- src/store/store.ts | 14 ++++++ tests/recovery/accountBinding.test.cjs | 61 +++++++++++++++++++++++++- tests/recovery/sagaHarness.cjs | 1 + 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 152ac95bcf..bf2c651bee 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -1132,20 +1132,22 @@ export function* backupFreshnessWatcher() { function* backupAllSignersAndVaultsWorker({ appId }: { appId: string }) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); if (!appId || appId !== id) return false; + const selected = yield select((state: RootState) => state.storage.appId === appId); + if (!selected) return false; yield put(setBackupAllSuccess({ appId, status: false })); yield put(setBackupAllFailure({ appId, status: false })); yield put(setBackupAllLoading({ appId, status: true })); try { const verified = yield call(runBackupInspection, true, appId, true); const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - if (current?.id === id) { - if (verified) yield put(setAutomaticCloudBackup({ appId, enabled: true })); - yield put( - verified - ? setBackupAllSuccess({ appId, status: true }) - : setBackupAllFailure({ appId, status: true }) - ); - } + const stillSelected = yield select((state: RootState) => state.storage.appId === appId); + if (current?.id !== appId || !stillSelected) return false; + if (verified) yield put(setAutomaticCloudBackup({ appId, enabled: true })); + yield put( + verified + ? setBackupAllSuccess({ appId, status: true }) + : setBackupAllFailure({ appId, status: true }) + ); return verified; } finally { yield put(setBackupAllLoading({ appId, status: false })); diff --git a/src/store/store.ts b/src/store/store.ts index 9a94620c5d..f19aa9f6c4 100644 --- a/src/store/store.ts +++ b/src/store/store.ts @@ -115,6 +115,20 @@ const accountOwnedUtxoUiActions = new Set([ ]); const bindActionOrigin = (api) => (next) => (action) => { const originAppId = api.getState()?.storage?.appId; + const enablesBackup = action?.type === 'bhr/setAutomaticCloudBackup' && + action.payload?.enabled === true; + const reportsBackupSuccess = action?.type === 'bhr/setBackupAllSuccess' && + action.payload?.status === true; + if (enablesBackup || reportsBackupSuccess) { + const appId = action.payload.appId; + if (!appId || originAppId !== appId) return action; + try { + if ((dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp)?.id !== appId) + return action; + } catch { + return action; + } + } if (action?.originAppId && accountOwnedUtxoUiActions.has(action.type)) { try { if ( diff --git a/tests/recovery/accountBinding.test.cjs b/tests/recovery/accountBinding.test.cjs index b17dd2c3f2..7b27b562eb 100644 --- a/tests/recovery/accountBinding.test.cjs +++ b/tests/recovery/accountBinding.test.cjs @@ -1,7 +1,9 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); -const { fixture, wallet, signer, enums, loadModule } = require('./sagaHarness.cjs'); +const { fixture, wallet, signer, enums, loadModule, functions } = require('./sagaHarness.cjs'); const { harness } = require('./helpers.cjs'); +const vm = require('node:vm'); +const ts = require('typescript'); function switchToOptedInB(f) { f.app.id = 'B'; @@ -61,6 +63,63 @@ test('selected B blocks stale A writes even before Realm finishes switching', as assert.equal(f.collections.Wallet[0].specs.totalExternalAddresses, 4); }); +test('verified A backup completion after selected B switch cannot enable A or report success', async () => { + const f = fixture(); + const originAppId = f.app.id; + f.state.bhr.automaticCloudBackupByAppId[originAppId] = false; + f.scope.runBackupInspection = function* () { + f.state.storage.appId = 'B'; + f.state.bhr.automaticCloudBackupByAppId.B = true; + return true; + }; + const result = await f.run('backupAllSignersAndVaultsWorker', { appId: originAppId }); + assert.equal(result, false); + assert.ok(!f.actions.some((action) => action.type === 'setAutomaticCloudBackup' && + action.payload.enabled === true)); + assert.ok(!f.actions.some((action) => action.type === 'setBackupAllSuccess' && + action.payload.status === true)); +}); + +test('dispatch gate drops stale enable and success actions while preserving account-specific resets', () => { + const scope = { + Set, + RealmSchema: { KeeperApp: 'KeeperApp' }, + dbManager: { getObjectByIndex: () => ({ id: realmAppId }) }, + }; + let selectedAppId = 'B'; + let realmAppId = 'A'; + vm.runInNewContext(ts.transpileModule( + functions('src/store/store.ts', [ + 'accountOwnedActions', 'accountOwnedUtxoUiActions', 'bindActionOrigin', + ]), + { compilerOptions: { target: ts.ScriptTarget.ES2020 } } + ).outputText, scope); + const seen = []; + const middleware = scope.bindActionOrigin({ + getState: () => ({ storage: { appId: selectedAppId } }), + })((action) => { seen.push(action); return action; }); + const enableA = { type: 'bhr/setAutomaticCloudBackup', payload: { appId: 'A', enabled: true } }; + middleware(enableA); + assert.equal(seen.length, 0, 'selected B blocks A enable even while Realm still A'); + middleware({ type: 'bhr/setBackupAllSuccess', payload: { appId: 'A', status: true } }); + assert.equal(seen.length, 0, 'selected B blocks A success even while Realm still A'); + selectedAppId = 'A'; + realmAppId = 'B'; + middleware(enableA); + assert.equal(seen.length, 0, 'Realm B blocks A enable even while Redux still A'); + middleware({ type: 'bhr/setBackupAllSuccess', payload: { appId: 'A', status: true } }); + assert.equal(seen.length, 0, 'Realm B blocks A success even while Redux still A'); + realmAppId = 'A'; + middleware(enableA); + assert.equal(seen.length, 1); + middleware({ type: 'bhr/setBackupAllSuccess', payload: { appId: 'A', status: true } }); + assert.equal(seen.length, 2); + selectedAppId = 'B'; + middleware({ type: 'bhr/setAutomaticCloudBackup', payload: { appId: 'A', enabled: false } }); + middleware({ type: 'bhr/setBackupAllSuccess', payload: { appId: 'A', status: false } }); + assert.equal(seen.length, 4, 'A disable and success reset remain account-specific after switch'); +}); + test('A to opted-in B during connectivity wait blocks upload and preserves B local wallet', async () => { const f = fixture(); const originAppId = f.app.id; diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs index 9e99f72a2a..1e5fd2a8b4 100644 --- a/tests/recovery/sagaHarness.cjs +++ b/tests/recovery/sagaHarness.cjs @@ -288,6 +288,7 @@ function fixture(options = {}) { 'deleteAppImageEntityWorker', 'deleteVaultImageWorker', 'deleteBackupWorker', + 'backupAllSignersAndVaultsWorker', 'checkBackupCondition', 'setServerBackupFailed', 'updateAppImageWorker',