@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,68 +1,67 @@
1
1
  /**
2
2
  * Ceremony controller — UI-free state machine for the insert → PIN → tap flow
3
- * that unwraps the vault key. Consumed by a React context that renders the
4
- * ceremony sheet; kept free of React and native imports so it is fully
5
- * unit-testable against the mock driver.
3
+ * that turns one enrolled YubiKey into a VaultSigner. Consumed by a React
4
+ * context that renders the ceremony sheet; kept free of React and native
5
+ * imports so it is fully unit-testable against the mock driver.
6
6
  *
7
- * What a ceremony PRODUCES: the YubiKey is an unwrap oracle, not a signer. One
8
- * tap performs exactly ONE on-token ECDH (PIV KeyAgreement) against the seal's
9
- * ephemeral public key; that shared secret opens the sealed 64-byte vault seed,
10
- * which becomes an HD node and is then zeroized. The ceremony's product is that
11
- * node — a VaultKeyHandle — from which the spend path derives every K1 child it
12
- * needs, in software, with no further card contact. There is no per-digest
13
- * round trip and no signing on the card at all.
7
+ * What a ceremony PRODUCES: a VaultSigner — the CHOSEN key's serial and
8
+ * compressed P-256 public key, plus `sign(digest)`, which runs the card's
9
+ * GENERAL AUTHENTICATE (driver.signEcdsa) for one 32-byte digest and returns
10
+ * the DER signature. There is no seed, no seal, no ECDH and no key material in
11
+ * JS memory at any point (spec D2): the card signs each vault input itself.
12
+ * What lives in this module while a signer is armed is the PIN string and the
13
+ * transport session — nothing else.
14
14
  *
15
- * Concurrency: one ceremony ARMING at a time — `requestKey()` calls that
16
- * overlap a single in-flight arm attempt (e.g. a deposit and its re-vault, or
17
- * two callers racing while `running` is true) share that one attempt and all
18
- * resolve to the SAME VaultKeyHandle; release() on it is idempotent by
19
- * construction, so whichever caller releases last simply no-ops. That guarantee
20
- * does NOT extend across separate ceremonies: once an attempt finishes arming,
21
- * `running` goes back to false, and the NEXT requestKey() call starts an
22
- * entirely new ceremony with its own handle — even if the previous one has not
23
- * been released yet. Two live, independently-armed handles can therefore
24
- * coexist for a stretch (see ceremony.test.ts's "late release() from a stale
25
- * handle" case); what is guaranteed is that a handle released late can only
26
- * affect its OWN subscription, never a successor's — see makeHandle's
27
- * `release()` doc for the one exception (the shared native transport).
15
+ * The caller (transfers.ts) names the key BEFORE the tap (spec D14): the
16
+ * ceremony reads `chosenSerial` against the store's key list, refuses a serial
17
+ * that is not enrolled (`not-enrolled`) before any hardware prompt, and refuses
18
+ * a tapped card whose serial is not the chosen one (`serial-mismatch`) on EVERY
19
+ * session, including the reopened ones described below.
28
20
  *
29
- * Session lifetime: arming means "the key is unwrapped and held", not "the
30
- * operation is done." A session-based transport's driver.stop() (which
31
- * dismisses the iOS NFC sheet) is therefore NOT called when the ceremony
32
- * completes; it moves to VaultKeyHandle.release(), so the session's lifetime
33
- * still brackets the caller's whole operation. The one exception is the error
34
- * path: if arming itself fails, no handle exists to own the session, so run()'s
35
- * finally closes it there.
21
+ * Concurrency: one Vault hardware operation at a time. Every overlapping
22
+ * `requestSigner()` is rejected with `ceremony-active`, even for the same
23
+ * serial. The process-wide lease is shared with enrollment and adoption and
24
+ * remains held until the native listener/session is completely torn down.
36
25
  *
37
- * The retention window is now a ZEROIZATION BOUNDARY, not a convenience timer.
38
- * While a handle is armed, the vault key is live in JS memory; release() (or
39
- * the retention timeout, or a detach) drops the reference so the runtime can
40
- * collect it.
26
+ * Session lifetime: arming means "the chosen card answered with the right
27
+ * serial and accepted the PIN", not "the operation is done." A session-based
28
+ * transport's driver.stop() is therefore not called when arming completes; it
29
+ * moves to VaultSigner.release() (and also dismisses the iOS NFC sheet),
30
+ * so the session's lifetime still brackets the caller's whole signing loop.
31
+ * The one exception is the error path: if arming itself fails, no signer
32
+ * exists to own the session, so run()'s finally closes it there.
41
33
  *
42
- * Two caveats on that word "boundary", both deliberate and both bounded:
43
- * - The window is refreshable. A post-arm progress note restarts it (see
44
- * noteProgress), so an operation that legitimately outruns one window is
45
- * not cut off mid-flight. It is NOT an open-ended lease: ARM_MAX_MULTIPLE
46
- * caps a session's total life at 3× the window measured from `armedAt`,
47
- * after which the relock fires however fresh the progress is. The
48
- * boundary is therefore "at most 3× retention", not "exactly retention".
49
- * - What gets dropped is a REFERENCE, not the bytes. The seed IS wiped
50
- * (fill(0)) the moment the HD node is built, but the node itself cannot
51
- * be zeroized — @bsv/sdk's HD holds the key as BigNumber/array internals
52
- * with no wipe API, and Hermes may have copied them anyway. Dropping the
53
- * reference is the best the runtime allows; this is the accepted residual
54
- * risk the K1-only design documents. And the ceremony can only drop its
55
- * OWN reference — see VaultKeyHandle on why callers must not keep one.
34
+ * Signing is RESUMABLE (spec §4.2 step 6). `sign()` retries a dropped tap in
35
+ * place — touch-timeout, nfc-lost, key-removed-mid-op REJECTED BY signEcdsa —
36
+ * by parking on the Retry prompt and, on a session-based transport, closing the
37
+ * dead session and opening a fresh one (serial and PIN re-checked) before
38
+ * signing the SAME digest again; the caller's reservation and the signatures
39
+ * already gathered are untouched. On a session-based transport it also closes
40
+ * and reopens the session every `inputsPerTap` successful signatures (the
41
+ * card's touch cache and CoreNFC's 60 s session both bound a batch), showing
42
+ * 'waiting-for-key' with the caller's progress so the sheet can say "batch b of
43
+ * n". A driver-EMITTED 'detached' while a signer is live is NOT a retry: it is
44
+ * the hardware leaving, and notifyKeyDetached relocks exactly as before.
56
45
  *
57
- * SECURITY: the PIN lives in the arm flow's closure until release(), and the
58
- * unwrapped key lives in the handle for the same span. Never log the PIN, the
59
- * ECDH secret, the seed, the HD node, or a mnemonic — and never put any of them
60
- * in CeremonyState, which is React-visible.
46
+ * The NFC alert text handed to driver.start() is the caller's `reason` — this
47
+ * module has no i18n, and YubiKit fixes the text for the life of one session
48
+ * anyway; per-batch progress is shown by the in-app sheet from
49
+ * CeremonyState.progress.
50
+ *
51
+ * The retention window bounds how long a signer stays usable. A progress note
52
+ * (noteProgress) or a `sign()` call carrying progress restarts it, so a long
53
+ * batch is not cut off mid-flight; ARM_MAX_MULTIPLE caps a session's total
54
+ * life at 3× the window measured from `armedAt`, after which the relock fires
55
+ * however fresh the progress is.
56
+ *
57
+ * SECURITY: the PIN lives in the arm flow's closure until release(). Never log
58
+ * the PIN, and never put it in CeremonyState, which is React-visible. Serials
59
+ * and public keys are public data and travel on the signer, not in state.
61
60
  */
62
- import { HD } from '@bsv/sdk'
61
+ import { Utils } from '@bsv/sdk'
63
62
  import { VaultDriver } from './driver'
