@dexterai/connect 0.29.1 → 0.31.1

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/README.md CHANGED
@@ -28,6 +28,24 @@ fresh passkey ceremony and replaces the active identity only after verification.
28
28
  Agent authority always requires a separate owner grant. Creating or connecting a
29
29
  Wallet grants no agent spending authority.
30
30
 
31
+ ## Interrupted wallet setup
32
+
33
+ `createWallet()` retains the original passkey when setup is interrupted. Calling
34
+ it again resumes that wallet, including after a page reload, and may ask the
35
+ owner to confirm the saved passkey. The pending wallet becomes active after
36
+ initialization succeeds. Its original name and authored allowance stay with it.
37
+
38
+ If enrollment never reached the server and its challenge expires, a fresh
39
+ passkey check can confirm that the saved credential has no server record.
40
+ Connect then clears that pending setup and returns `enrollment_not_saved`.
41
+ The next explicit Create action starts a new wallet. Network errors, generic
42
+ 404 responses, and server failures retain the pending setup for another retry.
43
+
44
+ On another device, `recoverWallet()` can finish an enrolled passkey's missing
45
+ wallet initialization after verifying that passkey. Recovery starts with zero
46
+ agent spending allowance. Full sign-in also restores a missing wallet record
47
+ while preserving the credential's existing account binding.
48
+
31
49
  ## Install
32
50
 
33
51
  ```bash
@@ -46,6 +64,57 @@ npm install @dexterai/connect @dexterai/vault react
46
64
  | `@dexterai/connect/server` | Local verification of Dexter account sessions |
47
65
  | `@dexterai/connect/worldid` | Optional World ID proof-of-personhood control |
48
66
 
67
+ ## Account panel
68
+
69
+ `DexterAccountControl` provides Dexter's account menu: balance, Send and Receive,
70
+ activity, connected apps, account switching, and connection settings. It uses the
71
+ same `useDexterConnection` instance as the app. The panel includes its brand marks,
72
+ styles, and motion; it inherits the host font and respects reduced motion.
73
+
74
+ ```tsx
75
+ import { DexterAccountControl, type UseDexterConnection } from '@dexterai/connect/react';
76
+
77
+ export function AccountEntry({ connection }: { connection: UseDexterConnection }) {
78
+ return <DexterAccountControl connection={connection} />;
79
+ }
80
+ ```
81
+
82
+ The panel reads the selected account's portfolio while open. Partial pricing is
83
+ labeled Priced assets. A failed read displays Balance unavailable; switching
84
+ accounts clears the previous balance immediately. Wallet holdings are bound to
85
+ `receiveAddress`, the asset address. `walletAddress` identifies the Swig control
86
+ account and must not be used to match a portfolio.
87
+
88
+ Destinations open Dexter by default and carry the selected account. Dexter asks
89
+ for confirmation if a different account is active there. `connection.connect({ userHandle })`
90
+ targets that account's saved credential when available and checks the returned account
91
+ before changing sessions. A device without that saved credential uses its passkey picker.
92
+ Set `navigation` to use local app routes,
93
+ or set an entry to `false` to hide it. `items` adds app-specific destinations with
94
+ `requires: 'account'` or `requires: 'wallet'`; only verified access exposes them.
95
+ The destination itself must enforce its own authorization.
96
+
97
+ ```tsx
98
+ <DexterAccountControl
99
+ connection={connection}
100
+ navigation={{
101
+ money: { href: '/money' },
102
+ activity: { href: '/activity' },
103
+ profile: false,
104
+ }}
105
+ items={[{ id: 'seller', label: 'Your servers', href: '/servers', requires: 'account' }]}
106
+ />
107
+ ```
108
+
109
+ `open` and `onOpenChange` optionally coordinate the panel with site navigation.
110
+ `LinkComponent` accepts an app router's anchor adapter. `profile` supplies a name
111
+ and email, shown only after account access is verified. For an existing portfolio
112
+ reader, `renderSummary` can render `DexterAccountSummary` with its bound result,
113
+ avoid a second read, and keep the shared presentation. `--dx-account-font` sets
114
+ the panel font; `styleNonce` supports a site's inline-style policy.
115
+
116
+ Device removal belongs in account management and is absent from this menu.
117
+
49
118
  ## Canonical React integration
50
119
 
51
120
  `useDexterConnection` is the controlled integration for a product header,
@@ -211,6 +280,31 @@ Dexter API while preserving provisional Wallet results for the opener. The root
211
280
  package continues to expose the complete identity transition rather than its
212
281
  private login and browser-roster steps.
213
282
 
283
+ ### Repair a missing Vault record
284
+
285
+ Connect 0.31.0 includes `recoverMissingVaultForAccount`. Update older installations
286
+ to use this recovery helper alongside the account panel.
287
+
288
+ Use this only after the API reports `vault_not_found` for an existing account.
289
+ The account holder must sign in to that same account again before starting the
290
+ repair.
291
+
292
+ ```ts
293
+ import { recoverMissingVaultForAccount } from '@dexterai/connect';
294
+
295
+ const result = await recoverMissingVaultForAccount({
296
+ accountAccessToken: session.access_token,
297
+ });
298
+
299
+ result.account.handle; // the X account confirmed by the API
300
+ result.vault.vaultPda; // the Vault attached to that account
301
+ ```
302
+
303
+ The passkey prompt runs in the pinned `dexter.cash` window. The account token
304
+ stays in the calling app. A successful repair attaches the missing Vault to the
305
+ account already signed in; it does not create an account, mint a new session, or
306
+ change the browser's active Wallet.
307
+
214
308
  ## Server verification
215
309
 
216
310
  ```ts
