@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.
@@ -4,6 +4,11 @@ import {
4
4
  } from "./chunk-EMCGL64H.js";
5
5
 
6
6
  // src/types.ts
7
+ function resolveTargetUserHandle(value) {
8
+ if (value === void 0) return void 0;
9
+ if (typeof value === "string" && /^[A-Za-z0-9_-]{22}$/.test(value)) return value;
10
+ throw new ConnectError("invalid_target_account");
11
+ }
7
12
  function resolveWalletStoreMode(mode) {
8
13
  if (mode === void 0 || mode === "commit") return "commit";
9
14
  if (mode === "provisional") return "provisional";
@@ -132,6 +137,36 @@ function accountBindingCandidate(accessToken) {
132
137
  );
133
138
  return candidate;
134
139
  }
140
+ async function fetchWithWalletIdentity(input) {
141
+ const material = walletBindings.get(input.wallet);
142
+ const active = requireActiveWalletIdentity(input.activeWallet);
143
+ if (!material || material.activeWallet.userHandle !== active.userHandle || material.activeWallet.vaultPda !== active.vaultPda) {
144
+ throw new ConnectError("wallet_identity_mismatch");
145
+ }
146
+ const apiBase = resolveDexterApiBase();
147
+ let url;
148
+ try {
149
+ url = new URL(input.url, apiBase);
150
+ } catch {
151
+ throw new ConnectError("invalid_wallet_request_url");
152
+ }
153
+ if (url.origin !== apiBase || url.username || url.password || url.hash || !url.pathname.startsWith("/api/")) {
154
+ throw new ConnectError("invalid_wallet_request_url");
155
+ }
156
+ const queryHandle = url.searchParams.getAll("user_handle");
157
+ if (queryHandle.length > 1 || queryHandle.length === 1 && queryHandle[0] !== active.userHandle) {
158
+ throw new ConnectError("wallet_identity_mismatch");
159
+ }
160
+ const headers = new Headers(input.init?.headers);
161
+ if (headers.has("authorization") || headers.has("x-dexter-wallet-proof") || headers.has("x-dexter-owner-handle") && headers.get("x-dexter-owner-handle") !== active.userHandle) {
162
+ throw new ConnectError("wallet_identity_mismatch");
163
+ }
164
+ headers.set("X-Dexter-Wallet-Proof", material.identityProof);
165
+ headers.set("X-Dexter-Owner-Handle", active.userHandle);
166
+ const fetchImpl = input.fetch ?? globalFetch();
167
+ if (!fetchImpl) throw new ConnectError("fetch_unavailable");
168
+ return fetchImpl(url.href, { ...input.init, headers, redirect: "error", credentials: "omit" });
169
+ }
135
170
  function isRecord(value) {
136
171
  return typeof value === "object" && value !== null && !Array.isArray(value);
137
172
  }
@@ -328,7 +363,7 @@ function frozenEvent(operation, handle, session) {
328
363
  return Object.freeze({ operation, handle, session });
329
364
  }
330
365
  function createWalletProofSessionStore(options = {}) {
331
- const storage = options.storage === void 0 ? browserStorage() : options.storage;
366
+ const storage2 = options.storage === void 0 ? browserStorage() : options.storage;
332
367
  const eventSource = options.eventSource === void 0 ? options.storage === void 0 ? browserEventSource() : null : options.eventSource;
333
368
  const nowEpochSeconds = options.nowEpochSeconds ?? (() => Date.now() / 1e3);
334
369
  const listeners2 = /* @__PURE__ */ new Set();
@@ -342,9 +377,9 @@ function createWalletProofSessionStore(options = {}) {
342
377
  }
343
378
  };