64
- import { unsealVaultKey } from './sealing'
65
- import { SealedBlob, VaultError, VaultErrorCode } from './types'
63
+ import { acquireVaultHardwareLease } from './hardwareLease'
64
+ import { VaultError, VaultErrorCode } from './types'
66
65
 
67
66
  export type CeremonyPhase =
68
67
  | 'idle'
@@ -76,69 +75,79 @@ export type CeremonyPhase =
76
75
  | 'error'
77
76
 
78
77
  /**
79
- * Work happening AFTER the key is armed, reported by the spend path so the
78
+ * Work happening AFTER the signer is armed, reported by the spend path so the
80
79
  * sheet can show activity instead of a frozen screen.
81
80
  *
82
- * There is no per-signature variant anymore: K1 signing is software-only and
83
- * fast, so the seconds-long stretches worth reporting are transaction assembly
84
- * ('preparing') and the network round trip ('broadcasting').
81
+ * 'preparing' carries the signing loop's position when it has one: `signed`
82
+ * inputs done out of `total`. The sheet renders it between batches and after
83
+ * the NFC sheet dismisses (it cannot draw under the iOS system sheet).
85
84
  */
86
- export type VaultProgress = { phase: 'preparing' } | { phase: 'broadcasting' }
85
+ export type VaultProgress = { phase: 'preparing'; signed?: number; total?: number } | { phase: 'broadcasting' }
87
86
 
88
87
  /**
89
88
  * Everything the ceremony publishes to React (see context/VaultContext.tsx).
90
89
  *
91
- * Kept to exactly these four fields on purpose: codes, a phase, a deadline and
92
- * the caller's own reason string. No key material, no PIN, no serial — see this
93
- * module's SECURITY note, and the "nothing key-shaped reaches the React-visible
94
- * ceremony state" case in __tests__/vault/ceremony.test.ts, which pins the key
95
- * set so a new field cannot be added here without a deliberate decision.
90
+ * Kept to exactly these five fields on purpose: a phase, a deadline, the
91
+ * caller's own reason string, an error code, and the signing position. No PIN,
92
+ * no serial, no pubkey, no signature — see this module's SECURITY note, and the
93
+ * "nothing key-shaped reaches the React-visible ceremony state" case in
94
+ * __tests__/vault/ceremony.test.ts, which pins the key set so a new field
95
+ * cannot be added here without a deliberate decision.
96
96
  */
97
97
  export interface CeremonyState {
98
98
  phase: CeremonyPhase
99
99
  reason?: string
100
100
  error?: { code: VaultErrorCode; retriesLeft?: number }
101
101
  armedUntil?: number
102
+ /** Signing position while a batch runs (spec §4.2 step 8). Cleared on release. */
103
+ progress?: { signed: number; total: number }
102
104
  }
103
105
 
104
106
  /**
105
- * A briefly-held, unwrapped vault key.
107
+ * An armed YubiKey: the chosen key's public identity plus the one operation
108
+ * the card performs for the vault.
106
109
  *
107
- * `hd` is the vault's private HD node — every deposit address and every
108
- * spending key derives from it, in software, for free. Callers MUST call
109
- * release() in a finally: on session-based transports that is what dismisses
110
- * the system NFC sheet, and on every transport it is what drops the key.
110
+ * Callers MUST call release() in a finally: on session-based transports that
111
+ * is what dismisses the system NFC sheet, and on every transport it is what
112
+ * ends the ceremony (phase back to 'idle') and drops the PIN.
111
113
  *
112
- * Reading `hd` after release (or after a timeout/detach relock) throws
113
- * `key-removed-mid-op` rather than handing back a key the ceremony has
114
- * declared dead. That check happens PER READ and nowhere else: it can refuse
115
- * to hand the node out again, but it cannot reach into a reference a caller
116
- * already took. A variable holding `handle.hd` keeps working — and keeps the
117
- * key alive — for as long as the caller holds it, whatever the ceremony
118
- * thinks.
119
- *
120
- * So: read `handle.hd` at each point of use. Passing it straight into a
121
- * derive/spend operation that completes inside the armed window, with
122
- * `release()` in a finally, is the intended shape. NEVER stash it in module
123
- * state, React state, a closure that outlives the operation, or any cache —
124
- * the ceremony has no way to revoke that, and the whole point of the
125
- * retention window is that the key does not outlive one operation.
114
+ * `sign()` after release (or after a timeout/detach relock) throws
115
+ * `key-removed-mid-op` rather than talking to a card the ceremony has declared
116
+ * dead. NEVER stash a signer in module state, React state, a closure that
117
+ * outlives the operation, or any cache — obtain it from ceremonyHost for one
118
+ * transfer and release it when that transfer ends.
126
119
  */
