@bsv/expo-wallet-toolbox 0.25.1 → 0.27.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/core/context/WalletContext.tsx +23 -2
  3. package/core/i18n/translations.tsx +245 -36
  4. package/core/identity/handleRegistry/classify.ts +74 -0
  5. package/core/identity/handleRegistry/client.ts +110 -16
  6. package/core/identity/handleRegistry/registration.ts +115 -17
  7. package/core/identity/handleRegistry/resolver.ts +77 -34
  8. package/core/identity/handleRegistry/rules.ts +4 -0
  9. package/core/index.ts +7 -0
  10. package/core/monitor/TaskDrainOutbox.ts +13 -3
  11. package/core/pay/paymail/address.ts +19 -0
  12. package/core/pay/paymail/client.ts +177 -0
  13. package/core/pay/paymail/networkCheck.ts +56 -0
  14. package/core/pay/rails/handle.ts +46 -9
  15. package/core/pay/rails/paymail.ts +542 -0
  16. package/core/peerpay/handleResendRequests.ts +6 -6
  17. package/core/peerpay/outbox.ts +185 -17
  18. package/core/peerpay/rebuildToken.ts +2 -2
  19. package/core/profiles/profileStore.ts +4 -1
  20. package/core/services/groupSpendingLimit.ts +26 -0
  21. package/core/services/signingPermissionPolicy.ts +14 -8
  22. package/core/services/vault/ceremony.ts +13 -0
  23. package/core/services/vault/ceremonyHost.ts +58 -0
  24. package/core/services/vault/failedVaultSpend.ts +40 -0
  25. package/core/services/vault/outputAuthority.ts +13 -6
  26. package/core/services/vault/transfers.ts +56 -12
  27. package/core/storage/encryptedDbImage.ts +11 -2
  28. package/core/theme/tokens.ts +26 -12
  29. package/package.json +2 -1
  30. package/ui/components/QRScanner.tsx +24 -22
  31. package/ui/components/pay/ImportedOutboxApproval.tsx +23 -2
  32. package/ui/components/pay/MessageBoxConfig.tsx +10 -16
  33. package/ui/components/pay/NearbyAdvisoryModal.tsx +6 -13
  34. package/ui/components/pay/NearbyFlow.tsx +72 -35
  35. package/ui/components/pay/PayForm.tsx +27 -19
  36. package/ui/components/pay/PaymentSuccessOverlay.tsx +8 -6
  37. package/ui/components/pay/UniversalSend.tsx +79 -5
  38. package/ui/components/ui/AlertCard.tsx +3 -2
  39. package/ui/components/ui/BalancedText.tsx +117 -0
  40. package/ui/components/ui/ErrorBoundary.tsx +31 -14
  41. package/ui/components/ui/GroupedList.tsx +28 -22
  42. package/ui/components/ui/ListRow.tsx +126 -35
  43. package/ui/components/ui/PermissionSheet.tsx +31 -24
  44. package/ui/components/ui/PresenceRow.tsx +15 -23
  45. package/ui/components/ui/Sheet.tsx +11 -17
  46. package/ui/components/ui/Toast.tsx +13 -17
  47. package/ui/components/vault/EnrollWizard.tsx +446 -196
  48. package/ui/components/vault/KeyChooser.tsx +7 -20
  49. package/ui/components/vault/VaultCeremonySheet.tsx +44 -36
  50. package/ui/components/wallet/AmountInput.tsx +11 -17
  51. package/ui/components/wallet/BiometricAdvisoryModal.tsx +13 -17
  52. package/ui/index.ts +1 -1
  53. package/ui/screens/TrustScreen.tsx +49 -61
  54. package/ui/screens/VaultScreen.tsx +99 -60
  55. package/ui/screens/VaultTransferScreen.tsx +34 -27
  56. package/ui/screens/WalletCheckScreen.tsx +25 -24
  57. package/ui/screens/WalletConfigScreen.tsx +66 -72
  58. package/ui/screens/WalletHomeScreen.tsx +104 -4
  59. package/ui/txStatus.ts +1 -1
@@ -16,10 +16,14 @@
16
16
 
17
17
  import { P2PKH, PublicKey, Transaction, type WalletInterface } from '@bsv/sdk'