344
379
  const safeRemove = (key) => {
345
- if (!storage) return false;
380
+ if (!storage2) return false;
346
381
  try {
347
- storage.removeItem(key);
382
+ storage2.removeItem(key);
348
383
  return true;
349
384
  } catch {
350
385
  return false;
@@ -352,11 +387,11 @@ function createWalletProofSessionStore(options = {}) {
352
387
  };
353
388
  const load = (handleValue) => {
354
389
  const handle = requireWalletHandle(handleValue);
355
- if (!storage) return null;
390
+ if (!storage2) return null;
356
391
  const key = keyForHandle(handle);
357
392
  let raw;
358
393
  try {
359
- raw = storage.getItem(key);
394
+ raw = storage2.getItem(key);
360
395
  } catch {
361
396
  return null;
362
397
  }
@@ -376,11 +411,11 @@ function createWalletProofSessionStore(options = {}) {
376
411
  };
377
412
  const clear = (handleValue) => {
378
413
  const handle = requireWalletHandle(handleValue);
379
- if (!storage) return false;
414
+ if (!storage2) return false;
380
415
  const key = keyForHandle(handle);
381
416
  let existed = false;
382
417
  try {
383
- existed = storage.getItem(key) !== null;
418
+ existed = storage2.getItem(key) !== null;
384
419
  } catch {
385
420
  return false;
386
421
  }
@@ -394,14 +429,14 @@ function createWalletProofSessionStore(options = {}) {
394
429
  if (parsed.expiresAt <= nowEpochSeconds()) {
395
430
  throw new ConnectError("wallet_identity_proof_expired");
396
431
  }
397
- if (!storage) return null;
432
+ if (!storage2) return null;
398
433
  const record = {
399
434
  v: STORAGE_VERSION,
400
435
  proof: parsed.token,
401
436
  expiresAt: parsed.expiresAt
402
437
  };
403
438
  try {
404
- storage.setItem(keyForHandle(handle), JSON.stringify(record));
439
+ storage2.setItem(keyForHandle(handle), JSON.stringify(record));
405
440
  } catch {
406
441
  return null;
407
442
  }
@@ -425,7 +460,7 @@ function createWalletProofSessionStore(options = {}) {
425
460
  return false;
426
461
  };
427
462
  const onStorage = (event) => {
428
- if (event.storageArea && storage && event.storageArea !== storage) return;
463
+ if (event.storageArea && storage2 && event.storageArea !== storage2) return;
429
464
  if (event.key === null) {
430
465
  publish(frozenEvent("external", null, null));
431
466
  return;
@@ -488,7 +523,7 @@ function authoredPolicy(usdInput) {
488
523
  }
489
524
 
490
525
  // src/enroll.ts
491
- import { startRegistration } from "@simplewebauthn/browser";
526
+ import { startRegistration, startAuthentication } from "@simplewebauthn/browser";
492
527
 
493
528
  // src/walletStore.ts
494
529
  var ACTIVE_HANDLE_KEY = "dexter:passkey:userHandle";
@@ -667,6 +702,9 @@ function setActiveWallet(wallet) {
667
702
  function setActiveHandle(handle, label, credentialId) {
668
703
  activateWallet({ handle, label, credentialId });
669
704
  }
705
+ function getCredentialId(handle) {
706
+ return readRoster().find((wallet) => wallet.handle === handle)?.credentialId;
707
+ }
670
708
  function disconnectActiveWallet() {
671
709
  if (!hasStorage()) return false;
672
710
  const previousActiveWallet = getActiveWallet();
@@ -760,6 +798,207 @@ function activateRecoveredVault(userHandle, credentialId, vault, walletIdentityP
760
798
  return activated;
761
799
  }
762
800
 
801
+ // src/missingVaultRecoveryContract.ts
802
+ var DEXTER_ORIGIN = "https://dexter.cash";
803
+ var MIN_CHALLENGE_BYTES = 16;
804
+ var MAX_CHALLENGE_BYTES = 128;
805
+ function normalizeMissingVaultRecoveryOptions(value) {
806
+ if (!value || typeof value !== "object") {
807
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
808
+ }
809
+ const options = value;
810
+ const challenge = canonicalBase64url(
811
+ options.challenge,
812
+ MIN_CHALLENGE_BYTES,
813
+ MAX_CHALLENGE_BYTES,
814
+ "missing_vault_recovery_challenge_malformed"
815
+ );
816
+ const challengeBytes = base64urlToBytes(challenge);
817
+ if (challengeBytes.byteLength < MIN_CHALLENGE_BYTES || challengeBytes.byteLength > MAX_CHALLENGE_BYTES || options.rpId !== DEXTER_RP_ID || options.userVerification !== "required" || options.allowCredentials !== void 0 || options.extensions !== void 0 && (!isPlainObject(options.extensions) || Object.keys(options.extensions).length !== 0)) {
818
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
819
+ }
820
+ if (options.timeout !== void 0 && (typeof options.timeout !== "number" || !Number.isFinite(options.timeout) || options.timeout <= 0 || options.timeout > 3e5)) {
821
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
822
+ }
823
+ return {
824
+ challenge,
825
+ rpId: DEXTER_RP_ID,
826
+ userVerification: "required",
827
+ ...typeof options.timeout === "number" ? { timeout: options.timeout } : {}
828
+ };
829
+ }
830
+ function parseMissingVaultRecoveryChallenge(value) {
831
+ if (!value || typeof value !== "object") {
832
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
833
+ }
834
+ const envelope = value;
835
+ if (envelope.operation !== "vault_missing_recovery") {
836
+ throw new ConnectError("missing_vault_recovery_operation_mismatch");
837
+ }
838
+ return {
839
+ options: normalizeMissingVaultRecoveryOptions(envelope.options),
840
+ account: parseMissingVaultRecoveryAccount(envelope.account)
841
+ };
842
+ }
843
+ async function validateMissingVaultRecoveryAssertion(value, expectedChallenge) {
844
+ if (!value || typeof value !== "object") {
845
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
846
+ }
847
+ const credential = value;
848
+ const response = credential.response;
849
+ if (!response || typeof response !== "object") {
850
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
851
+ }
852
+ const assertion = response;
853
+ const id = canonicalBase64url(
854
+ credential.id,
855
+ 1,
856
+ 1024,
857
+ "missing_vault_recovery_assertion_malformed"
858
+ );
859
+ const rawId = canonicalBase64url(
860
+ credential.rawId,
861
+ 1,
862
+ 1024,
863
+ "missing_vault_recovery_assertion_malformed"
864
+ );
865
+ if (!bytesEqual(base64urlToBytes(id), base64urlToBytes(rawId)) || credential.type !== "public-key" || !isPlainObject(credential.clientExtensionResults) || Object.keys(credential.clientExtensionResults).length !== 0) {
866
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
867
+ }
868
+ const clientDataJSON = canonicalBase64url(
869
+ assertion.clientDataJSON,
870
+ 1,
871
+ 8192,
872
+ "missing_vault_recovery_assertion_malformed"
873
+ );
874
+ const authenticatorData = canonicalBase64url(
875
+ assertion.authenticatorData,
876
+ 37,
877
+ 4096,
878
+ "missing_vault_recovery_assertion_malformed"
879
+ );
880
+ const signature = canonicalBase64url(
881
+ assertion.signature,
882
+ 1,
883
+ 1024,
884
+ "missing_vault_recovery_assertion_malformed"
885
+ );
886
+ const userHandle = assertion.userHandle === void 0 || assertion.userHandle === null ? void 0 : canonicalBase64url(
887
+ assertion.userHandle,
888
+ 1,
889
+ 1024,
890
+ "missing_vault_recovery_assertion_malformed"
891
+ );
892
+ let clientData;
893
+ try {
894
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(
895
+ base64urlToBytes(clientDataJSON)
896
+ );
897
+ clientData = JSON.parse(decoded);
898
+ } catch {
899
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
900
+ }
901
+ if (clientData.type !== "webauthn.get" || clientData.challenge !== expectedChallenge || clientData.origin !== DEXTER_ORIGIN || clientData.crossOrigin !== false) {
902
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
903
+ }
904
+ const authData = base64urlToBytes(authenticatorData);
905
+ const expectedRpHash = new Uint8Array(
906
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(DEXTER_RP_ID))
907
+ );
908
+ const flags = authData[32] ?? 0;
909
+ if (!bytesEqual(authData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
910
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
911
+ }
912
+ const authenticatorAttachment = credential.authenticatorAttachment;
913
+ if (authenticatorAttachment !== void 0 && authenticatorAttachment !== "platform" && authenticatorAttachment !== "cross-platform") {
914
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
915
+ }
916
+ return {
917
+ id,
918
+ rawId,
919
+ type: "public-key",
920
+ response: {
921
+ clientDataJSON,
922
+ authenticatorData,
923
+ signature,
924
+ ...userHandle ? { userHandle } : {}
925
+ },
926
+ clientExtensionResults: {},
927
+ ...authenticatorAttachment ? { authenticatorAttachment } : {}
928
+ };
929
+ }
930
+ function parseMissingVaultRecoveryResult(value, credential, expectedAccount) {
931
+ if (!value || typeof value !== "object") {
932
+ throw new ConnectError("missing_vault_recovery_result_malformed");
933
+ }
934
+ const result = value;
935
+ const vault = result.vault;
936
+ if (result.recovered !== true || typeof result.alreadyRecovered !== "boolean" || result.relation !== "bound" || !vault || typeof vault !== "object") {
937
+ throw new ConnectError("missing_vault_recovery_result_malformed");
938
+ }
939
+ const row = vault;
940
+ const account = parseMissingVaultRecoveryAccount(result.account);
941
+ const credentialId = canonicalBase64url(
942
+ row.credentialId,
943
+ 1,
944
+ 1024,
945
+ "missing_vault_recovery_result_malformed"
946
+ );
947
+ const userHandle = canonicalBase64url(
948
+ row.userHandle,
949
+ 1,
950
+ 1024,
951
+ "missing_vault_recovery_result_malformed"
952
+ );
953
+ if (account.provider !== expectedAccount.provider || account.handle !== expectedAccount.handle || credentialId !== credential.id || credential.response.userHandle !== void 0 && userHandle !== credential.response.userHandle || !nonEmptyString(row.vaultPda) || !nonEmptyString(row.swigAddress) || !nonEmptyString(row.receiveAddress) || row.state !== "initialized") {
954
+ throw new ConnectError("missing_vault_recovery_result_malformed");
955
+ }
956
+ return {
957
+ recovered: true,
958
+ alreadyRecovered: result.alreadyRecovered,
959
+ relation: "bound",
960
+ account,
961
+ vault: {
962
+ vaultPda: row.vaultPda,
963
+ swigAddress: row.swigAddress,
964
+ receiveAddress: row.receiveAddress,
965
+ userHandle,
966
+ credentialId,
967
+ state: "initialized"
968
+ }
969
+ };
970
+ }
971
+ function parseMissingVaultRecoveryAccount(value) {
972
+ if (!value || typeof value !== "object") {
973
+ throw new ConnectError("missing_vault_recovery_account_malformed");
974
+ }
975
+ const account = value;
976
+ if (account.provider !== "x" || typeof account.handle !== "string" || !/^@[A-Za-z0-9_]{1,64}$/.test(account.handle)) {
977
+ throw new ConnectError("missing_vault_recovery_account_malformed");
978
+ }
979
+ return { provider: "x", handle: account.handle };
980
+ }
981
+ function canonicalBase64url(value, minBytes, maxBytes, errorCode) {
982
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) {
983
+ throw new ConnectError(errorCode);
984
+ }
985
+ try {
986
+ const bytes = base64urlToBytes(value);
987
+ if (bytes.byteLength < minBytes || bytes.byteLength > maxBytes || bytesToBase64url(bytes) !== value) {
988
+ throw new Error("non-canonical");
989
+ }
990
+ } catch {
991
+ throw new ConnectError(errorCode);
992
+ }
993
+ return value;
994
+ }
995
+ function nonEmptyString(value) {
996
+ return typeof value === "string" && value.length > 0 && value.length <= 256;
997
+ }
998
+ function isPlainObject(value) {
999
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1000
+ }
1001
+
763
1002
  // src/popup.ts
764
1003
  var POPUP_TIMEOUT_MS = 12e4;
765
1004
  var CANONICAL_ORIGIN = "https://dexter.cash";
@@ -778,6 +1017,10 @@ function openCeremonyPopup(op, config = {}) {
778
1017
  const openerOrigin = window.location.origin;
779
1018
  const requestId = makeNonce();
780
1019
  const signRequest = snapshotSignRequest(op, config.signRequest);
1020
+ const recoveryOptionsLoader = snapshotRecoveryLoader(
1021
+ op,
1022
+ config.missingVaultRecoveryRequest
1023
+ );
781
1024
  const walletStore = resolveWalletStoreMode(config.walletStore);
782
1025
  const createsWallet = op === "create" || op === "continue";
783
1026
  if (!createsWallet && config.agentDelegation !== void 0) {
@@ -789,6 +1032,7 @@ function openCeremonyPopup(op, config = {}) {
789
1032
  const agentDelegation = createsWallet ? resolveAgentDelegationMode(config.agentDelegation) : void 0;
790
1033
  const params = new URLSearchParams({ v: "1", op, requestId, origin: openerOrigin });
791
1034
  if (config.name) params.set("name", config.name);
1035
+ if (config.targetUserHandle) params.set("targetUserHandle", config.targetUserHandle);
792
1036
  if (config.preferImmediate) params.set("preferImmediate", "1");
793
1037
  if (walletStore === "provisional") params.set("walletStore", "provisional");
794
1038
  if (agentDelegation) params.set("agentDelegation", agentDelegation);
@@ -803,6 +1047,33 @@ function openCeremonyPopup(op, config = {}) {
803
1047
  }
804
1048
  let settled = false;
805
1049
  let handshakeComplete = false;
1050
+ let recoveryRequestSent = false;
1051
+ let recoveryRequest;
1052
+ const sendRecoveryRequest = () => {
1053
+ if (settled || !handshakeComplete || recoveryRequestSent || !recoveryRequest) {
1054
+ return;
1055
+ }
1056
+ const request = {
1057
+ v: 1,
1058
+ type: "dexter-connect:missing-vault-recovery-request",
1059
+ requestId,
1060
+ op: "recover-missing-vault",
1061
+ payload: recoveryRequest
1062
+ };
1063
+ try {
1064
+ popup.postMessage(request, hostOrigin);
1065
+ recoveryRequestSent = true;
1066
+ } catch (err) {
1067
+ finish(
1068
+ () => reject(
1069
+ new ConnectError(
1070
+ "popup_handshake_failed",
1071
+ err instanceof Error ? err.message : String(err)
1072
+ )
1073
+ )
1074
+ );
1075
+ }
1076
+ };
806
1077
  const onMessage = (event) => {
807
1078
  if (event.origin !== hostOrigin) return;
808
1079
  if (event.source !== popup) return;
@@ -829,6 +1100,7 @@ function openCeremonyPopup(op, config = {}) {
829
1100
  popup.postMessage(request, event.origin);
830
1101
  }
831
1102
  handshakeComplete = true;
1103
+ sendRecoveryRequest();
832
1104
  } catch (err) {
833
1105
  finish(
834
1106
  () => reject(
@@ -842,6 +1114,7 @@ function openCeremonyPopup(op, config = {}) {
842
1114
  return;
843
1115
  }
844
1116
  if (data.type !== "dexter-connect:result" || !handshakeComplete) return;
1117
+ if (op === "recover-missing-vault" && !recoveryRequestSent) return;
845
1118
  if (data.ok) finish(() => resolve(data.result));
846
1119
  else
847
1120
  finish(
@@ -868,8 +1141,63 @@ function openCeremonyPopup(op, config = {}) {
868
1141
  act();
869
1142
  }
870
1143
  window.addEventListener("message", onMessage);
1144
+ if (recoveryOptionsLoader) {
1145
+ let pendingOptions;
1146
+ try {
1147
+ pendingOptions = recoveryOptionsLoader();
1148
+ } catch (err) {
1149
+ finish(() => reject(asRecoveryOptionsError(err)));
1150
+ return;
1151
+ }
1152
+ void pendingOptions.then(
1153
+ (request) => {
1154
+ if (settled) return;
1155
+ try {
1156
+ recoveryRequest = {
1157
+ options: normalizeMissingVaultRecoveryOptions(request?.options),
1158
+ account: snapshotRecoveryAccount(request?.account)
1159
+ };
1160
+ sendRecoveryRequest();
1161
+ } catch (err) {
1162
+ finish(() => reject(asRecoveryOptionsError(err)));
1163
+ }
1164
+ },
1165
+ (err) => finish(() => reject(asRecoveryOptionsError(err)))
1166
+ );
1167
+ }
871
1168
  });
872
1169
  }
1170
+ function snapshotRecoveryLoader(op, loader) {
1171
+ if (op !== "recover-missing-vault") {
1172
+ if (loader !== void 0) {
1173
+ throw new ConnectError(
1174
+ "unexpected_missing_vault_recovery_request",
1175
+ "missing Vault recovery options require the recovery operation"
1176
+ );
1177
+ }
1178
+ return void 0;
1179
+ }
1180
+ if (typeof loader !== "function") {
1181
+ throw new ConnectError(
1182
+ "missing_vault_recovery_request",
1183
+ "missing Vault recovery requires server-issued public-key options"
1184
+ );
1185
+ }
1186
+ return loader;
1187
+ }
1188
+ function snapshotRecoveryAccount(value) {
1189
+ if (value?.provider !== "x" || typeof value.handle !== "string" || !/^@[A-Za-z0-9_]{1,64}$/.test(value.handle)) {
1190
+ throw new ConnectError("missing_vault_recovery_account_malformed");
1191
+ }
1192
+ return { provider: "x", handle: value.handle };
1193
+ }
1194
+ function asRecoveryOptionsError(err) {
1195
+ if (err instanceof ConnectError) return err;
1196
+ return new ConnectError(
1197
+ "missing_vault_recovery_challenge_failed",
1198
+ err instanceof Error ? err.message : String(err)
1199
+ );
1200
+ }
873
1201
  function snapshotSignRequest(op, request) {
874
1202
  if (op !== "sign") {
875
1203
  if (request !== void 0) {
@@ -943,9 +1271,73 @@ async function readErrorCode(res) {
943
1271
  return `http_${res.status}`;
944
1272
  }
945
1273
 
1274
+ // src/pendingCreation.ts
1275
+ var KEY = "dexter:pending-wallet-creation:v1";
1276
+ var retained = null;
1277
+ function storage() {
1278
+ try {
1279
+ return typeof window === "undefined" ? null : window.localStorage;
1280
+ } catch {
1281
+ return null;
1282
+ }
1283
+ }
1284
+ function readPendingCreation() {
1285
+ const store = storage();
1286
+ if (!store) return retained;
1287
+ let raw;
1288
+ try {
1289
+ raw = store.getItem(KEY);
1290
+ } catch {
1291
+ return retained;
1292
+ }
1293
+ if (!raw) return retained = null;
1294
+ try {
1295
+ const value = JSON.parse(raw);
1296
+ if (value.version !== 1 || !value.credentialId || typeof value.name !== "string" || value.registration?.id !== value.credentialId) throw new Error();
1297
+ if (value.enrolled) {
1298
+ if (value.enrolled.credentialId !== value.credentialId || !value.enrolled.userHandle || !value.enrolled.publicKey) throw new Error();
1299
+ value.enrolled.walletIdentityProof = parseWalletIdentityProof(value.enrolled.walletIdentityProof);
1300
+ }
1301
+ return retained = value;
1302
+ } catch {
1303
+ throw new ConnectError("pending_creation_invalid", "Sign in with your saved passkey to finish setting up your wallet.");
1304
+ }
1305
+ }
1306
+ function savePendingCreation(value) {
1307
+ retained = value;
1308
+ try {
1309
+ storage()?.setItem(KEY, JSON.stringify(value));
1310
+ } catch {
1311
+ }
1312
+ }
1313
+ function clearPendingCreation(credentialId) {
1314
+ let current;
1315
+ try {
1316
+ current = readPendingCreation();
1317
+ } catch {
1318
+ return;
1319
+ }
1320
+ if (current?.credentialId !== credentialId) return;
1321
+ retained = null;
1322
+ try {
1323
+ storage()?.removeItem(KEY);
1324
+ } catch {
1325
+ }
1326
+ }
1327
+
946
1328
  // src/enroll.ts
947
1329
  var DEFAULT_WALLET_NAME = "Dexter Wallet";
1330
+ var creationInProgress = false;
948
1331
  async function createWallet(config = {}) {
1332
+ if (creationInProgress) throw new ConnectError("wallet_creation_in_progress");
1333
+ creationInProgress = true;
1334
+ try {
1335
+ return await createWalletOperation(config);
1336
+ } finally {
1337
+ creationInProgress = false;
1338
+ }
1339
+ }
1340
+ async function createWalletOperation(config = {}) {
949
1341
  const walletStore = resolveWalletStoreMode(config.walletStore);
950
1342
  const agentDelegation = resolveAgentDelegationMode(
951
1343
  config.agentDelegation ?? (config.spendPolicy ? "configure-now" : void 0)
@@ -982,6 +1374,8 @@ async function createWallet(config = {}) {
982
1374
  if (typeof navigator === "undefined" || !navigator.credentials) {
983
1375
  throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
984
1376
  }
1377
+ const pending = readPendingCreation();
1378
+ if (pending) return resumeCreation(apiBase, pending, walletStore, config.onPhase);
985
1379
  const name = config.name && config.name.trim() || DEFAULT_WALLET_NAME;
986
1380
  config.onPhase?.("challenge");
987
1381
  const options = await fetchEnrollChallenge(apiBase);
@@ -997,30 +1391,115 @@ async function createWallet(config = {}) {
997
1391
  } catch (err) {
998
1392
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
999
1393
  }
1394
+ const checkpoint = {
1395
+ version: 1,
1396
+ credentialId: regResponse.id,
1397
+ registration: regResponse,
1398
+ name: config.name?.trim() || "",
1399
+ ...config.spendPolicy ? { spendPolicy: { ...config.spendPolicy } } : {}
1400
+ };
1401
+ savePendingCreation(checkpoint);
1000
1402
  config.onPhase?.("verifying");
1001
1403
  const enrolled = await submitEnrollComplete(apiBase, regResponse);
1002
- config.onPhase?.("finalizing");
1003
- const init = await initializeVault(
1004
- apiBase,
1005
- enrolled.userHandle,
1006
- enrolled.credentialId,
1007
- config.spendPolicy,
1008
- config.name?.trim() || void 0
1009
- );
1404
+ checkpoint.enrolled = enrolled;
1405
+ savePendingCreation(checkpoint);
1406
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, config.onPhase);
1407
+ }
1408
+ async function resumeCreation(apiBase, checkpoint, walletStore, onPhase) {
1409
+ let enrolled;
1410
+ if (!checkpoint.enrolled) {
1411
+ try {
1412
+ onPhase?.("verifying");
1413
+ enrolled = await submitEnrollComplete(apiBase, checkpoint.registration);
1414
+ checkpoint.enrolled = enrolled;
1415
+ savePendingCreation(checkpoint);
1416
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1417
+ } catch (error) {
1418
+ if (!(error instanceof ConnectError) || !["challenge_replayed", "verification_failed"].includes(error.code)) throw error;
1419
+ }
1420
+ }
1421
+ onPhase?.("challenge");
1422
+ const challenge = await fetch(`${apiBase}/api/passkey-anon/sign/recover-challenge`, {
1423
+ method: "POST",
1424
+ headers: { "content-type": "application/json" },
1425
+ body: "{}"
1426
+ });
1427
+ if (!challenge.ok) throw new ConnectError(await readErrorCode(challenge));
1428
+ const { options } = await challenge.json();
1429
+ resolveDexterRpId(options?.rpId);
1430
+ onPhase?.("passkey");
1431
+ let credential;
1432
+ try {
1433
+ credential = await startAuthentication({ optionsJSON: {
1434
+ ...options,
1435
+ allowCredentials: [{ id: checkpoint.credentialId, type: "public-key" }]
1436
+ } });
1437
+ } catch (error) {
1438
+ throw new ConnectError("webauthn_failed", error instanceof Error ? error.message : String(error));
1439
+ }
1440
+ if (credential.id !== checkpoint.credentialId) throw new ConnectError("creation_credential_mismatch");
1441
+ onPhase?.("verifying");
1442
+ const verification = await fetch(`${apiBase}/api/passkey-anon/sign/recover-verify`, {
1443
+ method: "POST",
1444
+ headers: { "content-type": "application/json" },
1445
+ body: JSON.stringify({ credential })
1446
+ });
1447
+ if (!verification.ok) {
1448
+ const code = await readErrorCode(verification);
1449
+ if (verification.status === 404 && code === "credential_not_found") {
1450
+ clearPendingCreation(checkpoint.credentialId);
1451
+ throw new ConnectError(
1452
+ "enrollment_not_saved",
1453
+ "Wallet setup was not saved. Start again to create your wallet."
1454
+ );
1455
+ }
1456
+ throw new ConnectError(code);
1457
+ }
1458
+ const verified = await verification.json();
1459
+ if (verified.verified !== true || verified.credentialId !== checkpoint.credentialId || checkpoint.enrolled && verified.userHandle !== checkpoint.enrolled.userHandle) {
1460
+ throw new ConnectError("creation_credential_mismatch");
1461
+ }
1462
+ enrolled = {
1463
+ userHandle: verified.userHandle,
1464
+ credentialId: verified.credentialId,
1465
+ publicKey: verified.publicKey ?? checkpoint.enrolled?.publicKey,
1466
+ walletIdentityProof: parseWalletIdentityProof(verified.walletIdentityProof)
1467
+ };
1468
+ if (!enrolled.publicKey || !enrolled.userHandle) throw new ConnectError("recover_verify_malformed");
1469
+ checkpoint.enrolled = enrolled;
1470
+ savePendingCreation(checkpoint);
1471
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1472
+ }
1473
+ async function finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase) {
1474
+ onPhase?.("finalizing");
1475
+ let init;
1476
+ try {
1477
+ init = await initializeVault(
1478
+ apiBase,
1479
+ enrolled.userHandle,
1480
+ enrolled.credentialId,
1481
+ checkpoint.spendPolicy,
1482
+ checkpoint.name || void 0,
1483
+ enrolled.walletIdentityProof
1484
+ );
1485
+ } catch (error) {
1486
+ throw new ConnectError(
1487
+ error instanceof ConnectError ? error.code : "initialize_failed",
1488
+ "Your passkey is saved. Retry to finish setting up this wallet."
1489
+ );
1490
+ }
1010
1491
  const vault = {
1011
1492
  vaultPda: init.vaultPda,
1012
1493
  swigAddress: init.swigStateAddress,
1013
- // Never substitute the configuration PDA for a missing deposit address.
1014
1494
  receiveAddress: init.receiveAddress ?? null,
1015
1495
  usdcAta: null,
1016
1496
  publicKey: enrolled.publicKey,
1017
1497
  userHandle: enrolled.userHandle,
1018
1498
  credentialId: enrolled.credentialId,
1019
- walletLabel: init.walletLabel ?? config.name?.trim() ?? null
1499
+ walletLabel: init.walletLabel ?? (checkpoint.name || null)
1020
1500
  };
1021
- if (walletStore === "commit") {
1022
- activateConnectVault(vault, enrolled.walletIdentityProof);
1023
- }
1501
+ if (walletStore === "commit") activateConnectVault(vault, enrolled.walletIdentityProof);
1502
+ clearPendingCreation(enrolled.credentialId);
1024
1503
  return {
1025
1504
  handle: enrolled.userHandle,
1026
1505
  credentialId: enrolled.credentialId,
@@ -1051,6 +1530,9 @@ async function submitEnrollComplete(apiBase, response) {
1051
1530
  });
1052
1531
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `enroll/complete ${res.status}`);
1053
1532
  const data = await res.json();
1533
+ if (data.credentialId !== response.id || typeof data.userHandle !== "string" || !data.userHandle || typeof data.publicKey !== "string" || !data.publicKey) {
1534
+ throw new ConnectError("enroll_complete_malformed");
1535
+ }
1054
1536
  return {
1055
1537
  credentialId: data.credentialId,
1056
1538
  publicKey: data.publicKey,
@@ -1058,7 +1540,7 @@ async function submitEnrollComplete(apiBase, response) {
1058
1540
  walletIdentityProof: parseWalletIdentityProof(data.walletIdentityProof)
1059
1541
  };
1060
1542
  }
1061
- async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label) {
1543
+ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label, walletIdentityProof) {
1062
1544
  const body = { userHandle, credentialId, coolingOffSeconds: 0 };
1063
1545
  if (label) body.label = label;
1064
1546
  if (spendPolicy) {
@@ -1067,7 +1549,7 @@ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, l
1067
1549
  }
1068
1550
  const res = await fetch(`${apiBase}/api/passkey-vault-anon/initialize`, {
1069
1551
  method: "POST",
1070
- headers: { "content-type": "application/json" },
1552
+ headers: { "content-type": "application/json", ...walletIdentityProof ? { authorization: `Bearer ${walletIdentityProof.token}` } : {} },
1071
1553
  body: JSON.stringify(body)
1072
1554
  });
1073
1555
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `initialize ${res.status}`);
@@ -1075,7 +1557,7 @@ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, l
1075
1557
  }
1076
1558
 
1077
1559
  // src/relay.ts
1078
- import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1560
+ import { startAuthentication as startAuthentication2, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1079
1561
 
1080
1562
  // src/immediate.ts
1081
1563
  var immediateCapPromise = null;
@@ -1143,13 +1625,16 @@ primeImmediateSupport();
1143
1625
  async function passkeyLogin(config = {}, onPhase) {
1144
1626
  const apiBase = resolveDexterApiBase(config.apiBase);
1145
1627
  const walletStore = resolveWalletStoreMode(config.walletStore);
1628
+ const targetUserHandle = resolveTargetUserHandle(config.targetUserHandle);
1146
1629
  if (shouldUsePopup(config.transport)) {
1147
1630
  const result2 = normalizeSignInResult(
1148
1631
  await openCeremonyPopup("signin", {
1149
1632
  connectHost: config.connectHost,
1633
+ ...targetUserHandle ? { targetUserHandle } : {},
1150
1634
  ...walletStore === "provisional" ? { walletStore } : {}
1151
1635
  })
1152
1636
  );
1637
+ assertTargetAccount(result2, targetUserHandle);
1153
1638
  if (walletStore === "commit") {
1154
1639
  activateConnectVault(result2.vault, result2.walletIdentityProof);
1155
1640
  }
@@ -1160,20 +1645,29 @@ async function passkeyLogin(config = {}, onPhase) {
1160
1645
  }
1161
1646
  onPhase?.("challenge");
1162
1647
  const options = await fetchLoginChallenge(apiBase);
1648
+ const credentialId = targetUserHandle ? getCredentialId(targetUserHandle) : void 0;
1649
+ const targetedOptions = credentialId ? { ...options, allowCredentials: [{ id: credentialId, type: "public-key" }] } : options;
1163
1650
  onPhase?.("passkey");
1164
1651
  let response;
1165
1652
  try {
1166
- response = await startAuthentication({ optionsJSON: options });
1653
+ response = await startAuthentication2({ optionsJSON: targetedOptions });
1167
1654
  } catch (err) {
1168
1655
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1169
1656
  }
1170
1657
  onPhase?.("verifying");
1171
1658
  const result = await submitLogin(apiBase, response);
1659
+ assertTargetAccount(result, targetUserHandle);
1172
1660
  if (walletStore === "commit") {
1173
1661
  activateConnectVault(result.vault, result.walletIdentityProof);
1174
1662
  }
1663
+ clearPendingCreation(result.vault.credentialId);
1175
1664
  return result;
1176
1665
  }
1666
+ function assertTargetAccount(result, expected) {
1667
+ if (expected && result.vault.userHandle !== expected) {
1668
+ throw new ConnectError("target_account_mismatch", "The selected passkey belongs to a different account.");
1669
+ }
1670
+ }
1177
1671
  async function continueWithDexter(config = {}, onPhase) {
1178
1672
  const walletStore = resolveWalletStoreMode(config.walletStore);
1179
1673
  const agentDelegation = resolveAgentDelegationMode(
@@ -1309,8 +1803,13 @@ export {
1309
1803
  readErrorCode,
1310
1804
  DEXTER_API_BASE,
1311
1805
  resolveDexterApiBase,
1806
+ resolveDexterConnectHost,
1312
1807
  resolveDexterRpId,
1313
1808
  bytesEqual,
1809
+ normalizeMissingVaultRecoveryOptions,
1810
+ parseMissingVaultRecoveryChallenge,
1811
+ validateMissingVaultRecoveryAssertion,
1812
+ parseMissingVaultRecoveryResult,
1314
1813
  shouldUsePopup,
1315
1814
  openCeremonyPopup,
1316
1815
  getActiveHandle,
@@ -1327,6 +1826,7 @@ export {
1327
1826
  WALLET_ACCOUNT_BINDING_PATH,
1328
1827
  walletBindingCandidate,
1329
1828
  accountBindingCandidate,
1829
+ fetchWithWalletIdentity,
1330
1830
  createWalletAccountBindingClient,
1331
1831
  WALLET_PROOF_SESSION_STORAGE_PREFIX,
1332
1832
  createWalletProofSessionStore,
@@ -1336,6 +1836,7 @@ export {
1336
1836
  SESSION_TTL_30D,
1337
1837
  usdToAtomic,
1338
1838
  authoredPolicy,
1839
+ clearPendingCreation,
1339
1840
  createWallet,
1340
1841
  immediateGetSupported,
1341
1842
  primeImmediateSupport,