@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,972 @@
1
+ /**
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.
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.
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).
28
+ *
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.
36
+ *
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.
41
+ *
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.
56
+ *
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.
61
+ */
62
+ import { HD } from '@bsv/sdk'
63
+ import { VaultDriver } from './driver'
64
+ import { unsealVaultKey } from './sealing'
65
+ import { SealedBlob, VaultError, VaultErrorCode } from './types'
66
+
67
+ export type CeremonyPhase =
68
+ | 'idle'
69
+ | 'waiting-for-key'
70
+ | 'connecting'
71
+ | 'pin-entry'
72
+ | 'awaiting-touch'
73
+ | 'preparing'
74
+ | 'broadcasting'
75
+ | 'armed'
76
+ | 'error'
77
+
78
+ /**
79
+ * Work happening AFTER the key is armed, reported by the spend path so the
80
+ * sheet can show activity instead of a frozen screen.
81
+ *
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').
85
+ */
86
+ export type VaultProgress = { phase: 'preparing' } | { phase: 'broadcasting' }
87
+
88
+ /**
89
+ * Everything the ceremony publishes to React (see context/VaultContext.tsx).
90
+ *
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.
96
+ */
97
+ export interface CeremonyState {
98
+ phase: CeremonyPhase
99
+ reason?: string
100
+ error?: { code: VaultErrorCode; retriesLeft?: number }
101
+ armedUntil?: number
102
+ }
103
+
104
+ /**
105
+ * A briefly-held, unwrapped vault key.
106
+ *
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.
111
+ *
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.
126
+ */
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. */
131
+ release(): void
132
+ }
133
+
134
+ interface CeremonyMeta {
135
+ slot: number
136
+ yubiSerial: string
137
+ }
138
+
139
+ interface CeremonyStoreView {
140
+ getMeta(): Promise<CeremonyMeta | null>
141
+ getSeal(): Promise<SealedBlob | null>
142
+ }
143
+
144
+ interface Deferred<T> {
145
+ promise: Promise<T>
146
+ resolve: (v: T) => void
147
+ reject: (e: unknown) => void
148
+ }
149
+
150
+ function defer<T>(): Deferred<T> {
151
+ let resolve!: (v: T) => void
152
+ let reject!: (e: unknown) => void
153
+ const promise = new Promise<T>((res, rej) => {
154
+ resolve = res
155
+ reject = rej
156
+ })
157
+ return { promise, resolve, reject }
158
+ }
159
+
160
+ /**
161
+ * A single arm attempt's driver-event subscription, boxed so each attempt
162
+ * owns its OWN unsubscribe token instead of sharing one controller-wide
163
+ * field. This is load-bearing, not tidiness: with a single shared field, a
164
+ * handle released late (after a successor ceremony has already resubscribed
165
+ * for its own arm) would unsubscribe the SUCCESSOR's listener and stop the
166
+ * SUCCESSOR's session — the successor's own openTapSession would then await
167
+ * an attachWaiter nothing can ever resolve. A per-attempt box makes a stale
168
+ * release() structurally unable to touch a later attempt's subscription.
169
+ */
170
+ interface KeyEventSession {
171
+ off?: () => void
172
+ }
173
+
174
+ export class CeremonyController {
175
+ state: CeremonyState = { phase: 'idle' }
176
+
177
+ onRelock?: (why: 'timeout' | 'detached' | 'manual') => void
178
+ onArmed?: (handle: VaultKeyHandle) => void
179
+
180
+ private subscribers = new Set<(s: CeremonyState) => void>()
181
+ private waiters: ((h: VaultKeyHandle) => void)[] = []
182
+ private rejecters: ((e: unknown) => void)[] = []
183
+ private running = false
184
+ private reason = ''
185
+
186
+ /** Monotonic id of the newest arm attempt. `running` alone cannot tell an
187
+ * attempt that it has been replaced: cancel() sets running=false while the
188
+ * 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. */
193
+ private generation = 0
194
+
195
+ /** The handle for the currently-armed session, if any. Set once arming
196
+ * succeeds. Cleared by VaultKeyHandle.release() itself (identity-checked
197
+ * against this field — see makeHandle) rather than by whoever calls
198
+ * release(), so this is accurate whether release() was invoked by the caller
199
+ * finishing normally, or by cancel()/notifyKeyDetached()/the retention timer
200
+ * 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
204
+
205
+ private pinWaiter?: Deferred<string>
206
+ private queuedPin?: string
207
+ private retryWaiter?: Deferred<void>
208
+ private attachWaiter?: Deferred<void>
209
+ private cancelled = false
210
+ private armTimer?: ReturnType<typeof setTimeout>
211
+ /** When the current session armed. The anchor for the absolute ceiling — see
212
+ * ARM_MAX_MULTIPLE — so a stream of progress notes cannot renew the retention
213
+ * window forever. */
214
+ private armedAt = 0
215
+
216
+ /** Grace period given to an operation that is still reporting progress when
217
+ * the retention window elapses, before the timeout is enforced regardless of
218
+ * phase. See checkArmTimeout. */
219
+ private static readonly ARM_GRACE_MS = 5_000
220
+
221
+ /** Hard ceiling on a session's life, as a multiple of the retention window.
222
+ * 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. */
228
+ private static readonly ARM_MAX_MULTIPLE = 3
229
+
230
+ /** Deadline for a session-based transport's waiting-for-key. CoreNFC caps a
231
+ * 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. */
237
+ private static readonly DEFAULT_ATTACH_TIMEOUT_MS = 65_000
238
+
239
+ constructor(
240
+ private deps: {
241
+ getDriver: () => VaultDriver | null
242
+ store: CeremonyStoreView
243
+ retentionMs: number
244
+ /** Test seam for the waiting-for-key watchdog (session-based only). */
245
+ attachTimeoutMs?: number
246
+ }
247
+ ) {}
248
+
249
+ subscribe(cb: (s: CeremonyState) => void): () => void {
250
+ this.subscribers.add(cb)
251
+ cb(this.state)
252
+ return () => this.subscribers.delete(cb)
253
+ }
254
+
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) => {
259
+ this.waiters.push(resolve)
260
+ this.rejecters.push(reject)
261
+ if (this.running) return // join the in-flight ceremony
262
+ this.reason = reason
263
+ this.cancelled = false
264
+ this.running = true
265
+ void this.run()
266
+ })
267
+ }
268
+
269
+ /**
270
+ * Report post-arm progress from the spend path.
271
+ *
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.
276
+ *
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.
282
+ *
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.
287
+ */
288
+ noteProgress(p: VaultProgress): void {
289
+ if (!this.activeHandle || this.running) return
290
+ this.set({ phase: p.phase, armedUntil: this.startArmTimer(), error: undefined })
291
+ }
292
+
293
+ submitPin(pin: string): void {
294
+ if (this.pinWaiter) {
295
+ const w = this.pinWaiter
296
+ this.pinWaiter = undefined
297
+ w.resolve(pin)
298
+ } else {
299
+ this.queuedPin = pin
300
+ }
301
+ }
302
+
303
+ retry(): void {
304
+ this.retryWaiter?.resolve()
305
+ this.retryWaiter = undefined
306
+ }
307
+
308
+ /** Give up. Aborts an in-flight arm attempt (rejecting every waiter with
309
+ * user-cancelled), and — separately — releases an already-armed session,
310
+ * since cancelling out of a mid-withdrawal prompt must not leave a key live
311
+ * in memory behind a session the UI just dismissed. release() itself does the
312
+ * activeHandle/timer/phase cleanup (identity checked), so this only needs to
313
+ * trigger it. */
314
+ cancel(): void {
315
+ this.cancelled = true
316
+ const err = new VaultError('user-cancelled')
317
+ this.pinWaiter?.reject(err)
318
+ this.retryWaiter?.reject(err)
319
+ this.attachWaiter?.reject(err)
320
+ if (this.running) {
321
+ this.failAll(err)
322
+ this.running = false
323
+ this.set({ phase: 'idle' })
324
+ }
325
+ if (this.activeHandle) {
326
+ this.activeHandle.release()
327
+ this.onRelock?.('manual')
328
+ }
329
+ }
330
+
331
+ /** A key detached. Aborts an in-flight arm attempt; releases an armed
332
+ * session, since the hardware that authorized holding this key is gone.
333
+ * release() itself does the activeHandle/timer/phase cleanup. */
334
+ notifyKeyDetached(): void {
335
+ if (this.activeHandle) {
336
+ const err = new VaultError('key-removed-mid-op')
337
+ this.retryWaiter?.reject(err)
338
+ this.attachWaiter?.reject(err)
339
+ this.activeHandle.release()
340
+ this.onRelock?.('detached')
341
+ return
342
+ }
343
+ if (this.running) {
344
+ const err = new VaultError('key-removed-mid-op')
345
+ this.pinWaiter?.reject(err)
346
+ this.retryWaiter?.reject(err)
347
+ this.attachWaiter?.reject(err)
348
+ }
349
+ }
350
+
351
+ /** A key attached — resolves a waiting waiting-for-key phase. */
352
+ notifyKeyAttached(): void {
353
+ this.attachWaiter?.resolve()
354
+ this.attachWaiter = undefined
355
+ }
356
+
357
+ /** The NFC session died before any key connected (system sheet cancelled,
358
+ * 60 s CoreNFC timeout, or a session that failed to present at all). Only
359
+ * meaningful while something is parked on waiting-for-key: neither attach
360
+ * nor detach fits — a detach here would misreport it as key-removed-mid-op
361
+ * on a key that was never there. */
362
+ notifySessionFailed(code: 'user-cancelled' | 'no-key' = 'no-key'): void {
363
+ this.attachWaiter?.reject(new VaultError(code))
364
+ this.attachWaiter = undefined
365
+ }
366
+
367
+ /**
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.
375
+ */
376
+ private subscribeKeyEvents(driver: VaultDriver, session: KeyEventSession): void {
377
+ session.off?.()
378
+ session.off = driver.onKeyEvent(e => {
379
+ if (e.type === 'attached') this.notifyKeyAttached()
380
+ else if (e.type === 'session-failed') this.notifySessionFailed(e.code)
381
+ else this.notifyKeyDetached()
382
+ })
383
+ }
384
+
385
+ private unsubscribeKeyEvents(session: KeyEventSession): void {
386
+ session.off?.()
387
+ session.off = undefined
388
+ }
389
+
390
+ private async run(): Promise<void> {
391
+ // This attempt's identity for the rest of its life — see `generation`.
392
+ const gen = ++this.generation
393
+ const driver = this.deps.getDriver()
394
+ if (!driver) {
395
+ this.failAll(new VaultError('driver-unavailable'))
396
+ this.running = false
397
+ return
398
+ }
399
+ // This attempt's own driver-event subscription box: a key connecting (an
400
+ // NFC tap / a USB plug) resolves waiting-for-key; a key dropping mid-flow
401
+ // aborts. Self-contained so it works whether or not WalletContext also
402
+ // watches for persistent relock. Boxed per-attempt — see KeyEventSession.
403
+ const session: KeyEventSession = {}
404
+ this.subscribeKeyEvents(driver, session)
405
+ // Attempt-local: whether THIS run() reached a successful arm. Deliberately
406
+ // NOT this.activeHandle, which is controller-wide — see the finally guard
407
+ // below for why that distinction is load-bearing.
408
+ let armed = false
409
+ // Set when this attempt discovers it has been superseded: it has already
410
+ // torn its own session down, so the finally must not do it twice.
411
+ let superseded = false
412
+ 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)
427
+ this.throwIfCancelled()
428
+
429
+ // 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.
437
+ if (gen !== this.generation) {
438
+ superseded = true
439
+ // Drop THIS attempt's listener box first (release() only unsubscribes
440
+ // on a session-based transport, and the post-arm unsubscribe below is
441
+ // never reached from here — without this a cancelled-and-replaced
442
+ // 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.
446
+ this.unsubscribeKeyEvents(session)
447
+ handle.release()
448
+ return
449
+ }
450
+
451
+ this.activeHandle = handle
452
+ armed = true
453
+ this.arm()
454
+ this.resolveAll(handle)
455
+ this.onArmed?.(handle)
456
+
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.
460
+ if (!driver.sessionBased) this.unsubscribeKeyEvents(session)
461
+ } catch (e) {
462
+ // Anything that is not a VaultError gets relabelled 'driver-unavailable',
463
+ // which renders as "YubiKey support is unavailable on this device" — so
464
+ // the original message is carried across as the detail rather than being
465
+ // dropped, otherwise an unrelated failure is indistinguishable from a
466
+ // genuinely absent driver.
467
+ const err = e instanceof VaultError ? e : new VaultError('driver-unavailable', String(e))
468
+ // Same generation guard as the success path, for the same reason: a
469
+ // superseded attempt's failure is not the CURRENT attempt's failure, and
470
+ // must not reject the successor's waiters or paint its phase. Its own
471
+ // waiters were already failed by the cancel() that superseded it, so
472
+ // there is nobody left to tell. The finally still closes its session.
473
+ if (gen !== this.generation) return
474
+ if (err.code === 'user-cancelled') {
475
+ this.set({ phase: 'idle' })
476
+ } else {
477
+ this.set({ phase: 'error', error: { code: err.code, retriesLeft: err.retriesLeft } })
478
+ }
479
+ this.failAll(err)
480
+ } finally {
481
+ // Only the CURRENT attempt owns `running`. A superseded attempt clearing
482
+ // 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.
485
+ if (gen === this.generation) this.running = false
486
+ // `armed` (this attempt's own outcome), NOT this.activeHandle (whoever
487
+ // the CONTROLLER currently considers active): an unreleased predecessor
488
+ // ceremony leaves this.activeHandle truthy for the whole time this
489
+ // attempt runs, which would otherwise make a FAILED successor's finally
490
+ // wrongly conclude "some handle must already own this session/
491
+ // subscription" and skip closing its own — the predecessor's activeHandle
492
+ // has nothing to do with whether this attempt itself succeeded.
493
+ if (!armed && !superseded) {
494
+ // Arming never completed: no handle exists to own the subscription
495
+ // or the session, so close both now — nothing else ever will.
496
+ // (A superseded attempt DID build a handle and released it above,
497
+ // which already did exactly this teardown — don't repeat it.)
498
+ // Unsubscribe BEFORE any stop so a session-end detach echo cannot
499
+ // relock a session that was already dead.
500
+ this.unsubscribeKeyEvents(session)
501
+ if (driver.sessionBased) {
502
+ try {
503
+ driver.stop()
504
+ } catch {
505
+ /* stop is best-effort */
506
+ }
507
+ }
508
+ }
509
+ }
510
+ }
511
+
512
+ private async safeKeyInfo(driver: VaultDriver) {
513
+ try {
514
+ return await driver.getKeyInfo()
515
+ } catch {
516
+ return null
517
+ }
518
+ }
519
+
520
+ /** Persistent reader (Android USB): key present, PIN entry and token ops
521
+ * interleave, so a wrong PIN is retried in place. */
522
+ private async armViaReader(
523
+ driver: VaultDriver,
524
+ meta: CeremonyMeta,
525
+ seal: SealedBlob,
526
+ session: KeyEventSession,
527
+ gen: number
528
+ ): Promise<VaultKeyHandle> {
529
+ this.throwIfStale(gen)
530
+ this.set({ phase: 'connecting' })
531
+ let info = await this.safeKeyInfo(driver)
532
+ if (!info) {
533
+ this.set({ phase: 'waiting-for-key' })
534
+ const waiter = (this.attachWaiter = defer<void>())
535
+ driver.start()
536
+ await waiter.promise
537
+ this.throwIfStale(gen)
538
+ this.set({ phase: 'connecting' })
539
+ info = await this.safeKeyInfo(driver)
540
+ }
541
+ if (!info) throw new VaultError('no-key')
542
+ if (info.serial !== meta.yubiSerial) {
543
+ throw new VaultError('serial-mismatch', `Expected key ${meta.yubiSerial}`)
544
+ }
545
+ const pin = await this.collectPin(driver, gen)
546
+ return this.makeHandle(driver, meta, seal, pin, session, gen)
547
+ }
548
+
549
+ /** 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
551
+ * 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. */
555
+ private static readonly RETRYABLE_TAP_ERRORS = new Set(['touch-timeout', 'nfc-lost', 'key-removed-mid-op'])
556
+
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. */
561
+ private async armViaTap(
562
+ driver: VaultDriver,
563
+ meta: CeremonyMeta,
564
+ seal: SealedBlob,
565
+ session: KeyEventSession,
566
+ gen: number
567
+ ): Promise<VaultKeyHandle> {
568
+ 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)
571
+ }
572
+
573
+ /** 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.
579
+ * (Re)subscribes `session` every time: the very first call replaces run()'s
580
+ * top-level subscription on the SAME box (harmless — nothing was pending on
581
+ * it yet), and every reopen needs a fresh one since the caller unsubscribed
582
+ * this same box around its matching driver.stop(). */
583
+ private async openTapSession(
584
+ driver: VaultDriver,
585
+ meta: CeremonyMeta,
586
+ pin: string,
587
+ session: KeyEventSession,
588
+ gen: number
589
+ ): Promise<void> {
590
+ this.throwIfStale(gen)
591
+ this.subscribeKeyEvents(driver, session)
592
+ this.set({ phase: 'waiting-for-key' })
593
+ const waiter = (this.attachWaiter = defer<void>())
594
+ driver.start()
595
+ // Watchdog: a session-based transport that reports NOTHING by the deadline
596
+ // is dead, and its death was swallowed below us (see
597
+ // DEFAULT_ATTACH_TIMEOUT_MS). Identity-checked against attachWaiter so a
598
+ // late firing can never touch a successor ceremony's waiter.
599
+ const attachDeadline = setTimeout(() => {
600
+ if (this.attachWaiter === waiter) {
601
+ this.attachWaiter = undefined
602
+ waiter.reject(new VaultError('no-key', 'No key connected before the NFC session deadline'))
603
+ }
604
+ }, this.deps.attachTimeoutMs ?? CeremonyController.DEFAULT_ATTACH_TIMEOUT_MS)
605
+ ;(attachDeadline as { unref?: () => void }).unref?.()
606
+ try {
607
+ await waiter.promise
608
+ } finally {
609
+ clearTimeout(attachDeadline)
610
+ }
611
+ this.throwIfStale(gen)
612
+ this.set({ phase: 'connecting' })
613
+ const info = await driver.getKeyInfo()
614
+ // getKeyInfo is a native call cancel() cannot interrupt.
615
+ 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)
620
+ this.throwIfStale(gen)
621
+ if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
622
+ }
623
+
624
+ /** Collect a PIN value from the UI only (no token verify) — used by the NFC
625
+ * path, which must gather the PIN before the tap. */
626
+ private async collectPinValue(gen: number): Promise<string> {
627
+ this.throwIfStale(gen)
628
+ this.set({ phase: 'pin-entry' })
629
+ if (this.queuedPin !== undefined) {
630
+ const p = this.queuedPin
631
+ this.queuedPin = undefined
632
+ return p
633
+ }
634
+ this.pinWaiter = defer<string>()
635
+ return this.pinWaiter.promise
636
+ }
637
+
638
+ private async collectPin(driver: VaultDriver, gen: number): Promise<string> {
639
+ for (;;) {
640
+ this.throwIfStale(gen)
641
+ this.set({ phase: 'pin-entry', error: this.state.error })
642
+ let pin: string
643
+ if (this.queuedPin !== undefined) {
644
+ pin = this.queuedPin
645
+ this.queuedPin = undefined
646
+ } else {
647
+ this.pinWaiter = defer<string>()
648
+ pin = await this.pinWaiter.promise
649
+ }
650
+ const res = await driver.verifyPin(pin)
651
+ // verifyPin is a native call cancel() cannot interrupt: without this, an
652
+ // attempt superseded while parked in it would resume and repaint the
653
+ // SUCCESSOR's phase back to 'pin-entry' over its armed session, then walk
654
+ // on to spend a second, unwanted touch on the card.
655
+ this.throwIfStale(gen)
656
+ if (res.ok) {
657
+ this.set({ phase: 'pin-entry', error: undefined })
658
+ return pin
659
+ }
660
+ this.set({ phase: 'pin-entry', error: { code: 'pin-invalid', retriesLeft: res.retriesLeft } })
661
+ }
662
+ }
663
+
664
+ /**
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.
667
+ *
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.
673
+ *
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.
678
+ *
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.
768
+ *
769
+ * release() is identity-checked against the controller's `activeHandle`:
770
+ * 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.
789
+ */
790
+ private async makeHandle(
791
+ driver: VaultDriver,
792
+ meta: CeremonyMeta,
793
+ seal: SealedBlob,
794
+ pin: string,
795
+ session: KeyEventSession,
796
+ gen: number
797
+ ): Promise<VaultKeyHandle> {
798
+ let hd: HD | undefined = await this.unwrapVaultKey(driver, meta, seal, pin, session, gen)
799
+ 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')
804
+ }
805
+ return hd
806
+ },
807
+ release: () => {
808
+ if (released) return
809
+ 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.
815
+ // 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 —
817
+ // see KeyEventSession — so a late release() here can never touch a
818
+ // successor ceremony's subscription or session.
819
+ if (driver.sessionBased) {
820
+ this.unsubscribeKeyEvents(session)
821
+ try {
822
+ driver.stop()
823
+ } catch {
824
+ /* stop is best-effort */
825
+ }
826
+ }
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) {
831
+ this.clearArmTimer()
832
+ this.activeHandle = undefined
833
+ this.set({ phase: 'idle' })
834
+ }
835
+ // Bound the PIN's exposure now that the session is closed for good —
836
+ // strings can't be wiped, but there is no reason to keep pinning the
837
+ // value in the module singleton once release() has run.
838
+ pin = ''
839
+ }
840
+ }
841
+ return handle
842
+ }
843
+
844
+ private arm(): void {
845
+ // Anchor the absolute ceiling BEFORE the first startArmTimer, which clamps
846
+ // against it.
847
+ this.armedAt = now()
848
+ this.set({ phase: 'armed', armedUntil: this.startArmTimer(), error: undefined })
849
+ }
850
+
851
+ /** The instant past which this session may not live, whatever it reports.
852
+ * See ARM_MAX_MULTIPLE. */
853
+ private armCeiling(): number {
854
+ return this.armedAt + CeremonyController.ARM_MAX_MULTIPLE * this.deps.retentionMs
855
+ }
856
+
857
+ /** (Re)start the retention countdown and report the new deadline. Shared by
858
+ * the initial arm and every progress note that refreshes it. The deadline is
859
+ * clamped to the absolute ceiling, so a refresh can only ever move it
860
+ * forward WITHIN the session's maximum life, never extend that maximum. */
861
+ private startArmTimer(): number {
862
+ this.clearArmTimer()
863
+ const t = now()
864
+ const deadline = Math.min(t + this.deps.retentionMs, this.armCeiling())
865
+ this.armTimer = setTimeout(() => this.checkArmTimeout(), Math.max(0, deadline - t))
866
+ // Don't let a pending relock timer keep a Node/Jest event loop alive; RN
867
+ // timers have no unref, so guard for it.
868
+ ;(this.armTimer as { unref?: () => void }).unref?.()
869
+ return deadline
870
+ }
871
+
872
+ /**
873
+ * Fires when the retention window elapses. If nothing is in flight
874
+ * (phase === 'armed'), relock immediately. If the spend path is mid-operation
875
+ * the phase won't be 'armed' at this exact instant ('preparing' /
876
+ * 'broadcasting') — rather than silently giving up forever (a one-shot timer
877
+ * that fires once and never reschedules would leave the vault key resident in
878
+ * memory indefinitely once the timer happens to land mid-operation), give the
879
+ * in-flight operation one short grace window to finish. A further progress
880
+ * note calls startArmTimer, which cancels this and starts a fresh window; if
881
+ * the operation still hasn't reported by the grace deadline, enforce the
882
+ * timeout regardless of phase.
883
+ *
884
+ * The grace is clamped to the absolute ceiling as well. Without that clamp
885
+ * the ceiling would be trivially escapable: each note past it would schedule
886
+ * a fresh 5 s grace, and the two would trade off forever.
887
+ */
888
+ private checkArmTimeout(): void {
889
+ if (!this.activeHandle) return // already released by some other path
890
+ if (this.state.phase !== 'armed') {
891
+ const t = now()
892
+ const graceEnd = Math.min(t + CeremonyController.ARM_GRACE_MS, this.armCeiling())
893
+ if (graceEnd > t) {
894
+ this.armTimer = setTimeout(() => this.enforceArmTimeout(), graceEnd - t)
895
+ ;(this.armTimer as { unref?: () => void }).unref?.()
896
+ return
897
+ }
898
+ // Ceiling already reached — no more grace to give.
899
+ }
900
+ this.enforceArmTimeout()
901
+ }
902
+
903
+ private enforceArmTimeout(): void {
904
+ if (!this.activeHandle) return // already released by some other path
905
+ const err = new VaultError('key-removed-mid-op')
906
+ this.retryWaiter?.reject(err)
907
+ this.attachWaiter?.reject(err)
908
+ this.activeHandle.release()
909
+ this.onRelock?.('timeout')
910
+ }
911
+
912
+ private clearArmTimer(): void {
913
+ if (this.armTimer) {
914
+ clearTimeout(this.armTimer)
915
+ this.armTimer = undefined
916
+ }
917
+ }
918
+
919
+ private throwIfCancelled(): void {
920
+ if (this.cancelled) throw new VaultError('user-cancelled')
921
+ }
922
+
923
+ /**
924
+ * The guard every step of an arm attempt resumes behind.
925
+ *
926
+ * `cancelled` alone is not enough, and this is the whole subtlety of the
927
+ * resurrection class: cancel() sets it, but the requestKey() that follows
928
+ * 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
931
+ * would carry on painting phases, installing waiters, and talking to the card
932
+ * on behalf of a ceremony that no longer exists. Only the generation can tell
933
+ * it apart, so every resumption point in the arm flow checks BOTH.
934
+ *
935
+ * Throwing (rather than returning) is deliberate: it unwinds to run()'s catch,
936
+ * which is generation-guarded and so swallows a superseded attempt's failure
937
+ * without touching the successor's waiters or phase, while its finally still
938
+ * closes this attempt's own session.
939
+ */
940
+ private throwIfStale(gen: number): void {
941
+ if (gen !== this.generation) {
942
+ throw new VaultError('user-cancelled', 'Superseded by a newer ceremony')
943
+ }
944
+ this.throwIfCancelled()
945
+ }
946
+
947
+ private resolveAll(handle: VaultKeyHandle): void {
948
+ const ws = this.waiters
949
+ this.waiters = []
950
+ this.rejecters = []
951
+ ws.forEach(w => w(handle))
952
+ }
953
+
954
+ private failAll(e: unknown): void {
955
+ const rs = this.rejecters
956
+ this.waiters = []
957
+ this.rejecters = []
958
+ rs.forEach(r => r(e))
959
+ }
960
+
961
+ private set(patch: Partial<CeremonyState>): void {
962
+ this.state = { ...this.state, ...patch, reason: this.reason }
963
+ this.subscribers.forEach(cb => cb(this.state))
964
+ }
965
+ }
966
+
967
+ // Wall-clock "now" for the arm timer's deadlines and its absolute ceiling.
968
+ // Kept as one named helper so the module's use of Date.now stays auditable in
969
+ // a single place; here Date.now is fine (RN app + jest).
970
+ function now(): number {
971
+ return Date.now()
972
+ }