@dexterai/connect 0.29.1 → 0.31.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.
@@ -132,6 +132,36 @@ function accountBindingCandidate(accessToken) {
132
132
  );
133
133
  return candidate;
134
134
  }
135
+ async function fetchWithWalletIdentity(input) {
136
+ const material = walletBindings.get(input.wallet);
137
+ const active = requireActiveWalletIdentity(input.activeWallet);
138
+ if (!material || material.activeWallet.userHandle !== active.userHandle || material.activeWallet.vaultPda !== active.vaultPda) {
139
+ throw new ConnectError("wallet_identity_mismatch");
140
+ }
141
+ const apiBase = resolveDexterApiBase();
142
+ let url;
143
+ try {
144
+ url = new URL(input.url, apiBase);
145
+ } catch {
146
+ throw new ConnectError("invalid_wallet_request_url");
147
+ }
148
+ if (url.origin !== apiBase || url.username || url.password || url.hash || !url.pathname.startsWith("/api/")) {
149
+ throw new ConnectError("invalid_wallet_request_url");
150
+ }
151
+ const queryHandle = url.searchParams.getAll("user_handle");
152
+ if (queryHandle.length > 1 || queryHandle.length === 1 && queryHandle[0] !== active.userHandle) {
153
+ throw new ConnectError("wallet_identity_mismatch");
154
+ }
155
+ const headers = new Headers(input.init?.headers);
156
+ if (headers.has("authorization") || headers.has("x-dexter-wallet-proof") || headers.has("x-dexter-owner-handle") && headers.get("x-dexter-owner-handle") !== active.userHandle) {
157
+ throw new ConnectError("wallet_identity_mismatch");
158
+ }
159
+ headers.set("X-Dexter-Wallet-Proof", material.identityProof);
160
+ headers.set("X-Dexter-Owner-Handle", active.userHandle);
161
+ const fetchImpl = input.fetch ?? globalFetch();
162
+ if (!fetchImpl) throw new ConnectError("fetch_unavailable");
163
+ return fetchImpl(url.href, { ...input.init, headers, redirect: "error", credentials: "omit" });
164
+ }
135
165
  function isRecord(value) {
136
166
  return typeof value === "object" && value !== null && !Array.isArray(value);
137
167
  }
@@ -328,7 +358,7 @@ function frozenEvent(operation, handle, session) {
328
358
  return Object.freeze({ operation, handle, session });
329
359
  }
330
360
  function createWalletProofSessionStore(options = {}) {
331
- const storage = options.storage === void 0 ? browserStorage() : options.storage;
361
+ const storage2 = options.storage === void 0 ? browserStorage() : options.storage;
332
362
  const eventSource = options.eventSource === void 0 ? options.storage === void 0 ? browserEventSource() : null : options.eventSource;
333
363
  const nowEpochSeconds = options.nowEpochSeconds ?? (() => Date.now() / 1e3);
334
364
  const listeners2 = /* @__PURE__ */ new Set();
@@ -342,9 +372,9 @@ function createWalletProofSessionStore(options = {}) {
342
372
  }
343
373
  };
