@bsv/expo-wallet-toolbox 0.5.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2000 -0
- package/README.md +66 -1
- package/core/amountFormatHelpers.ts +258 -36
- package/core/backup/RemoteSyncReader.ts +133 -24
- package/core/backup/appData.ts +157 -0
- package/core/backup/client.ts +15 -1
- package/core/backup/codec.ts +149 -11
- package/core/backup/constants.ts +30 -1
- package/core/backup/cursor.ts +31 -2
- package/core/backup/push.ts +71 -5
- package/core/backup/restore.ts +104 -16
- package/core/backup/restoreOnImport.ts +94 -30
- package/core/backup/status.ts +13 -8
- package/core/config.tsx +12 -5
- package/core/constants.ts +14 -1
- package/core/contacts/contactActivity.ts +153 -0
- package/core/contacts/contactCache.ts +41 -0
- package/core/contacts/contactsStore.ts +183 -0
- package/core/context/ExchangeRateContext.tsx +34 -27
- package/core/context/LocalStorageProvider.tsx +43 -40
- package/core/context/UserContext.tsx +18 -7
- package/core/context/VaultContext.tsx +49 -2
- package/core/context/WalletConnectionContext.tsx +203 -11
- package/core/context/WalletContext.tsx +685 -171
- package/core/demo/demoAssets.ts +60 -0
- package/core/demo/demoLedger.ts +240 -0
- package/core/demo/demoMandalaRuntime.ts +96 -0
- package/core/demo/demoMode.ts +38 -0
- package/core/demo/demoWallet.ts +25 -0
- package/core/demo/index.ts +26 -0
- package/core/demo/useDemo.ts +59 -0
- package/core/headers/OfflineFirstChaintracks.ts +99 -17
- package/core/headers/headerStore.ts +33 -14
- package/core/headers/syncHeaders.ts +12 -1
- package/core/i18n/translations.tsx +2186 -98
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +314 -0
- package/core/identity/handleRegistry/keyPinStore.ts +70 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +315 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +53 -5
- package/core/localpay/build.ts +225 -24
- package/core/localpay/pending.ts +110 -7
- package/core/localpay/pendingAbortAuthority.ts +95 -0
- package/core/localpay/pendingAborts.ts +266 -26
- package/core/localpay/session.ts +42 -17
- package/core/localpay/settlementAck.ts +10 -1
- package/core/localpay/transport/socket.ts +52 -3
- package/core/localpay/verify.ts +100 -10
- package/core/mandala/abortGuard.ts +96 -20
- package/core/mandala/createRuntime.ts +206 -33
- package/core/mandala/drain.ts +89 -11
- package/core/mandala/inboxPrehold.ts +186 -0
- package/core/mandala/permissionModule.ts +202 -20
- package/core/mandala/settlementStore.ts +24 -2
- package/core/mandala/types.ts +40 -5
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +15 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +15 -1
- package/core/monitor/TaskSendOffline.ts +15 -1
- package/core/net/online.ts +49 -0
- package/core/net/publicDestination.ts +91 -0
- package/core/net/validateArcUrl.ts +22 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/cancelParked.ts +134 -13
- package/core/offline/payerHold.ts +100 -24
- package/core/offline/plan.ts +37 -8
- package/core/pay/beefRepair.ts +6 -2
- package/core/pay/damagedInbox.ts +24 -0
- package/core/pay/rails/address.ts +107 -12
- package/core/pay/rails/handle.ts +117 -22
- package/core/pay/rails/index.ts +45 -7
- package/core/pay/rails/nativeIntent.ts +61 -0
- package/core/pay/receiveHistory.ts +93 -0
- package/core/pay/recordProof.ts +21 -7
- package/core/pay/refreshProofGuard.ts +42 -1
- package/core/pay/watchlist.ts +5 -2
- package/core/peerpay/control.ts +17 -18
- package/core/peerpay/handleResendRequests.ts +58 -4
- package/core/peerpay/outbox.ts +3 -1
- package/core/recovery/backupMaterial.ts +61 -0
- package/core/recovery/createWallet.ts +95 -0
- package/core/recovery/recoverWallet.ts +120 -0
- package/core/recovery/restoreWallet.ts +170 -0
- package/core/recovery/secret.ts +92 -0
- package/core/recovery/shareCollector.ts +71 -0
- package/core/recovery/shareParsing.ts +87 -0
- package/core/recovery/shares.ts +116 -0
- package/core/recovery/useRecoveryDeps.ts +70 -0
- package/core/services/arcTokenStorage.ts +52 -0
- package/core/services/arcadeBroadcastProvider.ts +233 -52
- package/core/services/autoApprovePolicy.ts +105 -0
- package/core/services/callbackToken.ts +19 -0
- package/core/services/capWalletArgs.ts +14 -2
- package/core/services/connectionAuthority.ts +98 -0
- package/core/services/exchangeRate.ts +36 -13
- package/core/services/externalOrigin.ts +16 -2
- package/core/services/secrets/kek.ts +126 -29
- package/core/services/secrets/migration.ts +16 -4
- package/core/services/secrets/store.ts +42 -14
- package/core/services/vault/VaultKeyService.ts +228 -45
- package/core/services/vault/chainRecovery.ts +483 -0
- package/core/services/vault/driver.ts +9 -1
- package/core/services/vault/enrolledSerialRegistry.ts +150 -0
- package/core/services/vault/guard.ts +218 -32
- package/core/services/vault/hardwareLease.ts +19 -0
- package/core/services/vault/metaAuthority.ts +210 -0
- package/core/services/vault/pivReset.ts +64 -23
- package/core/services/vault/r1comb.ts +139 -3
- package/core/services/vault/session.ts +25 -4
- package/core/services/vault/transfers.ts +868 -172
- package/core/services/vault/types.ts +19 -4
- package/core/services/vault/vaultStore.ts +256 -29
- package/core/services/walletArgLimits.ts +45 -2
- package/core/services/walletConnectionValidation.ts +76 -6
- package/core/services/walletServiceConfig.ts +40 -27
- package/core/storage/StorageExpoSQLite.ts +88 -47
- package/core/storage/methods/findSql.ts +24 -2
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +2 -2
- package/core/storage/methods/offlineActions.ts +10 -1
- package/core/storage/methods/processOfflineActions.ts +117 -25
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/schema/createTables.ts +155 -2
- package/core/stores/ConnectionStore.ts +34 -0
- package/core/toolboxConfig.ts +104 -0
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletDbRegistry.ts +63 -0
- package/core/walletMonitor.ts +25 -4
- package/core/walletRepair/releaseStuckReservations.ts +72 -0
- package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
- package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
- package/package.json +7 -7
- package/ui/activityFilter.ts +115 -0
- package/ui/backupShares.ts +26 -169
- package/ui/components/pay/AddressReceive.tsx +13 -6
- package/ui/components/pay/AssetPicker.tsx +30 -9
- package/ui/components/pay/MessageBoxConfig.tsx +16 -0
- package/ui/components/pay/NearbyFlow.tsx +480 -243
- package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
- package/ui/components/pay/RecipientField.tsx +84 -70
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +827 -205
- package/ui/components/ui/AlertCard.tsx +38 -5
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/PermissionSheet.tsx +197 -66
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/vault/EnrollWizard.tsx +61 -13
- package/ui/components/vault/vaultErrorCopy.ts +3 -1
- package/ui/components/wallet/ActivityRow.tsx +227 -123
- package/ui/components/wallet/AmountInput.tsx +26 -8
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
- package/ui/components/wallet/Balance.tsx +42 -23
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
- package/ui/components/wallet/ContactActivityList.tsx +149 -0
- package/ui/components/wallet/ContactSigil.tsx +49 -0
- package/ui/components/wallet/EditPictureSheet.tsx +99 -0
- package/ui/components/wallet/FitAmount.tsx +148 -0
- package/ui/components/wallet/IconPickerSheet.tsx +168 -0
- package/ui/components/wallet/IdentifierRow.tsx +69 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
- package/ui/components/wallet/ProfileButton.tsx +62 -0
- package/ui/components/wallet/UserAvatar.tsx +85 -0
- package/ui/components/wallet/avatarIcons.ts +122 -0
- package/ui/exportTransactions.ts +36 -4
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useExportWalletData.ts +25 -2
- package/ui/hooks/useMandala.ts +18 -1
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/importDatabases.ts +339 -24
- package/ui/index.ts +33 -2
- package/ui/isImageUrl.ts +6 -0
- package/ui/printRecoveryShares.ts +9 -10
- package/ui/recoveryPrompts.ts +91 -0
- package/ui/resolveIdentity.ts +31 -9
- package/ui/screens/ConnectionsScreen.tsx +86 -19
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +256 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PairScreen.tsx +74 -2
- package/ui/screens/PayScreen.tsx +20 -7
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/SettingsScreen.tsx +10 -4
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +100 -5
- package/ui/screens/VaultScreen.tsx +410 -61
- package/ui/screens/VaultTransferScreen.tsx +59 -7
- package/ui/screens/WalletCheckScreen.tsx +17 -6
- package/ui/screens/WalletConfigScreen.tsx +124 -28
- package/ui/screens/WalletHomeScreen.tsx +640 -104
- package/ui/screens/detailActionKeys.ts +55 -0
- package/ui/tokenFormat.ts +44 -4
- package/ui/tokenStatus.ts +21 -0
- package/ui/txStatus.ts +48 -5
- package/core/storage/LocalStorageAdapter.ts +0 -58
|
@@ -7,13 +7,17 @@
|
|
|
7
7
|
* tap — so a dropped session can never leave the enrollment quarantine
|
|
8
8
|
* machinery in a state it was not designed for.
|
|
9
9
|
*
|
|
10
|
-
* SAFETY. A PIV reset destroys the P-256 key in Vault slot 0x82.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
10
|
+
* SAFETY. A PIV reset destroys the P-256 key in Vault slot 0x82. The vault
|
|
11
|
+
* script accepts a signature from ANY ONE of its enrolled keys (1-of-N, not a
|
|
12
|
+
* threshold scheme), so resetting one enrolled key does not by itself lock
|
|
13
|
+
* funds committed to multiple keys — but it permanently removes that key's
|
|
14
|
+
* own ability to satisfy the script, and if the vault currently has only one
|
|
15
|
+
* enrolled key (or an output was locked before other keys were added), that
|
|
16
|
+
* reset destroys the only remaining way to spend those outputs. The
|
|
17
|
+
* enrolled-serial refusal below runs before the card is touched AND again
|
|
18
|
+
* inside the session, and is deliberately not overridable by any caller flag
|
|
19
|
+
* — unlike `replaceOccupiedVaultSlot`, which consents to replacing a slot
|
|
20
|
+
* that is by definition not yet part of the vault.
|
|
17
21
|
*
|
|
18
22
|
* "Enrolled" is read wider than `getMeta` reads it, on purpose:
|
|
19
23
|
*
|
|
@@ -26,15 +30,24 @@
|
|
|
26
30
|
* testnet enrollment wizard sees as unknown, so the refusal set comes from
|
|
27
31
|
* `vaultStore.enrolledSerialsAcrossChains`, not `getMeta`.
|
|
28
32
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
33
|
+
* XQ-014 UPDATE. `vaultStore.enrolledSerialsAcrossChains` still only ever
|
|
34
|
+
* sees ONE wallet identity: a vault belonging to a DIFFERENT identity on this
|
|
35
|
+
* device was genuinely invisible to it, because SecureStore cannot be
|
|
36
|
+
* enumerated across identities. `enrolledSerialRegistry.ts` closes most of
|
|
37
|
+
* that gap: a plain, device-wide, non-secret set of bare serials that EVERY
|
|
38
|
+
* identity's vaultStore writes to when it commits or fully removes an
|
|
39
|
+
* enrolled key, checked below alongside the identity-scoped set and refused
|
|
40
|
+
* exactly as unconditionally. What is left, and cannot be fully resolved
|
|
41
|
+
* without the same cross-identity enumeration SecureStore disallows, is one
|
|
42
|
+
* physical key committed under two different identities' vaults on this
|
|
43
|
+
* device where one identity has since fully removed its own copy — see
|
|
44
|
+
* enrolledSerialRegistry.ts's header. Against THAT narrower residual there is
|
|
45
|
+
* still the one last, purely local signal — a key sitting in slot 0x82 means
|
|
46
|
+
* this card is a vault key for SOME vault — so an occupied slot is refused
|
|
47
|
+
* unless the caller passes `acknowledgeUnrecognizedVaultKey`. That one IS
|
|
48
|
+
* overridable, because a card left over from a vault the user has already
|
|
49
|
+
* abandoned is the whole reason this service exists; neither enrolled-serial
|
|
50
|
+
* refusal above is.
|
|
38
51
|
*
|
|
39
52
|
* That occupancy question goes to `isVaultSlotOccupied`, which both platforms
|
|
40
53
|
* answer from the card (iOS attests the slot; Android reads its metadata) and
|
|
@@ -44,10 +57,24 @@
|
|
|
44
57
|
* reports null for every 0x82 and this refusal would never fire there.
|
|
45
58
|
*/
|
|
46
59
|
import { getVaultDriver } from './driver'
|
|
47
|
-
import {
|
|
60
|
+
import { enrolledSerialRegistry } from './enrolledSerialRegistry'
|
|
61
|
+
import { withKeySession, VaultSessionGuard } from './session'
|
|
48
62
|
import { VaultError } from './types'
|
|
49
63
|
import { isVaultSerial, vaultStore, type VaultScopeToken } from './vaultStore'
|
|
50
64
|
|
|
65
|
+
/**
|
|
66
|
+
* XR-004: mirrors VaultKeyService.ts's assertSessionCurrent — the same
|
|
67
|
+
* wallet/chain scope check this reset already runs before every mutation,
|
|
68
|
+
* plus session.assertCurrent so a timed-out/detached session's continuation
|
|
69
|
+
* (the native reset/discard calls it wraps cannot be cancelled) refuses its
|
|
70
|
+
* next write once a NEWER Vault hardware session has been acquired, instead
|
|
71
|
+
* of racing a retry's.
|
|
72
|
+
*/
|
|
73
|
+
function assertSessionCurrent(session: VaultSessionGuard, scopeToken: VaultScopeToken): void {
|
|
74
|
+
session.assertCurrent()
|
|
75
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
76
|
+
}
|
|
77
|
+
|
|
51
78
|
export type PivResetPhase = 'waiting' | 'resetting'
|
|
52
79
|
|
|
53
80
|
export async function resetPivApplication(args: {
|
|
@@ -87,6 +114,13 @@ export async function resetPivApplication(args: {
|
|
|
87
114
|
// The message IS the serial, matching enrollKey's convention.
|
|
88
115
|
throw new VaultError('key-already-enrolled', args.serial, undefined, { serial: args.serial })
|
|
89
116
|
}
|
|
117
|
+
// XQ-014: the device-wide registry can see a serial committed under a
|
|
118
|
+
// DIFFERENT wallet identity's vault on this device — never overridable
|
|
119
|
+
// by `acknowledgeUnrecognizedVaultKey`, exactly like the identity-scoped
|
|
120
|
+
// check above (see this module's header).
|
|
121
|
+
if (await enrolledSerialRegistry.has(args.serial)) {
|
|
122
|
+
throw new VaultError('key-already-enrolled', args.serial, undefined, { serial: args.serial })
|
|
123
|
+
}
|
|
90
124
|
}
|
|
91
125
|
|
|
92
126
|
// Guard 1: before any card contact.
|
|
@@ -95,8 +129,8 @@ export async function resetPivApplication(args: {
|
|
|
95
129
|
|
|
96
130
|
await withKeySession(
|
|
97
131
|
driver,
|
|
98
|
-
async
|
|
99
|
-
|
|
132
|
+
async session => {
|
|
133
|
+
assertSessionCurrent(session, scopeToken)
|
|
100
134
|
const info = await driver.getKeyInfo()
|
|
101
135
|
if (info.serial !== args.serial) {
|
|
102
136
|
throw new VaultError('serial-mismatch', 'A different YubiKey was presented', undefined, {
|
|
@@ -108,7 +142,7 @@ export async function resetPivApplication(args: {
|
|
|
108
142
|
// first check and the tap, and this is the last chance before an
|
|
109
143
|
// irreversible destruction.
|
|
110
144
|
await refuse()
|
|
111
|
-
|
|
145
|
+
assertSessionCurrent(session, scopeToken)
|
|
112
146
|
|
|
113
147
|
// Guard 3: the card's own answer, for the vaults no namespace on this
|
|
114
148
|
// device can show us. Reused code, not new copy: 'slot-occupied' is
|
|
@@ -128,14 +162,21 @@ export async function resetPivApplication(args: {
|
|
|
128
162
|
{ serial: args.serial }
|
|
129
163
|
)
|
|
130
164
|
}
|
|
131
|
-
|
|
165
|
+
assertSessionCurrent(session, scopeToken)
|
|
132
166
|
|
|
133
167
|
args.onPhase?.('resetting')
|
|
134
168
|
await driver.resetPivApplication(args.serial)
|
|
135
169
|
|
|
136
170
|
// The reset destroyed whatever partial state these described. Leaving
|
|
137
|
-
// them would refuse this key forever
|
|
138
|
-
|
|
171
|
+
// them would refuse this key forever — but XR-004 still applies here:
|
|
172
|
+
// if this continuation is only resuming now because the native reset
|
|
173
|
+
// call stalled and a NEWER session has since run (e.g. re-enrolling
|
|
174
|
+
// this same, now-actually-reset serial), these discards must not wipe
|
|
175
|
+
// out whatever fresh draft/quarantine state that session just wrote.
|
|
176
|
+
// Refusing here leaves a stale entry that the next explicit reset
|
|
177
|
+
// attempt clears — a mild extra tap, not a permanent block, since the
|
|
178
|
+
// card is by then already factory and that retry completes at once.
|
|
179
|
+
assertSessionCurrent(session, scopeToken)
|
|
139
180
|
await vaultStore.discardEnrollmentDraft(args.serial, scopeToken)
|
|
140
181
|
await vaultStore.discardEnrollmentQuarantine(args.serial, scopeToken)
|
|
141
182
|
},
|
|
@@ -870,7 +870,38 @@ export interface VaultInstructionsV6 {
|
|
|
870
870
|
createdAt: number
|
|
871
871
|
keys: VaultInstructionKey[]
|
|
872
872
|
}
|
|
873
|
-
|
|
873
|
+
/**
|
|
874
|
+
* v7 recovery metadata: exactly the v6 fields minus `salt`. The salt is never
|
|
875
|
+
* persisted for a v7 output — it is re-derived in memory (deriveVaultSalt)
|
|
876
|
+
* whenever a v7 lock must be rebuilt or a v7 witness built, from the same
|
|
877
|
+
* unchanged HMAC protocol v6 always used. See docs/security's v7 design: the
|
|
878
|
+
* exact 8-field shape and the `v===7` gate make it structurally impossible
|
|
879
|
+
* for a salt to ride along with a v7 record, and structurally impossible for
|
|
880
|
+
* a v6 record (which REQUIRES `salt`) to decode as v7 or vice versa.
|
|
881
|
+
*/
|
|
882
|
+
export interface VaultInstructionsV7 {
|
|
883
|
+
v: 7
|
|
884
|
+
type: 'R1C'
|
|
885
|
+
/** Canonical positive decimal wallet key index (`"1"`, `"2"`, ...). */
|
|
886
|
+
saltKeyId: string
|
|
887
|
+
/** Network scope of the output. */
|
|
888
|
+
chain: VaultSaltChain
|
|
889
|
+
vaultId: string
|
|
890
|
+
revision: number
|
|
891
|
+
createdAt: number
|
|
892
|
+
keys: VaultInstructionKey[]
|
|
893
|
+
}
|
|
894
|
+
export type VaultInstructions = VaultInstructionsV6 | VaultInstructionsV7
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Hard cap on the v7 descriptor's AES-256-GCM ciphertext
|
|
898
|
+
* (`iv(32B) || ciphertext || authTag(16B)`, @bsv/sdk SymmetricKey.encrypt),
|
|
899
|
+
* enforced at both encode time (creation fails closed) and decode time (an
|
|
900
|
+
* oversized blob is never trusted, not merely truncated). Measured worst case:
|
|
901
|
+
* N=5 keys at max field lengths serializes to roughly 1.45 KB of v7 JSON, so
|
|
902
|
+
* +48 B of AES-GCM overhead leaves a comfortable margin under 2,200.
|
|
903
|
+
*/
|
|
904
|
+
export const MAX_DESCRIPTOR_CIPHERTEXT_BYTES = 2200
|
|
874
905
|
|
|
875
906
|
const MAX_CUSTOM_INSTRUCTIONS_CHARS = 4096
|
|
876
907
|
const exactFields = (v: Record<string, unknown>, fields: readonly string[]): boolean => {
|
|
@@ -883,7 +914,7 @@ const positiveSafeInteger = (v: unknown): v is number => Number.isSafeInteger(v)
|
|
|
883
914
|
* Parse exact v6 output recovery metadata. Older and extended shapes fail
|
|
884
915
|
* closed: future code must explicitly version any semantic change.
|
|
885
916
|
*/
|
|
886
|
-
export function
|
|
917
|
+
export function decodeVaultInstructionsV6(ci?: string): VaultInstructionsV6 | null {
|
|
887
918
|
if (typeof ci !== 'string' || ci.length === 0 || ci.length > MAX_CUSTOM_INSTRUCTIONS_CHARS) return null
|
|
888
919
|
let parsed: unknown
|
|
889
920
|
try {
|
|
@@ -971,6 +1002,111 @@ export function encodeVaultInstructions(i: VaultInstructionsV6): string {
|
|
|
971
1002
|
enrolledAt: k.enrolledAt
|
|
972
1003
|
}))
|
|
973
1004
|
})
|
|
974
|
-
if (
|
|
1005
|
+
if (decodeVaultInstructionsV6(s) === null) throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
|
|
1006
|
+
return s
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Parse exact v7 output recovery metadata: the v6 shape minus `salt`. A
|
|
1011
|
+
* record carrying a `salt` field (extra field), a `p.v` other than 7, or any
|
|
1012
|
+
* other v6-shaped field set fails closed here — see VaultInstructionsV7's
|
|
1013
|
+
* docstring. Every other field rule is identical to the v6 decoder.
|
|
1014
|
+
*/
|
|
1015
|
+
export function decodeVaultInstructionsV7(ci?: string): VaultInstructionsV7 | null {
|
|
1016
|
+
if (typeof ci !== 'string' || ci.length === 0 || ci.length > MAX_CUSTOM_INSTRUCTIONS_CHARS) return null
|
|
1017
|
+
let parsed: unknown
|
|
1018
|
+
try {
|
|
1019
|
+
parsed = JSON.parse(ci)
|
|
1020
|
+
} catch {
|
|
1021
|
+
return null
|
|
1022
|
+
}
|
|
1023
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
|
|
1024
|
+
const p = parsed as Record<string, unknown>
|
|
1025
|
+
if (!exactFields(p, ['v', 'type', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys'])) return null
|
|
1026
|
+
if (p.v !== 7 || p.type !== 'R1C') return null
|
|
1027
|
+
if (typeof p.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(p.vaultId)) return null
|
|
1028
|
+
if (
|
|
1029
|
+
typeof p.saltKeyId !== 'string' ||
|
|
1030
|
+
!/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)
|
|
1031
|
+
) return null
|
|
1032
|
+
if (p.chain !== 'main' && p.chain !== 'test' && p.chain !== 'teratest') return null
|
|
1033
|
+
const saltIndex = Number(p.saltKeyId)
|
|
1034
|
+
if (!positiveSafeInteger(saltIndex)) return null
|
|
1035
|
+
if (!positiveSafeInteger(p.revision) || !positiveSafeInteger(p.createdAt)) return null
|
|
1036
|
+
if (!Array.isArray(p.keys) || p.keys.length < 1 || p.keys.length > R1C_MAX_KEYS) return null
|
|
1037
|
+
const keys: VaultInstructionKey[] = []
|
|
1038
|
+
for (const raw of p.keys) {
|
|
1039
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
|
|
1040
|
+
const k = raw as Record<string, unknown>
|
|
1041
|
+
if (!exactFields(k, ['serial', 'slot', 'pubkey', 'nickname', 'enrolledAt'])) return null
|
|
1042
|
+
if (typeof k.serial !== 'string' || !/^[A-Za-z0-9._:-]{1,64}$/.test(k.serial)) return null
|
|
1043
|
+
if (k.slot !== 0x82) return null
|
|
1044
|
+
if (typeof k.pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(k.pubkey)) return null
|
|
1045
|
+
if (
|
|
1046
|
+
typeof k.nickname !== 'string' || k.nickname.length < 1 || k.nickname.length > 64 ||
|
|
1047
|
+
k.nickname !== k.nickname.trim() || /[\u0000-\u001f\u007f]/.test(k.nickname)
|
|
1048
|
+
) return null
|
|
1049
|
+
if (!positiveSafeInteger(k.enrolledAt)) return null
|
|
1050
|
+
try {
|
|
1051
|
+
if (compressPubkey(k.pubkey) !== k.pubkey) return null
|
|
1052
|
+
} catch {
|
|
1053
|
+
return null
|
|
1054
|
+
}
|
|
1055
|
+
keys.push({
|
|
1056
|
+
serial: k.serial,
|
|
1057
|
+
slot: k.slot,
|
|
1058
|
+
pubkey: k.pubkey,
|
|
1059
|
+
nickname: k.nickname,
|
|
1060
|
+
enrolledAt: k.enrolledAt
|
|
1061
|
+
})
|
|
1062
|
+
}
|
|
1063
|
+
if (new Set(keys.map(k => k.serial)).size !== keys.length) return null
|
|
1064
|
+
if (new Set(keys.map(k => k.pubkey)).size !== keys.length) return null
|
|
1065
|
+
try {
|
|
1066
|
+
vaultSaltHmacData(keys.map(k => k.serial))
|
|
1067
|
+
} catch {
|
|
1068
|
+
return null
|
|
1069
|
+
}
|
|
1070
|
+
return {
|
|
1071
|
+
v: 7,
|
|
1072
|
+
type: 'R1C',
|
|
1073
|
+
saltKeyId: p.saltKeyId,
|
|
1074
|
+
chain: p.chain,
|
|
1075
|
+
vaultId: p.vaultId,
|
|
1076
|
+
revision: p.revision,
|
|
1077
|
+
createdAt: p.createdAt,
|
|
1078
|
+
keys
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** Serialise only the canonical v7 fields (no `salt`), after applying the decoder's validation. */
|
|
1083
|
+
export function encodeVaultInstructionsV7(i: VaultInstructionsV7): string {
|
|
1084
|
+
const s = JSON.stringify({
|
|
1085
|
+
v: 7,
|
|
1086
|
+
type: 'R1C',
|
|
1087
|
+
saltKeyId: i.saltKeyId,
|
|
1088
|
+
chain: i.chain,
|
|
1089
|
+
vaultId: i.vaultId,
|
|
1090
|
+
revision: i.revision,
|
|
1091
|
+
createdAt: i.createdAt,
|
|
1092
|
+
keys: i.keys.map(k => ({
|
|
1093
|
+
serial: k.serial,
|
|
1094
|
+
slot: k.slot,
|
|
1095
|
+
pubkey: k.pubkey,
|
|
1096
|
+
nickname: k.nickname,
|
|
1097
|
+
enrolledAt: k.enrolledAt
|
|
1098
|
+
}))
|
|
1099
|
+
})
|
|
1100
|
+
if (decodeVaultInstructionsV7(s) === null) throw invalid('encodeVaultInstructionsV7: record would not decode as canonical v7 vault metadata')
|
|
975
1101
|
return s
|
|
976
1102
|
}
|
|
1103
|
+
|
|
1104
|
+
/**
|
|
1105
|
+
* Union decoder: try the exact v6 shape (carries `salt`), then the exact v7
|
|
1106
|
+
* shape (no `salt`). The two decoders' exact-field checks and `v` gate make
|
|
1107
|
+
* the two shapes mutually exclusive, so this can never reinterpret one
|
|
1108
|
+
* version as the other.
|
|
1109
|
+
*/
|
|
1110
|
+
export function decodeVaultInstructions(ci?: string): VaultInstructions | null {
|
|
1111
|
+
return decodeVaultInstructionsV6(ci) ?? decodeVaultInstructionsV7(ci)
|
|
1112
|
+
}
|
|
@@ -21,9 +21,22 @@
|
|
|
21
21
|
* swallows several failure paths, so no delegate fix makes this redundant).
|
|
22
22
|
*/
|
|
23
23
|
import { VaultDriver } from './driver'
|
|
24
|
-
import { acquireVaultHardwareLease } from './hardwareLease'
|
|
24
|
+
import { acquireVaultHardwareLease, currentVaultHardwareGeneration, isCurrentVaultHardwareGeneration } from './hardwareLease'
|
|
25
25
|
import { VaultError } from './types'
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* XR-004: `work()` is unbounded native work this function cannot cancel — a
|
|
29
|
+
* lost completion can still be running (and can still resolve much later)
|
|
30
|
+
* after the timeout/detach race below has already settled and released the
|
|
31
|
+
* lease for a retry. `work` receives this guard so it can refuse its own
|
|
32
|
+
* next mutation once a NEWER session has been acquired since, rather than
|
|
33
|
+
* racing that retry's writes to vaultStore/the card. Cheap and synchronous:
|
|
34
|
+
* safe to call as often as the existing per-step scope checks already do.
|
|
35
|
+
*/
|
|
36
|
+
export interface VaultSessionGuard {
|
|
37
|
+
assertCurrent(): void
|
|
38
|
+
}
|
|
39
|
+
|
|
27
40
|
interface Deferred<T> {
|
|
28
41
|
promise: Promise<T>
|
|
29
42
|
resolve: (v: T) => void
|
|
@@ -59,13 +72,21 @@ const DEFAULT_WORK_TIMEOUT_MS = 180_000
|
|
|
59
72
|
|
|
60
73
|
export async function withKeySession<T>(
|
|
61
74
|
driver: VaultDriver,
|
|
62
|
-
work: () => Promise<T>,
|
|
75
|
+
work: (session: VaultSessionGuard) => Promise<T>,
|
|
63
76
|
onWaiting?: () => void,
|
|
64
77
|
opts?: { nfcMessage?: string; attachTimeoutMs?: number; workTimeoutMs?: number }
|
|
65
78
|
): Promise<T> {
|
|
66
79
|
const releaseLease = acquireVaultHardwareLease()
|
|
80
|
+
const generation = currentVaultHardwareGeneration()
|
|
81
|
+
const session: VaultSessionGuard = {
|
|
82
|
+
assertCurrent(): void {
|
|
83
|
+
if (!isCurrentVaultHardwareGeneration(generation)) {
|
|
84
|
+
throw new VaultError('scope-changed', 'A newer Vault hardware session has started; this one was abandoned')
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
67
88
|
try {
|
|
68
|
-
if (!driver.sessionBased) return await work()
|
|
89
|
+
if (!driver.sessionBased) return await work(session)
|
|
69
90
|
|
|
70
91
|
const connected = defer<void>()
|
|
71
92
|
// Rejects when the key leaves before `work` has resolved; raced against it.
|
|
@@ -105,7 +126,7 @@ export async function withKeySession<T>(
|
|
|
105
126
|
)
|
|
106
127
|
;(workWatchdog as { unref?: () => void }).unref?.()
|
|
107
128
|
try {
|
|
108
|
-
return await Promise.race([work(), detached.promise, stalled.promise])
|
|
129
|
+
return await Promise.race([work(session), detached.promise, stalled.promise])
|
|
109
130
|
} finally {
|
|
110
131
|
clearTimeout(workWatchdog)
|
|
111
132
|
}
|