@@ -278,3 +372,29 @@ The server entry depends only on `jose`.
278
372
  ## License
279
373
 
280
374
  MIT
375
+
376
+ ### Private wallet activity
377
+
378
+ Use the retained proof from the existing passkey ceremony for wallet activity and
379
+ owner-operation status. The proof identifies the wallet; the server still verifies
380
+ an exact operation assertion before any financial action. The request helper keeps
381
+ proof material inside the SDK and only sends it to the canonical Dexter API.
382
+
383
+ ```ts
384
+ import { fetchWithWalletIdentity, walletProofSessionStore } from '@dexterai/connect';
385
+
386
+ const activeWallet = { userHandle, vaultPda };
387
+ const wallet = walletProofSessionStore.bindingCandidate(userHandle, activeWallet);
388
+ if (wallet) {
389
+ const response = await fetchWithWalletIdentity({
390
+ wallet,
391
+ activeWallet,
392
+ url: `/api/passkey-vault-anon/activity/v4?user_handle=${userHandle}`,
393
+ });
394
+ }
395
+ ```
396
+
397
+ Older device records can save `walletIdentityProof` returned after their normal
398
+ verified owner-operation claim using `walletProofSessionStore.save(userHandle,
399
+ walletIdentityProof)`. Preparation and the exact claim do not require a second
400
+ passkey ceremony. A missing or expired proof does not authorize private reads.
@@ -2,20 +2,134 @@ import {
2
2
  ConnectError,
3
3
  activateRecoveredVault,
4
4
  classifyWebAuthnRejection,
5
+ clearPendingCreation,
5
6
  immediateAuthentication,
6
7
  immediateGetSupported,
8
+ normalizeMissingVaultRecoveryOptions,
7
9
  openCeremonyPopup,
10
+ parseMissingVaultRecoveryChallenge,
11
+ parseMissingVaultRecoveryResult,
8
12
  parseWalletIdentityProof,
9
13
  primeImmediateSupport,
10
14
  readErrorCode,
11
15
  resolveDexterApiBase,
16
+ resolveDexterConnectHost,
12
17
  resolveDexterRpId,
13
18
  resolveWalletStoreMode,
14
- shouldUsePopup
15
- } from "./chunk-CZL7NGVV.js";
19
+ shouldUsePopup,
20
+ validateMissingVaultRecoveryAssertion
21
+ } from "./chunk-IPEINLMT.js";
22
+
23
+ // src/missingVaultRecovery.ts
24
+ import {
25
+ startAuthentication
26
+ } from "@simplewebauthn/browser";
27
+ var RECOVERY_PATH = "/api/passkey-vault/recover-missing";
28
+ var INDEXTER_RECOVERY_ORIGIN = "https://indexter.cash";
29
+ async function recoverMissingVaultForAccount(config) {
30
+ requireIndexterRecoveryOpener();
31
+ const apiBase = resolveDexterApiBase(config.apiBase);
32
+ const connectHost = resolveDexterConnectHost(config.connectHost);
33
+ const accountAccessToken = requireAccountAccessToken(config.accountAccessToken);
34
+ let expectedRequest;
35
+ const popupResult = await openCeremonyPopup(
36
+ "recover-missing-vault",
37
+ {
38
+ connectHost,
39
+ missingVaultRecoveryRequest: async () => {
40
+ expectedRequest = await fetchRecoveryChallenge(apiBase, accountAccessToken);
41
+ return expectedRequest;
42
+ }
43
+ }
44
+ );
45
+ if (!expectedRequest) {
46
+ throw new ConnectError("missing_vault_recovery_challenge_missing");
47
+ }
48
+ const credential = await validateMissingVaultRecoveryAssertion(
49
+ popupResult,
50
+ expectedRequest.options.challenge
51
+ );
52
+ return completeRecovery(
53
+ apiBase,
54
+ accountAccessToken,
55
+ credential,
56
+ expectedRequest.account
57
+ );
58
+ }
59
+ function requireIndexterRecoveryOpener() {
60
+ if (typeof window === "undefined") {
61
+ throw new ConnectError(
62
+ "not_browser",
63
+ "missing Vault recovery requires the Indexter browser session"
64
+ );
65
+ }
66
+ if (window.location.origin !== INDEXTER_RECOVERY_ORIGIN) {
67
+ throw new ConnectError(
68
+ "untrusted_missing_vault_recovery_opener",
69
+ "missing Vault recovery is restricted to Indexter"
70
+ );
71
+ }
72
+ }
73
+ async function runHostedMissingVaultRecoveryProof(options) {
74
+ const normalized = normalizeMissingVaultRecoveryOptions(options);
75
+ let credential;
76
+ try {
77
+ credential = await startAuthentication({ optionsJSON: normalized });
78
+ } catch (err) {
79
+ throw new ConnectError(
80
+ "webauthn_failed",
81
+ err instanceof Error ? err.message : String(err)
82
+ );
83
+ }
84
+ return validateMissingVaultRecoveryAssertion(credential, normalized.challenge);
85
+ }
86
+ async function fetchRecoveryChallenge(apiBase, accountAccessToken) {
87
+ const res = await fetch(`${apiBase}${RECOVERY_PATH}/challenge`, {
88
+ method: "POST",
89
+ headers: {
90
+ authorization: `Bearer ${accountAccessToken}`,
91
+ "content-type": "application/json"
92
+ },
93
+ body: "{}"
94
+ });
95
+ if (!res.ok) {
96
+ throw new ConnectError(
97
+ await readErrorCode(res),
98
+ `missing Vault recovery challenge ${res.status}`
99
+ );
100
+ }
101
+ return parseMissingVaultRecoveryChallenge(await res.json());
102
+ }
103
+ async function completeRecovery(apiBase, accountAccessToken, credential, expectedAccount) {
104
+ const res = await fetch(`${apiBase}${RECOVERY_PATH}/complete`, {
105
+ method: "POST",
106
+ headers: {
107
+ authorization: `Bearer ${accountAccessToken}`,
108
+ "content-type": "application/json"
109
+ },
110
+ body: JSON.stringify({ credential })
111
+ });
112
+ if (!res.ok) {
113
+ throw new ConnectError(
114
+ await readErrorCode(res),
115
+ `missing Vault recovery completion ${res.status}`
116
+ );
117
+ }
118
+ return parseMissingVaultRecoveryResult(
119
+ await res.json(),
120
+ credential,
121
+ expectedAccount
122
+ );
123
+ }
124
+ function requireAccountAccessToken(value) {
125
+ if (typeof value !== "string" || value.length < 16 || value.length > 16384 || /\s/.test(value)) {
126
+ throw new ConnectError("missing_account_session");
127
+ }
128
+ return value;
129
+ }
16
130
 
