@dexterai/connect 0.25.2 → 0.26.3

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
@@ -41,7 +41,7 @@ npm install @dexterai/connect @dexterai/vault react
41
41
  ```
42
42
 
43
43
  `@solana/web3.js` and `@worldcoin/idkit` are optional peers: the first for
44
- agent-spend signing, the second only if you use the World ID button.
44
+ passkey and agent-spend signing, the second only if you use the World ID button.
45
45
 
46
46
  ## Quick start
47
47
 
@@ -67,9 +67,27 @@ the wallet chip: address plus **"$X.XX available."**
67
67
 
68
68
  The ceremony is not limited to dexter.cash. On a foreign origin, `passkeyLogin`
69
69
  opens a hosted popup on `dexter.cash/connect`, runs the ceremony there, and
70
- posts the result back to your page (origin-checked and nonce-bound on both
71
- sides). The default `transport: 'auto'` picks the right mode; `'popup'` and
72
- `'inline'` force it.
70
+ posts the result back to your page. A browser-stamped hello/ack binds the exact
71
+ popup window, hosted origin, caller origin, request nonce, and requested
72
+ operation; the caller-origin may be any HTTPS website and is not allowlisted.
73
+ The default `transport: 'auto'` picks the right mode; `'popup'` and `'inline'`
74
+ force it.
75
+
76
+ The connected `passkeySigner.signOperation(rawOperation)` follows the same
77
+ cross-origin rule. On an unrelated website it opens the pinned Dexter consent
78
+ window and sends the raw operation plus the selected vault identity only after
79
+ the exact hello/ack handshake. Those bytes are structured-cloned in a
80
+ `sign-request`; they are never put in the URL. The Dexter window displays the
81
+ requesting origin and operation-specific consent before returning the
82
+ on-chain-ready assertion bytes.
83
+
84
+ WebAuthn challenge and verification calls are pinned to
85
+ `https://api.dexter.cash`. The legacy `apiBase` option remains source-compatible
86
+ only for that exact value (an optional trailing slash is normalized); any other
87
+ server fails before a popup, fetch, or authenticator call. `apiBase` is never
88
+ placed in the hosted popup URL. The legacy `connectHost` option is likewise
89
+ compatibility-only and may name only `https://dexter.cash/connect`; this pins
90
+ the credential-handling window without restricting the embedding website.
73
91
 
74
92
  ```ts
75
93
  import { passkeyLogin } from '@dexterai/connect';
@@ -77,6 +95,34 @@ import { passkeyLogin } from '@dexterai/connect';
77
95
  const { session, vault } = await passkeyLogin({ transport: 'auto' });
78
96
  ```
79
97
 
98
+ By default, a successful sign-in immediately makes its wallet active in the
99
+ browser wallet store, preserving existing behavior. A flow that must finish a
100
+ separate account-level approval can instead keep the result provisional:
101
+
102
+ ```ts
103
+ import { passkeyLogin, setActiveHandle } from '@dexterai/connect';
104
+
105
+ const result = await passkeyLogin({
106
+ transport: 'auto',
107
+ walletStore: 'provisional',
108
+ });
109
+
110
+ // Only after your approval has bound this exact wallet to the account:
111
+ if (result.vault) {
112
+ setActiveHandle(
113
+ result.vault.userHandle,
114
+ result.vault.walletLabel ?? undefined,
115
+ result.vault.credentialId,
116
+ );
117
+ }
118
+ ```
119
+
120
+ `provisional` suppresses both active-handle and wallet-roster writes on the
121
+ hosted Dexter origin and the calling origin. It does not weaken passkey
122
+ verification or persist a second identity. `recoverWallet` accepts the same
123
+ option. The only supported modes are exact `commit` and `provisional`; omitted
124
+ means `commit`.
125
+
80
126
  ## Verify the session on your server
81
127
 