18
18
  import { BRC29_PROTOCOL_ID } from './brc29'
19
+ import { isPublicHttpsUrl } from '../net/publicDestination'
20
+ import { parsePaymail } from '../pay/paymail/address'
19
21
 
20
22
  // ── Types ──────────────────────────────────────────────────────────────────────
21
23
 
22
- export interface OutboxEntry {
24
+ export interface PeerPayOutboxEntry {
25
+ /** Absent on rows stored before the paymail kind existed; those are PeerPay rows. */
26
+ kind?: 'peerpay'
23
27
  /** `${timestamp}_${recipientKey.slice(0, 8)}`, with a suffix on collision. */
24
28
  id: string
25
29
  /** ISO 8601 creation timestamp */
@@ -83,6 +87,46 @@ export interface OutboxEntry {
83
87
  via?: 'direct'
84
88
  }
85
89
 
90
+ /** A payment to a legacy paymail (P2P destination plus BEEF). */
91
+ export interface PaymailOutboxEntry {
92
+ kind: 'paymail'
93
+ id: string
94
+ createdAt: string
95
+ status: 'unsent' | 'sent' | 'import_hold'
96
+ lastAttemptAt?: string
97
+ lastError?: string
98
+ /** Our txid, 64 hex. */
99
+ txid: string
100
+ paymail: string
101
+ /** The BEEF URL, resolved at send time. */
102
+ endpoint: string
103
+ /** The receiver's reference, not the wallet action reference. */
104
+ paymailReference: string
105
+ /** Plain BEEF. */
106
+ beefHex: string
107
+ satoshis: number
108
+ /** The user's note. */
109
+ note?: string
110
+ /** Set just before the POST. */
111
+ delivering?: boolean
112
+ /** The receiver accepted. */
113
+ delivered?: boolean
114
+ receiverTxid?: string
115
+ receiverNote?: string
116
+ /** A retry saw a refusal and did not abort: only a user Cancel can finish it. */
117
+ refused?: boolean
118
+ }
119
+
120
+ export type OutboxEntry = PeerPayOutboxEntry | PaymailOutboxEntry
121
+
122
+ export function isPaymailEntry(e: OutboxEntry): e is PaymailOutboxEntry {
123
+ return e.kind === 'paymail'
124
+ }
125
+
126
+ export function isPeerPayEntry(e: OutboxEntry): e is PeerPayOutboxEntry {
127
+ return e.kind !== 'paymail'
128
+ }
129
+
86
130
  interface StorageLike {
87
131
  getKeyValue: (key: string) => Promise<string | undefined>
88
132
  setKeyValue: (key: string, value: string) => Promise<void>
@@ -172,17 +216,84 @@ export async function quarantineImportedOutbox(storage: StorageLike): Promise<nu
172
216
  })
173
217
  }
174
218
 
