@bsv/expo-wallet-toolbox 0.5.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2000 -0
- package/README.md +66 -1
- package/core/amountFormatHelpers.ts +258 -36
- package/core/backup/RemoteSyncReader.ts +133 -24
- package/core/backup/appData.ts +157 -0
- package/core/backup/client.ts +15 -1
- package/core/backup/codec.ts +149 -11
- package/core/backup/constants.ts +30 -1
- package/core/backup/cursor.ts +31 -2
- package/core/backup/push.ts +71 -5
- package/core/backup/restore.ts +104 -16
- package/core/backup/restoreOnImport.ts +94 -30
- package/core/backup/status.ts +13 -8
- package/core/config.tsx +12 -5
- package/core/constants.ts +14 -1
- package/core/contacts/contactActivity.ts +153 -0
- package/core/contacts/contactCache.ts +41 -0
- package/core/contacts/contactsStore.ts +183 -0
- package/core/context/ExchangeRateContext.tsx +34 -27
- package/core/context/LocalStorageProvider.tsx +43 -40
- package/core/context/UserContext.tsx +18 -7
- package/core/context/VaultContext.tsx +49 -2
- package/core/context/WalletConnectionContext.tsx +203 -11
- package/core/context/WalletContext.tsx +685 -171
- package/core/demo/demoAssets.ts +60 -0
- package/core/demo/demoLedger.ts +240 -0
- package/core/demo/demoMandalaRuntime.ts +96 -0
- package/core/demo/demoMode.ts +38 -0
- package/core/demo/demoWallet.ts +25 -0
- package/core/demo/index.ts +26 -0
- package/core/demo/useDemo.ts +59 -0
- package/core/headers/OfflineFirstChaintracks.ts +99 -17
- package/core/headers/headerStore.ts +33 -14
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +2186 -98
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +314 -0
- package/core/identity/handleRegistry/keyPinStore.ts +70 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +315 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +53 -5
- package/core/localpay/build.ts +225 -24
- package/core/localpay/pending.ts +110 -7
- package/core/localpay/pendingAbortAuthority.ts +95 -0
- package/core/localpay/pendingAborts.ts +266 -26
- package/core/localpay/session.ts +42 -17
- package/core/localpay/settlementAck.ts +10 -1
- package/core/localpay/transport/socket.ts +52 -3
- package/core/localpay/verify.ts +100 -10
- package/core/mandala/abortGuard.ts +96 -20
- package/core/mandala/createRuntime.ts +206 -33
- package/core/mandala/drain.ts +89 -11
- package/core/mandala/inboxPrehold.ts +186 -0
- package/core/mandala/permissionModule.ts +202 -20
- package/core/mandala/settlementStore.ts +24 -2
- package/core/mandala/types.ts +40 -5
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +15 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +15 -1
- package/core/monitor/TaskSendOffline.ts +15 -1
- package/core/net/online.ts +49 -0
- package/core/net/publicDestination.ts +91 -0
- package/core/net/validateArcUrl.ts +22 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/cancelParked.ts +134 -13
- package/core/offline/payerHold.ts +100 -24
- package/core/offline/plan.ts +37 -8
- package/core/pay/beefRepair.ts +6 -2
- package/core/pay/damagedInbox.ts +24 -0
- package/core/pay/rails/address.ts +107 -12
- package/core/pay/rails/handle.ts +117 -22
- package/core/pay/rails/index.ts +45 -7
- package/core/pay/rails/nativeIntent.ts +61 -0
- package/core/pay/receiveHistory.ts +93 -0
- package/core/pay/recordProof.ts +21 -7
- package/core/pay/refreshProofGuard.ts +42 -1
- package/core/pay/watchlist.ts +5 -2
- package/core/peerpay/control.ts +17 -18
- package/core/peerpay/handleResendRequests.ts +58 -4
- package/core/peerpay/outbox.ts +3 -1
- package/core/recovery/backupMaterial.ts +61 -0
- package/core/recovery/createWallet.ts +95 -0
- package/core/recovery/recoverWallet.ts +120 -0
- package/core/recovery/restoreWallet.ts +170 -0
- package/core/recovery/secret.ts +92 -0
- package/core/recovery/shareCollector.ts +71 -0
- package/core/recovery/shareParsing.ts +87 -0
- package/core/recovery/shares.ts +116 -0
- package/core/recovery/useRecoveryDeps.ts +70 -0
- package/core/services/arcTokenStorage.ts +52 -0
- package/core/services/arcadeBroadcastProvider.ts +233 -52
- package/core/services/autoApprovePolicy.ts +105 -0
- package/core/services/callbackToken.ts +19 -0
- package/core/services/capWalletArgs.ts +14 -2
- package/core/services/connectionAuthority.ts +98 -0
- package/core/services/exchangeRate.ts +36 -13
- package/core/services/externalOrigin.ts +16 -2
- package/core/services/secrets/kek.ts +126 -29
- package/core/services/secrets/migration.ts +16 -4
- package/core/services/secrets/store.ts +42 -14
- package/core/services/vault/VaultKeyService.ts +228 -45
- package/core/services/vault/chainRecovery.ts +483 -0
- package/core/services/vault/driver.ts +9 -1
- package/core/services/vault/enrolledSerialRegistry.ts +150 -0
- package/core/services/vault/guard.ts +218 -32
- package/core/services/vault/hardwareLease.ts +19 -0
- package/core/services/vault/metaAuthority.ts +210 -0
- package/core/services/vault/pivReset.ts +64 -23
- package/core/services/vault/r1comb.ts +139 -3
- package/core/services/vault/session.ts +25 -4
- package/core/services/vault/transfers.ts +868 -172
- package/core/services/vault/types.ts +19 -4
- package/core/services/vault/vaultStore.ts +256 -29
- package/core/services/walletArgLimits.ts +45 -2
- package/core/services/walletConnectionValidation.ts +76 -6
- package/core/services/walletServiceConfig.ts +40 -27
- package/core/storage/StorageExpoSQLite.ts +88 -47
- package/core/storage/methods/findSql.ts +24 -2
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +2 -2
- package/core/storage/methods/offlineActions.ts +10 -1
- package/core/storage/methods/processOfflineActions.ts +117 -25
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/schema/createTables.ts +155 -2
- package/core/stores/ConnectionStore.ts +34 -0
- package/core/toolboxConfig.ts +104 -0
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletDbRegistry.ts +63 -0
- package/core/walletMonitor.ts +25 -4
- package/core/walletRepair/releaseStuckReservations.ts +72 -0
- package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
- package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
- package/package.json +7 -7
- package/ui/activityFilter.ts +115 -0
- package/ui/backupShares.ts +26 -169
- package/ui/components/pay/AddressReceive.tsx +13 -6
- package/ui/components/pay/AssetPicker.tsx +30 -9
- package/ui/components/pay/MessageBoxConfig.tsx +16 -0
- package/ui/components/pay/NearbyFlow.tsx +480 -243
- package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
- package/ui/components/pay/RecipientField.tsx +84 -70
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +827 -205
- package/ui/components/ui/AlertCard.tsx +38 -5
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/PermissionSheet.tsx +197 -66
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/vault/EnrollWizard.tsx +61 -13
- package/ui/components/vault/vaultErrorCopy.ts +3 -1
- package/ui/components/wallet/ActivityRow.tsx +227 -123
- package/ui/components/wallet/AmountInput.tsx +26 -8
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
- package/ui/components/wallet/Balance.tsx +42 -23
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
- package/ui/components/wallet/ContactActivityList.tsx +149 -0
- package/ui/components/wallet/ContactSigil.tsx +49 -0
- package/ui/components/wallet/EditPictureSheet.tsx +99 -0
- package/ui/components/wallet/FitAmount.tsx +148 -0
- package/ui/components/wallet/IconPickerSheet.tsx +168 -0
- package/ui/components/wallet/IdentifierRow.tsx +69 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
- package/ui/components/wallet/ProfileButton.tsx +62 -0
- package/ui/components/wallet/UserAvatar.tsx +85 -0
- package/ui/components/wallet/avatarIcons.ts +122 -0
- package/ui/exportTransactions.ts +36 -4
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useExportWalletData.ts +25 -2
- package/ui/hooks/useMandala.ts +18 -1
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/importDatabases.ts +339 -24
- package/ui/index.ts +33 -2
- package/ui/isImageUrl.ts +6 -0
- package/ui/printRecoveryShares.ts +9 -10
- package/ui/recoveryPrompts.ts +91 -0
- package/ui/resolveIdentity.ts +31 -9
- package/ui/screens/ConnectionsScreen.tsx +86 -19
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +256 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PairScreen.tsx +74 -2
- package/ui/screens/PayScreen.tsx +20 -7
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/SettingsScreen.tsx +10 -4
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +100 -5
- package/ui/screens/VaultScreen.tsx +410 -61
- package/ui/screens/VaultTransferScreen.tsx +59 -7
- package/ui/screens/WalletCheckScreen.tsx +17 -6
- package/ui/screens/WalletConfigScreen.tsx +124 -28
- package/ui/screens/WalletHomeScreen.tsx +640 -104
- package/ui/screens/detailActionKeys.ts +55 -0
- package/ui/tokenFormat.ts +44 -4
- package/ui/tokenStatus.ts +21 -0
- package/ui/txStatus.ts +48 -5
- package/core/storage/LocalStorageAdapter.ts +0 -58
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every calendar date this device has issued a conventional-receive address for.
|
|
3
|
+
*
|
|
4
|
+
* XR-055. `pay/watchlist.ts` prunes by a 7-day calendar age no matter how recently an
|
|
5
|
+
* address was swept — that bound exists to keep the BACKGROUND sweeper's polling cost
|
|
6
|
+
* bounded, and is deliberately left alone here (see watchlist.ts's own "spec open question
|
|
7
|
+
* 5" note and its pinned-bounds test). But it means the watchlist cannot answer "which
|
|
8
|
+
* dates has this wallet ever issued an address for", which is exactly what a payer-sat-on-
|
|
9
|
+
* it-for-a-month recovery scan needs: a payer who pays a legitimately-displayed address more
|
|
10
|
+
* than MAX_WATCH_DAYS/MAX_RECOVERY_DAYS after issue had no shipped path back to
|
|
11
|
+
* internalizeAction once the watchlist entry aged out.
|
|
12
|
+
*
|
|
13
|
+
* This store answers that question. It is capped by COUNT, not calendar age — an issued
|
|
14
|
+
* date is worth remembering indefinitely, since sweepAddress (core/pay/rails/address.ts) is
|
|
15
|
+
* idempotent and cheap to retry for a date that turns out to hold nothing — and it rides the
|
|
16
|
+
* encrypted backup envelope (core/backup/appData.ts) so a restored device CAN resume
|
|
17
|
+
* scanning every date this wallet has ever shown, not just the ones the restoring device
|
|
18
|
+
* itself issued — but only for a date recorded in a window where some OTHER entity change
|
|
19
|
+
* also happened to get pushed; see appData.ts's own "KNOWN, STILL-OPEN GAP" note for why a
|
|
20
|
+
* date issued with nothing else going on in the wallet at the time can still fail to reach
|
|
21
|
+
* the log at all.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export const RECEIVE_HISTORY_KEY = 'pay_receive_issued_dates'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Count cap, not calendar-age cap (see module docstring). One entry is a ~10-byte
|
|
28
|
+
* YYYY-MM-DD string, so even this many costs nothing to store or to carry in a backup
|
|
29
|
+
* envelope — it exists only so a pathological caller cannot grow this list forever, not
|
|
30
|
+
* because any realistic wallet would approach it.
|
|
31
|
+
*/
|
|
32
|
+
export const MAX_RECEIVE_HISTORY = 3650
|
|
33
|
+
|
|
34
|
+
export interface KVStorage {
|
|
35
|
+
getKeyValue (k: string): Promise<string | undefined>
|
|
36
|
+
setKeyValue (k: string, v: string): Promise<void>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Same discipline as localpay/pending.ts and pay/watchlist.ts: every read-modify-write on
|
|
40
|
+
// this single storage key runs through one chain, or a write built from a stale read
|
|
41
|
+
// silently drops an entry.
|
|
42
|
+
let queueLock: Promise<unknown> = Promise.resolve()
|
|
43
|
+
|
|
44
|
+
function withQueueLock<T> (fn: () => Promise<T>): Promise<T> {
|
|
45
|
+
const run = queueLock.then(fn, fn)
|
|
46
|
+
queueLock = run.catch(() => undefined)
|
|
47
|
+
return run
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function readAll (storage: KVStorage): Promise<string[]> {
|
|
51
|
+
const raw = await storage.getKeyValue(RECEIVE_HISTORY_KEY)
|
|
52
|
+
if (!raw) return []
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(raw) as unknown
|
|
55
|
+
return Array.isArray(parsed) ? parsed.filter((d): d is string => typeof d === 'string') : []
|
|
56
|
+
} catch {
|
|
57
|
+
return []
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function normalise (dates: Iterable<string>): string[] {
|
|
62
|
+
return [...new Set(dates)].sort().slice(-MAX_RECEIVE_HISTORY)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Record a newly issued date, deduplicated. Called from the same place AddressReceive.tsx
|
|
67
|
+
* already calls watchAddress — every address this app has shown the user gets its date
|
|
68
|
+
* remembered here too, independent of whether that address also survives the watchlist's
|
|
69
|
+
* own 7-day prune.
|
|
70
|
+
*/
|
|
71
|
+
export async function recordIssuedDate (storage: KVStorage, date: string): Promise<void> {
|
|
72
|
+
return withQueueLock(async () => {
|
|
73
|
+
const all = await readAll(storage)
|
|
74
|
+
if (all.includes(date)) return
|
|
75
|
+
await storage.setKeyValue(RECEIVE_HISTORY_KEY, JSON.stringify(normalise([...all, date])))
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Every recorded date, deduplicated and sorted ascending. */
|
|
80
|
+
export async function getIssuedDates (storage: KVStorage): Promise<string[]> {
|
|
81
|
+
return normalise(await readAll(storage))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Replace the whole list. Used only by backup restore (core/backup/appData.ts), which has
|
|
86
|
+
* already merged every device's own history into one deduplicated, capped list and wants a
|
|
87
|
+
* single write rather than N individual `recordIssuedDate` inserts.
|
|
88
|
+
*/
|
|
89
|
+
export async function setIssuedDates (storage: KVStorage, dates: string[]): Promise<void> {
|
|
90
|
+
return withQueueLock(async () => {
|
|
91
|
+
await storage.setKeyValue(RECEIVE_HISTORY_KEY, JSON.stringify(normalise(dates)))
|
|
92
|
+
})
|
|
93
|
+
}
|
package/core/pay/recordProof.ts
CHANGED
|
@@ -10,12 +10,9 @@
|
|
|
10
10
|
* no req, the proof is written directly: a proven_tx row (the toolbox's own
|
|
11
11
|
* `findOrInsertProvenTx` shape) and the transaction promoted to `completed`.
|
|
12
12
|
*/
|
|
13
|
-
import
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
TableTransaction
|
|
17
|
-
} from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
|
|
18
|
-
import type { UpdateProvenTxReqWithNewProvenTxArgs } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
|
|
13
|
+
import { Transaction } from '@bsv/sdk'
|
|
14
|
+
import type { TableProvenTx, TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile'
|
|
15
|
+
import type { UpdateProvenTxReqWithNewProvenTxArgs } from '../toolboxTypes'
|
|
19
16
|
|
|
20
17
|
export interface ProofStorage {
|
|
21
18
|
findProvenTxReqs(args: {
|
|
@@ -74,13 +71,30 @@ export async function recordProof(
|
|
|
74
71
|
|
|
75
72
|
let provenTxId = (await storage.findProvenTxs({ partial: { txid } }))[0]?.provenTxId
|
|
76
73
|
if (provenTxId === undefined) {
|
|
74
|
+
// XR-029: the direct path has no proven_tx_req to have already checked
|
|
75
|
+
// these bytes against anything — the BUMP/root check that authenticated
|
|
76
|
+
// `txid` never touches the separately-fetched rawTx. Require it to
|
|
77
|
+
// actually parse and hash to the txid we are recording a proof for
|
|
78
|
+
// before it is ever inserted or a transaction is promoted to completed;
|
|
79
|
+
// a mismatched or unparsable response from a compromised/faulty raw-tx
|
|
80
|
+
// endpoint must not corrupt local data.
|
|
81
|
+
const rawTx = await args.fetchRawTx()
|
|
82
|
+
let parsedTxid: string
|
|
83
|
+
try {
|
|
84
|
+
parsedTxid = Transaction.fromBinary(rawTx).id('hex')
|
|
85
|
+
} catch (e: any) {
|
|
86
|
+
throw new Error(`recordProof: fetched raw tx for ${txid} does not parse as a transaction: ${e.message}`)
|
|
87
|
+
}
|
|
88
|
+
if (parsedTxid !== txid) {
|
|
89
|
+
throw new Error(`recordProof: fetched raw tx hashes to ${parsedTxid}, expected ${txid}`)
|
|
90
|
+
}
|
|
77
91
|
const now = new Date()
|
|
78
92
|
provenTxId = await storage.insertProvenTx({
|
|
79
93
|
created_at: now,
|
|
80
94
|
updated_at: now,
|
|
81
95
|
provenTxId: 0,
|
|
82
96
|
txid,
|
|
83
|
-
rawTx
|
|
97
|
+
rawTx,
|
|
84
98
|
...proof
|
|
85
99
|
})
|
|
86
100
|
}
|
|
@@ -18,6 +18,22 @@ export type OfflineRefreshStatus =
|
|
|
18
18
|
// Held back deliberately, never released for broadcast. Like queued and
|
|
19
19
|
// posting, a Refresh must not decide such a transaction has failed.
|
|
20
20
|
| 'parked'
|
|
21
|
+
// Written only by a raw database import (ui/importDatabases.ts) over a
|
|
22
|
+
// copied-in 'queued'/'posting' row (XR-085): still an unresolved, possibly
|
|
23
|
+
// already-handed-off spend awaiting the user's renewed review, so it must
|
|
24
|
+
// not be failed either — same reasoning as 'parked'.
|
|
25
|
+
| 'import_hold'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* refreshProof's /tx/hash/{txid} probe is advisory, single-source. Only an
|
|
29
|
+
* authoritative 404 means the network doesn't have the tx; any other
|
|
30
|
+
* completed non-OK response (429 rate-limit, 5xx, 401/403 auth trouble, ...)
|
|
31
|
+
* is a service problem, not proof of absence, and must be treated as
|
|
32
|
+
* inconclusive — exactly like a thrown network error.
|
|
33
|
+
*/
|
|
34
|
+
export function isChainAbsenceConfirmed(status: number): boolean {
|
|
35
|
+
return status === 404
|
|
36
|
+
}
|
|
21
37
|
|
|
22
38
|
export function shouldFailUnprovenTx(args: {
|
|
23
39
|
offlineStatus?: OfflineRefreshStatus
|
|
@@ -25,10 +41,35 @@ export function shouldFailUnprovenTx(args: {
|
|
|
25
41
|
updatedAtMs: number
|
|
26
42
|
nowMs: number
|
|
27
43
|
}): 'pending' | 'failed' {
|
|
28
|
-
if (
|
|
44
|
+
if (
|
|
45
|
+
args.offlineStatus === 'queued' ||
|
|
46
|
+
args.offlineStatus === 'posting' ||
|
|
47
|
+
args.offlineStatus === 'parked' ||
|
|
48
|
+
args.offlineStatus === 'import_hold'
|
|
49
|
+
) {
|
|
29
50
|
return 'pending'
|
|
30
51
|
}
|
|
31
52
|
if (!IN_FLIGHT.has(args.txStatus)) return 'pending'
|
|
32
53
|
if (args.updatedAtMs && args.nowMs - args.updatedAtMs < STUCK_AFTER_MS) return 'pending'
|
|
33
54
|
return 'failed'
|
|
34
55
|
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* XR-059 remainder: refreshProof's two chain-service reads — the merkle BUMP
|
|
59
|
+
* hex from WoC's /proof/bump, and the raw-tx hex fetched inside its
|
|
60
|
+
* fetchRawTx callback — were unbounded, exactly like the address-sweep/BEEF
|
|
61
|
+
* reads XR-059 already bounded in address.ts's parseWocBeefBody and
|
|
62
|
+
* beefRepair.ts's refetchAtomicBeef. Same guard, same shape: a
|
|
63
|
+
* compromised/misbehaving configured indexer must not be able to force an
|
|
64
|
+
* arbitrarily large hex-decode (MerklePath.fromHex / Utils.toArray) just by
|
|
65
|
+
* answering with more bytes than any real proof or raw tx ever carries.
|
|
66
|
+
* Returns undefined for anything empty, oversized, odd-length, or not hex —
|
|
67
|
+
* the caller fails closed exactly as it already does for an unparseable body.
|
|
68
|
+
*/
|
|
69
|
+
export function boundedHexResponse(text: string, maxChars: number): string | undefined {
|
|
70
|
+
const hex = text.trim()
|
|
71
|
+
if (hex.length === 0 || hex.length > maxChars || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) {
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
return hex
|
|
75
|
+
}
|
package/core/pay/watchlist.ts
CHANGED
|
@@ -14,8 +14,11 @@
|
|
|
14
14
|
* · never older than MAX_WATCH_DAYS by its issue date
|
|
15
15
|
*
|
|
16
16
|
* A dropped address is not lost money: the Get paid → conventional wallet view
|
|
17
|
-
* re-registers today's address every time it is opened,
|
|
18
|
-
*
|
|
17
|
+
* re-registers today's address every time it is opened, the durable issued-date
|
|
18
|
+
* history (pay/receiveHistory.ts, XR-055) lets the automatic repair scan reach
|
|
19
|
+
* ANY previously issued date regardless of age, and the earlier-day recovery
|
|
20
|
+
* stepper can reach back MAX_MANUAL_RECOVERY_DAYS (core/pay/rails/address.ts)
|
|
21
|
+
* and sweep by hand.
|
|
19
22
|
*/
|
|
20
23
|
|
|
21
24
|
export const WATCHLIST_KEY = 'pay_address_watchlist'
|
package/core/peerpay/control.ts
CHANGED
|
@@ -15,12 +15,7 @@ export type PaymentControlMessage =
|
|
|
15
15
|
| { type: 'resend_request'; txid: string; reason: ResendReason; messageId?: string }
|
|
16
16
|
| { type: 'payment_cancelled'; txid: string }
|
|
17
17
|
|
|
18
|
-
const RESEND_REASONS: ReadonlySet<string> = new Set([
|
|
19
|
-
'corrupt',
|
|
20
|
-
'uncreditible',
|
|
21
|
-
'double_spent',
|
|
22
|
-
'bounced_offline'
|
|
23
|
-
])
|
|
18
|
+
const RESEND_REASONS: ReadonlySet<string> = new Set(['corrupt', 'uncreditible', 'double_spent', 'bounced_offline'])
|
|
24
19
|
|
|
25
20
|
function asObject(body: unknown): Record<string, unknown> | undefined {
|
|
26
21
|
let value: unknown = body
|
|
@@ -76,15 +71,9 @@ export async function sendControlMessage(
|
|
|
76
71
|
export type ControlBoxMessage = { messageId: string; sender: string; body: unknown }
|
|
77
72
|
|
|
78
73
|
/** Raw `payment_control` messages. `acceptPayments: false` avoids fee auto-internalize. */
|
|
79
|
-
export async function listControlMessages(
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
messageBox: string
|
|
83
|
-
host?: string
|
|
84
|
-
acceptPayments?: boolean
|
|
85
|
-
}): Promise<ControlBoxMessage[]>
|
|
86
|
-
}
|
|
87
|
-
): Promise<ControlBoxMessage[]> {
|
|
74
|
+
export async function listControlMessages(client: {
|
|
75
|
+
listMessages(args: { messageBox: string; host?: string; acceptPayments?: boolean }): Promise<ControlBoxMessage[]>
|
|
76
|
+
}): Promise<ControlBoxMessage[]> {
|
|
88
77
|
const listed = await client.listMessages({
|
|
89
78
|
messageBox: PAYMENT_CONTROL_BOX,
|
|
90
79
|
acceptPayments: false
|
|
@@ -112,11 +101,21 @@ export async function ackControlMessages(
|
|
|
112
101
|
* never succeed — and the alternative, perturbing the body so it earns a fresh
|
|
113
102
|
* id, would plant a second copy of a payment the recipient already holds.
|
|
114
103
|
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
104
|
+
* XR-046: matched ONLY on `@bsv/message-box-client`'s own structured
|
|
105
|
+
* `ERR_DUPLICATE_MESSAGE` code (`Message Box send failed with HTTP 400
|
|
106
|
+
* (ERR_DUPLICATE_MESSAGE).`), never on free prose. The client builds that
|
|
107
|
+
* string itself from a server response field it validates against
|
|
108
|
+
* `/^ERR_[A-Z0-9_]{1,64}$/` before embedding it — everything else in a
|
|
109
|
+
* thrown Error's message is attacker/host-controlled text a malicious or
|
|
110
|
+
* compromised recipientHost can fabricate at will for a 400 the recipient
|
|
111
|
+
* never actually received, which would wrongly mark retryDelivery's caller
|
|
112
|
+
* `delivered` and broadcast. Narrowing this does not close the deeper gap —
|
|
113
|
+
* a bare, non-throwing `sendMessage` success is still accepted with no
|
|
114
|
+
* recipient-authenticated receipt — closing that needs a receipt protocol
|
|
115
|
+
* change out of scope for this fix.
|
|
117
116
|
*/
|
|
118
117
|
export function isDuplicateMessageError(e: unknown): boolean {
|
|
119
118
|
const text = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
|
|
120
119
|
if (!/\b400\b/.test(text)) return false
|
|
121
|
-
return
|
|
120
|
+
return /\bERR_DUPLICATE_MESSAGE\b/.test(text)
|
|
122
121
|
}
|
|
@@ -271,6 +271,30 @@ export function makeListPeerPayAction(
|
|
|
271
271
|
}
|
|
272
272
|
}
|
|
273
273
|
|
|
274
|
+
/**
|
|
275
|
+
* The payment's recorded recipient for `txid`, or undefined when this device
|
|
276
|
+
* cannot resolve one (matches the recipient half of rebuildAndDeliver's own
|
|
277
|
+
* resolution exactly, but without building the full action or touching
|
|
278
|
+
* derivation data / the network — this is the cheap pre-check that has to run
|
|
279
|
+
* BEFORE any of that expensive work, not a replacement for it).
|
|
280
|
+
*
|
|
281
|
+
* XR-051: this is the authority a resend_request's sender is checked
|
|
282
|
+
* against. `entry.recipient` (an outbox row this device itself created) is
|
|
283
|
+
* always trusted over a listed action's labels, exactly like
|
|
284
|
+
* rebuildAndDeliver.
|
|
285
|
+
*/
|
|
286
|
+
async function resolveResendRecipient(
|
|
287
|
+
storage: StorageLike,
|
|
288
|
+
txid: string,
|
|
289
|
+
listPeerPayAction?: (txid: string) => Promise<PeerPayActionLike | undefined>
|
|
290
|
+
): Promise<string | undefined> {
|
|
291
|
+
const entries = await getOutboxEntries(storage)
|
|
292
|
+
const entry = entries.find(e => outboxTxid(e) === txid)
|
|
293
|
+
if (entry?.recipient) return entry.recipient
|
|
294
|
+
const listed = listPeerPayAction ? await listPeerPayAction(txid) : undefined
|
|
295
|
+
return recipientFromLabels(listed?.labels)
|
|
296
|
+
}
|
|
297
|
+
|
|
274
298
|
export async function loadUnansweredResends(storage: StorageLike): Promise<PendingResend[]> {
|
|
275
299
|
try {
|
|
276
300
|
const raw = await storage.getKeyValue(UNANSWERED_RESENDS_KEY)
|
|
@@ -301,6 +325,12 @@ async function storeUnansweredResends(storage: StorageLike, pending: PendingRese
|
|
|
301
325
|
export async function listPendingResendRequests(args: {
|
|
302
326
|
client: ListAckClient
|
|
303
327
|
storage: StorageLike
|
|
328
|
+
/** Optional for backward compatibility: omitting it preserves the exact
|
|
329
|
+
* pre-XR-051 behavior (every resend_request is surfaced as pending) since
|
|
330
|
+
* without a way to list this wallet's own actions there is no way to
|
|
331
|
+
* resolve a recipient to check the sender against. Every production caller
|
|
332
|
+
* should pass it. */
|
|
333
|
+
listPeerPayAction?: (txid: string) => Promise<PeerPayActionLike | undefined>
|
|
304
334
|
}): Promise<{ pending: PendingResend[] }> {
|
|
305
335
|
const messages = await listControlMessages(args.client)
|
|
306
336
|
const pending: PendingResend[] = []
|
|
@@ -316,10 +346,22 @@ export async function listPendingResendRequests(args: {
|
|
|
316
346
|
continue
|
|
317
347
|
}
|
|
318
348
|
if (!parsed || parsed.type !== 'resend_request') continue
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
349
|
+
const sender = typeof msg.sender === 'string' ? msg.sender : ''
|
|
350
|
+
try {
|
|
351
|
+
// XR-051: a resend_request whose sender is provably NOT the payment's
|
|
352
|
+
// recorded recipient must never be persisted (or it would keep showing
|
|
353
|
+
// up as an unanswered resend banner forever) -- ack it away instead.
|
|
354
|
+
const recipient = await resolveResendRecipient(args.storage, parsed.txid, args.listPeerPayAction)
|
|
355
|
+
if (recipient !== undefined && recipient !== sender) {
|
|
356
|
+
await ackControlMessages(args.client, [msg.messageId])
|
|
357
|
+
continue
|
|
358
|
+
}
|
|
359
|
+
} catch {
|
|
360
|
+
// Resolution failed transiently (e.g. a storage read error) -- fall
|
|
361
|
+
// through and surface it as pending like before this fix, rather than
|
|
362
|
+
// silently dropping a request that might be entirely legitimate.
|
|
363
|
+
}
|
|
364
|
+
pending.push({ txid: parsed.txid, sender })
|
|
323
365
|
}
|
|
324
366
|
await storeUnansweredResends(args.storage, pending)
|
|
325
367
|
return { pending }
|
|
@@ -450,6 +492,18 @@ export async function handleResendRequests(args: {
|
|
|
450
492
|
if (!parsed || parsed.type !== 'resend_request') continue
|
|
451
493
|
const sender = typeof msg.sender === 'string' ? msg.sender : ''
|
|
452
494
|
try {
|
|
495
|
+
// XR-051: authenticate the request BEFORE any of the decrypt/rebuild/
|
|
496
|
+
// refetch/send work below. A resend_request is legitimate only from
|
|
497
|
+
// the payment's own recorded recipient -- anyone else who can address
|
|
498
|
+
// this wallet's control box must never be able to trigger that work
|
|
499
|
+
// (or a persistent retry of it) just by naming a txid it knows or
|
|
500
|
+
// guesses. Ack-and-drop silently: the requester gets no signal either
|
|
501
|
+
// way, and the control message cannot be replayed to try again.
|
|
502
|
+
const recipient = await resolveResendRecipient(storage, parsed.txid, listPeerPayAction)
|
|
503
|
+
if (recipient !== undefined && recipient !== sender) {
|
|
504
|
+
await ackControlMessages(client, [msg.messageId])
|
|
505
|
+
continue
|
|
506
|
+
}
|
|
453
507
|
const deliveredTo = await rebuildAndDeliver({
|
|
454
508
|
client,
|
|
455
509
|
storage,
|
package/core/peerpay/outbox.ts
CHANGED
|
@@ -80,7 +80,9 @@ interface StorageLike {
|
|
|
80
80
|
|
|
81
81
|
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
/** Exported so backup/appData.ts (XR-011/XR-012) can snapshot/replay this row without
|
|
84
|
+
* duplicating the literal — this module stays the single source of truth for the key. */
|
|
85
|
+
export const OUTBOX_KEY = 'peerpay_outbox'
|
|
84
86
|
|
|
85
87
|
/** How long sent entries are kept as a sender-side token copy before pruning. */
|
|
86
88
|
export const SENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* readBackupMaterial — what the "view/export my recovery material" screen
|
|
3
|
+
* shows.
|
|
4
|
+
*
|
|
5
|
+
* A wallet has exactly one secret at a time (restoreWallet.ts's write order
|
|
6
|
+
* guarantees that), so this never needs to reconcile two. The mnemonic wins
|
|
7
|
+
* when present — it is the richer material (it also derives the vault key)
|
|
8
|
+
* — and only when there is none does this fall back to the raw WIF, whose
|
|
9
|
+
* hex form is what actually gets shown/exported as `text` (the WIF encoding
|
|
10
|
+
* itself is still returned separately, for callers that need it as-is).
|
|
11
|
+
*
|
|
12
|
+
* `getRecoveredKey` is not even called once a mnemonic is found: an extra
|
|
13
|
+
* secure-store read (and, on some platforms, a biometric prompt) for a value
|
|
14
|
+
* that will not be used is a cost with no benefit.
|
|
15
|
+
*
|
|
16
|
+
* Neither secret present is not a recoverable state for this screen — it
|
|
17
|
+
* throws rather than returning something the caller could render as if it
|
|
18
|
+
* were valid.
|
|
19
|
+
*
|
|
20
|
+
* Does NOT decide who is allowed to call this, does not touch UI, i18n, or
|
|
21
|
+
* navigation.
|
|
22
|
+
*/
|
|
23
|
+
import { PrivateKey } from '@bsv/sdk'
|
|
24
|
+
import { recoverMnemonicWallet } from '../mnemonicWallet'
|
|
25
|
+
|
|
26
|
+
export interface BackupMaterial {
|
|
27
|
+
text: string
|
|
28
|
+
mnemonic: string | null
|
|
29
|
+
wif: string | null
|
|
30
|
+
identityKey: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ReadBackupMaterialDeps {
|
|
34
|
+
getMnemonic(): Promise<string | null>
|
|
35
|
+
getRecoveredKey(): Promise<string | null>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function readBackupMaterial(deps: ReadBackupMaterialDeps): Promise<BackupMaterial> {
|
|
39
|
+
const mnemonic = await deps.getMnemonic()
|
|
40
|
+
if (mnemonic != null) {
|
|
41
|
+
return {
|
|
42
|
+
text: mnemonic,
|
|
43
|
+
mnemonic,
|
|
44
|
+
wif: null,
|
|
45
|
+
identityKey: recoverMnemonicWallet(mnemonic).identityKey
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const wif = await deps.getRecoveredKey()
|
|
50
|
+
if (wif != null) {
|
|
51
|
+
const key = PrivateKey.fromWif(wif)
|
|
52
|
+
return {
|
|
53
|
+
text: key.toHex(),
|
|
54
|
+
mnemonic: null,
|
|
55
|
+
wif,
|
|
56
|
+
identityKey: key.toPublicKey().toString()
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
throw new Error('Wallet keys unavailable')
|
|
61
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createNewWallet — the "generate a brand new wallet" path
|
|
3
|
+
* (mnemonic.tsx's handleGenerateNew). SDK-free: the mnemonic generator
|
|
4
|
+
* itself is injected (`deps.generate`, normally `generateMnemonicWallet`),
|
|
5
|
+
* so this module never touches `@bsv/sdk`.
|
|
6
|
+
*
|
|
7
|
+
* Guards FIRST, before generating anything: an already-built wallet or an
|
|
8
|
+
* already-stored identity means this call landed on a device/session that
|
|
9
|
+
* does not need a new secret — generating one anyway and then discovering
|
|
10
|
+
* `createMnemonic` refuses to overwrite it would be a wasted generation (and
|
|
11
|
+
* a phrase shown to the user that was never actually stored). `exists` tells
|
|
12
|
+
* the caller to route to the backup flow for the wallet that is already
|
|
13
|
+
* there instead.
|
|
14
|
+
*
|
|
15
|
+
* `createMnemonic` can also refuse for the same reason (a race: something
|
|
16
|
+
* else created an identity between this function's guard check and the
|
|
17
|
+
* store call) — checked again after a refusal, so that race still resolves
|
|
18
|
+
* to `exists` rather than the more alarming `refused`.
|
|
19
|
+
*
|
|
20
|
+
* Write order on success: generate → createMnemonic (the actual store,
|
|
21
|
+
* which is where the real "does an identity already exist" check lives) →
|
|
22
|
+
* `onStored` (fires BEFORE markPending/build, so the caller can show the
|
|
23
|
+
* words to the user while the build runs in the background — mirrors
|
|
24
|
+
* today's screen's setMnemonic/setMode/setHasExistingWallet timing) →
|
|
25
|
+
* markPending (best-effort: throwing here must not undo a secret that is
|
|
26
|
+
* already safely stored, so it is caught and warned, never propagated) →
|
|
27
|
+
* buildWalletFromMnemonic, called with NO options — a freshly generated
|
|
28
|
+
* mnemonic has no backup history to replay, unlike the restore path.
|
|
29
|
+
*
|
|
30
|
+
* Does NOT touch UI, i18n, or navigation.
|
|
31
|
+
*/
|
|
32
|
+
export interface CreateWalletDeps {
|
|
33
|
+
/** generateMnemonicWallet, injected so this module stays sdk-free. */
|
|
34
|
+
generate(): { mnemonic: string; identityKey: string }
|
|
35
|
+
hasStoredIdentity(): Promise<boolean>
|
|
36
|
+
createMnemonic(mnemonic: string): Promise<boolean>
|
|
37
|
+
/** backupAttestation.markPending; errors swallowed and warned. */
|
|
38
|
+
markPending(identityKey: string): Promise<void>
|
|
39
|
+
buildWalletFromMnemonic(mnemonic: string): Promise<void>
|
|
40
|
+
isWalletBuilt(): boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type CreateOutcome =
|
|
44
|
+
| { kind: 'created'; mnemonic: string; identityKey: string }
|
|
45
|
+
| { kind: 'exists' } // a wallet is already built or an identity is already stored → caller goes to backup flow
|
|
46
|
+
| { kind: 'refused' } // createMnemonic returned false and still no identity stored
|
|
47
|
+
| { kind: 'cancelled' } // opts.cancelled() became true after the identity guard → nothing generated or stored
|
|
48
|
+
| { kind: 'failed'; error: string }
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* `onStored` fires right after `createMnemonic` succeeds (before
|
|
52
|
+
* markPending/build) so the screen can show the words while the build runs.
|
|
53
|
+
*
|
|
54
|
+
* `cancelled`, when given, is re-checked right after the `hasStoredIdentity`
|
|
55
|
+
* await and before anything is generated. The caller's own screen state can
|
|
56
|
+
* change while that await is in flight (e.g. its route flips to the backup
|
|
57
|
+
* flow); if `cancelled()` now says yes, this returns `{ kind: 'cancelled' }`
|
|
58
|
+
* without generating or storing anything, rather than racing ahead on state
|
|
59
|
+
* that is already stale.
|
|
60
|
+
*/
|
|
61
|
+
export async function createNewWallet(
|
|
62
|
+
deps: CreateWalletDeps,
|
|
63
|
+
opts?: { onStored?: (w: { mnemonic: string; identityKey: string }) => void; cancelled?: () => boolean }
|
|
64
|
+
): Promise<CreateOutcome> {
|
|
65
|
+
try {
|
|
66
|
+
if (deps.isWalletBuilt() || (await deps.hasStoredIdentity())) {
|
|
67
|
+
return { kind: 'exists' }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (opts?.cancelled?.()) {
|
|
71
|
+
return { kind: 'cancelled' }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const generated = deps.generate()
|
|
75
|
+
|
|
76
|
+
const stored = await deps.createMnemonic(generated.mnemonic)
|
|
77
|
+
if (!stored) {
|
|
78
|
+
return (await deps.hasStoredIdentity()) ? { kind: 'exists' } : { kind: 'refused' }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
opts?.onStored?.(generated)
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
await deps.markPending(generated.identityKey)
|
|
85
|
+
} catch (err) {
|
|
86
|
+
console.warn('[recovery] markPending failed (mnemonic is already stored):', err)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
await deps.buildWalletFromMnemonic(generated.mnemonic)
|
|
90
|
+
|
|
91
|
+
return { kind: 'created', mnemonic: generated.mnemonic, identityKey: generated.identityKey }
|
|
92
|
+
} catch (err) {
|
|
93
|
+
return { kind: 'failed', error: err instanceof Error ? err.message : String(err) }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* recoverWallet — the single retry policy for a recovery attempt (audit §3:
|
|
3
|
+
* on any failure, go back to the input the user already gave, never loop
|
|
4
|
+
* silently on a server error). Wraps `restoreWallet` (called as a value —
|
|
5
|
+
* this module owns no restore logic of its own, only the policy for when to
|
|
6
|
+
* call it again) with the two prompts a screen needs to show:
|
|
7
|
+
*
|
|
8
|
+
* - `biometric-refused`: the user declined to authenticate the store write.
|
|
9
|
+
* `retry` tries the exact same secret again (the common case: they meant
|
|
10
|
+
* to approve and fumbled the prompt); `cancel` gives up after exactly one
|
|
11
|
+
* store attempt — restoreWallet's own write-order guarantee means a
|
|
12
|
+
* single refused attempt never partially wrote anything, so there is
|
|
13
|
+
* nothing to unwind.
|
|
14
|
+
* - `confirmReplace`: asked ONCE, before the first `restoreWallet` attempt
|
|
15
|
+
* of a call, whenever `deps.hasStoredIdentity()` says a secret is already
|
|
16
|
+
* on this device (P1-7: a deep link or any other entry point must never
|
|
17
|
+
* silently overwrite a wallet whose phrase may be unsaved). `keep` (or a
|
|
18
|
+
* dismissal — see `ui/recoveryPrompts.ts`) returns `cancelled` before
|
|
19
|
+
* touching `restoreWallet` at all. `replace` proceeds into the ordinary
|
|
20
|
+
* loop below, which never re-checks `hasStoredIdentity` or re-prompts —
|
|
21
|
+
* a biometric retry on the SAME call must not ask the user to confirm the
|
|
22
|
+
* replace a second time. This also means the onboarding "replace an
|
|
23
|
+
* auto-created wallet" path sees this same confirm, deliberately: any
|
|
24
|
+
* caller of `recoverWallet` that reaches this point already has a stored
|
|
25
|
+
* identity to protect, in-app or not.
|
|
26
|
+
* - `restore-failed`: the secret was stored but the wallet was NOT built —
|
|
27
|
+
* the encrypted backup log failed to replay, so `WalletContext` destroys
|
|
28
|
+
* its never-published storage and the build never completes. `retry`
|
|
29
|
+
* returns control to the caller's input
|
|
30
|
+
* state (`retry-later`) rather than looping here — a server-side failure
|
|
31
|
+
* does not get better by hammering it in a tight loop, and the user may
|
|
32
|
+
* want to check connectivity first. `skip` re-attempts with
|
|
33
|
+
* `restore: false`: the secret is stored again (a no-op re-write, since
|
|
34
|
+
* the KEK is already held this session — see restoreWallet's docs) and
|
|
35
|
+
* the wallet is (re)built without asking for history replay, which is
|
|
36
|
+
* the only way this policy can turn a stuck restore into a usable wallet.
|
|
37
|
+
*
|
|
38
|
+
* SDK-FREE BY DESIGN, same as restoreWallet.ts: only `import type` reaches
|
|
39
|
+
* into `./secret`. `restoreWallet` itself is imported as a VALUE (it is
|
|
40
|
+
* called, not just typed), which is exactly why restoreWallet.ts must stay
|
|
41
|
+
* SDK-free too — a value import transitively pulls in whatever that module
|
|
42
|
+
* imports at runtime.
|
|
43
|
+
*
|
|
44
|
+
* The loop is bounded by construction: every branch either returns
|
|
45
|
+
* immediately or falls through to exactly one more `restoreWallet` call
|
|
46
|
+
* before the next prompt decides the branch again. No branch re-enters the
|
|
47
|
+
* loop without first awaiting a human's choice, so it cannot spin without a
|
|
48
|
+
* prompt resolving — and it does not use recursion, so there is no risk of
|
|
49
|
+
* unbounded stack growth either.
|
|
50
|
+
*
|
|
51
|
+
* Does NOT render prompts itself (that's `ui/recoveryPrompts.ts`'s
|
|
52
|
+
* `restorePrompts(t)`, injected here as `opts.prompts`), and does not touch
|
|
53
|
+
* i18n or navigation.
|
|
54
|
+
*/
|
|
55
|
+
import { restoreWallet } from './restoreWallet'
|
|
56
|
+
import type { RestoreWalletDeps, RestoreHistory } from './restoreWallet'
|
|
57
|
+
import type { WalletSecret } from './secret'
|
|
58
|
+
import type { BackupMedium } from '../services/vault/backupAttestation'
|
|
59
|
+
|
|
60
|
+
export interface RestorePrompts {
|
|
61
|
+
biometricRefused(): Promise<'retry' | 'cancel'>
|
|
62
|
+
restoreFailed(error?: string): Promise<'retry' | 'skip'>
|
|
63
|
+
confirmReplace(): Promise<'replace' | 'keep'>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type RecoveryOutcome =
|
|
67
|
+
| {
|
|
68
|
+
kind: 'ok'
|
|
69
|
+
identityKey: string
|
|
70
|
+
secret: WalletSecret
|
|
71
|
+
history: RestoreHistory
|
|
72
|
+
attested: boolean
|
|
73
|
+
/** See restoreWallet.ts's RestoreOutcome — forwarded verbatim. */
|
|
74
|
+
verified: boolean
|
|
75
|
+
}
|
|
76
|
+
| { kind: 'cancelled' } // user declined biometrics
|
|
77
|
+
| { kind: 'retry-later' } // restore failed and the user chose retry → caller returns to its input state
|
|
78
|
+
| { kind: 'failed'; error: string }
|
|
79
|
+
|
|
80
|
+
export async function recoverWallet(
|
|
81
|
+
deps: RestoreWalletDeps,
|
|
82
|
+
secret: WalletSecret,
|
|
83
|
+
opts: { medium: BackupMedium; prompts: RestorePrompts }
|
|
84
|
+
): Promise<RecoveryOutcome> {
|
|
85
|
+
if (await deps.hasStoredIdentity()) {
|
|
86
|
+
if ((await opts.prompts.confirmReplace()) !== 'replace') return { kind: 'cancelled' }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let restore = true
|
|
90
|
+
|
|
91
|
+
for (;;) {
|
|
92
|
+
const r = await restoreWallet(deps, secret, { restore, medium: opts.medium })
|
|
93
|
+
|
|
94
|
+
if (r.kind === 'ok') {
|
|
95
|
+
return {
|
|
96
|
+
kind: 'ok',
|
|
97
|
+
identityKey: r.identityKey,
|
|
98
|
+
secret: r.secret,
|
|
99
|
+
history: r.history,
|
|
100
|
+
attested: r.attested,
|
|
101
|
+
verified: r.verified
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (r.kind === 'failed') {
|
|
106
|
+
return { kind: 'failed', error: r.error }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (r.kind === 'biometric-refused') {
|
|
110
|
+
const choice = await opts.prompts.biometricRefused()
|
|
111
|
+
if (choice === 'cancel') return { kind: 'cancelled' }
|
|
112
|
+
continue // retry: same secret, same restore flag
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// r.kind === 'restore-failed'
|
|
116
|
+
const choice = await opts.prompts.restoreFailed(r.error)
|
|
117
|
+
if (choice === 'retry') return { kind: 'retry-later' }
|
|
118
|
+
restore = false // skip: re-attempt without asking for history replay
|
|
119
|
+
}
|
|
120
|
+
}
|