82
128
  ```ts
@@ -209,8 +255,8 @@ React: `<SignInWithDexter mode="recover" preferImmediate onRecovered={…} />`
209
255
  | Peer | Required | Why |
210
256
  |---|---|---|
211
257
  | `react` >=18 | yes | the `/react` and `/worldid` surfaces |
212
- | `@dexterai/vault` >=0.30 | yes | signer + agent-spend message builders (0.30 matches the deployed program's account layout) |
213
- | `@solana/web3.js` | optional | agent-spend signing paths |
258
+ | `@dexterai/vault` ^0.43 | yes | hardened signer envelope validation + agent-spend message builders |
259
+ | `@solana/web3.js` | optional | passkey and agent-spend signing paths |
214
260
  | `@worldcoin/idkit` | optional | only for `/worldid` |
215
261
 
216
262
  The `/server` entry has none of these peers; it depends only on `jose`.
@@ -1,4 +1,12 @@
1
1
  // src/types.ts
2
+ function resolveWalletStoreMode(mode) {
3
+ if (mode === void 0 || mode === "commit") return "commit";
4
+ if (mode === "provisional") return "provisional";
5
+ throw new ConnectError(
6
+ "invalid_wallet_store_mode",
7
+ "walletStore must be exactly commit or provisional"
8
+ );
9
+ }
2
10
  var ConnectError = class extends Error {
3
11
  code;
4
12
  constructor(code, message) {
@@ -145,8 +153,40 @@ function authoredPolicy(usdInput) {
145
153
  // src/enroll.ts
146
154
  import { startRegistration } from "@simplewebauthn/browser";
147
155
 
156
+ // src/trust.ts
157
+ var DEXTER_API_BASE = "https://api.dexter.cash";
158
+ var DEXTER_CONNECT_HOST = "https://dexter.cash/connect";
159
+ var DEXTER_RP_ID = "dexter.cash";
160
+ function resolveDexterApiBase(apiBase) {
161
+ if (apiBase === void 0 || typeof apiBase === "string" && apiBase.replace(/\/+$/, "") === DEXTER_API_BASE) {
162
+ return DEXTER_API_BASE;
163
+ }
164
+ throw new ConnectError(
165
+ "untrusted_api_base",
166
+ `Dexter WebAuthn is pinned to ${DEXTER_API_BASE}`
167
+ );
168
+ }
169
+ function resolveDexterConnectHost(connectHost) {
170
+ if (connectHost === void 0 || typeof connectHost === "string" && connectHost.replace(/\/+$/, "") === DEXTER_CONNECT_HOST) {
171
+ return DEXTER_CONNECT_HOST;
172
+ }
173
+ throw new ConnectError(
174
+ "untrusted_connect_host",
175
+ `Dexter WebAuthn ceremonies are pinned to ${DEXTER_CONNECT_HOST}`
176
+ );
177
+ }
178
+ function resolveDexterRpId(rpId) {
179
+ if (rpId === void 0 || rpId === DEXTER_RP_ID) return DEXTER_RP_ID;
180
+ throw new ConnectError("untrusted_rp_id", `Dexter WebAuthn is pinned to ${DEXTER_RP_ID}`);
181
+ }
182
+ function bytesEqual(a, b) {
183
+ if (a.byteLength !== b.byteLength) return false;
184
+ let difference = 0;
185
+ for (let i = 0; i < a.byteLength; i += 1) difference |= a[i] ^ b[i];
186
+ return difference === 0;
187
+ }
188
+
148
189
  // src/popup.ts
149
- var DEFAULT_CONNECT_HOST = "https://dexter.cash/connect";
150
190
  var POPUP_TIMEOUT_MS = 12e4;
151
191
  var CANONICAL_ORIGIN = "https://dexter.cash";
152
192
  function shouldUsePopup(transport) {
@@ -159,14 +199,16 @@ function openCeremonyPopup(op, config = {}) {
159
199
  if (typeof window === "undefined") {
160
200
  return Promise.reject(new ConnectError("not_browser", "popup ceremony requires a browser"));
161
201
  }
162
- const host = (config.connectHost ?? DEFAULT_CONNECT_HOST).replace(/\/$/, "");
202
+ const host = resolveDexterConnectHost(config.connectHost);
163
203
  const hostOrigin = new URL(host).origin;
164
204
  const openerOrigin = window.location.origin;
165
205
  const requestId = makeNonce();
206
+ const signRequest = snapshotSignRequest(op, config.signRequest);
207
+ const walletStore = resolveWalletStoreMode(config.walletStore);
166
208
  const params = new URLSearchParams({ v: "1", op, requestId, origin: openerOrigin });
167
209
  if (config.name) params.set("name", config.name);
168
- if (config.apiBase) params.set("apiBase", config.apiBase);
169
210
  if (config.preferImmediate) params.set("preferImmediate", "1");
211
+ if (walletStore === "provisional") params.set("walletStore", "provisional");
170
212
  const url = `${host}?${params.toString()}`;
171
213
  return new Promise((resolve, reject) => {
172
214
  const popup = window.open(url, "dexter-connect", popupFeatures());
@@ -177,10 +219,46 @@ function openCeremonyPopup(op, config = {}) {
177
219
  return;
178
220
  }
179
221
  let settled = false;
222
+ let handshakeComplete = false;
180
223
  const onMessage = (event) => {
181
224
  if (event.origin !== hostOrigin) return;
225
+ if (event.source !== popup) return;
182
226
  const data = event.data;
183
- if (!data || data.type !== "dexter-connect:result" || data.requestId !== requestId) return;
227
+ if (!data || data.v !== 1 || data.requestId !== requestId || data.op !== op) return;
228
+ if (data.type === "dexter-connect:hello") {
229
+ if (handshakeComplete) return;
230
+ const ack = {
231
+ v: 1,
232
+ type: "dexter-connect:hello-ack",
233
+ requestId,
234
+ op
235
+ };
236
+ try {
237
+ popup.postMessage(ack, event.origin);
238
+ if (signRequest) {
239
+ const request = {
240
+ v: 1,
241
+ type: "dexter-connect:sign-request",
242
+ requestId,
243
+ op: "sign",
244
+ payload: signRequest
245
+ };
246
+ popup.postMessage(request, event.origin);
247
+ }
248
+ handshakeComplete = true;
249
+ } catch (err) {
250
+ finish(
251
+ () => reject(
252
+ new ConnectError(
253
+ "popup_handshake_failed",
254
+ err instanceof Error ? err.message : String(err)
255
+ )
256
+ )
257
+ );
258
+ }
259
+ return;
260
+ }
261
+ if (data.type !== "dexter-connect:result" || !handshakeComplete) return;
184
262
  if (data.ok) finish(() => resolve(data.result));
185
263
  else
186
264
  finish(
@@ -209,6 +287,47 @@ function openCeremonyPopup(op, config = {}) {
209
287
  window.addEventListener("message", onMessage);
210
288
  });
211
289
  }
290
+ function snapshotSignRequest(op, request) {
291
+ if (op !== "sign") {
292
+ if (request !== void 0) {
293
+ throw new ConnectError("unexpected_sign_request", "sign payload requires op=sign");
294
+ }
295
+ return void 0;
296
+ }
297
+ if (!request || !(request.operationMessage instanceof Uint8Array) || request.operationMessage.length === 0 || request.operationMessage.length > 4096) {
298
+ throw new ConnectError("missing_sign_request", "hosted signing requires raw operation bytes");
299
+ }
300
+ if (isAccountProofOperation(request.operationMessage)) {
301
+ throw new ConnectError(
302
+ "unsupported_operation",
303
+ "account-claim proofs cannot be requested by a third-party website"
304
+ );
305
+ }
306
+ const vault = request.vault;
307
+ if (!vault || !vault.vaultPda || !vault.publicKey || !vault.userHandle || !vault.credentialId) {
308
+ throw new ConnectError("invalid_sign_identity", "hosted signing requires a complete vault identity");
309
+ }
310
+ return {
311
+ // Snapshot before opening the window so caller mutation cannot change what
312
+ // the user sees/signs after the ceremony begins.
313
+ operationMessage: new Uint8Array(request.operationMessage),
314
+ vault: {
315
+ vaultPda: vault.vaultPda,
316
+ publicKey: vault.publicKey,
317
+ userHandle: vault.userHandle,
318
+ credentialId: vault.credentialId,
319
+ ...vault.walletLabel !== void 0 ? { walletLabel: vault.walletLabel } : {}
320
+ }
321
+ };
322
+ }
323
+ function isAccountProofOperation(operation) {
324
+ const prefix = new TextEncoder().encode("siwx_login");
325
+ if (operation.length !== prefix.length + 32) return false;
326
+ for (let i = 0; i < prefix.length; i += 1) {
327
+ if (operation[i] !== prefix[i]) return false;
328
+ }
329
+ return true;
330
+ }
212
331
  function popupFeatures() {
213
332
  const w = 420;
214
333
  const h = 660;
@@ -242,15 +361,14 @@ async function readErrorCode(res) {
242
361
  }
243
362
 
244
363
  // src/enroll.ts
245
- var DEFAULT_API_BASE = "https://api.dexter.cash";
246
- var DEFAULT_RP_ID = "dexter.cash";
247
364
  var DEFAULT_WALLET_NAME = "Dexter Wallet";
248
365
  async function createWallet(config = {}) {
366
+ const apiBase = resolveDexterApiBase(config.apiBase);
367
+ resolveDexterRpId(config.rpId);
249
368
  if (shouldUsePopup(config.transport)) {
250
369
  const result = await openCeremonyPopup("create", {
251
370
  connectHost: config.connectHost,
252
- name: config.name,
253
- apiBase: config.apiBase
371
+ name: config.name
254
372
  });
255
373
  setActiveHandle(result.handle, result.label ?? config.name, result.credentialId);
256
374
  return result;
@@ -258,15 +376,13 @@ async function createWallet(config = {}) {
258
376
  if (typeof navigator === "undefined" || !navigator.credentials) {
259
377
  throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
260
378
  }
261
- const apiBase = (config.apiBase ?? DEFAULT_API_BASE).replace(/\/$/, "");
262
- const rpId = config.rpId ?? DEFAULT_RP_ID;
263
379
  const name = config.name && config.name.trim() || DEFAULT_WALLET_NAME;
264
380
  config.onPhase?.("challenge");
265
381
  const options = await fetchEnrollChallenge(apiBase);
266
382
  config.onPhase?.("passkey");
267
383
  const optionsJSON = {
268
384
  ...options,
269
- rp: { ...options.rp, id: options.rp.id ?? rpId, name: "Dexter" },
385
+ rp: { ...options.rp, id: DEXTER_RP_ID, name: "Dexter" },
270
386
  user: { ...options.user, name, displayName: name }
271
387
  };
272
388
  let regResponse;
@@ -316,6 +432,7 @@ async function fetchEnrollChallenge(apiBase) {
316
432
  if (!data?.options?.challenge) {
317
433
  throw new ConnectError("enroll_challenge_malformed", "no creation options in response");
318
434
  }
435
+ resolveDexterRpId(data.options.rp?.id);
319
436
  return data.options;
320
437
  }
321
438
  async function submitEnrollComplete(apiBase, response) {
@@ -366,10 +483,6 @@ function bytesToBase64(bytes) {
366
483
  function bytesToBase64url(bytes) {
367
484
  return bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
368
485
  }
369
- function base64urlToBase64(s) {
370
- const t = s.replace(/-/g, "+").replace(/_/g, "/");
371
- return t + "=".repeat((4 - t.length % 4) % 4);
372
- }
373
486
  function compactSignatureToDer(compact) {
374
487
  if (compact.length !== 64) {
375
488
  throw new Error(`expected 64-byte compact signature, got ${compact.length}`);
@@ -463,16 +576,17 @@ function classifyWebAuthnRejection(err) {
463
576
  }
464
577
 
465
578
  // src/relay.ts
466
- var DEFAULT_API_BASE2 = "https://api.dexter.cash";
467
579
  var ANON_SIGN_BASE = "/api/passkey-anon/sign";
468
580
  primeImmediateSupport();
469
581
  async function passkeyLogin(config = {}, onPhase) {
582
+ const apiBase = resolveDexterApiBase(config.apiBase);
583
+ const walletStore = resolveWalletStoreMode(config.walletStore);
470
584
  if (shouldUsePopup(config.transport)) {
471
585
  const result2 = await openCeremonyPopup("signin", {
472
586
  connectHost: config.connectHost,
473
- apiBase: config.apiBase
587
+ ...walletStore === "provisional" ? { walletStore } : {}
474
588
  });
475
- if (result2.vault) {
589
+ if (walletStore === "commit" && result2.vault) {
476
590
  setActiveHandle(result2.vault.userHandle, result2.vault.walletLabel ?? void 0, result2.vault.credentialId);
477
591
  }
478
592
  return result2;
@@ -480,7 +594,6 @@ async function passkeyLogin(config = {}, onPhase) {
480
594
  if (!browserSupportsWebAuthn()) {
481
595
  throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
482
596
  }
483
- const apiBase = (config.apiBase ?? DEFAULT_API_BASE2).replace(/\/$/, "");
484
597
  onPhase?.("challenge");
485
598
  const options = await fetchLoginChallenge(apiBase);
486
599
  onPhase?.("passkey");
@@ -492,17 +605,17 @@ async function passkeyLogin(config = {}, onPhase) {
492
605
  }
493
606
  onPhase?.("verifying");
494
607
  const result = await submitLogin(apiBase, response);
495
- if (result.vault) {
608
+ if (walletStore === "commit" && result.vault) {
496
609
  setActiveHandle(result.vault.userHandle, result.vault.walletLabel ?? void 0, result.vault.credentialId);
497
610
  }
498
611
  return result;
499
612
  }
500
613
  async function continueWithDexter(config = {}, onPhase) {
614
+ resolveDexterApiBase(config.apiBase);
501
615
  if (shouldUsePopup(config.transport)) {
502
616
  const result = await openCeremonyPopup("continue", {
503
617
  connectHost: config.connectHost,
504
- name: config.name,
505
- apiBase: config.apiBase
618
+ name: config.name
506
619
  });
507
620
  if (result.kind === "create") {
508
621
  setActiveHandle(result.handle, result.label ?? config.name, result.credentialId);
@@ -526,7 +639,7 @@ async function continueWithDexter(config = {}, onPhase) {
526
639
  return { kind: "needs_choice" };
527
640
  }
528
641
  async function immediatePasskeyLogin(config, onPhase) {
529
- const apiBase = (config.apiBase ?? DEFAULT_API_BASE2).replace(/\/$/, "");
642
+ const apiBase = resolveDexterApiBase(config.apiBase);
530
643
  onPhase?.("challenge");
531
644
  const options = await fetchLoginChallenge(apiBase);
532
645
  onPhase?.("passkey");
@@ -563,7 +676,7 @@ async function fetchLoginChallenge(apiBase) {
563
676
  if (!data?.options?.challenge) {
564
677
  throw new ConnectError("login_challenge_malformed", "no challenge in response");
565
678
  }
566
- return data.options;
679
+ return { ...data.options, rpId: resolveDexterRpId(data.options.rpId) };
567
680
  }
568
681
  async function submitLogin(apiBase, response) {
569
682
  const res = await fetch(`${apiBase}${ANON_SIGN_BASE}/passkey-login`, {
@@ -586,18 +699,19 @@ async function submitLogin(apiBase, response) {
586
699
  }
587
700
 
588
701
  // src/anon-policy.ts
589
- var DEFAULT_API_BASE3 = "https://api.dexter.cash";
590
702
  var ANON_SIGN_BASE2 = "/api/passkey-anon/sign";
591
- function createAnonServerPolicy(apiBase = DEFAULT_API_BASE3) {
592
- const base = apiBase.replace(/\/$/, "");
703
+ function createAnonServerPolicy(apiBase) {
704
+ const base = resolveDexterApiBase(apiBase);
593
705
  return {
594
- async issueChallenge({ userHandle, operationHash }) {
706
+ async issueChallenge({ userHandle, operationMessage, operationHash }) {
595
707
  const res = await fetch(`${base}${ANON_SIGN_BASE2}/challenge`, {
596
708
  method: "POST",
597
709
  headers: { "content-type": "application/json" },
598
710
  body: JSON.stringify({
599
711
  userHandle: bytesToBase64url(userHandle),
600
- operationHash: bytesToBase64url(operationHash)
712
+ operationHash: bytesToBase64url(operationHash),
713
+ operationMessage: bytesToBase64url(operationMessage),
714
+ operation: "vault_operation"
601
715
  })
602
716
  });
603
717
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `challenge ${res.status}`);
@@ -606,14 +720,15 @@ function createAnonServerPolicy(apiBase = DEFAULT_API_BASE3) {
606
720
  if (!options?.challenge) {
607
721
  throw new ConnectError("challenge_malformed", "no challenge in response");
608
722
  }
723
+ const challenge = base64urlToBytes(options.challenge);
609
724
  const cred = options.allowCredentials?.[0];
610
725
  if (!cred?.id) {
611
726
  throw new ConnectError("no_credential", "no allow-listed credential for this userHandle");
612
727
  }
613
728
  return {
614
- challenge: base64urlToBytes(options.challenge),
729
+ challenge,
615
730
  credentialId: base64urlToBytes(cred.id),
616
- rpId: options.rpId,
731
+ rpId: resolveDexterRpId(options.rpId),
617
732
  transports: cred.transports
618
733
  };
619
734
  },
@@ -625,7 +740,7 @@ function createAnonServerPolicy(apiBase = DEFAULT_API_BASE3) {
625
740
  response: {
626
741
  clientDataJSON: bytesToBase64url(clientDataJSON),
627
742
  authenticatorData: bytesToBase64url(authenticatorData),
628
- // SDK 0.19 passes the COMPACT sig; dexter-api's verifier wants DER.
743
+ // The SDK passes the COMPACT sig; dexter-api's verifier wants DER.
629
744
  signature: bytesToBase64url(compactSignatureToDer(signature)),
630
745
  userHandle: null
631
746
  },
@@ -639,8 +754,8 @@ function createAnonServerPolicy(apiBase = DEFAULT_API_BASE3) {
639
754
  });
640
755
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `verify ${res.status}`);
641
756
  const data = await res.json();
642
- if (data?.verified === false) {
643
- throw new ConnectError("verification_failed", "server returned verified=false");
757
+ if (data?.verified !== true) {
758
+ throw new ConnectError("verification_failed", "server did not return verified=true");
644
759
  }
645
760
  }
646
761
  };
@@ -648,14 +763,106 @@ function createAnonServerPolicy(apiBase = DEFAULT_API_BASE3) {
648
763
 
649
764
  // src/signer.ts
650
765
  import { DexterApiBrowserPasskeySigner } from "@dexterai/vault/signers/browser";
766
+ import {
767
+ parseStrictCollectedClientData,
768
+ validatePasskeyAuthorizationChallenge
769
+ } from "@dexterai/vault";
770
+ import { PublicKey } from "@solana/web3.js";
771
+ var HostedPopupPasskeySigner = class {
772
+ constructor(vault, expectedVault, connectHost) {
773
+ this.expectedVault = expectedVault;
774
+ this.connectHost = connectHost;
775
+ this.vault = { ...vault };
776
+ this.credentialId = base64urlToBytes(vault.credentialId);
777
+ this.publicKey = base64ToBytes(vault.publicKey);
778
+ }
779
+ expectedVault;
780
+ connectHost;
781
+ credentialId;
782
+ publicKey;
783
+ vault;
784
+ async signOperation(operationMessage) {
785
+ if (!(operationMessage instanceof Uint8Array) || operationMessage.length === 0) {
786
+ throw new ConnectError("invalid_operation", "signOperation requires non-empty bytes");
787
+ }
788
+ const exactOperationMessage = new Uint8Array(operationMessage);
789
+ const result = await openCeremonyPopup("sign", {
790
+ ...this.connectHost ? { connectHost: this.connectHost } : {},
791
+ signRequest: {
792
+ operationMessage: exactOperationMessage,
793
+ vault: {
794
+ vaultPda: this.vault.vaultPda,
795
+ publicKey: this.vault.publicKey,
796
+ userHandle: this.vault.userHandle,
797
+ credentialId: this.vault.credentialId,
798
+ ...this.vault.walletLabel !== void 0 ? { walletLabel: this.vault.walletLabel } : {}
799
+ }
800
+ }
801
+ });
802
+ return validateHostedSignResult(result, exactOperationMessage, this.expectedVault);
803
+ }
804
+ };
651
805
  function createPasskeySigner(vault, apiBase, opts = {}) {
806
+ resolveDexterApiBase(apiBase);
807
+ const expectedVault = new PublicKey(vault.vaultPda);
808
+ if (shouldUsePopup()) {
809
+ return new HostedPopupPasskeySigner(vault, expectedVault, opts.connectHost);
810
+ }
652
811
  return new DexterApiBrowserPasskeySigner({
653
812
  identity: { kind: "guest", userHandle: base64urlToBytes(vault.userHandle) },
654
813
  publicKey: base64ToBytes(vault.publicKey),
655
814
  anonPolicy: createAnonServerPolicy(apiBase),
815
+ // The API resolves the authorization envelope, but this browser still
816
+ // knows which connected vault the caller selected. Pin that exact PDA so a
817
+ // valid Dexter envelope for another vault cannot reach WebAuthn.
818
+ expectedVault,
656
819
  ...opts.__assertion ? { __assertion: opts.__assertion } : {}
657
820
  });
658
821
  }
822
+ async function validateHostedSignResult(result, operationMessage, expectedVault) {
823
+ if (!result || !(result.signature instanceof Uint8Array) || result.signature.length !== 64 || !(result.clientDataJSON instanceof Uint8Array) || result.clientDataJSON.length === 0 || !(result.authenticatorData instanceof Uint8Array) || result.authenticatorData.length < 37) {
824
+ throw new ConnectError("popup_result_malformed", "hosted signer returned malformed assertion bytes");
825
+ }
826
+ let clientData;
827
+ try {
828
+ clientData = parseStrictCollectedClientData(result.clientDataJSON);
829
+ } catch {
830
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid clientDataJSON");
831
+ }
832
+ if (clientData.type !== "webauthn.get" || clientData.origin !== "https://dexter.cash" || clientData.crossOrigin !== false || !/^[A-Za-z0-9_-]+$/.test(clientData.challenge)) {
833
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid WebAuthn client data");
834
+ }
835
+ const expectedRpHash = new Uint8Array(
836
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode("dexter.cash"))
837
+ );
838
+ const flags = result.authenticatorData[32] ?? 0;
839
+ if (!bytesEqual(result.authenticatorData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
840
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid authenticator context");
841
+ }
842
+ let challenge;
843
+ try {
844
+ challenge = base64urlToBytes(clientData.challenge);
845
+ if (bytesToBase64url(challenge) !== clientData.challenge) throw new Error("non-canonical");
846
+ } catch {
847
+ throw new ConnectError("popup_result_malformed", "hosted signer returned an invalid challenge encoding");
848
+ }
849
+ try {
850
+ const operationHash = new Uint8Array(
851
+ await crypto.subtle.digest("SHA-256", new Uint8Array(operationMessage))
852
+ );
853
+ validatePasskeyAuthorizationChallenge({ challenge, operationHash, expectedVault });
854
+ } catch {
855
+ throw new ConnectError(
856
+ "popup_result_unbound",
857
+ "hosted signer returned an assertion for a different operation or vault"
858
+ );
859
+ }
860
+ return {
861
+ signature: new Uint8Array(result.signature),
862
+ clientDataJSON: new Uint8Array(result.clientDataJSON),
863
+ authenticatorData: new Uint8Array(result.authenticatorData)
864
+ };
865
+ }
659
866
 
660
867
  // src/identity.ts
661
868
  function presentOrNull(value) {
@@ -674,24 +881,39 @@ function resolveIdentity(input) {
674
881
 
675
882
  // src/recover.ts
676
883
  import { startAuthentication as startAuthentication2, browserSupportsWebAuthn as browserSupportsWebAuthn2 } from "@simplewebauthn/browser";
677
- var DEFAULT_API_BASE4 = "https://api.dexter.cash";
678
884
  var ANON_SIGN_BASE3 = "/api/passkey-anon/sign";
679
885
  primeImmediateSupport();
680
886
  async function recoverWallet(config = {}) {
887
+ let apiBase;
888
+ let walletStore;
889
+ try {
890
+ apiBase = resolveDexterApiBase(config.apiBase);
891
+ } catch (err) {
892
+ return netError("untrusted_api_base", err);
893
+ }
894
+ try {
895
+ walletStore = resolveWalletStoreMode(config.walletStore);
896
+ } catch (err) {
897
+ return {
898
+ ok: false,
899
+ reason: "error",
900
+ error: err instanceof ConnectError ? err : new ConnectError("invalid_wallet_store_mode")
901
+ };
902
+ }
681
903
  if (shouldUsePopup(config.transport)) {
682
904
  let outcome;
683
905
  try {
684
906
  outcome = await openCeremonyPopup("recover", {
685
907
  connectHost: config.connectHost,
686
- apiBase: config.apiBase,
687
- preferImmediate: config.preferImmediate
908
+ preferImmediate: config.preferImmediate,
909
+ ...walletStore === "provisional" ? { walletStore } : {}
688
910
  });
689
911
  } catch (err) {
690
912
  const ce = err instanceof ConnectError ? err : new ConnectError("popup_failed", err instanceof Error ? err.message : String(err));
691
913
  if (ce.code === "popup_closed") return { ok: false, reason: "cancelled" };
692
914
  return { ok: false, reason: "error", error: ce };
693
915
  }
694
- if (outcome.ok) {
916
+ if (walletStore === "commit" && outcome.ok) {
695
917
  setActiveHandle(outcome.userHandle, outcome.vault.walletLabel ?? void 0, outcome.credentialId);
696
918
  }
697
919
  return outcome;
@@ -703,7 +925,6 @@ async function recoverWallet(config = {}) {
703
925
  error: new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment")
704
926
  };
705
927
  }
706
- const apiBase = (config.apiBase ?? DEFAULT_API_BASE4).replace(/\/$/, "");
707
928
  const onPhase = config.onPhase;
708
929
  onPhase?.("challenge");
709
930
  let options;
@@ -714,8 +935,19 @@ async function recoverWallet(config = {}) {
714
935
  body: "{}"
715
936
  });
716
937
  if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
717
- options = (await res.json()).options;
938
+ const serverOptions = (await res.json()).options;
939
+ if (!serverOptions?.challenge) {
940
+ return {
941
+ ok: false,
942
+ reason: "error",
943
+ error: new ConnectError("recover_challenge_malformed", "no challenge in response")
944
+ };
945
+ }
946
+ options = { ...serverOptions, rpId: resolveDexterRpId(serverOptions.rpId) };
718
947
  } catch (err) {
948
+ if (err instanceof ConnectError && err.code === "untrusted_rp_id") {
949
+ return { ok: false, reason: "error", error: err };
950
+ }
719
951
  return netError("recover_challenge_failed", err);
720
952
  }
721
953
  onPhase?.("passkey");
@@ -774,7 +1006,9 @@ async function recoverWallet(config = {}) {
774
1006
  } catch (err) {
775
1007
  return netError("vault_status_failed", err);
776
1008
  }
777
- setActiveHandle(userHandle, vault.walletLabel ?? void 0, credentialId);
1009
+ if (walletStore === "commit") {
1010
+ setActiveHandle(userHandle, vault.walletLabel ?? void 0, credentialId);
1011
+ }
778
1012
  return { ok: true, userHandle, credentialId, vault };
779
1013
  }
780
1014
  function netError(code, err) {
@@ -858,6 +1092,9 @@ async function syncAcceptedPasskeys(args) {
858
1092
 
859
1093
  export {
860
1094
  ConnectError,
1095
+ resolveDexterApiBase,
1096
+ resolveDexterRpId,
1097
+ bytesEqual,
861
1098
  shouldUsePopup,
862
1099
  getActiveHandle,
863
1100
  setActiveHandle,
@@ -872,8 +1109,9 @@ export {
872
1109
  usdToAtomic,
873
1110
  authoredPolicy,
874
1111
  createWallet,
1112
+ base64urlToBytes,
1113
+ bytesToBase64,
875
1114
  bytesToBase64url,
876
- base64urlToBase64,
877
1115
  passkeyLogin,
878
1116
  continueWithDexter,
879
1117
  createAnonServerPolicy,