219
+ /** The most outputs a paymail transaction is allowed to have for the subset check. */
220
+ const MAX_SUBSET_OUTPUTS = 24
221
+
222
+ /**
223
+ * A loose check, and it is the most an offline import can do.
224
+ *
225
+ * The row holds the signed transaction, a display amount and a paymail, and
226
+ * nothing that says which output is the wallet's own change. So the amount must
227
+ * only equal the sum of SOME subset of the outputs (the rest being change); a
228
+ * transaction with no outputs, or none that add up to the amount, is refused.
229
+ *
230
+ * Limits: this does NOT bind the recipient to any output (the P2P destination
231
+ * script comes from the receiver's server and cannot be derived offline), and it
232
+ * does not prove that the subset is what the recipient is paid. A tampered
233
+ * backup could show one paymail and amount while the transaction pays another
234
+ * output. The approval screen therefore says these terms are unchecked.
235
+ */
236
+ function outputsCanPay(tx: Transaction, satoshis: number): boolean {
237
+ const values = tx.outputs.map(o => o.satoshis)
238
+ if (values.length === 0 || values.length > MAX_SUBSET_OUTPUTS) return false
239
+ if (!values.every(v => typeof v === 'number' && Number.isSafeInteger(v) && v > 0)) return false
240
+ let sums = new Set<number>([0])
241
+ for (const v of values as number[]) {
242
+ const next = new Set(sums)
243
+ for (const s of sums) if (s + v <= satoshis) next.add(s + v)
244
+ sums = next
245
+ }
246
+ return sums.has(satoshis)
247
+ }
248
+
249
+ function validateImportedPaymailEntry(entry: PaymailOutboxEntry): void {
250
+ let tx: Transaction
251
+ try {
252
+ if (typeof entry.beefHex !== 'string' || !entry.beefHex) throw new Error('empty')
253
+ tx = Transaction.fromHexBEEF(entry.beefHex)
254
+ } catch {
255
+ throw new Error('Imported payment has an invalid signed transaction')
256
+ }
257
+ if (
258
+ typeof entry.txid !== 'string' ||
259
+ !/^[0-9a-f]{64}$/i.test(entry.txid) ||
260
+ tx.id('hex').toLowerCase() !== entry.txid.toLowerCase()
261
+ ) {
262
+ throw new Error('Imported payment transaction ID does not match its signed transaction')
263
+ }
264
+ if (!Number.isSafeInteger(entry.satoshis) || entry.satoshis <= 0) {
265
+ throw new Error('Imported payment has an invalid amount')
266
+ }
267
+ if (!parsePaymail(entry.paymail)) {
268
+ throw new Error('Imported payment has an invalid paymail')
269
+ }
270
+ if (!outputsCanPay(tx, entry.satoshis)) {
271
+ throw new Error('Imported payment amount does not match its signed outputs')
272
+ }
273
+ if (typeof entry.endpoint !== 'string' || !isPublicHttpsUrl(entry.endpoint)) {
274
+ throw new Error('Imported payment has an invalid endpoint')
275
+ }
276
+ if (typeof entry.paymailReference !== 'string' || !entry.paymailReference) {
277
+ throw new Error('Imported payment has no paymail reference')
278
+ }
279
+ }
280
+
175
281
  /** Verify an imported snapshot before its amount or recipient is offered for
176
282
  * approval. Only public-key derivation is needed; no payment is signed or sent. */