344
374
  const safeRemove = (key) => {
345
- if (!storage) return false;
375
+ if (!storage2) return false;
346
376
  try {
347
- storage.removeItem(key);
377
+ storage2.removeItem(key);
348
378
  return true;
349
379
  } catch {
350
380
  return false;
@@ -352,11 +382,11 @@ function createWalletProofSessionStore(options = {}) {
352
382
  };
353
383
  const load = (handleValue) => {
354
384
  const handle = requireWalletHandle(handleValue);
355
- if (!storage) return null;
385
+ if (!storage2) return null;
356
386
  const key = keyForHandle(handle);
357
387
  let raw;
358
388
  try {
359
- raw = storage.getItem(key);
389
+ raw = storage2.getItem(key);
360
390
  } catch {
361
391
  return null;
362
392
  }
@@ -376,11 +406,11 @@ function createWalletProofSessionStore(options = {}) {
376
406
  };
377
407
  const clear = (handleValue) => {
378
408
  const handle = requireWalletHandle(handleValue);
379
- if (!storage) return false;
409
+ if (!storage2) return false;
380
410
  const key = keyForHandle(handle);
381
411
  let existed = false;
382
412
  try {
383
- existed = storage.getItem(key) !== null;
413
+ existed = storage2.getItem(key) !== null;
384
414
  } catch {
385
415
  return false;
386
416
  }
@@ -394,14 +424,14 @@ function createWalletProofSessionStore(options = {}) {
394
424
  if (parsed.expiresAt <= nowEpochSeconds()) {
395
425
  throw new ConnectError("wallet_identity_proof_expired");
396
426
  }
397
- if (!storage) return null;
427
+ if (!storage2) return null;
398
428
  const record = {
399
429
  v: STORAGE_VERSION,
400
430
  proof: parsed.token,
401
431
  expiresAt: parsed.expiresAt
402
432
  };
403
433
  try {
404
- storage.setItem(keyForHandle(handle), JSON.stringify(record));
434
+ storage2.setItem(keyForHandle(handle), JSON.stringify(record));
405
435
  } catch {
406
436
  return null;
407
437
  }
@@ -425,7 +455,7 @@ function createWalletProofSessionStore(options = {}) {
425
455
  return false;
426
456
  };
427
457
  const onStorage = (event) => {
428
- if (event.storageArea && storage && event.storageArea !== storage) return;
458
+ if (event.storageArea && storage2 && event.storageArea !== storage2) return;
429
459
  if (event.key === null) {
430
460
  publish(frozenEvent("external", null, null));
431
461
  return;
@@ -488,7 +518,7 @@ function authoredPolicy(usdInput) {
488
518
  }
489
519
 
490
520
  // src/enroll.ts
491
- import { startRegistration } from "@simplewebauthn/browser";
521
+ import { startRegistration, startAuthentication } from "@simplewebauthn/browser";
492
522
 
493
523
  // src/walletStore.ts
494
524
  var ACTIVE_HANDLE_KEY = "dexter:passkey:userHandle";
@@ -760,6 +790,207 @@ function activateRecoveredVault(userHandle, credentialId, vault, walletIdentityP
760
790
  return activated;
761
791
  }
762
792
 
793
+ // src/missingVaultRecoveryContract.ts
794
+ var DEXTER_ORIGIN = "https://dexter.cash";
795
+ var MIN_CHALLENGE_BYTES = 16;
796
+ var MAX_CHALLENGE_BYTES = 128;
797
+ function normalizeMissingVaultRecoveryOptions(value) {
798
+ if (!value || typeof value !== "object") {
799
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
800
+ }
801
+ const options = value;
802
+ const challenge = canonicalBase64url(
803
+ options.challenge,
804
+ MIN_CHALLENGE_BYTES,
805
+ MAX_CHALLENGE_BYTES,
806
+ "missing_vault_recovery_challenge_malformed"
807
+ );
808
+ const challengeBytes = base64urlToBytes(challenge);
809
+ 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)) {
810
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
811
+ }
812
+ if (options.timeout !== void 0 && (typeof options.timeout !== "number" || !Number.isFinite(options.timeout) || options.timeout <= 0 || options.timeout > 3e5)) {
813
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
814
+ }
815
+ return {
816
+ challenge,
817
+ rpId: DEXTER_RP_ID,
818
+ userVerification: "required",
819
+ ...typeof options.timeout === "number" ? { timeout: options.timeout } : {}
820
+ };
821
+ }
822
+ function parseMissingVaultRecoveryChallenge(value) {
823
+ if (!value || typeof value !== "object") {
824
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
825
+ }
826
+ const envelope = value;
827
+ if (envelope.operation !== "vault_missing_recovery") {
828
+ throw new ConnectError("missing_vault_recovery_operation_mismatch");
829
+ }
830
+ return {
831
+ options: normalizeMissingVaultRecoveryOptions(envelope.options),
832
+ account: parseMissingVaultRecoveryAccount(envelope.account)
833
+ };
834
+ }
835
+ async function validateMissingVaultRecoveryAssertion(value, expectedChallenge) {
836
+ if (!value || typeof value !== "object") {
837
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
838
+ }
839
+ const credential = value;
840
+ const response = credential.response;
841
+ if (!response || typeof response !== "object") {
842
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
843
+ }
844
+ const assertion = response;
845
+ const id = canonicalBase64url(
846
+ credential.id,
847
+ 1,
848
+ 1024,
849
+ "missing_vault_recovery_assertion_malformed"
850
+ );
851
+ const rawId = canonicalBase64url(
852
+ credential.rawId,
853
+ 1,
854
+ 1024,
855
+ "missing_vault_recovery_assertion_malformed"
856
+ );
857
+ if (!bytesEqual(base64urlToBytes(id), base64urlToBytes(rawId)) || credential.type !== "public-key" || !isPlainObject(credential.clientExtensionResults) || Object.keys(credential.clientExtensionResults).length !== 0) {
858
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
859
+ }
860
+ const clientDataJSON = canonicalBase64url(
861
+ assertion.clientDataJSON,
862
+ 1,
863
+ 8192,
864
+ "missing_vault_recovery_assertion_malformed"
865
+ );
866
+ const authenticatorData = canonicalBase64url(
867
+ assertion.authenticatorData,
868
+ 37,
869
+ 4096,
870
+ "missing_vault_recovery_assertion_malformed"
871
+ );
872
+ const signature = canonicalBase64url(
873
+ assertion.signature,
874
+ 1,
875
+ 1024,
876
+ "missing_vault_recovery_assertion_malformed"
877
+ );
878
+ const userHandle = assertion.userHandle === void 0 || assertion.userHandle === null ? void 0 : canonicalBase64url(
879
+ assertion.userHandle,
880
+ 1,
881
+ 1024,
882
+ "missing_vault_recovery_assertion_malformed"
883
+ );
884
+ let clientData;
885
+ try {
886
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(
887
+ base64urlToBytes(clientDataJSON)
888
+ );
889
+ clientData = JSON.parse(decoded);
890
+ } catch {
891
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
892
+ }
893
+ if (clientData.type !== "webauthn.get" || clientData.challenge !== expectedChallenge || clientData.origin !== DEXTER_ORIGIN || clientData.crossOrigin !== false) {
894
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
895
+ }
896
+ const authData = base64urlToBytes(authenticatorData);
897
+ const expectedRpHash = new Uint8Array(
898
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(DEXTER_RP_ID))
899
+ );
900
+ const flags = authData[32] ?? 0;
901
+ if (!bytesEqual(authData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
902
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
903
+ }
904
+ const authenticatorAttachment = credential.authenticatorAttachment;
905
+ if (authenticatorAttachment !== void 0 && authenticatorAttachment !== "platform" && authenticatorAttachment !== "cross-platform") {
906
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
907
+ }
908
+ return {
909
+ id,
910
+ rawId,
911
+ type: "public-key",
912
+ response: {
913
+ clientDataJSON,
914
+ authenticatorData,
915
+ signature,
916
+ ...userHandle ? { userHandle } : {}
917
+ },
918
+ clientExtensionResults: {},
919
+ ...authenticatorAttachment ? { authenticatorAttachment } : {}
920
+ };
921
+ }
922
+ function parseMissingVaultRecoveryResult(value, credential, expectedAccount) {
923
+ if (!value || typeof value !== "object") {
924
+ throw new ConnectError("missing_vault_recovery_result_malformed");
925
+ }
926
+ const result = value;
927
+ const vault = result.vault;
928
+ if (result.recovered !== true || typeof result.alreadyRecovered !== "boolean" || result.relation !== "bound" || !vault || typeof vault !== "object") {
929
+ throw new ConnectError("missing_vault_recovery_result_malformed");
930
+ }
931
+ const row = vault;
932
+ const account = parseMissingVaultRecoveryAccount(result.account);
933
+ const credentialId = canonicalBase64url(
934
+ row.credentialId,
935
+ 1,
936
+ 1024,
937
+ "missing_vault_recovery_result_malformed"
938
+ );
939
+ const userHandle = canonicalBase64url(
940
+ row.userHandle,
941
+ 1,
942
+ 1024,
943
+ "missing_vault_recovery_result_malformed"
944
+ );
945
+ 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") {
946
+ throw new ConnectError("missing_vault_recovery_result_malformed");
947
+ }
948
+ return {
949
+ recovered: true,
950
+ alreadyRecovered: result.alreadyRecovered,
951
+ relation: "bound",
952
+ account,
953
+ vault: {
954
+ vaultPda: row.vaultPda,
955
+ swigAddress: row.swigAddress,
956
+ receiveAddress: row.receiveAddress,
957
+ userHandle,
958
+ credentialId,
959
+ state: "initialized"
960
+ }
961
+ };
962
+ }
963
+ function parseMissingVaultRecoveryAccount(value) {
964
+ if (!value || typeof value !== "object") {
965
+ throw new ConnectError("missing_vault_recovery_account_malformed");
966
+ }
967
+ const account = value;
968
+ if (account.provider !== "x" || typeof account.handle !== "string" || !/^@[A-Za-z0-9_]{1,64}$/.test(account.handle)) {
969
+ throw new ConnectError("missing_vault_recovery_account_malformed");
970
+ }
971
+ return { provider: "x", handle: account.handle };
972
+ }
973
+ function canonicalBase64url(value, minBytes, maxBytes, errorCode) {
974
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) {
975
+ throw new ConnectError(errorCode);
976
+ }
977
+ try {
978
+ const bytes = base64urlToBytes(value);
979
+ if (bytes.byteLength < minBytes || bytes.byteLength > maxBytes || bytesToBase64url(bytes) !== value) {
980
+ throw new Error("non-canonical");
981
+ }
982
+ } catch {
983
+ throw new ConnectError(errorCode);
984
+ }
985
+ return value;
986
+ }
987
+ function nonEmptyString(value) {
988
+ return typeof value === "string" && value.length > 0 && value.length <= 256;
989
+ }
990
+ function isPlainObject(value) {
991
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
992
+ }
993
+
763
994
  // src/popup.ts
764
995
  var POPUP_TIMEOUT_MS = 12e4;
765
996
  var CANONICAL_ORIGIN = "https://dexter.cash";
@@ -778,6 +1009,10 @@ function openCeremonyPopup(op, config = {}) {
778
1009
  const openerOrigin = window.location.origin;
779
1010
  const requestId = makeNonce();
780
1011
  const signRequest = snapshotSignRequest(op, config.signRequest);
1012
+ const recoveryOptionsLoader = snapshotRecoveryLoader(
1013
+ op,
1014
+ config.missingVaultRecoveryRequest
1015
+ );
781
1016
  const walletStore = resolveWalletStoreMode(config.walletStore);
782
1017
  const createsWallet = op === "create" || op === "continue";
783
1018
  if (!createsWallet && config.agentDelegation !== void 0) {
@@ -803,6 +1038,33 @@ function openCeremonyPopup(op, config = {}) {
803
1038
  }
804
1039
  let settled = false;
805
1040
  let handshakeComplete = false;
1041
+ let recoveryRequestSent = false;
1042
+ let recoveryRequest;
1043
+ const sendRecoveryRequest = () => {
1044
+ if (settled || !handshakeComplete || recoveryRequestSent || !recoveryRequest) {
1045
+ return;
1046
+ }
1047
+ const request = {
1048
+ v: 1,
1049
+ type: "dexter-connect:missing-vault-recovery-request",
1050
+ requestId,
1051
+ op: "recover-missing-vault",
1052
+ payload: recoveryRequest
1053
+ };
1054
+ try {
1055
+ popup.postMessage(request, hostOrigin);
1056
+ recoveryRequestSent = true;
1057
+ } catch (err) {
1058
+ finish(
1059
+ () => reject(
1060
+ new ConnectError(
1061
+ "popup_handshake_failed",
1062
+ err instanceof Error ? err.message : String(err)
1063
+ )
1064
+ )
1065
+ );
1066
+ }
1067
+ };
806
1068
  const onMessage = (event) => {
807
1069
  if (event.origin !== hostOrigin) return;
808
1070
  if (event.source !== popup) return;
@@ -829,6 +1091,7 @@ function openCeremonyPopup(op, config = {}) {
829
1091
  popup.postMessage(request, event.origin);
830
1092
  }
831
1093
  handshakeComplete = true;
1094
+ sendRecoveryRequest();
832
1095
  } catch (err) {
833
1096
  finish(
834
1097
  () => reject(
@@ -842,6 +1105,7 @@ function openCeremonyPopup(op, config = {}) {
842
1105
  return;
843
1106
  }
844
1107
  if (data.type !== "dexter-connect:result" || !handshakeComplete) return;
1108
+ if (op === "recover-missing-vault" && !recoveryRequestSent) return;
845
1109
  if (data.ok) finish(() => resolve(data.result));
846
1110
  else
847
1111
  finish(
@@ -868,8 +1132,63 @@ function openCeremonyPopup(op, config = {}) {
868
1132
  act();
869
1133
  }
870
1134
  window.addEventListener("message", onMessage);
1135
+ if (recoveryOptionsLoader) {
1136
+ let pendingOptions;
1137
+ try {
1138
+ pendingOptions = recoveryOptionsLoader();
1139
+ } catch (err) {
1140
+ finish(() => reject(asRecoveryOptionsError(err)));
1141
+ return;
1142
+ }
1143
+ void pendingOptions.then(
1144
+ (request) => {
1145
+ if (settled) return;
1146
+ try {
1147
+ recoveryRequest = {
1148
+ options: normalizeMissingVaultRecoveryOptions(request?.options),
1149
+ account: snapshotRecoveryAccount(request?.account)
1150
+ };
1151
+ sendRecoveryRequest();
1152
+ } catch (err) {
1153
+ finish(() => reject(asRecoveryOptionsError(err)));
1154
+ }
1155
+ },
1156
+ (err) => finish(() => reject(asRecoveryOptionsError(err)))
1157
+ );
1158
+ }
871
1159
  });
872
1160
  }
1161
+ function snapshotRecoveryLoader(op, loader) {
1162
+ if (op !== "recover-missing-vault") {
1163
+ if (loader !== void 0) {
1164
+ throw new ConnectError(
1165
+ "unexpected_missing_vault_recovery_request",
1166
+ "missing Vault recovery options require the recovery operation"
1167
+ );
1168
+ }
1169
+ return void 0;
1170
+ }
1171
+ if (typeof loader !== "function") {
1172
+ throw new ConnectError(
1173
+ "missing_vault_recovery_request",
1174
+ "missing Vault recovery requires server-issued public-key options"
1175
+ );
1176
+ }
1177
+ return loader;
1178
+ }
1179
+ function snapshotRecoveryAccount(value) {
1180
+ if (value?.provider !== "x" || typeof value.handle !== "string" || !/^@[A-Za-z0-9_]{1,64}$/.test(value.handle)) {
1181
+ throw new ConnectError("missing_vault_recovery_account_malformed");
1182
+ }
1183
+ return { provider: "x", handle: value.handle };
1184
+ }
1185
+ function asRecoveryOptionsError(err) {
1186
+ if (err instanceof ConnectError) return err;
1187
+ return new ConnectError(
1188
+ "missing_vault_recovery_challenge_failed",
1189
+ err instanceof Error ? err.message : String(err)
1190
+ );
1191
+ }
873
1192
  function snapshotSignRequest(op, request) {
874
1193
  if (op !== "sign") {
875
1194
  if (request !== void 0) {
@@ -943,9 +1262,73 @@ async function readErrorCode(res) {
943
1262
  return `http_${res.status}`;
944
1263
  }
945
1264
 
1265
+ // src/pendingCreation.ts
1266
+ var KEY = "dexter:pending-wallet-creation:v1";
1267
+ var retained = null;
1268
+ function storage() {
1269
+ try {
1270
+ return typeof window === "undefined" ? null : window.localStorage;
1271
+ } catch {
1272
+ return null;
1273
+ }
1274
+ }
1275
+ function readPendingCreation() {
1276
+ const store = storage();
1277
+ if (!store) return retained;
1278
+ let raw;
1279
+ try {
1280
+ raw = store.getItem(KEY);
1281
+ } catch {
1282
+ return retained;
1283
+ }
1284
+ if (!raw) return retained = null;
1285
+ try {
1286
+ const value = JSON.parse(raw);
1287
+ if (value.version !== 1 || !value.credentialId || typeof value.name !== "string" || value.registration?.id !== value.credentialId) throw new Error();
1288
+ if (value.enrolled) {
1289
+ if (value.enrolled.credentialId !== value.credentialId || !value.enrolled.userHandle || !value.enrolled.publicKey) throw new Error();
1290
+ value.enrolled.walletIdentityProof = parseWalletIdentityProof(value.enrolled.walletIdentityProof);
1291
+ }
1292
+ return retained = value;
1293
+ } catch {
1294
+ throw new ConnectError("pending_creation_invalid", "Sign in with your saved passkey to finish setting up your wallet.");
1295
+ }
1296
+ }
1297
+ function savePendingCreation(value) {
1298
+ retained = value;
1299
+ try {
1300
+ storage()?.setItem(KEY, JSON.stringify(value));
1301
+ } catch {
1302
+ }
1303
+ }
1304
+ function clearPendingCreation(credentialId) {
1305
+ let current;
1306
+ try {
1307
+ current = readPendingCreation();
1308
+ } catch {
1309
+ return;
1310
+ }
1311
+ if (current?.credentialId !== credentialId) return;
1312
+ retained = null;
1313
+ try {
1314
+ storage()?.removeItem(KEY);
1315
+ } catch {
1316
+ }
1317
+ }
1318
+
946
1319
  // src/enroll.ts
947
1320
  var DEFAULT_WALLET_NAME = "Dexter Wallet";
1321
+ var creationInProgress = false;
948
1322
  async function createWallet(config = {}) {
1323
+ if (creationInProgress) throw new ConnectError("wallet_creation_in_progress");
1324
+ creationInProgress = true;
1325
+ try {
1326
+ return await createWalletOperation(config);
1327
+ } finally {
1328
+ creationInProgress = false;
1329
+ }
1330
+ }
1331
+ async function createWalletOperation(config = {}) {
949
1332
  const walletStore = resolveWalletStoreMode(config.walletStore);
950
1333
  const agentDelegation = resolveAgentDelegationMode(
951
1334
  config.agentDelegation ?? (config.spendPolicy ? "configure-now" : void 0)
@@ -982,6 +1365,8 @@ async function createWallet(config = {}) {
982
1365
  if (typeof navigator === "undefined" || !navigator.credentials) {
983
1366
  throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
984
1367
  }
1368
+ const pending = readPendingCreation();
1369
+ if (pending) return resumeCreation(apiBase, pending, walletStore, config.onPhase);
985
1370
  const name = config.name && config.name.trim() || DEFAULT_WALLET_NAME;
986
1371
  config.onPhase?.("challenge");
987
1372
  const options = await fetchEnrollChallenge(apiBase);
@@ -997,30 +1382,115 @@ async function createWallet(config = {}) {
997
1382
  } catch (err) {
998
1383
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
999
1384
  }
1385
+ const checkpoint = {
1386
+ version: 1,
1387
+ credentialId: regResponse.id,
1388
+ registration: regResponse,
1389
+ name: config.name?.trim() || "",
1390
+ ...config.spendPolicy ? { spendPolicy: { ...config.spendPolicy } } : {}
1391
+ };
1392
+ savePendingCreation(checkpoint);
1000
1393
  config.onPhase?.("verifying");
1001
1394
  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
- );
1395
+ checkpoint.enrolled = enrolled;
1396
+ savePendingCreation(checkpoint);
1397
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, config.onPhase);
1398
+ }
1399
+ async function resumeCreation(apiBase, checkpoint, walletStore, onPhase) {
1400
+ let enrolled;
1401
+ if (!checkpoint.enrolled) {
1402
+ try {
1403
+ onPhase?.("verifying");
1404
+ enrolled = await submitEnrollComplete(apiBase, checkpoint.registration);
1405
+ checkpoint.enrolled = enrolled;
1406
+ savePendingCreation(checkpoint);
1407
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1408
+ } catch (error) {
1409
+ if (!(error instanceof ConnectError) || !["challenge_replayed", "verification_failed"].includes(error.code)) throw error;
1410
+ }
1411
+ }
1412
+ onPhase?.("challenge");
1413
+ const challenge = await fetch(`${apiBase}/api/passkey-anon/sign/recover-challenge`, {
1414
+ method: "POST",
1415
+ headers: { "content-type": "application/json" },
1416
+ body: "{}"
1417
+ });
1418
+ if (!challenge.ok) throw new ConnectError(await readErrorCode(challenge));
1419
+ const { options } = await challenge.json();
1420
+ resolveDexterRpId(options?.rpId);
1421
+ onPhase?.("passkey");
1422
+ let credential;
1423
+ try {
1424
+ credential = await startAuthentication({ optionsJSON: {
1425
+ ...options,
1426
+ allowCredentials: [{ id: checkpoint.credentialId, type: "public-key" }]
1427
+ } });
1428
+ } catch (error) {
1429
+ throw new ConnectError("webauthn_failed", error instanceof Error ? error.message : String(error));
1430
+ }
1431
+ if (credential.id !== checkpoint.credentialId) throw new ConnectError("creation_credential_mismatch");
1432
+ onPhase?.("verifying");
1433
+ const verification = await fetch(`${apiBase}/api/passkey-anon/sign/recover-verify`, {
1434
+ method: "POST",
1435
+ headers: { "content-type": "application/json" },
1436
+ body: JSON.stringify({ credential })
1437
+ });
1438
+ if (!verification.ok) {
1439
+ const code = await readErrorCode(verification);
1440
+ if (verification.status === 404 && code === "credential_not_found") {
1441
+ clearPendingCreation(checkpoint.credentialId);
1442
+ throw new ConnectError(
1443
+ "enrollment_not_saved",
1444
+ "Wallet setup was not saved. Start again to create your wallet."
1445
+ );
1446
+ }
1447
+ throw new ConnectError(code);
1448
+ }
1449
+ const verified = await verification.json();
1450
+ if (verified.verified !== true || verified.credentialId !== checkpoint.credentialId || checkpoint.enrolled && verified.userHandle !== checkpoint.enrolled.userHandle) {
1451
+ throw new ConnectError("creation_credential_mismatch");
1452
+ }
1453
+ enrolled = {
1454
+ userHandle: verified.userHandle,
1455
+ credentialId: verified.credentialId,
1456
+ publicKey: verified.publicKey ?? checkpoint.enrolled?.publicKey,
1457
+ walletIdentityProof: parseWalletIdentityProof(verified.walletIdentityProof)
1458
+ };
1459
+ if (!enrolled.publicKey || !enrolled.userHandle) throw new ConnectError("recover_verify_malformed");
1460
+ checkpoint.enrolled = enrolled;
1461
+ savePendingCreation(checkpoint);
1462
+ return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1463
+ }
1464
+ async function finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase) {
1465
+ onPhase?.("finalizing");
1466
+ let init;
1467
+ try {
1468
+ init = await initializeVault(
1469
+ apiBase,
1470
+ enrolled.userHandle,
1471
+ enrolled.credentialId,
1472
+ checkpoint.spendPolicy,
1473
+ checkpoint.name || void 0,
1474
+ enrolled.walletIdentityProof
1475
+ );
1476
+ } catch (error) {
1477
+ throw new ConnectError(
1478
+ error instanceof ConnectError ? error.code : "initialize_failed",
1479
+ "Your passkey is saved. Retry to finish setting up this wallet."
1480
+ );
1481
+ }
1010
1482
  const vault = {
1011
1483
  vaultPda: init.vaultPda,
1012
1484
  swigAddress: init.swigStateAddress,
1013
- // Never substitute the configuration PDA for a missing deposit address.
1014
1485
  receiveAddress: init.receiveAddress ?? null,
1015
1486
  usdcAta: null,
1016
1487
  publicKey: enrolled.publicKey,
1017
1488
  userHandle: enrolled.userHandle,
1018
1489
  credentialId: enrolled.credentialId,
1019
- walletLabel: init.walletLabel ?? config.name?.trim() ?? null
1490
+ walletLabel: init.walletLabel ?? (checkpoint.name || null)
1020
1491
  };
1021
- if (walletStore === "commit") {
1022
- activateConnectVault(vault, enrolled.walletIdentityProof);
1023
- }
1492
+ if (walletStore === "commit") activateConnectVault(vault, enrolled.walletIdentityProof);
1493
+ clearPendingCreation(enrolled.credentialId);
1024
1494
  return {
1025
1495
  handle: enrolled.userHandle,
1026
1496
  credentialId: enrolled.credentialId,
@@ -1051,6 +1521,9 @@ async function submitEnrollComplete(apiBase, response) {
1051
1521
  });
1052
1522
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `enroll/complete ${res.status}`);
1053
1523
  const data = await res.json();
1524
+ if (data.credentialId !== response.id || typeof data.userHandle !== "string" || !data.userHandle || typeof data.publicKey !== "string" || !data.publicKey) {
1525
+ throw new ConnectError("enroll_complete_malformed");
1526
+ }
1054
1527
  return {
1055
1528
  credentialId: data.credentialId,
1056
1529
  publicKey: data.publicKey,
@@ -1058,7 +1531,7 @@ async function submitEnrollComplete(apiBase, response) {
1058
1531
  walletIdentityProof: parseWalletIdentityProof(data.walletIdentityProof)
1059
1532
  };
1060
1533
  }
1061
- async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label) {
1534
+ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label, walletIdentityProof) {
1062
1535
  const body = { userHandle, credentialId, coolingOffSeconds: 0 };
1063
1536
  if (label) body.label = label;
1064
1537
  if (spendPolicy) {
@@ -1067,7 +1540,7 @@ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, l
1067
1540
  }
1068
1541
  const res = await fetch(`${apiBase}/api/passkey-vault-anon/initialize`, {
1069
1542
  method: "POST",
1070
- headers: { "content-type": "application/json" },
1543
+ headers: { "content-type": "application/json", ...walletIdentityProof ? { authorization: `Bearer ${walletIdentityProof.token}` } : {} },
1071
1544
  body: JSON.stringify(body)
1072
1545
  });
1073
1546
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `initialize ${res.status}`);
@@ -1075,7 +1548,7 @@ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, l
1075
1548
  }
1076
1549
 
1077
1550
  // src/relay.ts
1078
- import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1551
+ import { startAuthentication as startAuthentication2, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1079
1552
 
1080
1553
  // src/immediate.ts
1081
1554
  var immediateCapPromise = null;
@@ -1163,7 +1636,7 @@ async function passkeyLogin(config = {}, onPhase) {
1163
1636
  onPhase?.("passkey");
1164
1637
  let response;
1165
1638
  try {
1166
- response = await startAuthentication({ optionsJSON: options });
1639
+ response = await startAuthentication2({ optionsJSON: options });
1167
1640
  } catch (err) {
1168
1641
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1169
1642
  }
@@ -1172,6 +1645,7 @@ async function passkeyLogin(config = {}, onPhase) {
1172
1645
  if (walletStore === "commit") {
1173
1646
  activateConnectVault(result.vault, result.walletIdentityProof);
1174
1647
  }
1648
+ clearPendingCreation(result.vault.credentialId);
1175
1649
  return result;
1176
1650
  }
1177
1651
  async function continueWithDexter(config = {}, onPhase) {
@@ -1309,8 +1783,13 @@ export {
1309
1783
  readErrorCode,
1310
1784
  DEXTER_API_BASE,
1311
1785
  resolveDexterApiBase,
1786
+ resolveDexterConnectHost,
1312
1787
  resolveDexterRpId,
1313
1788
  bytesEqual,
1789
+ normalizeMissingVaultRecoveryOptions,
1790
+ parseMissingVaultRecoveryChallenge,
1791
+ validateMissingVaultRecoveryAssertion,
1792
+ parseMissingVaultRecoveryResult,
1314
1793
  shouldUsePopup,
1315
1794
  openCeremonyPopup,
1316
1795
  getActiveHandle,
@@ -1327,6 +1806,7 @@ export {
1327
1806
  WALLET_ACCOUNT_BINDING_PATH,
1328
1807
  walletBindingCandidate,
1329
1808
  accountBindingCandidate,
1809
+ fetchWithWalletIdentity,
1330
1810
  createWalletAccountBindingClient,
1331
1811
  WALLET_PROOF_SESSION_STORAGE_PREFIX,
1332
1812
  createWalletProofSessionStore,
@@ -1336,6 +1816,7 @@ export {
1336
1816
  SESSION_TTL_30D,
1337
1817
  usdToAtomic,
1338
1818
  authoredPolicy,
1819
+ clearPendingCreation,
1339
1820
  createWallet,
1340
1821
  immediateGetSupported,
1341
1822
  primeImmediateSupport,