127
- export interface VaultKeyHandle {
128
- readonly hd: HD
129
- /** Idempotent: safe to call more than once, and safe for concurrent callers
130
- * that were all handed the same handle to release independently. */
120
+ export interface VaultSigner {
121
+ readonly serial: string
122
+ /** 33-byte compressed P-256 public key, lowercase hex (as enrolled). */
123
+ readonly pubkey: string
124
+ /**
125
+ * Sign one 32-byte digest (64 hex chars) on the card; returns DER bytes.
126
+ * Retries in place on touch-timeout / nfc-lost / key-removed-mid-op REJECTED
127
+ * BY the driver (re-opens the session on session-based transports,
128
+ * re-checking serial + PIN); on session-based transports re-opens a fresh
129
+ * session every `inputsPerTap` calls. `progress` publishes the loop position
130
+ * to the sheet and refreshes the retention window. Throws
131
+ * 'key-removed-mid-op' after release(), whatever released it (a cancel(),
132
+ * a detach, the retention ceiling, or the caller).
133
+ */
134
+ sign(digestHex: string, progress?: { index: number; total: number }): Promise<number[]>
135
+ /** Idempotent for the owning caller's cleanup paths. */
131
136
  release(): void
132
137
  }
133
138
 
134
- interface CeremonyMeta {
139
+ /** One enrolled key as the ceremony sees it — the public part of a
140
+ * vaultStore VaultKeyRecord. */
141
+ interface CeremonyKey {
142
+ serial: string
135
143
  slot: number
136
- yubiSerial: string
144
+ pubkey: string
137
145
  }
138
146
 
139
- interface CeremonyStoreView {
140
- getMeta(): Promise<CeremonyMeta | null>
141
- getSeal(): Promise<SealedBlob | null>
147
+ /** The store's key list, narrowed to what a tap needs. ceremonyHost maps
148
+ * vaultStore's scoped meta v6 onto it; tests hand in a literal. */
149
+ export interface CeremonyStoreView {
150
+ getMeta(): Promise<{ keys: CeremonyKey[] } | null>
142
151
  }
143
152
 
144
153
  interface Deferred<T> {
@@ -175,32 +184,35 @@ export class CeremonyController {
175
184
  state: CeremonyState = { phase: 'idle' }
176
185
 
177
186
  onRelock?: (why: 'timeout' | 'detached' | 'manual') => void
178
- onArmed?: (handle: VaultKeyHandle) => void
187
+ onArmed?: (signer: VaultSigner) => void
179
188
 
180
189
  private subscribers = new Set<(s: CeremonyState) => void>()
181
- private waiters: ((h: VaultKeyHandle) => void)[] = []
190
+ private waiters: ((s: VaultSigner) => void)[] = []
182
191
  private rejecters: ((e: unknown) => void)[] = []
183
192
  private running = false
184
193
  private reason = ''
194
+ /** The serial the in-flight (or most recent) ceremony was asked for. */
195
+ private chosenSerial = ''
185
196
 
186
197
  /** Monotonic id of the newest arm attempt. `running` alone cannot tell an
187
198
  * attempt that it has been replaced: cancel() sets running=false while the
188
199
  * cancelled attempt is still parked inside an await (a tap can still land
189
- * seconds later), and the requestKey() that follows starts a fresh attempt
190
- * AND resets `cancelled`. Every run() captures its own generation and
191
- * re-checks it before touching any shared state, so a late-returning attempt
192
- * can only ever clean itself up. */
200
+ * seconds later), and the requestSigner() that follows starts a fresh
201
+ * attempt AND resets `cancelled`. Every run() captures its own generation
202
+ * and re-checks it before touching any shared state, so a late-returning
203
+ * attempt can only ever clean itself up. */
193
204
  private generation = 0
194
205
 
195
- /** The handle for the currently-armed session, if any. Set once arming
196
- * succeeds. Cleared by VaultKeyHandle.release() itself (identity-checked
206
+ /** The signer for the currently-armed session, if any. Set once arming
207
+ * succeeds. Cleared by VaultSigner.release() itself (identity-checked
197
208
  * against this field — see makeHandle) rather than by whoever calls
198
209
  * release(), so this is accurate whether release() was invoked by the caller
199
210
  * finishing normally, or by cancel()/notifyKeyDetached()/the retention timer
200
211
  * relocking it. Its presence — not `state.phase` — is what the relock paths
201
- * key off of, because a handle can be "active" while the visible phase is
202
- * 'preparing' or 'broadcasting', not just 'armed'. */
203
- private activeHandle?: VaultKeyHandle
212
+ * key off of, because a signer can be "active" while the visible phase is
213
+ * 'awaiting-touch', 'preparing' or 'broadcasting', not just 'armed'. (The
214
+ * field keeps its historical name; every relock path reads it.) */
215
+ private activeHandle?: VaultSigner
204
216
 
205
217
  private pinWaiter?: Deferred<string>
206
218
  private queuedPin?: string
@@ -220,22 +232,25 @@ export class CeremonyController {
220
232
 
221
233
  /** Hard ceiling on a session's life, as a multiple of the retention window.
222
234
  * A progress note refreshes the window (see noteProgress), which on its own
223
- * would make the retention period a lease the caller can renew indefinitely —
224
- * i.e. no zeroization boundary at all. Past `armedAt + this × retentionMs` the
225
- * relock fires no matter how fresh the progress is, and the grace window is
226
- * clamped to it too, so the key's maximum lifetime is bounded by construction
227
- * rather than by caller good behaviour. */
235
+ * would make the retention period a lease the caller can renew indefinitely.
236
+ * Past `armedAt + this × retentionMs` the relock fires no matter how fresh
237
+ * the progress is, and the grace window is clamped to it too, so the
238
+ * signer's maximum lifetime is bounded by construction rather than by caller
239
+ * good behaviour. */
228
240
  private static readonly ARM_MAX_MULTIPLE = 3
229
241
 
230
242
  /** Deadline for a session-based transport's waiting-for-key. CoreNFC caps a
231
243
  * tag-reader session at 60 s; if nothing (attach OR failure) has arrived in
232
- * 65 s the session is dead and its ending was swallowed somewhere below us —
233
- * YubiKit drops several such paths internally (readingAvailable false at
234
- * start, a session invalidated before it ever became active), so no delegate
235
- * fix can make this watchdog redundant. Persistent readers (Android USB)
236
- * are exempt: waiting for an insert legitimately has no deadline. */
244
+ * 65 s the session is dead and its ending was swallowed somewhere below us.
245
+ * This also bounds an Android ceremony that sees neither an inserted USB key
246
+ * nor an NFC tap. Persistent test readers are exempt. */
237
247
  private static readonly DEFAULT_ATTACH_TIMEOUT_MS = 65_000
238
248
 
249
+ /** Signatures one session-based tap covers before the ceremony closes the
250
+ * session and asks for a fresh tap (spec §4.2 step 6). ceremonyHost passes
251
+ * VAULT_INPUTS_PER_TAP; this is the fallback for a bare controller. */
252
+ private static readonly DEFAULT_INPUTS_PER_TAP = 16
253
+
239
254
  constructor(
240
255
  private deps: {
241
256
  getDriver: () => VaultDriver | null
@@ -243,6 +258,8 @@ export class CeremonyController {
243
258
  retentionMs: number
244
259
  /** Test seam for the waiting-for-key watchdog (session-based only). */
245
260
  attachTimeoutMs?: number
261
+ /** Session-based transports only: how many sign() calls one tap covers. */
262
+ inputsPerTap?: number
246
263
  }
247
264
  ) {}
248
265
 
@@ -252,42 +269,52 @@ export class CeremonyController {
252
269
  return () => this.subscribers.delete(cb)
253
270
  }
254
271
 
255
- /** Ask for the unwrapped vault key. Concurrent calls share one ceremony and
256
- * all receive the SAME handle, so release() is idempotent by construction. */
257
- requestKey(reason: string): Promise<VaultKeyHandle> {
258
- return new Promise<VaultKeyHandle>((resolve, reject) => {
272
+ /** Ask for the chosen key as a signer. Every overlapping request is refused:
273
+ * one caller must have sole ownership of both the signer and the process-wide
274
+ * native discovery/session object through release and teardown. */
275
+ requestSigner(reason: string, chosenSerial: string): Promise<VaultSigner> {
276
+ return new Promise<VaultSigner>((resolve, reject) => {
277
+ if (this.activeHandle || this.running) {
278
+ reject(new VaultError('ceremony-active', 'A vault signing operation is already active'))
279
+ return
280
+ }
281
+ let releaseLease: () => void
282
+ try {
283
+ releaseLease = acquireVaultHardwareLease()
284
+ } catch (e) {
285
+ reject(e)
286
+ return
287
+ }
259
288
  this.waiters.push(resolve)
260
289
  this.rejecters.push(reject)
261
- if (this.running) return // join the in-flight ceremony
262
290
  this.reason = reason
291
+ this.chosenSerial = chosenSerial
263
292
  this.cancelled = false
264
293
  this.running = true
265
- void this.run()
294
+ void this.run(releaseLease)
266
295
  })
267
296
  }
268
297
 
269
298
  /**
270
299
  * Report post-arm progress from the spend path.
271
300
  *
272
- * Guarded on an armed session: the K1 recovery sweep runs the same spend code
273
- * from a mnemonic-derived HD node with no ceremony at all, and must not raise
274
- * a YubiKey sheet. Also ignores anything arriving mid-arm, where the arming
275
- * phases own the display.
301
+ * Guarded on an armed session: a note with no signer armed (a deposit, which
302
+ * is hardware-free, or a caller that has already released) must not raise a
303
+ * sheet, and anything arriving mid-arm is ignored because the arming phases
304
+ * own the display.
276
305
  *
277
- * A progress note also REFRESHES the retention window. Nothing else can:
278
- * the single ECDH is spent at arm time, so without this an operation that
279
- * legitimately outlives the window (a slow broadcast) would have the key
280
- * pulled out from under it mid-flight. This is the direct successor of the
281
- * old design's "every signature re-arms" refresh.
306
+ * A progress note also REFRESHES the retention window, bounded twice over
307
+ * (see startArmTimer / ARM_MAX_MULTIPLE): progress must keep arriving, AND no
308
+ * refresh may push the relock past `armedAt + ARM_MAX_MULTIPLE × retentionMs`.
282
309
  *
283
- * The refresh is bounded twice over, so it cannot become an unbounded lease
284
- * a caller renews at will: progress must keep arriving (or checkArmTimeout's
285
- * grace path relocks), AND no refresh may push the relock past
286
- * `armedAt + ARM_MAX_MULTIPLE × retentionMs` — see startArmTimer.
310
+ * 'preparing' with both counters publishes them as `state.progress`; any
311
+ * other note clears it, so a stale "3 of 10" never outlives its batch.
287
312
  */
288
313
  noteProgress(p: VaultProgress): void {
289
314
  if (!this.activeHandle || this.running) return
290
- this.set({ phase: p.phase, armedUntil: this.startArmTimer(), error: undefined })
315
+ const progress =
316
+ p.phase === 'preparing' && p.signed != null && p.total != null ? { signed: p.signed, total: p.total } : undefined
317
+ this.set({ phase: p.phase, progress, armedUntil: this.startArmTimer(), error: undefined })
291
318
  }
292
319
 
293
320
  submitPin(pin: string): void {
@@ -313,18 +340,32 @@ export class CeremonyController {
313
340
  * trigger it. */
314
341
  cancel(): void {
315
342
  this.cancelled = true
343
+ // A PIN submitted before anything was waiting for it belongs to the
344
+ // ceremony being cancelled; the next one must show pin-entry, not
345
+ // silently consume it.
346
+ this.queuedPin = undefined
316
347
  const err = new VaultError('user-cancelled')
317
348
  this.pinWaiter?.reject(err)
318
349
  this.retryWaiter?.reject(err)
319
350
  this.attachWaiter?.reject(err)
320
351
  if (this.running) {
321
352
  this.failAll(err)
322
- this.running = false
353
+ // run() owns this flag through its finally. A native operation may still
354
+ // be returning, and its finally may still need to stop the process-wide
355
+ // transport. requestSigner refuses successors while cancelled+running.
323
356
  this.set({ phase: 'idle' })
324
357
  }
325
358
  if (this.activeHandle) {
326
359
  this.activeHandle.release()
327
360
  this.onRelock?.('manual')
361
+ } else if (!this.running && this.state.phase !== 'idle') {
362
+ // Dismissing a finished attempt's error phase (e.g. serial-mismatch):
363
+ // running is already false (run()'s finally cleared it) and there is
364
+ // no armed handle for release() to relock, so nothing above touches
365
+ // phase. Left uncleared, the sheet's `visible` (phase !== 'idle')
366
+ // never flips, so a swipe-to-dismiss slides the sheet view away while
367
+ // its full-screen backdrop stays mounted and eats every touch.
368
+ this.set({ phase: 'idle' })
328
369
  }
329
370
  }
330
371
 
@@ -365,13 +406,12 @@ export class CeremonyController {
365
406
  }
366
407
 
367
408
  /**
368
- * Why this outlives `run()` for a session-based transport: WalletContext's
369
- * own persistent-reader listener explicitly skips `sessionBased` drivers
370
- * (it exists only to relock Android USB on unplug), so a session's OWN
371
- * subscription (in its own KeyEventSession box) is the only thing that can
372
- * ever learn a tap-session detached while a handle is armed. A persistent
373
- * reader has that separate always-on listener, so its ceremony-owned
374
- * subscription is dropped right after arming.
409
+ * Why this outlives `run()` for a session-based transport: WalletContext
410
+ * skips ceremony-owned native discovery, so this subscription is the only
411
+ * source of Android USB-unplug events while a handle is armed. NFC loss
412
+ * during a command also rejects from the native operation. A persistent test
413
+ * reader has a separate always-on listener, so its ceremony subscription is
414
+ * dropped right after arming.
375
415
  */
376
416
  private subscribeKeyEvents(driver: VaultDriver, session: KeyEventSession): void {
377
417
  session.off?.()
@@ -387,13 +427,20 @@ export class CeremonyController {
387
427
  session.off = undefined
388
428
  }
389
429
 
390
- private async run(): Promise<void> {
430
+ private async run(releaseLease: () => void): Promise<void> {
391
431
  // This attempt's identity for the rest of its life — see `generation`.
392
432
  const gen = ++this.generation
433
+ // Synchronous with requestSigner(): anything queued BEFORE this ceremony
434
+ // was asked for is stale (a failed or superseded attempt's leftovers) and
435
+ // must not be consumed by this attempt's collectPin. A PIN submitted
436
+ // after this point — including one that lands before pin-entry is
437
+ // painted — is this attempt's and is still queued for it.
438
+ this.queuedPin = undefined
393
439
  const driver = this.deps.getDriver()
394
440
  if (!driver) {
395
441
  this.failAll(new VaultError('driver-unavailable'))
396
442
  this.running = false
443
+ releaseLease()
397
444
  return
398
445
  }
399
446
  // This attempt's own driver-event subscription box: a key connecting (an
@@ -410,53 +457,54 @@ export class CeremonyController {
410
457
  // torn its own session down, so the finally must not do it twice.
411
458
  let superseded = false
412
459
  try {
413
- // Both halves of an enrollment, read before any hardware prompt: a
414
- // half-enrolled install (meta but no seal, or the reverse) has nothing
415
- // a tap could unwrap, so it must fail before the sheet ever opens.
416
- // Mirrors vaultStore.isEnrolled(), which also requires both.
417
- const [meta, seal] = await Promise.all([this.deps.store.getMeta(), this.deps.store.getSeal()])
418
- if (!meta || !seal) throw new VaultError('not-enrolled')
419
-
420
- // NFC (session-based) collects the PIN BEFORE the tap and verifies it in
421
- // that one tap (the scan sheet covers the app, so no PIN entry mid-tap).
422
- // A persistent USB reader can interleave PIN entry and the serial/PIN
423
- // checks.
424
- const handle = driver.sessionBased
425
- ? await this.armViaTap(driver, meta, seal, session, gen)
426
- : await this.armViaReader(driver, meta, seal, session, gen)
460
+ // The key list, read before any hardware prompt: a serial that is not
461
+ // enrolled (a removed key, a stale chooser) has nothing a tap could do,
462
+ // so it must fail before the sheet ever opens (spec §4.2 step 6).
463
+ const meta = await this.deps.store.getMeta()
464
+ if (!meta) throw new VaultError('not-enrolled')
465
+ const key = meta.keys.find(k => k.serial === this.chosenSerial)
466
+ if (!key) {
467
+ throw new VaultError('not-enrolled', `Key ${this.chosenSerial} is not one of this vault's keys`)
468
+ }
469
+
470
+ // Native discovery collects the PIN first and verifies it after one USB
471
+ // or NFC device connects. This is required by iOS's modal scan sheet and
472
+ // gives Android the same single-ceremony, single-device contract.
473
+ const signer = driver.sessionBased
474
+ ? await this.armViaTap(driver, key, session, gen, releaseLease)
475
+ : await this.armViaReader(driver, key, session, gen, releaseLease)
427
476
  this.throwIfCancelled()
428
477
 
429
478
  // Have we been superseded while parked on the tap? `cancelled` cannot
430
- // answer this: cancel() sets it, but the very next requestKey() resets it
431
- // to false for the NEW attempt, so by the time a cancelled-then-replaced
432
- // attempt's ECDH lands, the flag reads clean again. Only the generation
433
- // does. Without this check that attempt would install ITS handle as
434
- // activeHandle over the successor's, arm a second timer, and hand its own
435
- // key to whoever is waiting on the successor — two unwrapped keys live,
436
- // one of them owned by nobody.
479
+ // answer this: cancel() sets it, but the very next requestSigner() resets
480
+ // it to false for the NEW attempt, so by the time a cancelled-then-
481
+ // replaced attempt's PIN check lands, the flag reads clean again. Only
482
+ // the generation does. Without this check that attempt would install ITS
483
+ // signer as activeHandle over the successor's, arm a second timer, and
484
+ // hand its own signer to whoever is waiting on the successor — two
485
+ // sessions live, one of them owned by nobody.
437
486
  if (gen !== this.generation) {
438
487
  superseded = true
439
488
  // Drop THIS attempt's listener box first (release() only unsubscribes
440
489
  // on a session-based transport, and the post-arm unsubscribe below is
441
490
  // never reached from here — without this a cancelled-and-replaced
442
491
  // attempt would leave a live listener behind on every persistent-reader
443
- // ceremony), then drop its key and close its session. The identity
444
- // check inside release() means none of the controller's shared state
445
- // (the successor's activeHandle, timer or phase) is touched.
492
+ // ceremony), then drop its session. The identity check inside
493
+ // release() means none of the controller's shared state (the
494
+ // successor's activeHandle, timer or phase) is touched.
446
495
  this.unsubscribeKeyEvents(session)
447
- handle.release()
496
+ signer.release()
448
497
  return
449
498
  }
450
499
 
451
- this.activeHandle = handle
500
+ this.activeHandle = signer
452
501
  armed = true
453
502
  this.arm()
454
- this.resolveAll(handle)
455
- this.onArmed?.(handle)
503
+ this.resolveAll(signer)
504
+ this.onArmed?.(signer)
456
505
 
457
- // Persistent readers hand relock-on-unplug to WalletContext's
458
- // longer-lived listener — drop ours now. Session-based transports keep
459
- // listening: see subscribeKeyEvents' doc above.
506
+ // Persistent test readers hand detach handling to their longer-lived
507
+ // owner. Session-based native drivers keep listening through release.
460
508
  if (!driver.sessionBased) this.unsubscribeKeyEvents(session)
461
509
  } catch (e) {
462
510
  // Anything that is not a VaultError gets relabelled 'driver-unavailable',
@@ -471,7 +519,7 @@ export class CeremonyController {
471
519
  // waiters were already failed by the cancel() that superseded it, so
472
520
  // there is nobody left to tell. The finally still closes its session.
473
521
  if (gen !== this.generation) return
474
- if (err.code === 'user-cancelled') {
522
+ if (this.cancelled || err.code === 'user-cancelled') {
475
523
  this.set({ phase: 'idle' })
476
524
  } else {
477
525
  this.set({ phase: 'error', error: { code: err.code, retriesLeft: err.retriesLeft } })
@@ -480,20 +528,20 @@ export class CeremonyController {
480
528
  } finally {
481
529
  // Only the CURRENT attempt owns `running`. A superseded attempt clearing
482
530
  // it would declare the successor's still-in-flight ceremony finished, so
483
- // the next requestKey() would start a third attempt alongside it instead
484
- // of joining the second.
531
+ // the next requestSigner() would start a third attempt alongside it
532
+ // instead of recognizing that the second still owns the controller.
485
533
  if (gen === this.generation) this.running = false
486
534
  // `armed` (this attempt's own outcome), NOT this.activeHandle (whoever
487
535
  // the CONTROLLER currently considers active): an unreleased predecessor
488
536
  // ceremony leaves this.activeHandle truthy for the whole time this
489
537
  // attempt runs, which would otherwise make a FAILED successor's finally
490
- // wrongly conclude "some handle must already own this session/
538
+ // wrongly conclude "some signer must already own this session/
491
539
  // subscription" and skip closing its own — the predecessor's activeHandle
492
540
  // has nothing to do with whether this attempt itself succeeded.
493
541
  if (!armed && !superseded) {
494
- // Arming never completed: no handle exists to own the subscription
542
+ // Arming never completed: no signer exists to own the subscription
495
543
  // or the session, so close both now — nothing else ever will.
496
- // (A superseded attempt DID build a handle and released it above,
544
+ // (A superseded attempt DID build a signer and released it above,
497
545
  // which already did exactly this teardown — don't repeat it.)
498
546
  // Unsubscribe BEFORE any stop so a session-end detach echo cannot
499
547
  // relock a session that was already dead.
@@ -505,6 +553,7 @@ export class CeremonyController {
505
553
  /* stop is best-effort */
506
554
  }
507
555
  }
556
+ releaseLease()
508
557
  }
509
558
  }
510
559
  }
@@ -517,72 +566,96 @@ export class CeremonyController {
517
566
  }
518
567
  }
519
568
 
520
- /** Persistent reader (Android USB): key present, PIN entry and token ops
569
+ /** Persistent test reader: key presence, PIN entry and token operations can
521
570
  * interleave, so a wrong PIN is retried in place. */
522
571
  private async armViaReader(
523
572
  driver: VaultDriver,
524
- meta: CeremonyMeta,
525
- seal: SealedBlob,
573
+ key: CeremonyKey,
526
574
  session: KeyEventSession,
527
- gen: number
528
- ): Promise<VaultKeyHandle> {
575
+ gen: number,
576
+ releaseLease: () => void
577
+ ): Promise<VaultSigner> {
529
578
  this.throwIfStale(gen)
530
579
  this.set({ phase: 'connecting' })
580
+ // Arm the attach waiter BEFORE probing. A key inserted while getKeyInfo is
581
+ // in flight fires 'attached' into notifyKeyAttached, which can only resolve
582
+ // a waiter that already exists: created after the probe, that event would
583
+ // be lost, the probe would still answer "no key", and waiting-for-key below
584
+ // would park forever behind a key that is already present. The no-op catch
585
+ // keeps a waiter that cancel()/detach rejects before it is awaited from
586
+ // surfacing as an unhandled rejection; the await below still observes it.
587
+ const waiter = (this.attachWaiter = defer<void>())
588
+ waiter.promise.catch(() => {})
531
589
  let info = await this.safeKeyInfo(driver)
532
590
  if (!info) {
533
591
  this.set({ phase: 'waiting-for-key' })
534
- const waiter = (this.attachWaiter = defer<void>())
535
- driver.start()
592
+ driver.start(this.reason)
536
593
  await waiter.promise
537
594
  this.throwIfStale(gen)
538
595
  this.set({ phase: 'connecting' })
539
596
  info = await this.safeKeyInfo(driver)
597
+ } else if (this.attachWaiter === waiter) {
598
+ this.attachWaiter = undefined
540
599
  }
541
600
  if (!info) throw new VaultError('no-key')
542
- if (info.serial !== meta.yubiSerial) {
543
- throw new VaultError('serial-mismatch', `Expected key ${meta.yubiSerial}`)
601
+ this.requireChosenSerial(info.serial, key)
602
+ const pin = await this.collectPin(driver, key, gen)
603
+ return this.makeHandle(driver, key, pin, session, gen, releaseLease)
604
+ }
605
+
606
+ /** The serial check, run on EVERY session (initial arm, and each reopen on
607
+ * a session-based transport): the tapped card must be THE chosen key. The
608
+ * detail names both serials so the sheet can say "That's X — you chose Y"
609
+ * (spec §4.2 step 6). A serial not enrolled at all lands here too: it is
610
+ * not the chosen one either, and the sheet has the key list to say so. */
611
+ private requireChosenSerial(tapped: string, key: CeremonyKey): void {
612
+ if (tapped !== key.serial) {
613
+ throw new VaultError('serial-mismatch', `Tapped key ${tapped}, chose key ${key.serial}`, undefined, {
614
+ tapped,
615
+ chosen: key.serial
616
+ })
544
617
  }
545
- const pin = await this.collectPin(driver, gen)
546
- return this.makeHandle(driver, meta, seal, pin, session, gen)
547
618
  }
548
619
 
549
620
  /** Errors from a single tap/touch attempt that are worth retrying without
550
- * throwing away the whole ceremony: a missed/short touch, or the field
621
+ * throwing away the whole operation: a missed/short touch, or the field
551
622
  * dropping mid-command (phone shifted, key lifted a hair early). On a
552
- * session-based transport both leave the dead NFC session behind, so a
553
- * retry must close it and open a fresh one — see the reopen in
554
- * unwrapVaultKey. */
623
+ * session-based transport all three leave the dead NFC session behind, so a
624
+ * retry must close it and open a fresh one — see the reopen inside
625
+ * VaultSigner.sign() (makeHandle). Only REJECTIONS of driver.signEcdsa are
626
+ * classified here; a driver-emitted 'detached' event is handled by
627
+ * notifyKeyDetached and relocks. */
555
628
  private static readonly RETRYABLE_TAP_ERRORS = new Set(['touch-timeout', 'nfc-lost', 'key-removed-mid-op'])
556
629
 
557
- /** NFC tap (iOS): PIN first in-app (the scan sheet is modal), then one tap
558
- * connects, checks the serial, verifies the PIN, and performs the unwrap. A
559
- * wrong PIN aborts the ceremony — we cannot re-prompt beneath an open system
560
- * NFC sheet. */
630
+ /** Ceremony-scoped native discovery: collect the PIN first, then connect one
631
+ * USB/NFC device, check its serial and verify the PIN. A wrong PIN aborts the
632
+ * ceremony because iOS cannot re-prompt beneath an open system NFC sheet. */
561
633
  private async armViaTap(
562
634
  driver: VaultDriver,
563
- meta: CeremonyMeta,
564
- seal: SealedBlob,
635
+ key: CeremonyKey,
565
636
  session: KeyEventSession,
566
- gen: number
567
- ): Promise<VaultKeyHandle> {
637
+ gen: number,
638
+ releaseLease: () => void
639
+ ): Promise<VaultSigner> {
568
640
  const pin = await this.collectPinValue(gen)
569
- await this.openTapSession(driver, meta, pin, session, gen)
570
- return this.makeHandle(driver, meta, seal, pin, session, gen)
641
+ await this.openTapSession(driver, key, pin, session, gen)
642
+ return this.makeHandle(driver, key, pin, session, gen, releaseLease)
571
643
  }
572
644
 
573
645
  /** Open (or reopen) an NFC session and get as far as a verified PIN. Used
574
- * both for the initial arm and — on a session-based transport — to
575
- * re-establish a fresh session after a dropped tap mid-unwrap. The serial
576
- * check lives here as well as in armViaReader deliberately: EVERY session,
577
- * including a reopened one, re-checks it, so a different card presented on
578
- * the retry tap is never asked to unwrap this vault's seal.
646
+ * for the initial arm and — on a session-based transport — by
647
+ * VaultSigner.sign() to re-establish a fresh session after a dropped tap
648
+ * and at every batch boundary. The serial check lives here as well as in
649
+ * armViaReader deliberately: EVERY session, including a reopened one,
650
+ * re-checks it, so a different card presented on the next tap is never
651
+ * asked to sign for this key.
579
652
  * (Re)subscribes `session` every time: the very first call replaces run()'s
580
653
  * top-level subscription on the SAME box (harmless — nothing was pending on
581
654
  * it yet), and every reopen needs a fresh one since the caller unsubscribed
582
655
  * this same box around its matching driver.stop(). */
583
656
  private async openTapSession(
584
657
  driver: VaultDriver,
585
- meta: CeremonyMeta,
658
+ key: CeremonyKey,
586
659
  pin: string,
587
660
  session: KeyEventSession,
588
661
  gen: number
@@ -591,7 +664,7 @@ export class CeremonyController {
591
664
  this.subscribeKeyEvents(driver, session)
592
665
  this.set({ phase: 'waiting-for-key' })
593
666
  const waiter = (this.attachWaiter = defer<void>())
594
- driver.start()
667
+ driver.start(this.reason)
595
668
  // Watchdog: a session-based transport that reports NOTHING by the deadline
596
669
  // is dead, and its death was swallowed below us (see
597
670
  // DEFAULT_ATTACH_TIMEOUT_MS). Identity-checked against attachWaiter so a
@@ -613,12 +686,13 @@ export class CeremonyController {
613
686
  const info = await driver.getKeyInfo()
614
687
  // getKeyInfo is a native call cancel() cannot interrupt.
615
688
  this.throwIfStale(gen)
616
- if (info.serial !== meta.yubiSerial) {
617
- throw new VaultError('serial-mismatch', `Expected key ${meta.yubiSerial}`)
618
- }
619
- const res = await driver.verifyPin(pin)
689
+ this.requireChosenSerial(info.serial, key)
690
+ const res = await driver.verifyPin(key.serial, pin)
620
691
  this.throwIfStale(gen)
621
- if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
692
+ if (!res.ok) {
693
+ if (res.retriesLeft <= 0) throw new VaultError('pin-locked', 'PIN is blocked', 0)
694
+ throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
695
+ }
622
696
  }
623
697
 
624
698
  /** Collect a PIN value from the UI only (no token verify) — used by the NFC
@@ -635,7 +709,7 @@ export class CeremonyController {
635
709
  return this.pinWaiter.promise
636
710
  }
637
711
 
638
- private async collectPin(driver: VaultDriver, gen: number): Promise<string> {
712
+ private async collectPin(driver: VaultDriver, key: CeremonyKey, gen: number): Promise<string> {
639
713
  for (;;) {
640
714
  this.throwIfStale(gen)
641
715
  this.set({ phase: 'pin-entry', error: this.state.error })
@@ -647,7 +721,7 @@ export class CeremonyController {
647
721
  this.pinWaiter = defer<string>()
648
722
  pin = await this.pinWaiter.promise
649
723
  }
650
- const res = await driver.verifyPin(pin)
724
+ const res = await driver.verifyPin(key.serial, pin)
651
725
  // verifyPin is a native call cancel() cannot interrupt: without this, an
652
726
  // attempt superseded while parked in it would resume and repaint the
653
727
  // SUCCESSOR's phase back to 'pin-entry' over its armed session, then walk
@@ -657,163 +731,148 @@ export class CeremonyController {
657
731
  this.set({ phase: 'pin-entry', error: undefined })
658
732
  return pin
659
733
  }
734
+ if (res.retriesLeft <= 0) throw new VaultError('pin-locked', 'PIN is blocked', 0)
660
735
  this.set({ phase: 'pin-entry', error: { code: 'pin-invalid', retriesLeft: res.retriesLeft } })
661
736
  }
662
737
  }
663
738
 
664
739
  /**
665
- * The one touch-gated operation in the whole flow: on-token ECDH against the
666
- * seal's ephemeral public key, retried in place on a dropped tap.
740
+ * Wrap the verified card in the armed signer.
667
741
  *
668
- * The PIN is already known good by the time we get here — only the physical
669
- * touch can fail — so a hiccup does not throw away the collected PIN or (on
670
- * a persistent reader) the connection. On a session-based transport the retry
671
- * closes the dead session and opens a fresh one, RE-CHECKING THE SERIAL and
672
- * re-verifying the PIN, before retrying the ECDH.
742
+ * `sign()` is where every touch is spent, so it carries the retry loop that
743
+ * guards each card signature: a retryable rejection (RETRYABLE_TAP_ERRORS)
744
+ * parks on the Retry prompt, then — on a session-based transport — closes
745
+ * the dead session and opens a fresh one via openTapSession (serial re-
746
+ * checked, PIN re-verified) before signing the SAME digest again. Nothing
747
+ * about the caller's transaction changes: the digest is the same, so the
748
+ * signatures already gathered stay valid and the loop resumes at input k.
749
+ * A non-retryable rejection (pin-locked, an unexpected native error) paints
750
+ * `error` and rethrows; the caller aborts its reservation and releases.
673
751
  *
674
- * Only the ECDH is inside the retry loop. The unseal that follows is pure
675
- * software: `seal-corrupt` means the wrong card, a rewritten slot, or a
676
- * tampered blob — never something another tap could fix — so it must not be
677
- * mistaken for a retryable tap error.
752
+ * Batches: on a session-based transport, after `inputsPerTap` successful
753
+ * signatures the NEXT sign() first closes the session and reopens it —
754
+ * publishing the caller's progress under 'waiting-for-key' so the sheet can
755
+ * say "batch b of n" — because the card's 15 s touch cache and CoreNFC's
756
+ * 60 s session both bound what one tap can cover. Persistent readers never
757
+ * reopen.
678
758
  *
679
- * `secret` is a hex STRING (the driver's JSON-bridge shape) and so cannot be
680
- * wiped — same residual as the PIN. It is confined to this function's frame
681
- * and never stored, returned, or logged; the seed it opens IS wiped.
682
- */
683
- private async unwrapVaultKey(
684
- driver: VaultDriver,
685
- meta: CeremonyMeta,
686
- seal: SealedBlob,
687
- pin: string,
688
- session: KeyEventSession,
689
- gen: number
690
- ): Promise<HD> {
691
- let secret: string
692
- for (;;) {
693
- // Redundant by construction today — every path into this loop (first
694
- // entry via collectPin/openTapSession, re-entry via the retry branch
695
- // below) has already checked. Kept anyway, and deliberately not
696
- // load-bearing: this loop's body spends a TOUCH on the card, so it
697
- // guards itself rather than trusting each caller to have done it. No
698
- // test can distinguish it; nothing reaches here stale.
699
- this.throwIfStale(gen)
700
- this.set({ phase: 'awaiting-touch' })
701
- try {
702
- secret = (await driver.ecdh(meta.slot, pin, seal.ePub)).secret
703
- break
704
- } catch (e) {
705
- const err = e instanceof VaultError ? e : new VaultError('nfc-lost')
706
- if (!CeremonyController.RETRYABLE_TAP_ERRORS.has(err.code)) {
707
- // A hard failure (pin-locked, an unexpected native error) is not
708
- // retryable — rethrow and let run()'s catch surface it as a real
709
- // error rather than leaving the machine stuck showing "awaiting
710
- // touch" forever.
711
- throw err
712
- }
713
- // driver.ecdh is the one park point cancel() cannot interrupt, so a
714
- // superseded attempt lands HERE with `cancelled` already reset to false
715
- // by the requestKey() that replaced it. Both statements below are
716
- // shared state: `set` would flip the SUCCESSOR's visible phase to
717
- // 'error' while its handle is legitimately armed — inviting a cancel()
718
- // that releases the successor's live vault key mid-operation — and
719
- // `retryWaiter` would hand the successor's retry()/cancel() a deferred
720
- // belonging to a dead ceremony. Bail before either.
721
- this.throwIfStale(gen)
722
- this.set({ phase: 'error', error: { code: err.code } })
723
- this.retryWaiter = defer<void>()
724
- await this.retryWaiter.promise // resolves on retry(); rejects on cancel/detach
725
- this.throwIfStale(gen)
726
- if (driver.sessionBased) {
727
- // Unsubscribe BEFORE our own stop() so its session-end detach echo
728
- // cannot be mistaken for a real one and abort the ceremony we are
729
- // about to legitimately continue. openTapSession resubscribes this
730
- // SAME box fresh for the reopened session.
731
- this.unsubscribeKeyEvents(session)
732
- try {
733
- driver.stop()
734
- } catch {
735
- /* best-effort */
736
- }
737
- await this.openTapSession(driver, meta, pin, session, gen)
738
- }
739
- // loop: retry the same ECDH
740
- }
741
- }
742
- // Software from here on. The seed is the one secret that CAN be wiped, so
743
- // it is wiped the instant the HD node exists — on the throwing path too.
744
- const seed = unsealVaultKey(seal, secret)
745
- try {
746
- return HD.fromSeed(seed)
747
- } finally {
748
- seed.fill(0)
749
- }
750
- }
751
-
752
- /**
753
- * Unwrap the vault key and wrap it in the armed handle.
754
- *
755
- * `hd` is read through a getter that refuses once released: whichever path
756
- * ends the session (the caller finishing normally, or the controller's own
757
- * cancel/detach/timeout relock) makes every later READ throw
758
- * `key-removed-mid-op` instead of handing back a key the ceremony considers
759
- * dead. It is only a read barrier — a reference the caller already took is
760
- * beyond its reach, which is why VaultKeyHandle's docblock tells callers to
761
- * read `hd` at each point of use and never to store it.
762
- *
763
- * `release()` drops the only reference this module keeps to the node, so the
764
- * runtime can collect it. It CANNOT zeroize it: @bsv/sdk's HD exposes no wipe
765
- * API and Hermes may have copied the internals anyway (the K1-only design's
766
- * accepted residual risk #1). The 64-byte seed the node came from is wiped in
767
- * unwrapVaultKey; the node itself is only dereferenced.
759
+ * `released` is checked on every resumption point: whichever path ends the
760
+ * session (the caller finishing normally, or the controller's own
761
+ * cancel/detach/timeout relock) makes every later sign() throw
762
+ * `key-removed-mid-op` instead of driving a card the ceremony considers
763
+ * gone. A sign() already parked inside driver.signEcdsa when that happens
764
+ * throws the same on return, whatever the card answered.
768
765
  *
769
766
  * release() is identity-checked against the controller's `activeHandle`:
770
767
  * whichever call reaches it first does the real cleanup — the transport
771
- * session AND, only if this is still the current handle, the shared arm
772
- * timer, activeHandle, and phase. That makes a handle released late (after a
773
- * successor has already armed) a no-op against the CONTROLLER's own state and
774
- * against the SUBSCRIPTION (each attempt owns its own KeyEventSession box, so
775
- * unsubscribing here can never touch a successor's listener — see
776
- * KeyEventSession).
777
- *
778
- * That scoping does NOT extend to the native transport itself:
779
- * `driver.stop()` (via the real adapter, `driver.ts`'s `adaptNative.stop`)
780
- * calls `native.stopDiscovery()` + `native.clearKeyListener()`, which are
781
- * process-wide — there is exactly one NFC/USB discovery session at the
782
- * native layer, not one per KeyEventSession box. A late release() on a
783
- * session-based transport therefore CAN silence a successor's still-open
784
- * native session even though it cannot touch the successor's JS-level
785
- * subscription or controller state. In practice this window is narrow (the
786
- * successor's own subsequent driver.start() reopens discovery), but it is
787
- * a real gap, not a theoretical one — do not read the subscription-safety
788
- * property above as a transport-safety one too.
768
+ * session AND, only if this is still the current signer, the shared arm
769
+ * timer, activeHandle, phase and progress. `requestSigner` prevents any
770
+ * successor from starting before this handle releases, which also protects
771
+ * the native process-wide discovery/session object from a late stop().
789
772
  */
790
- private async makeHandle(
773
+ private makeHandle(
791
774
  driver: VaultDriver,
792
- meta: CeremonyMeta,
793
- seal: SealedBlob,
775
+ key: CeremonyKey,
794
776
  pin: string,
795
777
  session: KeyEventSession,
796
- gen: number
797
- ): Promise<VaultKeyHandle> {
798
- let hd: HD | undefined = await this.unwrapVaultKey(driver, meta, seal, pin, session, gen)
778
+ gen: number,
779
+ releaseLease: () => void
780
+ ): VaultSigner {
781
+ const inputsPerTap = this.deps.inputsPerTap ?? CeremonyController.DEFAULT_INPUTS_PER_TAP
799
782
  let released = false
800
- const handle: VaultKeyHandle = {
801
- get hd(): HD {
802
- if (released || !hd) {
803
- throw new VaultError('key-removed-mid-op', 'Vault key handle already released')
783
+ let signing = false
784
+ /** Successful signatures in the CURRENT transport session. Only consulted
785
+ * on session-based transports. */
786
+ let signedThisSession = 0
787
+ const deadSigner = (): VaultError => new VaultError('key-removed-mid-op', 'Vault signer already released')
788
+
789
+ /** Close the dead or exhausted session and open a fresh one on the same
790
+ * box, re-checking serial and PIN. */
791
+ const reopen = async (): Promise<void> => {
792
+ // Unsubscribe BEFORE our own stop() so its session-end detach echo
793
+ // cannot be mistaken for a real one and relock the signer we are about
794
+ // to legitimately continue. openTapSession resubscribes this SAME box
795
+ // fresh for the reopened session.
796
+ this.unsubscribeKeyEvents(session)
797
+ try {
798
+ driver.stop()
799
+ } catch {
800
+ /* best-effort */
801
+ }
802
+ await this.openTapSession(driver, key, pin, session, gen)
803
+ signedThisSession = 0
804
+ }
805
+
806
+ const signer: VaultSigner = {
807
+ serial: key.serial,
808
+ pubkey: key.pubkey,
809
+ sign: async (digestHex, progress) => {
810
+ if (released) throw deadSigner()
811
+ if (signing) throw new VaultError('ceremony-active', 'A Vault signature is already in progress')
812
+ signing = true
813
+ try {
814
+ // Stale-but-unreleased: a successor ceremony has armed since this
815
+ // signer was handed out.
816
+ // Refuse before painting a phase, restarting the retention timer or
817
+ // installing a retry/attach waiter over the successor's session. No
818
+ // caller can produce this today (transfers releases in a finally);
819
+ // hardening only.
820
+ if (this.activeHandle !== signer) throw deadSigner()
821
+ if (progress) this.noteSigning(progress)
822
+ // Batch boundary (spec §4.2 step 6). The progress published just above
823
+ // is what the sheet shows under 'waiting-for-key' ("batch b of n").
824
+ if (driver.sessionBased && signedThisSession >= inputsPerTap) {
825
+ await reopen()
826
+ if (released) throw deadSigner()
827
+ }
828
+ for (;;) {
829
+ if (released) throw deadSigner()
830
+ this.set({ phase: 'awaiting-touch', error: undefined })
831
+ try {
832
+ const { signature } = await driver.signEcdsa(key.serial, pin, digestHex)
833
+ // signEcdsa is a native call cancel() cannot interrupt: if the
834
+ // signer was released while we were parked, the answer is not ours
835
+ // to hand out.
836
+ if (released) throw deadSigner()
837
+ signedThisSession++
838
+ return Utils.toArray(signature, 'hex')
839
+ } catch (e) {
840
+ if (released) throw deadSigner()
841
+ const err = e instanceof VaultError ? e : new VaultError('nfc-lost')
842
+ if (!CeremonyController.RETRYABLE_TAP_ERRORS.has(err.code)) {
843
+ // A hard failure is not retryable — paint it so the sheet can
844
+ // explain, and rethrow so the caller aborts and releases;
845
+ // release() then takes the phase back to idle.
846
+ this.set({ phase: 'error', error: { code: err.code, retriesLeft: err.retriesLeft } })
847
+ throw err
848
+ }
849
+ // Park on the Retry prompt. retryWaiter resolves on retry(); it
850
+ // rejects on cancel() (user-cancelled), on notifyKeyDetached or the
851
+ // retention ceiling (key-removed-mid-op) — each of which has
852
+ // already released this signer by the time the rejection lands.
853
+ this.set({ phase: 'error', error: { code: err.code } })
854
+ this.retryWaiter = defer<void>()
855
+ await this.retryWaiter.promise
856
+ if (released) throw deadSigner()
857
+ if (driver.sessionBased) await reopen()
858
+ // loop: sign the SAME digest again
859
+ }
860
+ }
861
+ } finally {
862
+ signing = false
863
+ // release() may have cancelled while a native signature/reopen was
864
+ // still in flight. Keep the global lease until that continuation has
865
+ // observed cancellation and completely unwound.
866
+ if (released) releaseLease()
804
867
  }
805
- return hd
806
868
  },
807
869
  release: () => {
808
870
  if (released) return
809
871
  released = true
810
- // Drop the only reference this module holds, so the node becomes
811
- // collectable. It cannot be wiped in place — see this method's doc.
812
- hd = undefined
813
- // Session-based transports (iOS NFC) held the scan session open for the
814
- // caller's whole operation; this is what finally dismisses the sheet.
872
+ // Session-based native transports hold discovery for the caller's whole
873
+ // signing loop; this closes it and also dismisses the iOS sheet.
815
874
  // Unsubscribe first so our own stop() cannot echo back as a detach and
816
- // re-enter this relock path. Scoped to THIS handle's own session box —
875
+ // re-enter this relock path. Scoped to THIS signer's own session box —
817
876
  // see KeyEventSession — so a late release() here can never touch a
818
877
  // successor ceremony's subscription or session.
819
878
  if (driver.sessionBased) {
@@ -824,28 +883,37 @@ export class CeremonyController {
824
883
  /* stop is best-effort */
825
884
  }
826
885
  }
827
- // Only touch controller-wide state if this is still THE active handle:
828
- // a stale/superseded handle's release() must not clobber a successor
829
- // ceremony's armed state, timer, or phase.
830
- if (this.activeHandle === handle) {
886
+ // Only touch controller-wide state if this is still THE active signer:
887
+ // a stale/superseded signer's release() must not clobber a successor
888
+ // ceremony's armed state, timer, phase or progress.
889
+ if (this.activeHandle === signer) {
831
890
  this.clearArmTimer()
832
891
  this.activeHandle = undefined
833
- this.set({ phase: 'idle' })
892
+ this.set({ phase: 'idle', progress: undefined })
834
893
  }
835
894
  // Bound the PIN's exposure now that the session is closed for good —
836
895
  // strings can't be wiped, but there is no reason to keep pinning the
837
896
  // value in the module singleton once release() has run.
838
897
  pin = ''
898
+ if (!signing) releaseLease()
839
899
  }
840
900
  }
841
- return handle
901
+ return signer
902
+ }
903
+
904
+ /** Publish the signing loop's position and refresh the retention window —
905
+ * the sign()-side twin of noteProgress, without a phase change (sign()
906
+ * paints 'awaiting-touch' itself a moment later). */
907
+ private noteSigning(p: { index: number; total: number }): void {
908
+ this.set({ progress: { signed: p.index, total: p.total }, armedUntil: this.startArmTimer() })
842
909
  }
843
910
 
844
911
  private arm(): void {
845
912
  // Anchor the absolute ceiling BEFORE the first startArmTimer, which clamps
846
- // against it.
913
+ // against it. `progress: undefined` is deliberate: the key is present in
914
+ // every armed state (the pinned key set), empty until the loop reports.
847
915
  this.armedAt = now()
848
- this.set({ phase: 'armed', armedUntil: this.startArmTimer(), error: undefined })
916
+ this.set({ phase: 'armed', armedUntil: this.startArmTimer(), error: undefined, progress: undefined })
849
917
  }
850
918
 
851
919
  /** The instant past which this session may not live, whatever it reports.
@@ -924,10 +992,10 @@ export class CeremonyController {
924
992
  * The guard every step of an arm attempt resumes behind.
925
993
  *
926
994
  * `cancelled` alone is not enough, and this is the whole subtlety of the
927
- * resurrection class: cancel() sets it, but the requestKey() that follows
995
+ * resurrection class: cancel() sets it, but the requestSigner() that follows
928
996
  * resets it to false for the NEW attempt. An attempt parked in a native call
929
- * that cancel() cannot interrupt — `driver.ecdh`, `driver.verifyPin`,
930
- * `driver.getKeyInfo` — therefore comes back to a flag that reads clean, and
997
+ * that cancel() cannot interrupt — `driver.verifyPin`, `driver.getKeyInfo`
998
+ * — therefore comes back to a flag that reads clean, and
931
999
  * would carry on painting phases, installing waiters, and talking to the card
932
1000
  * on behalf of a ceremony that no longer exists. Only the generation can tell
933
1001
  * it apart, so every resumption point in the arm flow checks BOTH.
@@ -944,11 +1012,11 @@ export class CeremonyController {
944
1012
  this.throwIfCancelled()
945
1013
  }
946
1014
 
947
- private resolveAll(handle: VaultKeyHandle): void {
1015
+ private resolveAll(signer: VaultSigner): void {
948
1016
  const ws = this.waiters
949
1017
  this.waiters = []
950
1018
  this.rejecters = []
951
- ws.forEach(w => w(handle))
1019
+ ws.forEach(w => w(signer))
952
1020
  }
953
1021
 
954
1022
  private failAll(e: unknown): void {