@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.
- package/CHANGELOG.md +547 -0
- package/README.md +19 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/amountFormatHelpers.ts +238 -34
- package/core/backup/RemoteSyncReader.ts +2 -5
- package/core/backup/codec.ts +2 -2
- package/core/backup/push.ts +1 -1
- package/core/config.tsx +16 -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/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +464 -30
- 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 +52 -14
- package/core/headers/headerStore.ts +7 -10
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +4562 -986
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +285 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +247 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +116 -15
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/pendingAborts.ts +5 -1
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +1 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +1 -1
- package/core/monitor/TaskSendOffline.ts +1 -1
- package/core/net/online.ts +49 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/plan.ts +1 -1
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/pay/recordProof.ts +2 -6
- package/core/services/arcadeBroadcastProvider.ts +1 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/exchangeRate.ts +1 -1
- package/core/services/externalOrigin.ts +42 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/services/walletServiceConfig.ts +31 -20
- package/core/storage/StorageExpoSQLite.ts +420 -87
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +3 -54
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +9 -5
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +265 -9
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +152 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +182 -1
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletMonitor.ts +8 -3
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +31 -30
- package/ui/activityFilter.ts +115 -0
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
- package/ui/components/pay/RecipientField.tsx +132 -73
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +1118 -86
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +283 -97
- package/ui/components/wallet/AmountInput.tsx +92 -28
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- 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/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +320 -0
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +75 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +234 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +145 -12
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +1 -1
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +80 -16
- package/ui/screens/WalletHomeScreen.tsx +915 -139
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +100 -0
- package/ui/txStatus.ts +43 -5
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every write to the registry, and the journal that makes each one idempotent.
|
|
3
|
+
*
|
|
4
|
+
* The order is the whole design: a certificate is signed and written to
|
|
5
|
+
* `key_value_store` BEFORE the first request, so a retry after a crash, a
|
|
6
|
+
* double tap or a timeout re-sends the identical bytes — which the registry
|
|
7
|
+
* treats as a no-op `200` rather than a second claim. That is why "the write
|
|
8
|
+
* landed but the response was lost" and "the write never landed" do not have
|
|
9
|
+
* to be told apart here: replaying settles both.
|
|
10
|
+
*
|
|
11
|
+
* `issuedAt` is the registry's replay guard, so it has to beat every value this
|
|
12
|
+
* device has already minted (a clock that jumped backwards would otherwise
|
|
13
|
+
* mint a certificate the server calls stale) while never running away from the
|
|
14
|
+
* server's own clock (more than five minutes ahead is refused outright). The
|
|
15
|
+
* corrected `serverNow` handles the second; the stored high-water mark, the
|
|
16
|
+
* first.
|
|
17
|
+
*/
|
|
18
|
+
import { parsePaymail } from './rules'
|
|
19
|
+
import { buildProfileCertificate, type ProfileCertJson, type ProfileSigner } from './profileCert'
|
|
20
|
+
import type { HandleRegistryClient } from './client'
|
|
21
|
+
|
|
22
|
+
/** The in-flight journal. One at a time; a second intent replaces it. */
|
|
23
|
+
export const PENDING_JOURNAL_KEY = 'profile_handle_pending'
|
|
24
|
+
/** The highest `issuedAt` this device has ever minted. */
|
|
25
|
+
export const ISSUED_AT_KV_KEY = 'profile_handle_issued_at'
|
|
26
|
+
/**
|
|
27
|
+
* How far ahead of the registry's own clock an `issuedAt` may be dated. The
|
|
28
|
+
* server refuses anything past five minutes (`profilecert.MaxClockSkew`); four
|
|
29
|
+
* leaves room for the request to arrive.
|
|
30
|
+
*/
|
|
31
|
+
export const MAX_ISSUED_AT_LEAD_MS = 240_000
|
|
32
|
+
|
|
33
|
+
/** Structurally satisfied by `StorageExpoSQLite`. */
|
|
34
|
+
export interface RegistrationStorage {
|
|
35
|
+
getKeyValue(key: string): Promise<string | undefined>
|
|
36
|
+
setKeyValue(key: string, value: string): Promise<void>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type RegistrationIntent = 'register' | 'update' | 'change'
|
|
40
|
+
|
|
41
|
+
export interface PendingStep {
|
|
42
|
+
kind: 'release' | 'claim'
|
|
43
|
+
paymail: string
|
|
44
|
+
cert: ProfileCertJson
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* `intent` is not in the design's journal shape. `resumePending` runs a journal
|
|
49
|
+
* it did not start and still has to say which of registered/updated/changed
|
|
50
|
+
* happened, and no combination of the other fields tells those apart.
|
|
51
|
+
* `attemptedPaymail` is there for the same reason: a rollback resumed on a
|
|
52
|
+
* later mount has to name the handle that was lost, and its one step is the
|
|
53
|
+
* reclaim. Nothing has shipped, so the version stays 1.
|
|
54
|
+
*/
|
|
55
|
+
export interface PendingJournal {
|
|
56
|
+
v: 1
|
|
57
|
+
intent: RegistrationIntent
|
|
58
|
+
steps: PendingStep[]
|
|
59
|
+
previousPaymail?: string
|
|
60
|
+
attemptedPaymail?: string
|
|
61
|
+
startedAt: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A refusal this module reached on its own rather than read off the wire, for a
|
|
66
|
+
* caller that has to say it in the user's language — `message` is diagnostic
|
|
67
|
+
* English, often the SDK's, and is the wrong thing to put in front of anybody.
|
|
68
|
+
*/
|
|
69
|
+
export type RegistrationFailureCode = 'invalid_handle' | 'wrong_domain' | 'same_handle' | 'clock_ahead'
|
|
70
|
+
|
|
71
|
+
export type RegistrationResult =
|
|
72
|
+
| { kind: 'registered'; paymail: string }
|
|
73
|
+
| { kind: 'updated'; paymail: string }
|
|
74
|
+
| { kind: 'changed'; paymail: string }
|
|
75
|
+
/** `attempted` is the handle that was lost; `paymail` is the one kept. */
|
|
76
|
+
| { kind: 'rolled_back'; paymail: string; attempted?: string }
|
|
77
|
+
| { kind: 'pending' }
|
|
78
|
+
| { kind: 'rejected'; code: string; description: string }
|
|
79
|
+
| { kind: 'failed'; message: string; code?: RegistrationFailureCode }
|
|
80
|
+
| { kind: 'unavailable' }
|
|
81
|
+
| { kind: 'idle' }
|
|
82
|
+
|
|
83
|
+
export interface RegistrationDeps {
|
|
84
|
+
/** null when this chain has no registry configured. */
|
|
85
|
+
client: HandleRegistryClient | null
|
|
86
|
+
signer: ProfileSigner
|
|
87
|
+
storage: RegistrationStorage
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* One run at a time, and the key is what makes that safe.
|
|
92
|
+
*
|
|
93
|
+
* Two mounted Profile screens or a double tap ask for the SAME thing, and the
|
|
94
|
+
* second caller should get the first caller's answer rather than mint a second
|
|
95
|
+
* certificate. Two DIFFERENT intents are not interchangeable: the mount's
|
|
96
|
+
* `resumePending` is routinely still in flight when the user taps Claim, and
|
|
97
|
+
* handing the claim the resume's `{kind:'idle'}` would spin the button, send
|
|
98
|
+
* nothing, and leave the user with no handle and no explanation. A different
|
|
99
|
+
* key therefore queues behind the run in progress instead of joining it.
|
|
100
|
+
*
|
|
101
|
+
* Which is why the live runs are a map rather than one slot: the tail of the
|
|
102
|
+
* queue is not the only run worth joining. A tap that arrives after the
|
|
103
|
+
* mount's resume has queued asks for exactly what the tap before it asked for,
|
|
104
|
+
* and one slot would have had it start its own release/claim pair behind the
|
|
105
|
+
* resume — twice the writes for one user action.
|
|
106
|
+
*/
|
|
107
|
+
const live = new Map<string, Promise<RegistrationResult>>()
|
|
108
|
+
/** What a genuinely new key chains onto, so runs never overlap. */
|
|
109
|
+
let tail: Promise<RegistrationResult> | null = null
|
|
110
|
+
|
|
111
|
+
function share(key: string, run: () => Promise<RegistrationResult>): Promise<RegistrationResult> {
|
|
112
|
+
const joined = live.get(key)
|
|
113
|
+
if (joined) return joined
|
|
114
|
+
const previous = tail
|
|
115
|
+
const promise = (async () => {
|
|
116
|
+
// Never reject on the predecessor's behalf: every entry point already
|
|
117
|
+
// answers a result rather than throwing, and a rejection here would be
|
|
118
|
+
// this caller's request never having been attempted.
|
|
119
|
+
if (previous) await previous.catch(() => undefined)
|
|
120
|
+
return await run()
|
|
121
|
+
})()
|
|
122
|
+
live.set(key, promise)
|
|
123
|
+
tail = promise
|
|
124
|
+
// `then(clear, clear)` rather than `finally`: an ignored `finally` chain
|
|
125
|
+
// would re-raise a rejection nobody is listening to.
|
|
126
|
+
const clear = () => {
|
|
127
|
+
if (live.get(key) === promise) live.delete(key)
|
|
128
|
+
if (tail === promise) tail = null
|
|
129
|
+
}
|
|
130
|
+
void promise.then(clear, clear)
|
|
131
|
+
return promise
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Test-only: forget the shared runs between cases. */
|
|
135
|
+
export function resetRegistrationState(): void {
|
|
136
|
+
live.clear()
|
|
137
|
+
tail = null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function messageOf(e: unknown): string {
|
|
141
|
+
return e instanceof Error ? e.message : String(e)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function readJournal(storage: RegistrationStorage): Promise<PendingJournal | null> {
|
|
145
|
+
const raw = await storage.getKeyValue(PENDING_JOURNAL_KEY)
|
|
146
|
+
if (!raw) return null
|
|
147
|
+
const parsed = parseJournal(raw)
|
|
148
|
+
// A row no reader can act on is a row nothing would ever clear: every reader
|
|
149
|
+
// answers "no journal" for it, so it would sit in the store for the life of
|
|
150
|
+
// the install. Whatever it is, it is not a write this app can finish.
|
|
151
|
+
if (!parsed) await clearJournal(storage)
|
|
152
|
+
return parsed
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function parseJournal(raw: string): PendingJournal | null {
|
|
156
|
+
try {
|
|
157
|
+
const parsed = JSON.parse(raw) as PendingJournal
|
|
158
|
+
if (parsed?.v !== 1 || !Array.isArray(parsed.steps) || parsed.steps.length === 0) return null
|
|
159
|
+
return parsed
|
|
160
|
+
} catch {
|
|
161
|
+
return null
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** `setKeyValue('')` rather than a delete: the store has no delete, and an
|
|
166
|
+
* empty string reads back as "no journal" everywhere it is checked. */
|
|
167
|
+
async function clearJournal(storage: RegistrationStorage): Promise<void> {
|
|
168
|
+
await storage.setKeyValue(PENDING_JOURNAL_KEY, '')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function writeJournal(storage: RegistrationStorage, journal: PendingJournal): Promise<void> {
|
|
172
|
+
await storage.setKeyValue(PENDING_JOURNAL_KEY, JSON.stringify(journal))
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Strictly after everything this device has minted, at least the server's own
|
|
177
|
+
* idea of now, and never so far ahead that the server refuses it.
|
|
178
|
+
*
|
|
179
|
+
* Stored before it is used, so a crash between minting and sending cannot let
|
|
180
|
+
* the next attempt repeat the value — the registry compares `issuedAt` AND
|
|
181
|
+
* `serialNumber`, and an equal `issuedAt` under a fresh serial is stale.
|
|
182
|
+
*
|
|
183
|
+
* The ceiling is what keeps a fast clock from being permanent. A phone an hour
|
|
184
|
+
* ahead mints `now + 1h` on its first write, the server refuses it, and that
|
|
185
|
+
* refused value is already the stored high-water mark; flooring alone would
|
|
186
|
+
* re-mint `+1h` for ever. A mark beyond the ceiling cannot correspond to any
|
|
187
|
+
* certificate the server accepted, so it is discarded rather than honoured —
|
|
188
|
+
* and by then the refused response has corrected `serverNow`'s skew, so the
|
|
189
|
+
* next attempt is inside the window with room left to climb.
|
|
190
|
+
*/
|
|
191
|
+
async function nextIssuedAt(deps: RegistrationDeps, client: HandleRegistryClient, after?: Date): Promise<Date> {
|
|
192
|
+
const serverMs = client.serverNow().getTime()
|
|
193
|
+
const ceiling = serverMs + MAX_ISSUED_AT_LEAD_MS
|
|
194
|
+
const stored = Date.parse((await deps.storage.getKeyValue(ISSUED_AT_KV_KEY)) ?? '')
|
|
195
|
+
const mark = Number.isFinite(stored) && stored < ceiling ? stored + 1 : 0
|
|
196
|
+
const at = new Date(Math.min(Math.max(serverMs, mark, after ? after.getTime() + 1 : 0), ceiling))
|
|
197
|
+
await deps.storage.setKeyValue(ISSUED_AT_KV_KEY, at.toISOString())
|
|
198
|
+
return at
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Whether the registry already shows the world this step was trying to make —
|
|
203
|
+
* with `unknown` for the registry that did not answer at all.
|
|
204
|
+
*
|
|
205
|
+
* That third answer is why this asks `lookupProfile` rather than
|
|
206
|
+
* `lookupIdentityKey`: the latter flattens "this key holds nothing" and "no
|
|
207
|
+
* answer" into one `null`, and reading silence as a tombstone would send the
|
|
208
|
+
* claim that follows a release on a premise nobody confirmed.
|
|
209
|
+
*
|
|
210
|
+
* A claim is applied when the profile on offer IS the profile the step asked
|
|
211
|
+
* for — the paymail and the display name both. The paymail alone tests nothing
|
|
212
|
+
* for an `update`, where the paymail is by definition one this key already
|
|
213
|
+
* holds, so a display name the registry refused would read back as saved.
|
|
214
|
+
*
|
|
215
|
+
* `paymailIsEnough` is the one case where it does test something: the claim of
|
|
216
|
+
* a change — one with a release behind it — where holding the new handle IS
|
|
217
|
+
* what the user asked for. The display name rides along on the same
|
|
218
|
+
* certificate, and denying a change that happened because the registry is
|
|
219
|
+
* serving an older name would leave the user told `failed` about a handle that
|
|
220
|
+
* is theirs.
|
|
221
|
+
*/
|
|
222
|
+
async function alreadyApplied(
|
|
223
|
+
client: HandleRegistryClient,
|
|
224
|
+
step: PendingStep,
|
|
225
|
+
paymailIsEnough: boolean
|
|
226
|
+
): Promise<boolean | 'unknown'> {
|
|
227
|
+
const seen = await client.lookupProfile(step.cert.subject)
|
|
228
|
+
if (seen.kind === 'failed') return 'unknown'
|
|
229
|
+
const mine = seen.kind === 'found' ? seen.profile : null
|
|
230
|
+
if (step.kind === 'claim') {
|
|
231
|
+
if (mine?.paymail !== step.paymail) return false
|
|
232
|
+
return paymailIsEnough || (mine.displayName ?? '') === (step.cert.fields.displayName ?? '')
|
|
233
|
+
}
|
|
234
|
+
return mine === null || mine.paymail !== step.paymail
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The `issuedAt` a step was minted with, as the journal carries it. */
|
|
238
|
+
function issuedAtOf(step: PendingStep | undefined): Date | undefined {
|
|
239
|
+
const ms = Date.parse(step?.cert.fields.issuedAt ?? '')
|
|
240
|
+
return Number.isFinite(ms) ? new Date(ms) : undefined
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The handle to put the user back on, when the step the registry just refused
|
|
245
|
+
* is the claim of a change that has already tombstoned the old one.
|
|
246
|
+
*
|
|
247
|
+
* `null` for everything else, and the `i > 0` is not decoration: `rollBack`
|
|
248
|
+
* writes a journal of exactly one claim for `previousPaymail`, so a rollback
|
|
249
|
+
* being resumed matches on paymail alone and would reclaim what it is already
|
|
250
|
+
* reclaiming instead of reporting the refusal.
|
|
251
|
+
*/
|
|
252
|
+
function reclaimFor(
|
|
253
|
+
journal: PendingJournal,
|
|
254
|
+
step: PendingStep,
|
|
255
|
+
i: number
|
|
256
|
+
): { paymail: string; releasedAt: Date | undefined; attempted: string } | null {
|
|
257
|
+
if (step.kind !== 'claim' || i === 0 || !journal.previousPaymail) return null
|
|
258
|
+
return {
|
|
259
|
+
paymail: journal.previousPaymail,
|
|
260
|
+
releasedAt: issuedAtOf(journal.steps.find(s => s.kind === 'release')),
|
|
261
|
+
attempted: step.paymail
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function runJournal(
|
|
266
|
+
deps: RegistrationDeps,
|
|
267
|
+
client: HandleRegistryClient,
|
|
268
|
+
journal: PendingJournal
|
|
269
|
+
): Promise<RegistrationResult> {
|
|
270
|
+
for (let i = 0; i < journal.steps.length; i++) {
|
|
271
|
+
const step = journal.steps[i]
|
|
272
|
+
const outcome = await client.putCertificate(step.cert)
|
|
273
|
+
if (outcome.kind === 'created' || outcome.kind === 'ok') continue
|
|
274
|
+
// No answer: the journal stays, and the next mount or an explicit retry
|
|
275
|
+
// re-sends the same bytes.
|
|
276
|
+
if (outcome.kind === 'failed') return { kind: 'pending' }
|
|
277
|
+
// Whatever the registry's reason, refusing the claim of a change that has
|
|
278
|
+
// already tombstoned the old handle leaves the user holding nothing — so
|
|
279
|
+
// both branches below reach for the reclaim rather than the verdict.
|
|
280
|
+
const reclaim = reclaimFor(journal, step, i)
|
|
281
|
+
if (outcome.code === 'ERR_STALE_CERTIFICATE') {
|
|
282
|
+
const applied = await alreadyApplied(client, step, reclaim !== null)
|
|
283
|
+
if (applied === true) continue
|
|
284
|
+
// Nobody said whether this step landed, so its fate is still open: the
|
|
285
|
+
// journal stays and the next mount asks again.
|
|
286
|
+
if (applied === 'unknown') return { kind: 'pending' }
|
|
287
|
+
// Stale on such a claim means whoever released the new handle dated
|
|
288
|
+
// their tombstone ahead of ours — any device a few minutes fast does —
|
|
289
|
+
// and is the same hazard as the handle being taken. Replaying cannot
|
|
290
|
+
// win, but the reclaim still can.
|
|
291
|
+
if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
|
|
292
|
+
// Replaying a certificate the registry calls stale can never win, so
|
|
293
|
+
// keeping the journal would only retry it on every mount, forever.
|
|
294
|
+
await clearJournal(deps.storage)
|
|
295
|
+
return { kind: 'failed', message: outcome.description }
|
|
296
|
+
}
|
|
297
|
+
if (reclaim) return await rollBack(deps, client, reclaim.paymail, reclaim.releasedAt, reclaim.attempted)
|
|
298
|
+
await clearJournal(deps.storage)
|
|
299
|
+
return { kind: 'rejected', code: outcome.code, description: outcome.description }
|
|
300
|
+
}
|
|
301
|
+
await clearJournal(deps.storage)
|
|
302
|
+
const paymail = journal.steps[journal.steps.length - 1].paymail
|
|
303
|
+
// `rollBack`'s own journal, resumed: intent `change`, one step, and that step
|
|
304
|
+
// reclaims the handle the change started from. It has to answer `rolled_back`
|
|
305
|
+
// — the new handle was taken and the old one kept — rather than `changed`,
|
|
306
|
+
// which would announce a handle the user never stopped holding.
|
|
307
|
+
if (journal.intent === 'change' && journal.steps.length === 1 && journal.previousPaymail === paymail) {
|
|
308
|
+
return {
|
|
309
|
+
kind: 'rolled_back',
|
|
310
|
+
paymail,
|
|
311
|
+
...(journal.attemptedPaymail ? { attempted: journal.attemptedPaymail } : {})
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (journal.intent === 'update') return { kind: 'updated', paymail }
|
|
315
|
+
if (journal.intent === 'change') return { kind: 'changed', paymail }
|
|
316
|
+
return { kind: 'registered', paymail }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Put the user back where they were. The previous owner is exempt from the
|
|
321
|
+
* cooldown on a handle they released themselves, so this claim is one the
|
|
322
|
+
* registry will accept.
|
|
323
|
+
*
|
|
324
|
+
* `releasedAt` is the release's own `issuedAt`, taken from the journal, and it
|
|
325
|
+
* is what the reclaim has to beat: a release rewrites the row's `issuedAt` to
|
|
326
|
+
* its own, and a reclaim not strictly after that is refused as stale. The
|
|
327
|
+
* stored high-water mark cannot be relied on for it — a mark sitting on the
|
|
328
|
+
* ceiling is discarded, and then the mint would land minutes BEHIND the
|
|
329
|
+
* tombstone it is undoing, leaving the user holding neither handle.
|
|
330
|
+
*
|
|
331
|
+
* Nor can the mint be trusted to honour it, because the ceiling is applied
|
|
332
|
+
* last: a phone four minutes fast dates its release on the fast clock, has it
|
|
333
|
+
* accepted, and is corrected by that very response — which leaves the ceiling
|
|
334
|
+
* sitting exactly on the tombstone. A reclaim that cannot beat the tombstone is
|
|
335
|
+
* one the registry refuses, so it is not sent at all and the caller's journal
|
|
336
|
+
* is left whole: the next attempt replays the release as a no-op, is refused
|
|
337
|
+
* the claim again, and reaches here with a ceiling that has moved on.
|
|
338
|
+
*/
|
|
339
|
+
async function rollBack(
|
|
340
|
+
deps: RegistrationDeps,
|
|
341
|
+
client: HandleRegistryClient,
|
|
342
|
+
previousPaymail: string,
|
|
343
|
+
releasedAt?: Date,
|
|
344
|
+
attempted?: string
|
|
345
|
+
): Promise<RegistrationResult> {
|
|
346
|
+
try {
|
|
347
|
+
const issuedAt = await nextIssuedAt(deps, client, releasedAt)
|
|
348
|
+
if (releasedAt && issuedAt.getTime() <= releasedAt.getTime()) return { kind: 'pending' }
|
|
349
|
+
const cert = await buildProfileCertificate({ signer: deps.signer, paymail: previousPaymail, issuedAt })
|
|
350
|
+
await writeJournal(deps.storage, {
|
|
351
|
+
v: 1,
|
|
352
|
+
intent: 'change',
|
|
353
|
+
steps: [{ kind: 'claim', paymail: previousPaymail, cert }],
|
|
354
|
+
previousPaymail,
|
|
355
|
+
// Carried so a rollback finished on a later mount can still name the
|
|
356
|
+
// handle that was lost: by then its own claim is gone from the journal.
|
|
357
|
+
...(attempted ? { attemptedPaymail: attempted } : {}),
|
|
358
|
+
startedAt: issuedAt.toISOString()
|
|
359
|
+
})
|
|
360
|
+
const outcome = await client.putCertificate(cert)
|
|
361
|
+
if (outcome.kind === 'failed') return { kind: 'pending' }
|
|
362
|
+
await clearJournal(deps.storage)
|
|
363
|
+
if (outcome.kind === 'rejected') return { kind: 'rejected', code: outcome.code, description: outcome.description }
|
|
364
|
+
return { kind: 'rolled_back', paymail: previousPaymail, ...(attempted ? { attempted } : {}) }
|
|
365
|
+
} catch (e) {
|
|
366
|
+
await clearJournal(deps.storage)
|
|
367
|
+
return { kind: 'failed', message: messageOf(e) }
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* An unfinished journal outranks a new intent, and answering with its outcome
|
|
373
|
+
* is the whole of the fix.
|
|
374
|
+
*
|
|
375
|
+
* A `release` is idempotent only while the IDENTICAL bytes are replayed: the
|
|
376
|
+
* registry recognises a replayed tombstone by its `issuedAt`, so a freshly
|
|
377
|
+
* minted one for a handle an earlier journal already tombstoned finds nothing
|
|
378
|
+
* to release and comes back `404 ERR_HANDLE_NOT_FOUND` — while the signed,
|
|
379
|
+
* still-replayable claim that would have finished the first attempt has already
|
|
380
|
+
* been overwritten, leaving the user holding neither handle and the journal
|
|
381
|
+
* that could have rescued them gone.
|
|
382
|
+
*
|
|
383
|
+
* So a second Claim press after a timeout, a display-name save arriving while a
|
|
384
|
+
* change is still in flight, or a second Profile screen, all finish what is
|
|
385
|
+
* already journalled rather than starting again. Nothing is minted until the
|
|
386
|
+
* store is empty.
|
|
387
|
+
*/
|
|
388
|
+
async function finishOutstanding(
|
|
389
|
+
deps: RegistrationDeps,
|
|
390
|
+
client: HandleRegistryClient
|
|
391
|
+
): Promise<RegistrationResult | null> {
|
|
392
|
+
const journal = await readJournal(deps.storage)
|
|
393
|
+
return journal ? await runJournal(deps, client, journal) : null
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function registerHandle(
|
|
397
|
+
deps: RegistrationDeps,
|
|
398
|
+
args: { handle: string; displayName?: string }
|
|
399
|
+
): Promise<RegistrationResult> {
|
|
400
|
+
return share(`register:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`, async () => {
|
|
401
|
+
const client = deps.client
|
|
402
|
+
if (!client) return { kind: 'unavailable' }
|
|
403
|
+
try {
|
|
404
|
+
const outstanding = await finishOutstanding(deps, client)
|
|
405
|
+
if (outstanding) return outstanding
|
|
406
|
+
const paymail = `${args.handle.trim().toLowerCase()}@${client.domain}`
|
|
407
|
+
if (!parsePaymail(paymail))
|
|
408
|
+
return { kind: 'failed', code: 'invalid_handle', message: `handleRegistry: not a valid handle: ${args.handle}` }
|
|
409
|
+
const issuedAt = await nextIssuedAt(deps, client)
|
|
410
|
+
const cert = await buildProfileCertificate({
|
|
411
|
+
signer: deps.signer,
|
|
412
|
+
paymail,
|
|
413
|
+
issuedAt,
|
|
414
|
+
displayName: args.displayName
|
|
415
|
+
})
|
|
416
|
+
const journal: PendingJournal = {
|
|
417
|
+
v: 1,
|
|
418
|
+
intent: 'register',
|
|
419
|
+
steps: [{ kind: 'claim', paymail, cert }],
|
|
420
|
+
startedAt: issuedAt.toISOString()
|
|
421
|
+
}
|
|
422
|
+
await writeJournal(deps.storage, journal)
|
|
423
|
+
return await runJournal(deps, client, journal)
|
|
424
|
+
} catch (e) {
|
|
425
|
+
return { kind: 'failed', message: messageOf(e) }
|
|
426
|
+
}
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function updateProfile(
|
|
431
|
+
deps: RegistrationDeps,
|
|
432
|
+
args: { paymail: string; displayName?: string }
|
|
433
|
+
): Promise<RegistrationResult> {
|
|
434
|
+
return share(`update:${args.paymail.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`, async () => {
|
|
435
|
+
const client = deps.client
|
|
436
|
+
if (!client) return { kind: 'unavailable' }
|
|
437
|
+
try {
|
|
438
|
+
const outstanding = await finishOutstanding(deps, client)
|
|
439
|
+
if (outstanding) return outstanding
|
|
440
|
+
const parsed = parsePaymail(args.paymail)
|
|
441
|
+
if (!parsed || parsed.domain !== client.domain) {
|
|
442
|
+
return {
|
|
443
|
+
kind: 'failed',
|
|
444
|
+
code: 'wrong_domain',
|
|
445
|
+
message: `handleRegistry: not this registry's paymail: ${args.paymail}`
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const paymail = `${parsed.handle}@${parsed.domain}`
|
|
449
|
+
const issuedAt = await nextIssuedAt(deps, client)
|
|
450
|
+
const cert = await buildProfileCertificate({
|
|
451
|
+
signer: deps.signer,
|
|
452
|
+
paymail,
|
|
453
|
+
issuedAt,
|
|
454
|
+
displayName: args.displayName
|
|
455
|
+
})
|
|
456
|
+
const journal: PendingJournal = {
|
|
457
|
+
v: 1,
|
|
458
|
+
intent: 'update',
|
|
459
|
+
steps: [{ kind: 'claim', paymail, cert }],
|
|
460
|
+
startedAt: issuedAt.toISOString()
|
|
461
|
+
}
|
|
462
|
+
await writeJournal(deps.storage, journal)
|
|
463
|
+
return await runJournal(deps, client, journal)
|
|
464
|
+
} catch (e) {
|
|
465
|
+
return { kind: 'failed', message: messageOf(e) }
|
|
466
|
+
}
|
|
467
|
+
})
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export function changeHandle(
|
|
471
|
+
deps: RegistrationDeps,
|
|
472
|
+
args: { previousPaymail: string; handle: string; displayName?: string }
|
|
473
|
+
): Promise<RegistrationResult> {
|
|
474
|
+
const key = `change:${args.previousPaymail.trim().toLowerCase()}:${args.handle.trim().toLowerCase()}:${args.displayName?.trim() ?? ''}`
|
|
475
|
+
return share(key, async () => {
|
|
476
|
+
const client = deps.client
|
|
477
|
+
if (!client) return { kind: 'unavailable' }
|
|
478
|
+
try {
|
|
479
|
+
const outstanding = await finishOutstanding(deps, client)
|
|
480
|
+
if (outstanding) return outstanding
|
|
481
|
+
const previous = parsePaymail(args.previousPaymail)
|
|
482
|
+
const paymail = `${args.handle.trim().toLowerCase()}@${client.domain}`
|
|
483
|
+
if (!previous || previous.domain !== client.domain || !parsePaymail(paymail)) {
|
|
484
|
+
return {
|
|
485
|
+
kind: 'failed',
|
|
486
|
+
code: 'wrong_domain',
|
|
487
|
+
message: `handleRegistry: cannot change ${args.previousPaymail} to ${paymail}`
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
const previousPaymail = `${previous.handle}@${previous.domain}`
|
|
491
|
+
// Releasing a live handle to claim it straight back buys nothing and
|
|
492
|
+
// costs a window in which the user holds neither — with every way a
|
|
493
|
+
// change can go wrong inherited for a no-op. A display name is saved
|
|
494
|
+
// through `updateProfile`, which needs no tombstone at all.
|
|
495
|
+
if (previousPaymail === paymail) {
|
|
496
|
+
return {
|
|
497
|
+
kind: 'failed',
|
|
498
|
+
code: 'same_handle',
|
|
499
|
+
message: `handleRegistry: ${paymail} is already the registered handle`
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
// One key may hold one handle, so the old one is tombstoned first and
|
|
503
|
+
// the claim must be dated strictly after that tombstone.
|
|
504
|
+
const releaseAt = await nextIssuedAt(deps, client)
|
|
505
|
+
const claimAt = await nextIssuedAt(deps, client, releaseAt)
|
|
506
|
+
// Both mints can land on the ceiling at once (a mark exactly one
|
|
507
|
+
// millisecond below it), and then the claim does not beat the tombstone
|
|
508
|
+
// the release leaves behind — nor would the reclaim that undoes it. Far
|
|
509
|
+
// better to refuse a change and leave the user the handle they have; the
|
|
510
|
+
// ceiling moves with the clock, so this clears itself in minutes.
|
|
511
|
+
if (claimAt.getTime() <= releaseAt.getTime()) {
|
|
512
|
+
return {
|
|
513
|
+
kind: 'failed',
|
|
514
|
+
code: 'clock_ahead',
|
|
515
|
+
message: 'handleRegistry: the clock is too far ahead to change handle yet'
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const release = await buildProfileCertificate({
|
|
519
|
+
signer: deps.signer,
|
|
520
|
+
paymail: previousPaymail,
|
|
521
|
+
issuedAt: releaseAt,
|
|
522
|
+
released: true
|
|
523
|
+
})
|
|
524
|
+
const claim = await buildProfileCertificate({
|
|
525
|
+
signer: deps.signer,
|
|
526
|
+
paymail,
|
|
527
|
+
issuedAt: claimAt,
|
|
528
|
+
displayName: args.displayName
|
|
529
|
+
})
|
|
530
|
+
const journal: PendingJournal = {
|
|
531
|
+
v: 1,
|
|
532
|
+
intent: 'change',
|
|
533
|
+
steps: [
|
|
534
|
+
{ kind: 'release', paymail: previousPaymail, cert: release },
|
|
535
|
+
{ kind: 'claim', paymail, cert: claim }
|
|
536
|
+
],
|
|
537
|
+
previousPaymail,
|
|
538
|
+
startedAt: releaseAt.toISOString()
|
|
539
|
+
}
|
|
540
|
+
await writeJournal(deps.storage, journal)
|
|
541
|
+
return await runJournal(deps, client, journal)
|
|
542
|
+
} catch (e) {
|
|
543
|
+
return { kind: 'failed', message: messageOf(e) }
|
|
544
|
+
}
|
|
545
|
+
})
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** Called on every Profile mount. Nothing journalled is the common case. */
|
|
549
|
+
export function resumePending(deps: RegistrationDeps): Promise<RegistrationResult> {
|
|
550
|
+
return share('resume', async () => {
|
|
551
|
+
const client = deps.client
|
|
552
|
+
if (!client) return { kind: 'unavailable' }
|
|
553
|
+
try {
|
|
554
|
+
return (await finishOutstanding(deps, client)) ?? { kind: 'idle' }
|
|
555
|
+
} catch (e) {
|
|
556
|
+
return { kind: 'failed', message: messageOf(e) }
|
|
557
|
+
}
|
|
558
|
+
})
|
|
559
|
+
}
|