17
131
  // src/recover.ts
18
- import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
132
+ import { startAuthentication as startAuthentication2, browserSupportsWebAuthn } from "@simplewebauthn/browser";
19
133
  var ANON_SIGN_BASE = "/api/passkey-anon/sign";
20
134
  primeImmediateSupport();
21
135
  async function recoverWallet(config = {}) {
@@ -106,7 +220,7 @@ async function recoverWallet(config = {}) {
106
220
  const useImmediate = Boolean(config.preferImmediate) && await immediateGetSupported();
107
221
  let credential;
108
222
  try {
109
- credential = useImmediate ? await immediateAuthentication(options) : await startAuthentication({ optionsJSON: options });
223
+ credential = useImmediate ? await immediateAuthentication(options) : await startAuthentication2({ optionsJSON: options });
110
224
  } catch (err) {
111
225
  if (classifyWebAuthnRejection(err)) {
112
226
  return { ok: false, reason: useImmediate ? "no_credential" : "cancelled" };
@@ -130,6 +244,9 @@ async function recoverWallet(config = {}) {
130
244
  if (res.status === 404) return { ok: false, reason: "no_credential" };
131
245
  if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
132
246
  const data = await res.json();
247
+ if (data.verified !== true || data.credentialId !== credential.id || typeof data.userHandle !== "string" || !data.userHandle) {
248
+ throw new ConnectError("recover_verify_malformed");
249
+ }
133
250
  userHandle = data.userHandle;
134
251
  credentialId = data.credentialId;
135
252
  walletIdentityProof = parseWalletIdentityProof(data.walletIdentityProof);
@@ -144,10 +261,23 @@ async function recoverWallet(config = {}) {
144
261
  if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
145
262
  const data = await res.json();
146
263
  if (!data.hasVault || !data.vault) {
147
- return {
148
- ok: false,
149
- reason: "error",
150
- error: new ConnectError("vault_not_found", "this sign-in key has no wallet attached")
264
+ const initialized = await fetch(`${apiBase}/api/passkey-vault-anon/initialize`, {
265
+ method: "POST",
266
+ headers: {
267
+ "content-type": "application/json",
268
+ authorization: `Bearer ${walletIdentityProof.token}`
269
+ },
270
+ body: JSON.stringify({ userHandle, credentialId })
271
+ });
272
+ if (!initialized.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(initialized)) };
273
+ const created = await initialized.json();
274
+ if (!created.vaultPda || !created.swigStateAddress) throw new ConnectError("initialize_malformed");
275
+ data.vault = {
276
+ vaultPda: created.vaultPda,
277
+ swigAddress: created.swigStateAddress,
278
+ receiveAddress: created.receiveAddress ?? null,
279
+ walletLabel: created.walletLabel ?? null,
280
+ isActivated: false
151
281
  };
152
282
  }
153
283
  vault = {
@@ -168,6 +298,7 @@ async function recoverWallet(config = {}) {
168
298
  walletIdentityProof
169
299
  );
170
300
  }
301
+ clearPendingCreation(credentialId);
171
302
  return { ok: true, userHandle, credentialId, vault, walletIdentityProof };
172
303
  }
173
304
  function netError(code, err) {
@@ -179,5 +310,7 @@ function netError(code, err) {
179
310
  }
180
311
 
181
312
  export {
313
+ recoverMissingVaultForAccount,
314
+ runHostedMissingVaultRecoveryProof,
182
315
  recoverWallet
183
316
  };