From ebea172d8655e1b0af64a90e41fe74d22e7a330e Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 01:23:41 +0530 Subject: [PATCH 1/8] Add privacy-safe stage diagnostics for backup verification --- src/services/backup/repair.ts | 27 +++++++++++++++++++++++++-- tests/recovery/helpers.cjs | 6 +++--- tests/recovery/repair.test.cjs | 9 +++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 25b543c7a..176781d03 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -35,6 +35,16 @@ export type RepairPhase = | 'verified' | 'conflict' | 'unverified'; +type InspectionStage = + | 'local-capture' + | 'snapshot-request' + | 'snapshot-validation' + | 'snapshot-decryption' + | 'comparison' + | 'repair-preparation' + | 'repair-upload' + | 'repair-readback' + | 'local-recheck'; const inFlight = new Map< string, { @@ -149,6 +159,7 @@ export function inspectBackup( listeners.forEach((listener) => listener(phase)); }; const result = withBackupSession(appId, async () => { + let stage: InspectionStage = 'local-capture'; const deadline = Date.now() + BACKUP_DEADLINE_MS; const revision = backupRevision(appId); const assertCurrent = () => { @@ -168,12 +179,14 @@ export function inspectBackup( assertCurrent(); let expectedRevision: string; let needsVaultRepair = false; - const read = async () => { + const read = async (readback = false) => { + stage = readback ? 'repair-readback' : 'snapshot-request'; const response = await boundedBackupPost( `${config.RELAY}getBackupSnapshot`, { appId }, deadline ); + if (!readback) stage = 'snapshot-validation'; assertCurrent(); if (!/^[a-f0-9]{64}$/.test(response.data?.revision)) throw new Error('Backup snapshot revision unavailable'); @@ -208,6 +221,7 @@ export function inspectBackup( }, } : response.data; + if (!readback) stage = 'snapshot-decryption'; const decoded = await decodeImage(key, availableResponse, appId, assertCurrent); needsVaultRepair = unavailable.length > 0 || @@ -219,6 +233,7 @@ export function inspectBackup( return decoded; }; const remote = await read(); + stage = 'comparison'; const contentComparison = await compareImages(local, remote, assertCurrent); const comparison = contentComparison === 'matched' && needsVaultRepair ? 'different' : contentComparison; @@ -232,6 +247,7 @@ export function inspectBackup( return 'different'; } if (comparison === 'different') { + stage = 'repair-preparation'; notify('preparing'); const payload = await encodeImage(app, local, assertCurrent); assertCurrent(); @@ -243,6 +259,7 @@ export function inspectBackup( throw new Error('Local backup changed'); assertCurrent(); notify('uploading'); + stage = 'repair-upload'; try { const response = await boundedBackupPost( `${config.RELAY}repairAppBackup`, @@ -257,13 +274,16 @@ export function inspectBackup( // A lost response is not proof the upload failed. Always read back. } notify('verifying'); - const verifiedRemote = await read(); + stage = 'repair-readback'; + const verifiedRemote = await read(true); + stage = 'repair-readback'; if ( needsVaultRepair || (await compareImages(local, verifiedRemote, assertCurrent)) !== 'matched' ) throw new Error('Backup not verified'); } + stage = 'local-recheck'; if ( (await compareImages(local, await captureBackupImage(assertCurrent), assertCurrent)) !== 'matched' @@ -273,6 +293,9 @@ export function inspectBackup( notify('verified'); return 'verified'; } catch { + // Only log the stage. Errors and response objects may contain encrypted + // backup data, account identifiers, headers, or request bodies. + console.warn('Assisted Server Backup check failed at stage:', stage); notify('unverified'); return 'unverified'; } diff --git a/tests/recovery/helpers.cjs b/tests/recovery/helpers.cjs index ccc8e1ad5..c03133b98 100644 --- a/tests/recovery/helpers.cjs +++ b/tests/recovery/helpers.cjs @@ -21,7 +21,7 @@ function harness(options = {}) { const remote = { appId: app.id, wallets: {}, signers: {}, nodes: [], vaults: [], labels: [] }; let vaults = [], labels = []; const revision = () => require('node:crypto').createHash('sha256').update(JSON.stringify({remote,vaults,labels})).digest('hex'); - const calls = [], phases = []; + const calls = [], phases = [], diagnostics = []; const db = { getObjectByIndex: (schema) => schema === 'KeeperApp' ? app : local[schema] }; const rest = { post: async (path, payload, _headers, config) => { calls.push(path.replace('fixture/', '')); @@ -48,8 +48,8 @@ function harness(options = {}) { 'src/utils/service-utilities/encryption': encryption, 'src/utils/utilities': { getKeyUID: s => s.id || s.masterFingerprint, sanitizeSeedKeyForBackup: s => s, sanitizeVaultSignersForSeedKeyBackup: s => s }, './transport': transport, './image': image, - }); - return { app, local, remote, calls, phases, transport, repair, + }, { console: { warn: (...args) => diagnostics.push(args) } }); + return { app, local, remote, calls, phases, diagnostics, transport, repair, run: (write = false) => repair.inspectBackup(app.id, write, phase => phases.push(phase)) }; } const wallet = (id = 'wallet', networkType = 'MAINNET') => ({ id, networkType, type: 'DEFAULT', diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index f72053092..467ef0ae0 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -21,6 +21,15 @@ for (const failure of ['readError','reject','corruptWrite']) test(`${failure} ne if (failure === 'readError') assert.deepEqual(f.calls, ['getBackupSnapshot']); }); +test('read-only failure identifies its stage without logging error contents or backup identifiers', async () => { + const f = harness({ adapter: async () => { throw Error('private-fixture-identifier'); } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-request']]); + assert.ok(!JSON.stringify(f.diagnostics).includes('private-fixture-identifier')); + assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + test('lost upload acknowledgement is resolved by readback without duplicate upload', async () => { const f = harness({ lostResponse: true }); f.local.Wallet.push(wallet()); assert.equal(await f.run(true), 'verified'); assert.deepEqual(f.calls, ['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); From a788900e41b61bbe8961a80d7c533fdd8dd87982 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 01:32:25 +0530 Subject: [PATCH 2/8] Retry read-only backup check after concurrent write --- src/services/backup/repair.ts | 27 +++++++++++++--- src/services/backup/transport.ts | 6 +++- tests/recovery/helpers.cjs | 1 + tests/recovery/repair.test.cjs | 53 ++++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 5 deletions(-) diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 176781d03..4385ed3d3 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -10,6 +10,7 @@ import { } from 'src/utils/utilities'; import { BACKUP_DEADLINE_MS, + backupQueuedRevision, backupRevision, boundedBackupPost, withBackupSession, @@ -158,17 +159,22 @@ export function inspectBackup( if (active) active.phase = phase; listeners.forEach((listener) => listener(phase)); }; - const result = withBackupSession(appId, async () => { + const inspectOnce = async (allowRetry: boolean): Promise => { let stage: InspectionStage = 'local-capture'; + let changedRevision = 0; const deadline = Date.now() + BACKUP_DEADLINE_MS; const revision = backupRevision(appId); const assertCurrent = () => { if ( Date.now() >= deadline || - (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId || - backupRevision(appId) !== revision + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId ) throw new Error('Backup changed during check'); + const currentRevision = backupRevision(appId); + if (currentRevision !== revision) { + changedRevision = currentRevision; + throw new Error('Backup changed during check'); + } }; try { notify('checking'); @@ -293,13 +299,26 @@ export function inspectBackup( notify('verified'); return 'verified'; } catch { + // A routine incremental write can be queued while a read-only check is + // running. Retry behind that write once before declaring the check failed. + if ( + changedRevision && + allowRetry && + !repair && + backupQueuedRevision(appId) >= changedRevision + ) + return 'retry'; // Only log the stage. Errors and response objects may contain encrypted // backup data, account identifiers, headers, or request bodies. console.warn('Assisted Server Backup check failed at stage:', stage); notify('unverified'); return 'unverified'; } - }); + }; + const runOnce = (allowRetry: boolean) => withBackupSession(appId, () => inspectOnce(allowRetry)); + const result: Promise = runOnce(true).then(async (phase) => + phase === 'retry' ? ((await runOnce(false)) as RepairPhase) : phase + ); inFlight.set(appId, { repair, promise: result, listeners }); const clean = () => { if (inFlight.get(appId)?.promise === result) inFlight.delete(appId); diff --git a/src/services/backup/transport.ts b/src/services/backup/transport.ts index 21339041e..c462fb2f9 100644 --- a/src/services/backup/transport.ts +++ b/src/services/backup/transport.ts @@ -3,7 +3,9 @@ import RestClient from '../rest/RestClient'; // One queue per account covers repair, incremental writes, labels and deletion. const queues = new Map>(); const revisions = new Map(); +const queuedMutationRevisions = new Map(); 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); export const BACKUP_STALL_MS = 30_000; export const BACKUP_DEADLINE_MS = 10 * 60_000; @@ -67,5 +69,7 @@ export function backupPost(path: string, body: any) { const appId = body.appId || body.appID; if (!appId) return Promise.reject(new Error('Missing backup account')); markBackupMutation(appId); - return withBackupSession(appId, () => boundedBackupPost(path, body)); + const result = withBackupSession(appId, () => boundedBackupPost(path, body)); + queuedMutationRevisions.set(appId, backupRevision(appId)); + return result; } diff --git a/tests/recovery/helpers.cjs b/tests/recovery/helpers.cjs index c03133b98..6950fb892 100644 --- a/tests/recovery/helpers.cjs +++ b/tests/recovery/helpers.cjs @@ -31,6 +31,7 @@ function harness(options = {}) { if (options.readError) throw Error('offline'); return { data: options.response || { appImage: remote, allVaultImages: vaults, labels, revision: revision() } }; } + if (path.endsWith('updateAppImage')) return { data: { updated: true } }; if (payload.expectedRevision !== revision()) throw Error('Backup changed'); if (options.reject) return { data: { updated: false } }; remote.wallets = { ...payload.walletObject }; remote.signers = { ...payload.signersObject }; remote.nodes = payload.nodes; diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index 467ef0ae0..14367ea19 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -30,6 +30,52 @@ test('read-only failure identifies its stage without logging error contents or b assert.deepEqual(f.calls, ['getBackupSnapshot']); }); +test('read-only check retries once after a concurrent incremental backup changes its revision', async () => { + let f, changed = false, write; + f = harness({ post: async ({ path, remote }) => { + if (path.endsWith('getBackupSnapshot') && !changed) { + changed = true; + write = f.transport.backupPost('fixture/updateAppImage', { appId: f.app.id }); + } + if (path.endsWith('updateAppImage')) { + remote.wallets.wallet = encryption.encrypt( + encryption.generateEncryptionKey(f.app.primarySeed), JSON.stringify(wallet()) + ); + } + } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(), 'verified'); + await write; + assert.deepEqual(f.calls, ['getBackupSnapshot', 'updateAppImage', 'getBackupSnapshot']); + assert.deepEqual(f.phases, ['checking', 'checking', 'verified']); + assert.deepEqual(f.diagnostics, []); +}); + +test('early revision change without a queued write stays unverified', async () => { + let f; + f = harness({ post: async ({ path }) => { + if (path.endsWith('getBackupSnapshot')) f.transport.markBackupMutation(f.app.id); + } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.deepEqual(f.phases, ['checking', 'unverified']); +}); + +test('continuous queued writes limit a read-only check to one retry', async () => { + let f; + const writes = []; + f = harness({ post: async ({ path }) => { + if (path.endsWith('getBackupSnapshot')) + writes.push(f.transport.backupPost('fixture/updateAppImage', { appId: f.app.id })); + } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(), 'unverified'); + await Promise.all(writes); + assert.equal(f.calls.filter((path) => path === 'getBackupSnapshot').length, 2); + assert.deepEqual(f.phases, ['checking', 'checking', 'unverified']); +}); + test('lost upload acknowledgement is resolved by readback without duplicate upload', async () => { const f = harness({ lostResponse: true }); f.local.Wallet.push(wallet()); assert.equal(await f.run(true), 'verified'); assert.deepEqual(f.calls, ['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); @@ -96,6 +142,7 @@ test('mutation arriving during upload invalidates completion and remains queued let f; f = harness({ post: async ({ path }) => { if (path.endsWith('repairAppBackup')) f.transport.markBackupMutation(f.app.id); } }); f.local.Wallet.push(wallet()); assert.equal(await f.run(true), 'unverified'); assert.ok(!f.phases.includes('verified')); + assert.deepEqual(f.calls, ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot']); }); test('account switch during check cannot upload one account with another account data', async () => { @@ -111,6 +158,12 @@ test('chunked encryption remains compatible with existing recovery including Uni assert.deepEqual(JSON.parse(JSON.stringify(await image.decryptRecord('test-only',cipher))), record); }); +test('existing large CryptoJS ciphertext remains readable by streamed backup verification', async () => { + const record = { id: 'legacy-large', text: 'a'.repeat(100_000) + '🔑বাংলা' }; + const ciphertext = encryption.encrypt('test-only', JSON.stringify(record)); + assert.equal(JSON.stringify(await image.decryptRecord('test-only', ciphertext)), JSON.stringify(record)); +}); + test('oversized record fails without uploading or truncating', async () => { const f = harness(); f.local.Wallet.push({ ...wallet(), text:'x'.repeat(image.MAX_RECORD_BYTES) }); assert.equal(await f.run(true),'unverified'); assert.deepEqual(f.calls,[]); From 3f9744c7d4415204f31a4417be660b0ad62a297b Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 01:46:51 +0530 Subject: [PATCH 3/8] Keep backup stage diagnostics in production bundle --- src/services/backup/repair.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 4385ed3d3..65a1953ff 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -310,7 +310,7 @@ export function inspectBackup( return 'retry'; // Only log the stage. Errors and response objects may contain encrypted // backup data, account identifiers, headers, or request bodies. - console.warn('Assisted Server Backup check failed at stage:', stage); + globalThis.console.warn('Assisted Server Backup check failed at stage:', stage); notify('unverified'); return 'unverified'; } From ef1f561f446f34b7f2202d65f48b5c3698582075 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 01:53:55 +0530 Subject: [PATCH 4/8] Classify backup snapshot transport failures without request data --- src/services/backup/repair.ts | 8 +++++--- src/services/backup/transport.ts | 30 +++++++++++++++++++++++++++--- tests/recovery/repair.test.cjs | 14 +++++++++++++- 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 65a1953ff..9d9c2f80c 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -10,6 +10,7 @@ import { } from 'src/utils/utilities'; import { BACKUP_DEADLINE_MS, + BackupRequestError, backupQueuedRevision, backupRevision, boundedBackupPost, @@ -298,7 +299,7 @@ export function inspectBackup( assertCurrent(); notify('verified'); return 'verified'; - } catch { + } catch (error) { // A routine incremental write can be queued while a read-only check is // running. Retry behind that write once before declaring the check failed. if ( @@ -308,9 +309,10 @@ export function inspectBackup( backupQueuedRevision(appId) >= changedRevision ) return 'retry'; - // Only log the stage. Errors and response objects may contain encrypted + // Only log fixed categories. Errors and responses can contain encrypted // backup data, account identifiers, headers, or request bodies. - globalThis.console.warn('Assisted Server Backup check failed at stage:', stage); + const category = error instanceof BackupRequestError ? error.category : 'non-transport'; + globalThis.console.warn('Assisted Server Backup check failed at stage:', stage, category); notify('unverified'); return 'unverified'; } diff --git a/src/services/backup/transport.ts b/src/services/backup/transport.ts index c462fb2f9..6b23798c7 100644 --- a/src/services/backup/transport.ts +++ b/src/services/backup/transport.ts @@ -10,6 +10,30 @@ export const markBackupMutation = (id: string) => revisions.set(id, backupRevisi export const BACKUP_STALL_MS = 30_000; export const BACKUP_DEADLINE_MS = 10 * 60_000; +export type BackupRequestFailure = 'http-4xx' | 'http-5xx' | 'timeout' | 'network' | 'other'; + +export class BackupRequestError extends Error { + constructor(public readonly category: BackupRequestFailure) { + super('Backup request could not be completed'); + } +} + +function requestFailureCategory(error: unknown, aborted: boolean): BackupRequestFailure { + if (aborted) return 'timeout'; + if (!error || typeof error !== 'object') return 'other'; + const failure = error as { response?: { status?: unknown }; status?: unknown; code?: unknown; name?: unknown; message?: unknown }; + const status = failure.response?.status ?? failure.status; + if (typeof status === 'number') { + if (status >= 400 && status < 500) return 'http-4xx'; + if (status >= 500 && status < 600) return 'http-5xx'; + return 'other'; + } + if (failure.code === 'ECONNABORTED' || failure.code === 'ETIMEDOUT' || failure.name === 'AbortError') + return 'timeout'; + if (failure.code === 'ERR_NETWORK' || failure.message === 'Network Error') return 'network'; + return 'other'; +} + export function withBackupSession(id: string, work: () => Promise): Promise { const previous = queues.get(id) || Promise.resolve(); const result = previous.catch(() => undefined).then(work); @@ -37,7 +61,7 @@ export async function boundedBackupPost( idle = setTimeout(() => controller.abort(), BACKUP_STALL_MS); }; const remaining = deadline - Date.now(); - if (remaining <= 0) throw new Error('Backup deadline exceeded'); + if (remaining <= 0) throw new BackupRequestError('timeout'); const total = setTimeout(() => controller.abort(), remaining); resetIdle(); try { @@ -56,9 +80,9 @@ export async function boundedBackupPost( } }, }); - } catch { + } catch (error) { // Do not propagate Axios errors: they can contain request bodies and headers. - throw new Error('Backup request could not be completed'); + throw new BackupRequestError(requestFailureCategory(error, controller.signal.aborted)); } finally { clearTimeout(idle); clearTimeout(total); diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index 14367ea19..59e97921e 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -25,11 +25,23 @@ test('read-only failure identifies its stage without logging error contents or b const f = harness({ adapter: async () => { throw Error('private-fixture-identifier'); } }); f.local.Wallet.push(wallet()); assert.equal(await f.run(), 'unverified'); - assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-request']]); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-request', 'other']]); assert.ok(!JSON.stringify(f.diagnostics).includes('private-fixture-identifier')); assert.deepEqual(f.calls, ['getBackupSnapshot']); }); +for (const [error, category] of [ + [{ response: { status: 404, data: 'private-fixture-identifier' }, config: { headers: { Authorization: 'private-fixture-identifier' } } }, 'http-4xx'], + [{ response: { status: 503, data: 'private-fixture-identifier' } }, 'http-5xx'], + [{ code: 'ECONNABORTED', message: 'private-fixture-identifier' }, 'timeout'], + [{ code: 'ERR_NETWORK', message: 'private-fixture-identifier' }, 'network'], +]) test(`snapshot transport diagnostics classify ${category} without request data`, async () => { + const f = harness({ adapter: async () => { throw error; } }); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-request', category]]); + assert.ok(!JSON.stringify(f.diagnostics).includes('private-fixture-identifier')); +}); + test('read-only check retries once after a concurrent incremental backup changes its revision', async () => { let f, changed = false, write; f = harness({ post: async ({ path, remote }) => { From 4b303f7b22baa5174bd7a95cd531e77995ee13c5 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 17:21:05 +0530 Subject: [PATCH 5/8] Check backup freshness after wallet sync completes --- src/store/sagaActions/wallets.ts | 6 +++-- src/store/sagas/login.ts | 12 +--------- src/store/sagas/wallets.ts | 31 +++++++++++++++++++++---- tests/recovery/backupFreshness.test.cjs | 27 +++++++++++++++++++++ tests/recovery/sagaHarness.cjs | 10 +++++++- 5 files changed, 68 insertions(+), 18 deletions(-) diff --git a/src/store/sagaActions/wallets.ts b/src/store/sagaActions/wallets.ts index 0508d2415..b9078e1e3 100644 --- a/src/store/sagaActions/wallets.ts +++ b/src/store/sagaActions/wallets.ts @@ -29,13 +29,15 @@ export const getTestcoins = (testWallet: Wallet) => ({ export const autoSyncWallets = ( syncAll?: boolean, hardRefresh?: boolean, - addNotifications?: boolean + addNotifications?: boolean, + backupCheckAppId?: string ) => ({ type: AUTO_SYNC_WALLETS, payload: { syncAll, hardRefresh, addNotifications, + backupCheckAppId, }, }); @@ -145,4 +147,4 @@ export const generateNewAddress = (wallet: Wallet | Vault) => ({ export const updateVaultSignersXpriv = (signers: Signer[]) => ({ type: UPDATED_VAULT_SIGNERS_XPRIV, signers, -}); \ No newline at end of file +}); diff --git a/src/store/sagas/login.ts b/src/store/sagas/login.ts index 35028a9bc..93465bf27 100644 --- a/src/store/sagas/login.ts +++ b/src/store/sagas/login.ts @@ -51,7 +51,6 @@ import { createWatcher } from '../utilities'; import { fetchExchangeRates } from '../sagaActions/send_and_receive'; import { setLoginMethod } from '../reducers/settings'; import { setSubscription } from 'src/store/sagaActions/settings'; -import { checkBackupFreshness } from '../sagaActions/bhr'; import { uaiChecks } from '../sagaActions/uai'; import { applyUpgradeSequence } from './upgrade'; import { resetSyncing } from '../reducers/wallets'; @@ -228,7 +227,7 @@ function* credentialsAuthWorker({ payload }) { // Wallet/node refresh runs through its watcher after local unlock. // Waiting for network work here can hold the success modal for 15s. yield put(resetSyncing()); - yield put(autoSyncWallets(false, false, true)); + yield put(autoSyncWallets(false, false, true, id)); yield put( uaiChecks([ @@ -241,15 +240,6 @@ function* credentialsAuthWorker({ payload }) { ]) ); - const { - pendingAllBackup, - automaticCloudBackup, - backupRepairCompletedByAppId = {}, - } = yield select((state: RootState) => state.bhr); - // Check without uploading; a mismatch requires Back Up Now. - if (automaticCloudBackup && (pendingAllBackup || !backupRepairCompletedByAppId[id])) { - yield put(checkBackupFreshness()); - } if (!allAccounts.length) { // upgraded app yield put(addAccount(appId)); diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts index d212e033d..cd3d78625 100644 --- a/src/store/sagas/wallets.ts +++ b/src/store/sagas/wallets.ts @@ -71,6 +71,7 @@ import { } from 'src/utils/utilities'; import { COLLABORATIVE_SCHEME } from 'src/screens/SigningDevices/SetupCollaborativeWallet'; import { RootState } from '../store'; +import { checkBackupFreshness } from '../sagaActions/bhr'; import { initiateVaultMigration, @@ -633,7 +634,7 @@ function* refreshWalletsWorker({ }); try { - if (!wallets || wallets.length === 0) return; + if (!wallets || wallets.length === 0) return true; if (!ELECTRUM_CLIENT.isClientConnected) { ElectrumClient.resetCurrentPeerIndex(); @@ -882,6 +883,7 @@ function* refreshWalletsWorker({ yield put(setPendingDustToast(synchedWallet.id)); } } // end for (synchedWalletWithUTXOs) + return true; } catch (err) { if ([ELECTRUM_NOT_CONNECTED_ERR, ELECTRUM_NOT_CONNECTED_ERR_TOR].includes(err?.message)) { yield put( @@ -897,6 +899,7 @@ function* refreshWalletsWorker({ ); captureError(err); } + return false; } finally { yield put(setSyncing({ wallets, isSyncing: false })); } @@ -907,9 +910,14 @@ export const refreshWalletsWatcher = createWatcher(refreshWalletsWorker, REFRESH export function* autoWalletsSyncWorker({ payload, }: { - payload: { syncAll?: boolean; hardRefresh?: boolean; addNotifications?: boolean }; + payload: { + syncAll?: boolean; + hardRefresh?: boolean; + addNotifications?: boolean; + backupCheckAppId?: string; + }; }) { - const { syncAll, hardRefresh, addNotifications } = payload; + 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); const { bitcoinNetworkType } = yield select((state: RootState) => state.settings); @@ -923,8 +931,9 @@ export function* autoWalletsSyncWorker({ } walletsToSync = walletsToSync.filter((wallet) => wallet.networkType === bitcoinNetworkType); + let refreshSucceeded = true; if (walletsToSync.length) { - yield call(refreshWalletsWorker, { + refreshSucceeded = yield call(refreshWalletsWorker, { payload: { wallets: walletsToSync, options: { @@ -934,6 +943,20 @@ 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) { + const { appId } = yield select((state: RootState) => state.storage); + const { automaticCloudBackup, pendingAllBackup, backupRepairCompletedByAppId = {} } = + yield select((state: RootState) => state.bhr); + if ( + appId === backupCheckAppId && + automaticCloudBackup && + (pendingAllBackup || !backupRepairCompletedByAppId[appId]) + ) { + yield put(checkBackupFreshness()); + } + } } export const autoWalletsSyncWatcher = createWatcher(autoWalletsSyncWorker, AUTO_SYNC_WALLETS); diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs index 03ff4b9ab..e03ad47b9 100644 --- a/tests/recovery/backupFreshness.test.cjs +++ b/tests/recovery/backupFreshness.test.cjs @@ -3,6 +3,33 @@ const assert = require('node:assert/strict'); const { fixture, enums, encryption, wallet, loadModule } = require('./sagaHarness.cjs'); const { NetworkType, WalletType } = enums; +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.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); + const running = f.run('autoWalletsSyncWorker', { + payload: { syncAll: false, hardRefresh: false, addNotifications: true, backupCheckAppId: f.app.id }, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(f.calls.map(([type]) => type), ['sync']); + assert.equal(f.actions.some((action) => action.type === 'checkBackupFreshness'), false); + finishSync(); + await running; + assert.equal(f.actions.filter((action) => action.type === 'checkBackupFreshness').length, 1); +}); + +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.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); + await f.run('autoWalletsSyncWorker', { + payload: { backupCheckAppId: f.app.id }, + }); + assert.equal(f.actions.some((action) => action.type === 'checkBackupFreshness'), false); + } +}); + for (const network of [NetworkType.MAINNET, NetworkType.TESTNET]) { test(`wallet added after initial backup survives encrypted restore: ${network}`, async () => { const f = fixture(); diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs index ab82a1d9c..37cc5412d 100644 --- a/tests/recovery/sagaHarness.cjs +++ b/tests/recovery/sagaHarness.cjs @@ -77,6 +77,7 @@ const signer = (fingerprint, networkType, type = enums.SignerType.COLDCARD, acco function fixture(options = {}) { const appId = require('crypto').createHash('sha256').update(Buffer.from('ab'.repeat(32), 'hex')).digest('hex'); const state = { + storage: { appId }, bhr: { automaticCloudBackup: true, pendingAllBackup: false, @@ -213,6 +214,12 @@ function fixture(options = {}) { semver: require('semver'), setupRecoveryKeySigningKey: () => signer('RECOVERY', NetworkType.MAINNET, enums.SignerType.SEED_WORDS), applyUpgradeSequence: () => {}, + refreshWalletsWorker: async () => { + calls.push(['sync']); + if (options.syncGate) await options.syncGate; + if (options.switchAppDuringSync) state.storage.appId = 'another-app'; + return options.syncFails !== true; + }, }; const names = [ 'setBackupRepairCompleted', @@ -235,6 +242,7 @@ function fixture(options = {}) { 'setAppId', 'setAppCreated', 'autoSyncWallets', + 'checkBackupFreshness', 'uaiChecks', 'loadConciergeUser', 'loadConciergeTickets', @@ -264,7 +272,7 @@ function fixture(options = {}) { functions('src/store/sagas/wallets.ts', [ 'addNewWalletsWorker', 'addSigningDeviceWorker', 'mergeSimilarKeysWorker', 'updateVaultSignerXprivWorker', 'updateSignerDetailsWorker', - 'updateKeyDetailsWorker', + 'updateKeyDetailsWorker', 'autoWalletsSyncWorker', ]); vm.runInNewContext( ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, From 8fa6bf7446bd828b8c446503312eec0566d8b400 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 18:20:05 +0530 Subject: [PATCH 6/8] Retry transient read-only backup checks within one deadline --- src/services/backup/repair.ts | 24 ++++++-- tests/recovery/helpers.cjs | 5 +- tests/recovery/repair.test.cjs | 101 ++++++++++++++++++++++++++++++++- 3 files changed, 123 insertions(+), 7 deletions(-) diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 9d9c2f80c..865cd213e 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -160,10 +160,12 @@ export function inspectBackup( if (active) active.phase = phase; listeners.forEach((listener) => listener(phase)); }; + let deadline: number; const inspectOnce = async (allowRetry: boolean): Promise => { let stage: InspectionStage = 'local-capture'; let changedRevision = 0; - const deadline = Date.now() + BACKUP_DEADLINE_MS; + // One deadline covers both read-only attempts; a retry must not double it. + deadline ??= Date.now() + BACKUP_DEADLINE_MS; const revision = backupRevision(appId); const assertCurrent = () => { if ( @@ -301,12 +303,26 @@ export function inspectBackup( return 'verified'; } catch (error) { // A routine incremental write can be queued while a read-only check is - // running. Retry behind that write once before declaring the check failed. + // running. A transient snapshot request can also fail while the backup is + // healthy. Retry either case once behind queued writes, within the same + // deadline. Never retry a repair, invalid response, or account switch. + let accountIsCurrent = false; + try { + accountIsCurrent = (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id === appId; + } catch { + // Realm may already be closed during an account switch. + } + const queuedWriteChanged = changedRevision && backupQueuedRevision(appId) >= changedRevision; + const transientSnapshotFailure = + stage === 'snapshot-request' && + error instanceof BackupRequestError && + ['http-5xx', 'network', 'timeout'].includes(error.category); if ( - changedRevision && allowRetry && !repair && - backupQueuedRevision(appId) >= changedRevision + accountIsCurrent && + Date.now() < deadline && + (queuedWriteChanged || transientSnapshotFailure) ) return 'retry'; // Only log fixed categories. Errors and responses can contain encrypted diff --git a/tests/recovery/helpers.cjs b/tests/recovery/helpers.cjs index 6950fb892..99e48d7bf 100644 --- a/tests/recovery/helpers.cjs +++ b/tests/recovery/helpers.cjs @@ -41,7 +41,8 @@ function harness(options = {}) { if (options.lostResponse) throw Error('response lost after commit'); return { data: { updated: true } }; } }; - const transport = loadModule('src/services/backup/transport.ts', { '../rest/RestClient': rest }); + const clock = options.now ? { Date: { now: options.now } } : {}; + const transport = loadModule('src/services/backup/transport.ts', { '../rest/RestClient': rest }, clock); const repair = loadModule('src/services/backup/repair.ts', { 'src/storage/realm/dbManager': db, 'src/storage/realm/enum': { RealmSchema: new Proxy({}, { get: (_, name) => name }) }, @@ -49,7 +50,7 @@ function harness(options = {}) { 'src/utils/service-utilities/encryption': encryption, 'src/utils/utilities': { getKeyUID: s => s.id || s.masterFingerprint, sanitizeSeedKeyForBackup: s => s, sanitizeVaultSignersForSeedKeyBackup: s => s }, './transport': transport, './image': image, - }, { console: { warn: (...args) => diagnostics.push(args) } }); + }, { ...clock, console: { warn: (...args) => diagnostics.push(args) } }); return { app, local, remote, calls, phases, diagnostics, transport, repair, run: (write = false) => repair.inspectBackup(app.id, write, phase => phases.push(phase)) }; } diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index 59e97921e..68883e696 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -1,6 +1,6 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); -const { encryption, image, makeImage, harness, wallet } = require('./helpers.cjs'); +const { encryption, image, makeImage, harness, wallet, loadModule } = require('./helpers.cjs'); test('upgrade check detects omissions without uploading; explicit repair verifies readback', async () => { const f = harness(); f.local.Wallet.push(wallet()); @@ -42,6 +42,105 @@ for (const [error, category] of [ assert.ok(!JSON.stringify(f.diagnostics).includes('private-fixture-identifier')); }); +for (const [error, category] of [ + [{ response: { status: 503, data: 'private-fixture-identifier' } }, 'http-5xx'], + [{ code: 'ERR_NETWORK', message: 'private-fixture-identifier' }, 'network'], + [{ code: 'ECONNABORTED', message: 'private-fixture-identifier' }, 'timeout'], +]) test(`read-only ${category} failure retries once and verifies the existing backup without upload`, async () => { + let calls = 0; + const f = harness({ post: async ({ path }) => { + if (path.endsWith('getBackupSnapshot') && ++calls === 1) throw error; + } }); + assert.equal(await f.run(), 'verified'); + assert.deepEqual(f.calls, ['getBackupSnapshot', 'getBackupSnapshot']); + assert.deepEqual(f.phases, ['checking', 'checking', 'verified']); + assert.deepEqual(f.diagnostics, []); +}); + +for (const os of ['ios', 'android']) test(`${os} RestClient preserves the read-only retry and abortable transport`, async () => { + const requests = []; + const rest = loadModule('src/services/rest/RestClient.ts', { + axios: { post: async (path, body, options) => { + requests.push({ path, body, options }); + if (requests.length === 1) throw { code: 'ERR_NETWORK' }; + return { data: { + appImage: { appId: 'disposable', wallets: {}, signers: {}, nodes: [], vaults: [], labels: [] }, + allVaultImages: [], labels: [], revision: 'a'.repeat(64), + } }; + } }, + 'react-native-device-info': { getVersion: () => 'fixture', getBuildNumber: () => 'fixture' }, + 'react-native': { Platform: { OS: os } }, + 'src/utils/service-utilities/config': { HEXA_ID: 'fixture-only' }, + }).default; + const f = harness({ adapter: (path, body, options) => rest.post(path, body, undefined, options) }); + assert.equal(await f.run(), 'verified'); + assert.deepEqual(requests.map(({ path }) => path), ['getBackupSnapshot', 'getBackupSnapshot']); + for (const { body, options } of requests) { + assert.deepEqual(Object.keys(body), ['appId']); + assert.equal(options.headers.os, os); + assert.equal(options.signal.aborted, false); + assert.equal(typeof options.onDownloadProgress, 'function'); + } +}); + +test('read-only retry shares the first attempt deadline', async () => { + let now = 0, reads = 0; + const f = harness({ now: () => now, post: async ({ path }) => { + if (path.endsWith('getBackupSnapshot')) { + now += 300_000; + if (++reads === 1) throw { code: 'ERR_NETWORK' }; + } + } }); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot', 'getBackupSnapshot']); + assert.deepEqual(f.phases, ['checking', 'checking', 'unverified']); +}); + +test('expired inspection makes no transient retry', async () => { + let now = 0; + const f = harness({ now: () => now, post: async () => { + now = 600_000; + throw { code: 'ERR_NETWORK' }; + } }); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +test('persistent network failures stop after one read-only retry', async () => { + const f = harness({ adapter: async () => { throw { code: 'ERR_NETWORK' }; } }); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot', 'getBackupSnapshot']); + assert.deepEqual(f.phases, ['checking', 'checking', 'unverified']); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-request', 'network']]); +}); + +test('4xx responses and invalid snapshots never retry', async () => { + for (const options of [ + { adapter: async () => { throw { response: { status: 404 } }; } }, + { response: { revision: 'a'.repeat(64) } }, + ]) { + const f = harness(options); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + } +}); + +test('transient snapshot failure after account switch makes no retry or upload', async () => { + const f = harness({ post: async ({ app }) => { + app.id = 'second'; + throw { code: 'ERR_NETWORK' }; + } }); + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +test('repair does not retry a failed snapshot request', async () => { + const f = harness({ adapter: async () => { throw { code: 'ERR_NETWORK' }; } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + test('read-only check retries once after a concurrent incremental backup changes its revision', async () => { let f, changed = false, write; f = harness({ post: async ({ path, remote }) => { From ccfdd3568310171898222da1b02b49a57d4e3e26 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 17:09:35 +0530 Subject: [PATCH 7/8] Classify malformed backup snapshots before decryption --- src/services/backup/image.ts | 28 +++++++++----- src/services/backup/repair.ts | 11 +++++- src/services/backup/restore.ts | 6 ++- tests/recovery/repair.test.cjs | 70 ++++++++++++++++++++++++++++++++++ 4 files changed, 103 insertions(+), 12 deletions(-) diff --git a/src/services/backup/image.ts b/src/services/backup/image.ts index f4e7ca668..c4325c643 100644 --- a/src/services/backup/image.ts +++ b/src/services/backup/image.ts @@ -16,6 +16,8 @@ export const pauseBackup = () => export const MAX_RECORD_BYTES = 8 * 1024 * 1024; export const MAX_BACKUP_BYTES = 32 * 1024 * 1024; +export class BackupSnapshotValidationError extends Error {} + export function canonical(value: any): string { if (value === undefined) return 'null'; if (value === null || typeof value !== 'object') return JSON.stringify(value); @@ -211,7 +213,7 @@ export async function encryptRecord(key: string, record: any): Promise { export async function decryptRecord(key: string, value: unknown) { if (typeof value !== 'string' || value.length > MAX_RECORD_BYTES * 2) - throw new Error('Invalid backup record'); + throw new BackupSnapshotValidationError('Invalid backup record'); // Parsing/format decoding still require native performance validation at the // supported size ceiling. Yield before and after each record. await pauseBackup(); @@ -238,7 +240,7 @@ export async function decryptRecord(key: string, value: unknown) { } const record = JSON.parse(text); if (!record || typeof record !== 'object' || Array.isArray(record)) - throw new Error('Invalid backup record'); + throw new BackupSnapshotValidationError('Invalid backup record'); await pauseBackup(); return record; } @@ -254,12 +256,16 @@ export async function decodeImage( !app || app.appId !== appId || !app.wallets || + typeof app.wallets !== 'object' || + Array.isArray(app.wallets) || !app.signers || + typeof app.signers !== 'object' || + Array.isArray(app.signers) || !Array.isArray(app.nodes) || !Array.isArray(response.allVaultImages) || !Array.isArray(response.labels) ) - throw new Error('Incomplete backup response'); + throw new BackupSnapshotValidationError('Incomplete backup response'); const checkReferences = (expected: unknown, actual: unknown[]) => { if (expected === undefined) return; // Legacy backups can omit reference lists. if ( @@ -269,7 +275,7 @@ export async function decodeImage( new Set(actual).size !== actual.length || actual.some((id) => typeof id !== 'string' || !expected.includes(id)) ) - throw new Error('Incomplete backup references'); + throw new BackupSnapshotValidationError('Incomplete backup references'); }; checkReferences( app.vaults, @@ -283,13 +289,15 @@ export async function decodeImage( let totalBytes = 0; const decode = async (value: unknown) => { checkpoint(); - if (typeof value !== 'string') throw new Error('Invalid backup record'); + if (typeof value !== 'string') throw new BackupSnapshotValidationError('Invalid backup record'); totalBytes += value.length; - if (totalBytes > MAX_BACKUP_BYTES) throw new Error('Backup exceeds supported size'); + if (totalBytes > MAX_BACKUP_BYTES) + throw new BackupSnapshotValidationError('Backup exceeds supported size'); return decryptRecord(key, value); }; const add = (kind: keyof BackupImage, id: string, record: any) => { - if (!id || image[kind][id]) throw new Error('Duplicate or unidentified backup record'); + if (!id || image[kind][id]) + throw new BackupSnapshotValidationError('Duplicate or unidentified backup record'); image[kind][id] = record; }; for (const value of Object.values(app.wallets)) { @@ -303,7 +311,7 @@ export async function decodeImage( for (const value of response.allVaultImages) { const record = await decode(value?.vault); if (value.vaultId !== undefined && value.vaultId !== record.id) - throw new Error('Vault backup identity mismatch'); + throw new BackupSnapshotValidationError('Vault backup identity mismatch'); add('vaults', record.id, record); } for (const value of app.nodes) { @@ -316,8 +324,8 @@ export async function decodeImage( } // A partial relay response must never look like an empty backup. if (Array.isArray(app.vaults) && app.vaults.length !== Object.keys(image.vaults).length) - throw new Error('Incomplete vault backup'); + throw new BackupSnapshotValidationError('Incomplete vault backup'); if (Array.isArray(app.labels) && app.labels.length !== Object.keys(image.labels).length) - throw new Error('Incomplete label backup'); + throw new BackupSnapshotValidationError('Incomplete label backup'); return image; } diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 865cd213e..20024cba0 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -18,6 +18,7 @@ import { } from './transport'; import { BackupImage, + BackupSnapshotValidationError, canonical, compareImages, decodeImage, @@ -328,7 +329,15 @@ export function inspectBackup( // Only log fixed categories. Errors and responses can contain encrypted // backup data, account identifiers, headers, or request bodies. const category = error instanceof BackupRequestError ? error.category : 'non-transport'; - globalThis.console.warn('Assisted Server Backup check failed at stage:', stage, category); + const diagnosticStage = + stage === 'snapshot-decryption' && error instanceof BackupSnapshotValidationError + ? 'snapshot-validation' + : stage; + globalThis.console.warn( + 'Assisted Server Backup check failed at stage:', + diagnosticStage, + category + ); notify('unverified'); return 'unverified'; } diff --git a/src/services/backup/restore.ts b/src/services/backup/restore.ts index 80a7b8bdf..4b521b3cd 100644 --- a/src/services/backup/restore.ts +++ b/src/services/backup/restore.ts @@ -11,12 +11,16 @@ export async function prepareRecoveryImage( labels: any[] ) { if (!appImage || appImage.appId !== appId) throw new Error('Recovery data unavailable'); + // Older Relay registrations and deletions stored empty maps as empty arrays. + // Keep those recoverable, but let decodeImage reject nonempty malformed arrays. + const legacyEmptyMap = (value: any) => (Array.isArray(value) && !value.length ? {} : value); return decodeImage( encryptionKey, { appImage: { ...appImage, - signers: appImage.signers === undefined ? {} : appImage.signers, + wallets: legacyEmptyMap(appImage.wallets), + signers: legacyEmptyMap(appImage.signers === undefined ? {} : appImage.signers), nodes: appImage.nodes === undefined ? [] : appImage.nodes, }, allVaultImages, diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index 68883e696..15ad8af32 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -125,6 +125,76 @@ test('4xx responses and invalid snapshots never retry', async () => { } }); +for (const [name, change] of [ + ['wrong account', (response) => { response.appImage.appId = 'another-account'; }], + ['invalid wallet collection', (response) => { response.appImage.wallets = 1; }], + ['invalid signer collection', (response) => { response.appImage.signers = []; }], + ['non-string record', (response) => { response.appImage.wallets.wallet = 42; }], + ['missing referenced vault', (response) => { response.appImage.vaults = ['missing']; }], + ['duplicate decrypted IDs', (response, key) => { + const encrypted = encryption.encrypt(key, JSON.stringify(wallet())); + response.appImage.wallets = { first: encrypted, second: encrypted }; + }], + ['vault ID mismatch', (response, key) => { + response.appImage.vaults = ['other']; + response.allVaultImages = [{ vaultId: 'other', vault: encryption.encrypt(key, JSON.stringify({ id: 'vault' })) }]; + }], + ['invalid decrypted record type', (response, key) => { + response.appImage.wallets.wallet = encryption.encrypt(key, '42'); + }], +]) test(`snapshot ${name} reports validation failure without retry or upload`, async () => { + const options = {}; + const f = harness(options); + const response = { + revision: 'a'.repeat(64), + appImage: { appId: f.app.id, wallets: {}, signers: {}, nodes: [], vaults: [], labels: [] }, + allVaultImages: [], labels: [], + }; + change(response, encryption.generateEncryptionKey(f.app.primarySeed)); + options.response = response; + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-validation', 'non-transport']]); +}); + +test('invalid decrypted JSON reports decryption failure without retry or upload', async () => { + const options = {}; + const f = harness(options); + options.response = { + revision: 'a'.repeat(64), + appImage: { + appId: f.app.id, + wallets: { wallet: encryption.encrypt(encryption.generateEncryptionKey(f.app.primarySeed), '{') }, + signers: {}, nodes: [], vaults: [], labels: [], + }, + allVaultImages: [], labels: [], + }; + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-decryption', 'non-transport']]); +}); + +test('legacy registered empty Relay image remains recoverable, but nonempty arrays are invalid', async () => { + const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); + const f = harness(); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + for (const signers of [undefined, []]) { + const recovered = await prepareRecoveryImage( + key, f.app.id, { appId: f.app.id, wallets: [], signers, nodes: [] }, [], [] + ); + assert.deepEqual(JSON.parse(JSON.stringify(recovered)), makeImage()); + } + for (const malformed of [{ wallets: ['ciphertext'] }, { signers: ['ciphertext'] }]) { + await assert.rejects( + prepareRecoveryImage( + key, f.app.id, + { appId: f.app.id, wallets: [], signers: [], nodes: [], ...malformed }, [], [] + ), + (error) => error instanceof image.BackupSnapshotValidationError + ); + } +}); + test('transient snapshot failure after account switch makes no retry or upload', async () => { const f = harness({ post: async ({ app }) => { app.id = 'second'; From ac868253f3460dd875035e1a4f73fc99ca658c1b Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 17:17:42 +0530 Subject: [PATCH 8/8] Bind inspected wallet map keys to decrypted IDs --- src/services/backup/image.ts | 9 +++-- src/services/backup/repair.ts | 4 ++- tests/recovery/repair.test.cjs | 66 +++++++++++++++++++++++++++++++--- 3 files changed, 72 insertions(+), 7 deletions(-) diff --git a/src/services/backup/image.ts b/src/services/backup/image.ts index c4325c643..a98e0dfa9 100644 --- a/src/services/backup/image.ts +++ b/src/services/backup/image.ts @@ -249,7 +249,8 @@ export async function decodeImage( key: string, response: any, appId: string, - checkpoint = () => {} + checkpoint = () => {}, + verifyWalletKeys = false ): Promise { const app = response?.appImage; if ( @@ -300,8 +301,12 @@ export async function decodeImage( throw new BackupSnapshotValidationError('Duplicate or unidentified backup record'); image[kind][id] = record; }; - for (const value of Object.values(app.wallets)) { + for (const [storedId, value] of Object.entries(app.wallets)) { const record = await decode(value); + if (typeof record.id !== 'string' || !record.id) + throw new BackupSnapshotValidationError('Invalid wallet backup identity'); + if (verifyWalletKeys && storedId !== record.id) + throw new BackupSnapshotValidationError('Wallet backup identity mismatch'); add('wallets', record.id, record); } for (const [id, value] of Object.entries(app.signers)) { diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 20024cba0..5d35580e0 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -232,7 +232,9 @@ export function inspectBackup( } : response.data; if (!readback) stage = 'snapshot-decryption'; - const decoded = await decodeImage(key, availableResponse, appId, assertCurrent); + // Restore can salvage legacy map aliases. Inspection requires the + // stored key to match the ID inside each encrypted wallet record. + const decoded = await decodeImage(key, availableResponse, appId, assertCurrent, true); needsVaultRepair = unavailable.length > 0 || response.data.allVaultImages.some( diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index 15ad8af32..513d53892 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -131,10 +131,6 @@ for (const [name, change] of [ ['invalid signer collection', (response) => { response.appImage.signers = []; }], ['non-string record', (response) => { response.appImage.wallets.wallet = 42; }], ['missing referenced vault', (response) => { response.appImage.vaults = ['missing']; }], - ['duplicate decrypted IDs', (response, key) => { - const encrypted = encryption.encrypt(key, JSON.stringify(wallet())); - response.appImage.wallets = { first: encrypted, second: encrypted }; - }], ['vault ID mismatch', (response, key) => { response.appImage.vaults = ['other']; response.allVaultImages = [{ vaultId: 'other', vault: encryption.encrypt(key, JSON.stringify({ id: 'vault' })) }]; @@ -195,6 +191,68 @@ test('legacy registered empty Relay image remains recoverable, but nonempty arra } }); +test('recovery rejects duplicate decrypted wallet IDs despite different stored keys', async () => { + const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); + const f = harness(); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + const encrypted = encryption.encrypt(key, JSON.stringify(wallet())); + await assert.rejects( + prepareRecoveryImage( + key, f.app.id, + { appId: f.app.id, wallets: { first: encrypted, second: encrypted }, signers: {}, nodes: [] }, + [], [] + ), + (error) => error instanceof image.BackupSnapshotValidationError && + error.message === 'Duplicate or unidentified backup record' + ); +}); + +for (const [name, keyedWallets] of [ + ['aliased wallet key', [['old-key', wallet('wallet')]]], + ['swapped wallet keys', [['one', wallet('two')], ['two', wallet('one')]]], +]) test(`inspection rejects ${name} while recovery can still salvage records`, async () => { + const options = {}; + const f = harness(options); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + f.local.Wallet.push(...keyedWallets.map(([, record]) => record)); + const appImage = { + appId: f.app.id, + wallets: Object.fromEntries(keyedWallets.map(([storedId, record]) => + [storedId, encryption.encrypt(key, JSON.stringify(record))] + )), + signers: {}, nodes: [], vaults: [], labels: [], + }; + options.response = { revision: 'a'.repeat(64), appImage, allVaultImages: [], labels: [] }; + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-validation', 'non-transport']]); + + const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); + const recovered = await prepareRecoveryImage(key, f.app.id, appImage, [], []); + assert.deepEqual(Object.keys(recovered.wallets).sort(), keyedWallets.map(([, record]) => record.id).sort()); +}); + +test('numeric decrypted wallet ID is invalid for inspection and recovery', async () => { + const options = {}; + const f = harness(options); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + const appImage = { + appId: f.app.id, + wallets: { wallet: encryption.encrypt(key, JSON.stringify({ ...wallet(), id: 42 })) }, + signers: {}, nodes: [], vaults: [], labels: [], + }; + options.response = { revision: 'a'.repeat(64), appImage, allVaultImages: [], labels: [] }; + assert.equal(await f.run(), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.deepEqual(f.diagnostics, [['Assisted Server Backup check failed at stage:', 'snapshot-validation', 'non-transport']]); + + const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); + await assert.rejects( + prepareRecoveryImage(key, f.app.id, appImage, [], []), + (error) => error instanceof image.BackupSnapshotValidationError + ); +}); + test('transient snapshot failure after account switch makes no retry or upload', async () => { const f = harness({ post: async ({ app }) => { app.id = 'second';