177
- export async function validateImportedOutboxEntry(
178
- entry: OutboxEntry,
283
+ export async function validateImportedOutboxEntry<E extends OutboxEntry>(
284
+ entry: E,
179
285
  wallet: Pick<WalletInterface, 'getPublicKey'>,
180
286
  adminOriginator: string
181
- ): Promise<OutboxEntry> {
287
+ ): Promise<E> {
182
288
  // Separate the checked snapshot from the caller's mutable imported object
183
289
  // before awaiting wallet derivation. Release still checks exact stored equality.
184
290
  const reviewed = JSON.parse(JSON.stringify(entry)) as OutboxEntry
291
+ const result = reviewed as E
185
292
  if (reviewed.status !== 'import_hold') throw new Error('Imported payment is not held for review')
293
+ if (isPaymailEntry(reviewed)) {
294
+ validateImportedPaymailEntry(reviewed)
295
+ return result
296
+ }
186
297
  const token = reviewed.token
187
298
  if (
188
299
  !token ||
@@ -235,16 +346,16 @@ export async function validateImportedOutboxEntry(
235
346
  if (output.lockingScript.toHex() !== expected) {
236
347
  throw new Error('Imported payment recipient does not match its signed output')
237
348
  }
238
- return reviewed
349
+ return result
239
350
  }
240
351
 
241
352
  /** Called only after reviewing the displayed imported payment for a new send. */
242
- export async function releaseImportedOutboxEntry(
353
+ export async function releaseImportedOutboxEntry<E extends OutboxEntry>(
243
354
  storage: StorageLike,
244
- reviewed: OutboxEntry,
355
+ reviewed: E,
245
356
  wallet: Pick<WalletInterface, 'getPublicKey'>,
246
357
  adminOriginator: string
247
- ): Promise<OutboxEntry> {
358
+ ): Promise<E> {
248
359
  return withOutboxLock(storage, async () => {
249
360
  const all = await readEntries(storage)
250
361
  const index = all.findIndex(entry => entry.id === reviewed.id)
@@ -253,10 +364,26 @@ export async function releaseImportedOutboxEntry(
253
364
  throw new Error('Imported payment changed; review it again')
254
365
  }
255
366
  const validated = await validateImportedOutboxEntry(current, wallet, adminOriginator)
256
- const approved = { ...validated, status: 'unsent' as const }
367
+ let approved: OutboxEntry
368
+ if (isPaymailEntry(validated)) {
369
+ // An imported row must not claim a delivery this wallet did not see.
370
+ const {
371
+ delivered: _d,
372
+ delivering: _g,
373
+ refused: _r,
374
+ receiverTxid: _t,
375
+ receiverNote: _n,
376
+ lastAttemptAt: _a,
377
+ lastError: _e,
378
+ ...rest
379
+ } = validated
380
+ approved = { ...rest, status: 'unsent' as const }
381
+ } else {
382
+ approved = { ...validated, status: 'unsent' as const }
383
+ }
257
384
  all[index] = approved
258
385
  await writeEntries(storage, all)
259
- return approved
386
+ return approved as E
260
387
  })
261
388
  }
262
389
 
@@ -268,16 +395,16 @@ export async function saveOutboxEntry(
268
395
  storage: StorageLike,
269
396
  params: {
270
397
  recipient: string
271
- token: OutboxEntry['token']
398
+ token: PeerPayOutboxEntry['token']
272
399
  messageBoxUrl: string
273
400
  txid?: string
274
401
  recipientHost?: string
275
- via?: OutboxEntry['via']
402
+ via?: PeerPayOutboxEntry['via']
276
403
  }
277
404
  ): Promise<string> {
278
405
  const { recipient, token, messageBoxUrl, txid, recipientHost, via } = params
279
406
  const id = `${Date.now()}_${recipient.slice(0, 8)}`
280
- const entry: OutboxEntry = {
407
+ const entry: PeerPayOutboxEntry = {
281
408
  id,
282
409
  createdAt: new Date().toISOString(),
283
410
  recipient,
@@ -302,6 +429,45 @@ export async function saveOutboxEntry(
302
429
  })
303
430
  }
304
431
 
432
+ /** Persist a paymail payment before the POST. Returns the generated entry ID. */
433
+ export async function savePaymailOutboxEntry(
434
+ storage: StorageLike,
435
+ params: {
436
+ paymail: string
437
+ endpoint: string
438
+ paymailReference: string
439
+ beefHex: string
440
+ satoshis: number
441
+ txid: string
442
+ note?: string
443
+ }
444
+ ): Promise<string> {
445
+ const { paymail, endpoint, paymailReference, beefHex, satoshis, txid, note } = params
446
+ const id = `${Date.now()}_pm_${txid.slice(0, 8)}`
447
+ const entry: PaymailOutboxEntry = {
448
+ kind: 'paymail',
449
+ id,
450
+ createdAt: new Date().toISOString(),
451
+ status: 'unsent',
452
+ txid,
453
+ paymail,
454
+ endpoint,
455
+ paymailReference,
456
+ beefHex,
457
+ satoshis,
458
+ ...(note ? { note } : {})
459
+ }
460
+ return withOutboxLock(storage, async () => {
461
+ const all = await readEntries(storage)
462
+ const usedIds = new Set(all.map(e => e.id))
463
+ let suffix = 0
464
+ while (usedIds.has(entry.id)) entry.id = `${id}_${++suffix}`
465
+ all.push(entry)
466
+ await writeEntries(storage, all)
467
+ return entry.id
468
+ })
469
+ }
470
+
305
471
  /**
306
472
  * Mark an entry as successfully delivered.
307
473
  * Called immediately after `sendMessage()` returns without error.
@@ -321,12 +487,14 @@ export async function markOutboxSent(storage: StorageLike, id: string): Promise<
321
487
  * Merge a partial update into an entry.
322
488
  * Used to record `lastAttemptAt` and `lastError` on failed retry attempts.
323
489
  */
324
- export async function updateOutboxEntry(storage: StorageLike, id: string, patch: Partial<OutboxEntry>): Promise<void> {
490
+ export async function updateOutboxEntry(storage: StorageLike, id: string,
491
+ patch: Partial<PeerPayOutboxEntry> | Partial<PaymailOutboxEntry>
492
+ ): Promise<void> {
325
493
  return withOutboxLock(storage, async () => {
326
494
  const all = await readEntries(storage)
327
495
  const idx = all.findIndex(e => e.id === id)
328
496
  if (idx !== -1) {
329
- all[idx] = { ...all[idx], ...patch }
497
+ all[idx] = { ...all[idx], ...patch } as OutboxEntry
330
498
  await writeEntries(storage, all)
331
499
  }
332
500
  })
@@ -372,12 +540,12 @@ export async function pruneExpiredSent(storage: StorageLike, now: number = Date.
372
540
  }
373
541
 
374
542
  /** Only explicitly authorized unsent entries may enter automatic delivery. */
375
- export function unsentEntries(entries: OutboxEntry[]): OutboxEntry[] {
543
+ export function unsentEntries<E extends OutboxEntry>(entries: E[]): E[] {
376
544
  return entries.filter(e => e.status === 'unsent')
377
545
  }
378
546
 
379
547
  /** Held or unrecognized history still needs retention, even though it cannot
380
548
  * be automatically delivered. Only sent entries are terminal. */
381
- export function unresolvedOutboxEntries(entries: OutboxEntry[]): OutboxEntry[] {
549
+ export function unresolvedOutboxEntries<E extends OutboxEntry>(entries: E[]): E[] {
382
550
  return entries.filter(e => e.status !== 'sent')
383
551
  }
@@ -1,4 +1,4 @@
1
- import type { OutboxEntry } from './outbox'
1
+ import type { PeerPayOutboxEntry } from './outbox'
2
2
 
3
3
  export function instructionsFromOutput(customInstructions: unknown):
4
4
  | {
@@ -54,7 +54,7 @@ export async function rebuildPeerPayToken(args: {
54
54
  action: { txid?: string; outputs?: RebuildOutput[] }
55
55
  recipient: string
56
56
  refetch: (txid: string) => Promise<number[] | undefined>
57
- }): Promise<{ token: OutboxEntry['token']; recipient: string } | undefined> {
57
+ }): Promise<{ token: PeerPayOutboxEntry['token']; recipient: string } | undefined> {
58
58
  const { action, recipient, refetch } = args
59
59
  if (!action.txid) return undefined
60
60
 
@@ -79,7 +79,10 @@ export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
79
79
  }
80
80
 
81
81
  export function defaultProfilesState(): ProfilesState {
82
- return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(DEFAULT_CHAIN) }] }
82
+ // E2E builds set this before the toolbox loads (index.js). A fresh install
83
+ // then starts on testnet. Production never sets it, so the default stays main.
84
+ const network = (globalThis as { __BSV_E2E_CHAIN?: string }).__BSV_E2E_CHAIN === 'test' ? 'test' : DEFAULT_CHAIN
85
+ return { active: 0, profiles: [{ index: 0, network: e2eSafeChain(network) }] }
83
86
  }
84
87
 
85
88
  /** Trim and cap a profile name; undefined when nothing is left (the default label applies). */
@@ -0,0 +1,26 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+ import { AUTO_APPROVE_STORAGE_KEY, DEFAULT_AUTO_APPROVE_THRESHOLD } from '../constants'
3
+ import { profileScopedKey } from '../profiles/profileStore'
4
+
5
+ /**
6
+ * The most a site's one-time group grant may let it spend each month: what it could spend without asking,
7
+ * per payment (the stored auto-approve threshold). 0 means the user wants every payment asked about.
8
+ */
9
+ export async function groupSpendingLimit(): Promise<number> {
10
+ const v = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY)).catch(() => null)
11
+ return v === null ? DEFAULT_AUTO_APPROVE_THRESHOLD : Number(v) || 0
12
+ }
13
+
14
+ /** The same group with its spending limited to `limit`; with a limit of 0 or less, with no spending at all. */
15
+ export function clampGroupSpending<T extends { spendingAuthorization?: { amount: number; description?: string } }>(
16
+ group: T,
17
+ limit: number
18
+ ): T {
19
+ const spending = group.spendingAuthorization
20
+ if (!spending) return group
21
+ if (!(limit > 0)) {
22
+ const { spendingAuthorization: _removed, ...rest } = group
23
+ return rest as T
24
+ }
25
+ return spending.amount <= limit ? group : { ...group, spendingAuthorization: { ...spending, amount: limit } }
26
+ }
@@ -1,5 +1,6 @@
1
1
  import { Hash, Utils } from '@bsv/sdk'
2
2
  import { WalletPermissionsManager, type GroupedPermissions } from '@bsv/wallet-toolbox-mobile'
3
+ import { groupSpendingLimit } from './groupSpendingLimit'
3
4
 
4
5
  /** A site's manifest group request (BRC-73), as the Connect sheet shows it and `mintGroupedPermissions` mints it. */
5
6
  export type GroupPermissions = GroupedPermissions
@@ -118,13 +119,13 @@ const isObject = (v: unknown): v is Record<string, any> => v !== null && typeof
118
119
  * the manifest, so every entry is checked: one that does not have the shape the manager reads is
119
120
  * left out, and what remains is both what the Connect sheet shows and what Connect mints.
120
121
  */
121
- function sanitizeGroup(raw: unknown): GroupPermissions | null {
122
+ export function sanitizeGroup(raw: unknown, limit: number): GroupPermissions | null {
122
123
  if (!isObject(raw)) return null
123
124
  const group: GroupPermissions = {}
124
125
  if (typeof raw.description === 'string') group.description = raw.description
125
126
  const spending = raw.spendingAuthorization
126
- if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0) {
127
- group.spendingAuthorization = { amount: spending.amount, description: str(spending.description) }
127
+ if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0 && limit > 0) {
128
+ group.spendingAuthorization = { amount: Math.min(spending.amount, limit), description: str(spending.description) }
128
129
  }
129
130
  const list = (v: unknown): any[] => (Array.isArray(v) ? v.filter(isObject) : [])
130
131
  group.protocolPermissions = list(raw.protocolPermissions)
@@ -327,7 +328,7 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
327
328
  try {
328
329
  const { normalized } = this.internals.prepareOriginator(originator)
329
330
  const { groupPermissions } = await this.internals.fetchManifestPermissions(normalized)
330
- return sanitizeGroup(groupPermissions)
331
+ return sanitizeGroup(groupPermissions, await groupSpendingLimit())
331
332
  } catch {
332
333
  return null
333
334
  }
@@ -347,19 +348,24 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
347
348
  protocolPermissions: (group.protocolPermissions ?? []).filter(p => !isAskEveryTimeProtocol(p.protocolID))
348
349
  }
349
350
  const todo = await i.filterAlreadyGrantedPermissions(normalized, wanted)
351
+ const limit = await groupSpendingLimit()
352
+ const spend =
353
+ todo.spendingAuthorization != null && limit > 0
354
+ ? { ...todo.spendingAuthorization, amount: Math.min(todo.spendingAuthorization.amount, limit) }
355
+ : null
350
356
  const lookup = i.buildOriginatorLookupValues(originator, normalized)
351
357
  const toCreate: MintItem[] = []
352
358
  const toRenew: MintItem[] = []
353
- if (todo.spendingAuthorization != null) {
359
+ if (spend != null) {
354
360
  toCreate.push({
355
361
  request: {
356
362
  type: 'spending',
357
363
  originator: normalized,
358
- spending: { satoshis: todo.spendingAuthorization.amount },
359
- reason: todo.spendingAuthorization.description
364
+ spending: { satoshis: spend.amount },
365
+ reason: spend.description
360
366
  },
361
367
  expiry: 0,
362
- amount: todo.spendingAuthorization.amount
368
+ amount: spend.amount
363
369
  })
364
370
  }
365
371
  for (const p of todo.protocolPermissions ?? []) {
@@ -269,6 +269,19 @@ export class CeremonyController {
269
269
  return () => this.subscribers.delete(cb)
270
270
  }
271
271
 
272
+ /** Whether `signer` is still the armed one: not released by its caller, by
273
+ * cancel(), by a detach or by the retention ceiling. Read by a shared signer
274
+ * session (ceremonyHost.openVaultSignerSession) before it reuses a signer. */
275
+ holds(signer: VaultSigner): boolean {
276
+ return this.activeHandle === signer
277
+ }
278
+
279
+ /** Whether cancel() ended the ceremony most recently asked for. requestSigner
280
+ * resets it, so it speaks only for that ceremony. */
281
+ get wasCancelled(): boolean {
282
+ return this.cancelled
283
+ }
284
+
272
285
  /** Ask for the chosen key as a signer. Every overlapping request is refused:
273
286
  * one caller must have sole ownership of both the signer and the process-wide
274
287
  * native discovery/session object through release and teardown. */
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { CeremonyController, VaultProgress, VaultSigner } from './ceremony'
9
9
  import { getVaultDriver } from './driver'
10
+ import { VaultError } from './types'
10
11
  import { vaultStore } from './vaultStore'
11
12
 
12
13
  /** How long an armed signer stays usable before it relocks — refreshed by
@@ -50,3 +51,60 @@ export function requestVaultSigner(reason: string, chosenSerial: string): Promis
50
51
  export function noteVaultProgress(p: VaultProgress): void {
51
52
  ceremony.noteProgress(p)
52
53
  }
54
+
55
+ /**
56
+ * One key session for a whole spend that also creates a Vault output (a
57
+ * withdrawal with a re-vaulted remainder, a re-lock): one PIN entry and one
58
+ * tap cover both the new output's possession proof and the input signatures.
59
+ * Before this, each step opened its own ceremony, so the person entered the
60
+ * PIN and tapped twice for one transfer.
61
+ *
62
+ * The session is a local of ONE operation and is closed in that operation's
63
+ * finally. It is never module state (see VaultSigner).
64
+ *
65
+ * - `acquire` arms the chosen key the first time. Later calls return the same
66
+ * signer while it is still armed. If the key left or the retention window
67
+ * closed in between (the proof is signed before the transaction is built, so
68
+ * the session stays open through the build), it asks for a fresh ceremony:
69
+ * the old two-tap behaviour, never a failed transfer. A session the person
70
+ * cancelled stays cancelled (`user-cancelled`).
71
+ * - `close` releases the signer. Idempotent, as VaultSigner.release() is, so
72
+ * the spend may release the signer itself as soon as the last input is
73
+ * signed and the operation's finally may close again.
74
+ */
75
+ export interface VaultSignerSession {
76
+ acquire(reason: string, chosenSerial: string): Promise<VaultSigner>
77
+ close(): void
78
+ }
79
+
80
+ export function openVaultSignerSession(
81
+ deps: {
82
+ request: (reason: string, chosenSerial: string) => Promise<VaultSigner>
83
+ holds: (signer: VaultSigner) => boolean
84
+ cancelled: () => boolean
85
+ } = {
86
+ request: requestVaultSigner,
87
+ holds: signer => ceremony.holds(signer),
88
+ cancelled: () => ceremony.wasCancelled
89
+ }
90
+ ): VaultSignerSession {
91
+ let held: VaultSigner | undefined
92
+ return {
93
+ async acquire(reason, chosenSerial) {
94
+ if (held && held.serial === chosenSerial && deps.holds(held)) return held
95
+ if (held) {
96
+ const ended = held
97
+ held = undefined
98
+ ended.release()
99
+ if (deps.cancelled()) throw new VaultError('user-cancelled', 'Vault key session was cancelled')
100
+ }
101
+ held = await deps.request(reason, chosenSerial)
102
+ return held
103
+ },
104
+ close() {
105
+ const signer = held
106
+ held = undefined
107
+ signer?.release()
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Which FAILED Vault spends (withdrawals, re-locks) hold a pending key removal
3
+ * open in finalizeVaultKeyRemoval.
4
+ *
5
+ * The tombstone exists so that no output the removed key can still open is
6
+ * missed. A failed spend is a risk to that only if it may yet be on the
7
+ * network, creating an output committed to the old key set. Refusing on every
8
+ * failed spend ever recorded (the earlier rule) could never clear: a failed
9
+ * action stays in the wallet's history for good, so one aborted re-lock
10
+ * attempt, or one failed withdrawal months before, kept the removal pending
11
+ * after its re-lock was mined.
12
+ *
13
+ * A failed spend blocks only when BOTH hold:
14
+ *
15
+ * 1. It has a transaction ID. A Vault input is signed by the card and by
16
+ * nothing else, and the wallet assigns the ID at signAction. A spend with
17
+ * none was aborted before any signature: no transaction with its inputs can
18
+ * exist.
19
+ * 2. It began at or after the removal did. finalize clears the tombstone only
20
+ * with an ACCEPTED re-lock and two scans that find no output authorizing
21
+ * the removed key, so every output an earlier spend could have consumed is
22
+ * spent by an accepted transaction: the earlier one can no longer confirm.
23
+ * (Should an accepted re-lock still be dropped, its sources return as
24
+ * outputs committed to the removed key, which the coverage badge offers to
25
+ * re-lock: the owner decision recorded at ACCEPTED_ACTION_STATUSES.)
26
+ *
27
+ * Fail closed where the spend cannot be placed in time: a signed spend with no
28
+ * readable creation time, or a removal with no readable start, blocks.
29
+ */
30
+ export function failedVaultSpendBlocksRemoval(
31
+ action: { txid?: string; created_at?: string | Date | number },
32
+ removalStartedAt: number
33
+ ): boolean {
34
+ if (typeof action.txid !== 'string' || action.txid === '') return false
35
+ const at = action.created_at
36
+ const created =
37
+ at instanceof Date ? at.getTime() : typeof at === 'number' ? at : typeof at === 'string' ? Date.parse(at) : NaN
38
+ if (!Number.isFinite(created) || !Number.isFinite(removalStartedAt)) return true
39
+ return created >= removalStartedAt
40
+ }
@@ -4,7 +4,7 @@
4
4
  * to, for this exact output, before any funding action is created. */
5
5
  import { Hash, Utils } from '@bsv/sdk'
6
6
  import { p256 } from '@noble/curves/nist.js'
7
- import { requestVaultSigner } from './ceremonyHost'
7
+ import { requestVaultSigner, type VaultSignerSession } from './ceremonyHost'
8
8
  import { randomBytes } from './random'
9
9
  import { VaultError } from './types'
10
10
  import { vaultStore, type VaultMeta, type VaultScopeToken } from './vaultStore'
@@ -19,7 +19,11 @@ export async function requireVaultOutputKeyPossession(
19
19
  meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'lastUsedSerial'>,
20
20
  scope: VaultScopeToken,
21
21
  output: VaultOutputAuthorityContext,
22
- chosenSerial?: string
22
+ chosenSerial?: string,
23
+ /** A spend's own key session: the proof is signed in it and the session
24
+ * stays open for the input signatures (one PIN, one tap). `reason` is the
25
+ * spend's, because the first ceremony fixes the NFC alert text. */
26
+ shared?: { session: VaultSignerSession; reason: string }
23
27
  ): Promise<void> {
24
28
  vaultStore.assertScopeToken(scope)
25
29
  const chosen =
@@ -46,7 +50,7 @@ export async function requireVaultOutputKeyPossession(
46
50
  'utf8'
47
51
  )
48
52
  )
49
- await proveKeyPossession(scope, chosen, digest, 'Verify vault key for new funds')
53
+ await proveKeyPossession(scope, chosen, digest, shared?.reason ?? 'Verify vault key for new funds', shared?.session)
50
54
  }
51
55
 
52
56
  /** Fresh hardware authority to promote a staged key (add-key, late-key) when
@@ -89,9 +93,12 @@ async function proveKeyPossession(
89
93
  scope: VaultScopeToken,
90
94
  chosen: VaultMeta['keys'][number],
91
95
  digest: number[],
92
- reason: string
96
+ reason: string,
97
+ /** When given, the signer belongs to the caller's session: it is not
98
+ * released here. The session's owner closes it, also when this throws. */
99
+ session?: VaultSignerSession
93
100
  ): Promise<void> {
94
- const signer = await requestVaultSigner(reason, chosen.serial)
101
+ const signer = session ? await session.acquire(reason, chosen.serial) : await requestVaultSigner(reason, chosen.serial)
95
102
  try {
96
103
  vaultStore.assertScopeToken(scope)
97
104
  if (signer.serial !== chosen.serial || signer.pubkey !== chosen.pubkey) {
@@ -116,6 +123,6 @@ async function proveKeyPossession(
116
123
  }
117
124
  if (!valid) throw new VaultError('wrong-key', 'Hardware failed the new vault output possession challenge')
118
125
  } finally {
119
- signer.release()
126
+ if (!session) signer.release()
120
127
  }
121
128
  }