@dexterai/connect 0.29.0 → 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.
@@ -44,9 +44,6 @@ function parseWalletIdentityProof(value) {
44
44
  };
45
45
  }
46
46
 
47
- // src/bindingResolver.ts
48
- import { PublicKey } from "@solana/web3.js";
49
-
50
47
  // src/trust.ts
51
48
  var DEXTER_API_BASE = "https://api.dexter.cash";
52
49
  var DEXTER_CONNECT_HOST = "https://dexter.cash/connect";
@@ -81,6 +78,7 @@ function bytesEqual(a, b) {
81
78
  }
82
79
 
83
80
  // src/bindingResolver.ts
81
+ import { PublicKey } from "@solana/web3.js";
84
82
  var WALLET_ACCOUNT_BINDING_PATH = "/api/passkey-anon/binding/resolve";
85
83
  var walletBindings = /* @__PURE__ */ new WeakMap();
86
84
  var accountTokens = /* @__PURE__ */ new WeakMap();
@@ -134,6 +132,36 @@ function accountBindingCandidate(accessToken) {
134
132
  );
135
133
  return candidate;
136
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
+ }
137
165
  function isRecord(value) {
138
166
  return typeof value === "object" && value !== null && !Array.isArray(value);
139
167
  }
@@ -330,7 +358,7 @@ function frozenEvent(operation, handle, session) {
330
358
  return Object.freeze({ operation, handle, session });
331
359
  }
332
360
  function createWalletProofSessionStore(options = {}) {
333
- const storage = options.storage === void 0 ? browserStorage() : options.storage;
361
+ const storage2 = options.storage === void 0 ? browserStorage() : options.storage;
334
362
  const eventSource = options.eventSource === void 0 ? options.storage === void 0 ? browserEventSource() : null : options.eventSource;
335
363
  const nowEpochSeconds = options.nowEpochSeconds ?? (() => Date.now() / 1e3);
336
364
  const listeners2 = /* @__PURE__ */ new Set();
@@ -344,9 +372,9 @@ function createWalletProofSessionStore(options = {}) {
344
372
  }
345
373
  };
346
374
  const safeRemove = (key) => {
347
- if (!storage) return false;
375
+ if (!storage2) return false;
348
376
  try {
349
- storage.removeItem(key);
377
+ storage2.removeItem(key);
350
378
  return true;
351
379
  } catch {
352
380
  return false;
@@ -354,11 +382,11 @@ function createWalletProofSessionStore(options = {}) {
354
382
  };
355
383
  const load = (handleValue) => {
356
384
  const handle = requireWalletHandle(handleValue);
357
- if (!storage) return null;
385
+ if (!storage2) return null;
358
386
  const key = keyForHandle(handle);
359
387
  let raw;
360
388
  try {
361
- raw = storage.getItem(key);
389
+ raw = storage2.getItem(key);
362
390
  } catch {
363
391
  return null;
364
392
  }
@@ -378,11 +406,11 @@ function createWalletProofSessionStore(options = {}) {
378
406
  };
379
407
  const clear = (handleValue) => {
380
408
  const handle = requireWalletHandle(handleValue);
381
- if (!storage) return false;
409
+ if (!storage2) return false;
382
410
  const key = keyForHandle(handle);
383
411
  let existed = false;
384
412
  try {
385
- existed = storage.getItem(key) !== null;
413
+ existed = storage2.getItem(key) !== null;
386
414
  } catch {
387
415
  return false;
388
416
  }
@@ -396,14 +424,14 @@ function createWalletProofSessionStore(options = {}) {
396
424
  if (parsed.expiresAt <= nowEpochSeconds()) {
397
425
  throw new ConnectError("wallet_identity_proof_expired");
398
426
  }
399
- if (!storage) return null;
427
+ if (!storage2) return null;
400
428
  const record = {
401
429
  v: STORAGE_VERSION,
402
430
  proof: parsed.token,
403
431
  expiresAt: parsed.expiresAt
404
432
  };
405
433
  try {
406
- storage.setItem(keyForHandle(handle), JSON.stringify(record));
434
+ storage2.setItem(keyForHandle(handle), JSON.stringify(record));
407
435
  } catch {
408
436
  return null;
409
437
  }
@@ -427,7 +455,7 @@ function createWalletProofSessionStore(options = {}) {
427
455
  return false;
428
456
  };
429
457
  const onStorage = (event) => {
430
- if (event.storageArea && storage && event.storageArea !== storage) return;
458
+ if (event.storageArea && storage2 && event.storageArea !== storage2) return;
431
459
  if (event.key === null) {
432
460
  publish(frozenEvent("external", null, null));
433
461
  return;
@@ -490,7 +518,7 @@ function authoredPolicy(usdInput) {
490
518
  }
491
519
 
492
520
  // src/enroll.ts
493
- import { startRegistration } from "@simplewebauthn/browser";
521
+ import { startRegistration, startAuthentication } from "@simplewebauthn/browser";
494
522
 
495
523
  // src/walletStore.ts
496
524
  var ACTIVE_HANDLE_KEY = "dexter:passkey:userHandle";
@@ -762,6 +790,207 @@ function activateRecoveredVault(userHandle, credentialId, vault, walletIdentityP
762
790
  return activated;
763
791
  }
764
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
+
765
994
  // src/popup.ts
766
995
  var POPUP_TIMEOUT_MS = 12e4;
767
996
  var CANONICAL_ORIGIN = "https://dexter.cash";
@@ -780,6 +1009,10 @@ function openCeremonyPopup(op, config = {}) {
780
1009
  const openerOrigin = window.location.origin;
781
1010
  const requestId = makeNonce();
782
1011
  const signRequest = snapshotSignRequest(op, config.signRequest);
1012
+ const recoveryOptionsLoader = snapshotRecoveryLoader(
1013
+ op,
1014
+ config.missingVaultRecoveryRequest
1015
+ );
783
1016
  const walletStore = resolveWalletStoreMode(config.walletStore);
784
1017
  const createsWallet = op === "create" || op === "continue";
785
1018
  if (!createsWallet && config.agentDelegation !== void 0) {
@@ -805,6 +1038,33 @@ function openCeremonyPopup(op, config = {}) {
805
1038
  }
806
1039
  let settled = false;
807
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
+ };
808
1068
  const onMessage = (event) => {
809
1069
  if (event.origin !== hostOrigin) return;
810
1070
  if (event.source !== popup) return;
@@ -831,6 +1091,7 @@ function openCeremonyPopup(op, config = {}) {
831
1091
  popup.postMessage(request, event.origin);
832
1092
  }
833
1093
  handshakeComplete = true;
1094
+ sendRecoveryRequest();
834
1095
  } catch (err) {
835
1096
  finish(
836
1097
  () => reject(
@@ -844,6 +1105,7 @@ function openCeremonyPopup(op, config = {}) {
844
1105
  return;
845
1106
  }
846
1107
  if (data.type !== "dexter-connect:result" || !handshakeComplete) return;
1108
+ if (op === "recover-missing-vault" && !recoveryRequestSent) return;
847
1109
  if (data.ok) finish(() => resolve(data.result));
848
1110
  else
849
1111
  finish(
@@ -870,8 +1132,63 @@ function openCeremonyPopup(op, config = {}) {
870
1132
  act();
871
1133
  }
872
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
+ }
873
1159
  });
874
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
+ }
875
1192
  function snapshotSignRequest(op, request) {
876
1193
  if (op !== "sign") {
877
1194
  if (request !== void 0) {
@@ -945,9 +1262,73 @@ async function readErrorCode(res) {
945
1262
  return `http_${res.status}`;
946
1263
  }
947
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
+
948
1319
  // src/enroll.ts
949
1320
  var DEFAULT_WALLET_NAME = "Dexter Wallet";
1321
+ var creationInProgress = false;
950
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 = {}) {
951
1332
  const walletStore = resolveWalletStoreMode(config.walletStore);
952
1333
  const agentDelegation = resolveAgentDelegationMode(
953
1334
  config.agentDelegation ?? (config.spendPolicy ? "configure-now" : void 0)
@@ -984,6 +1365,8 @@ async function createWallet(config = {}) {
984
1365
  if (typeof navigator === "undefined" || !navigator.credentials) {
985
1366
  throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
986
1367
  }
1368
+ const pending = readPendingCreation();
1369
+ if (pending) return resumeCreation(apiBase, pending, walletStore, config.onPhase);
987
1370
  const name = config.name && config.name.trim() || DEFAULT_WALLET_NAME;
988
1371
  config.onPhase?.("challenge");
989
1372
  const options = await fetchEnrollChallenge(apiBase);
@@ -999,30 +1382,115 @@ async function createWallet(config = {}) {
999
1382
  } catch (err) {
1000
1383
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1001
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);
1002
1393
  config.onPhase?.("verifying");
1003
1394
  const enrolled = await submitEnrollComplete(apiBase, regResponse);
1004
- config.onPhase?.("finalizing");
1005
- const init = await initializeVault(
1006
- apiBase,
1007
- enrolled.userHandle,
1008
- enrolled.credentialId,
1009
- config.spendPolicy,
1010
- config.name?.trim() || void 0
1011
- );
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
+ }
1012
1482
  const vault = {
1013
1483
  vaultPda: init.vaultPda,
1014
1484
  swigAddress: init.swigStateAddress,
1015
- // Never substitute the configuration PDA for a missing deposit address.
1016
1485
  receiveAddress: init.receiveAddress ?? null,
1017
1486
  usdcAta: null,
1018
1487
  publicKey: enrolled.publicKey,
1019
1488
  userHandle: enrolled.userHandle,
1020
1489
  credentialId: enrolled.credentialId,
1021
- walletLabel: init.walletLabel ?? config.name?.trim() ?? null
1490
+ walletLabel: init.walletLabel ?? (checkpoint.name || null)
1022
1491
  };
1023
- if (walletStore === "commit") {
1024
- activateConnectVault(vault, enrolled.walletIdentityProof);
1025
- }
1492
+ if (walletStore === "commit") activateConnectVault(vault, enrolled.walletIdentityProof);
1493
+ clearPendingCreation(enrolled.credentialId);
1026
1494
  return {
1027
1495
  handle: enrolled.userHandle,
1028
1496
  credentialId: enrolled.credentialId,
@@ -1053,6 +1521,9 @@ async function submitEnrollComplete(apiBase, response) {
1053
1521
  });
1054
1522
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `enroll/complete ${res.status}`);
1055
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
+ }
1056
1527
  return {
1057
1528
  credentialId: data.credentialId,
1058
1529
  publicKey: data.publicKey,
@@ -1060,7 +1531,7 @@ async function submitEnrollComplete(apiBase, response) {
1060
1531
  walletIdentityProof: parseWalletIdentityProof(data.walletIdentityProof)
1061
1532
  };
1062
1533
  }
1063
- async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label) {
1534
+ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label, walletIdentityProof) {
1064
1535
  const body = { userHandle, credentialId, coolingOffSeconds: 0 };
1065
1536
  if (label) body.label = label;
1066
1537
  if (spendPolicy) {
@@ -1069,411 +1540,15 @@ async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, l
1069
1540
  }
1070
1541
  const res = await fetch(`${apiBase}/api/passkey-vault-anon/initialize`, {
1071
1542
  method: "POST",
1072
- headers: { "content-type": "application/json" },
1543
+ headers: { "content-type": "application/json", ...walletIdentityProof ? { authorization: `Bearer ${walletIdentityProof.token}` } : {} },
1073
1544
  body: JSON.stringify(body)
1074
1545
  });
1075
1546
  if (!res.ok) throw new ConnectError(await readErrorCode(res), `initialize ${res.status}`);
1076
1547
  return await res.json();
1077
1548
  }
1078
1549
 
1079
- // src/relationController.ts
1080
- function provisionalRelation(walletPresent, accountPresent) {
1081
- if (walletPresent) return "wallet_only";
1082
- if (accountPresent) return "account_only";
1083
- return "none";
1084
- }
1085
- function frozenRuntime(runtime) {
1086
- return Object.freeze({ ...runtime });
1087
- }
1088
- function frozenSnapshot(relation, runtime, walletPresent, accountPresent, verifiedAt, revision) {
1089
- const readyAndBound = relation === "bound" && runtime.phase === "ready";
1090
- return Object.freeze({
1091
- relation,
1092
- runtime: frozenRuntime(runtime),
1093
- walletPresent,
1094
- accountPresent,
1095
- privateAccountAccess: readyAndBound,
1096
- quarantined: relation === "conflict",
1097
- verifiedAt: readyAndBound || relation === "conflict" ? verifiedAt : null,
1098
- revision
1099
- });
1100
- }
1101
- function isVerifiedResult(value) {
1102
- if (!value || typeof value !== "object") return false;
1103
- const result = value;
1104
- if (result.ok !== true) return false;
1105
- if (result.relation !== "bound" && result.relation !== "conflict") return false;
1106
- return result.verifiedAt === void 0 || Number.isFinite(result.verifiedAt);
1107
- }
1108
- function isFailureResult(value) {
1109
- if (!value || typeof value !== "object") return false;
1110
- const result = value;
1111
- if (result.ok !== false) return false;
1112
- if (result.reason === "offline") return true;
1113
- if (result.reason === "expired") {
1114
- return result.subject === "wallet" || result.subject === "account" || result.subject === "both";
1115
- }
1116
- return result.reason === "error" && typeof result.code === "string" && result.code.length > 0;
1117
- }
1118
- var WalletAccountRelationController = class {
1119
- wallet = null;
1120
- account = null;
1121
- revision = 0;
1122
- activeCheck = null;
1123
- listeners = /* @__PURE__ */ new Set();
1124
- verify;
1125
- now;
1126
- snapshot;
1127
- constructor(options) {
1128
- this.verify = options.verify;
1129
- this.now = options.now ?? Date.now;
1130
- this.snapshot = frozenSnapshot("none", { phase: "hydrating" }, false, false, null, 0);
1131
- }
1132
- getSnapshot() {
1133
- return this.snapshot;
1134
- }
1135
- subscribe(listener) {
1136
- this.listeners.add(listener);
1137
- return () => this.listeners.delete(listener);
1138
- }
1139
- /** Restore cached candidates, then verify the exact pair before unlocking account access. */
1140
- restore(candidates) {
1141
- this.replaceCandidates(candidates.wallet, candidates.account, { phase: "hydrating" });
1142
- return this.settle("restore");
1143
- }
1144
- /** Lock account-owned data while the host restores its account session. */
1145
- beginRestore() {
1146
- this.invalidate({ phase: "hydrating" });
1147
- }
1148
- /** An explicit Wallet event always invalidates prior binding, even for the same object. */
1149
- setWallet(wallet) {
1150
- this.replaceCandidates(wallet, this.account, this.runtimeAfterChange("wallet_change", wallet, this.account));
1151
- return this.settle("wallet_change");
1152
- }
1153
- /** An explicit account event always invalidates prior binding, even for the same object. */
1154
- setAccount(account) {
1155
- this.replaceCandidates(this.wallet, account, this.runtimeAfterChange("account_change", this.wallet, account));
1156
- return this.settle("account_change");
1157
- }
1158
- retry() {
1159
- this.invalidate(this.runtimeAfterChange("retry", this.wallet, this.account));
1160
- return this.settle("retry");
1161
- }
1162
- dispose() {
1163
- this.activeCheck?.abort();
1164
- this.activeCheck = null;
1165
- this.listeners.clear();
1166
- }
1167
- runtimeAfterChange(reason, wallet, account) {
1168
- return wallet !== null && account !== null ? { phase: "checking", reason } : { phase: "ready" };
1169
- }
1170
- replaceCandidates(wallet, account, runtime) {
1171
- this.wallet = wallet;
1172
- this.account = account;
1173
- this.invalidate(runtime);
1174
- }
1175
- invalidate(runtime) {
1176
- this.activeCheck?.abort();
1177
- this.activeCheck = null;
1178
- this.revision += 1;
1179
- const walletPresent = this.wallet !== null;
1180
- const accountPresent = this.account !== null;
1181
- this.publish(
1182
- provisionalRelation(walletPresent, accountPresent),
1183
- runtime,
1184
- walletPresent,
1185
- accountPresent,
1186
- null,
1187
- this.revision
1188
- );
1189
- }
1190
- settle(reason) {
1191
- if (this.wallet !== null && this.account !== null) return this.runCheck(reason);
1192
- if (this.snapshot.runtime.phase !== "ready") {
1193
- this.publish(
1194
- provisionalRelation(this.wallet !== null, this.account !== null),
1195
- { phase: "ready" },
1196
- this.wallet !== null,
1197
- this.account !== null,
1198
- null,
1199
- this.revision
1200
- );
1201
- }
1202
- return Promise.resolve(this.snapshot);
1203
- }
1204
- async runCheck(reason) {
1205
- const wallet = this.wallet;
1206
- const account = this.account;
1207
- if (wallet === null || account === null) return this.settle(reason);
1208
- const revision = this.revision;
1209
- const check = new AbortController();
1210
- this.activeCheck?.abort();
1211
- this.activeCheck = check;
1212
- if (this.snapshot.runtime.phase !== "checking" || this.snapshot.runtime.reason !== reason) {
1213
- this.publish(
1214
- provisionalRelation(true, true),
1215
- { phase: "checking", reason },
1216
- true,
1217
- true,
1218
- null,
1219
- revision
1220
- );
1221
- }
1222
- try {
1223
- const result = await this.verify({ wallet, account, reason, signal: check.signal });
1224
- if (!this.isCurrentCheck(check, revision)) return this.snapshot;
1225
- this.activeCheck = null;
1226
- if (isVerifiedResult(result)) {
1227
- this.publish(result.relation, { phase: "ready" }, true, true, result.verifiedAt ?? this.now(), revision);
1228
- return this.snapshot;
1229
- }
1230
- if (isFailureResult(result)) {
1231
- const runtime = result.reason === "offline" ? { phase: "offline" } : result.reason === "expired" ? { phase: "expired", subject: result.subject } : { phase: "error", code: result.code };
1232
- this.publish("wallet_only", runtime, true, true, null, revision);
1233
- return this.snapshot;
1234
- }
1235
- this.publish("wallet_only", { phase: "error", code: "invalid_verification_result" }, true, true, null, revision);
1236
- } catch (error) {
1237
- if (!this.isCurrentCheck(check, revision)) return this.snapshot;
1238
- this.activeCheck = null;
1239
- const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "verification_failed";
1240
- this.publish("wallet_only", { phase: "error", code }, true, true, null, revision);
1241
- }
1242
- return this.snapshot;
1243
- }
1244
- isCurrentCheck(check, revision) {
1245
- return this.activeCheck === check && this.revision === revision && !check.signal.aborted;
1246
- }
1247
- publish(relation, runtime, walletPresent, accountPresent, verifiedAt, revision) {
1248
- this.snapshot = frozenSnapshot(
1249
- relation,
1250
- runtime,
1251
- walletPresent,
1252
- accountPresent,
1253
- verifiedAt,
1254
- revision
1255
- );
1256
- for (const listener of this.listeners) {
1257
- try {
1258
- listener(this.snapshot);
1259
- } catch {
1260
- }
1261
- }
1262
- }
1263
- };
1264
-
1265
- // src/identityCoordinator.ts
1266
- import { decodeJwt } from "jose";
1267
- var CANONICAL_ACCOUNT_SUBJECT = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1268
- function walletCandidate(wallet, proofStore) {
1269
- if (!wallet) return null;
1270
- let proof = null;
1271
- try {
1272
- proof = wallet.vaultPda ? proofStore.bindingCandidate(wallet.handle, {
1273
- userHandle: wallet.handle,
1274
- vaultPda: wallet.vaultPda
1275
- }) : null;
1276
- } catch {
1277
- proof = null;
1278
- }
1279
- return Object.freeze({ handle: wallet.handle, wallet, proof });
1280
- }
1281
- function accountCandidate(accessToken) {
1282
- return accessToken ? accountBindingCandidate(accessToken) : null;
1283
- }
1284
- function canonicalAccountSubject(accessToken) {
1285
- try {
1286
- const subject = decodeJwt(accessToken).sub;
1287
- return typeof subject === "string" && CANONICAL_ACCOUNT_SUBJECT.test(subject) ? subject : null;
1288
- } catch {
1289
- return null;
1290
- }
1291
- }
1292
- function createDexterIdentityCoordinator(options = {}) {
1293
- const proofStore = options.proofSessionStore ?? walletProofSessionStore;
1294
- const bindingClient = options.bindingClient ?? createWalletAccountBindingClient({
1295
- ...options.apiBase ? { apiBase: options.apiBase } : {},
1296
- ...options.fetch ? { fetch: options.fetch } : {}
1297
- });
1298
- const controller = new WalletAccountRelationController({
1299
- verify: async ({ wallet, account, reason, signal }) => {
1300
- if (!wallet.proof) {
1301
- return {
1302
- ok: false,
1303
- reason: "expired",
1304
- subject: "wallet"
1305
- };
1306
- }
1307
- return bindingClient.verify({
1308
- wallet: wallet.proof,
1309
- account,
1310
- reason,
1311
- signal
1312
- });
1313
- }
1314
- });
1315
- let currentAccount = null;
1316
- let currentAccountAccessToken = null;
1317
- let currentAccountSubject = null;
1318
- let invalidatedAccountSubject = null;
1319
- let allowedAccountAccessToken = null;
1320
- let pendingAccountSettlement = null;
1321
- let accountLoading = false;
1322
- let disposed = false;
1323
- let started = false;
1324
- let unsubscribeWallet = null;
1325
- let unsubscribeProof = null;
1326
- let proofExpiryTimer = null;
1327
- const currentWallet = () => walletCandidate(getActiveWallet(), proofStore);
1328
- const clearCurrentAccount = () => {
1329
- currentAccount = null;
1330
- currentAccountAccessToken = null;
1331
- currentAccountSubject = null;
1332
- pendingAccountSettlement = null;
1333
- };
1334
- const setCurrentAccount = (accountAccessToken) => {
1335
- currentAccount = accountCandidate(accountAccessToken);
1336
- currentAccountAccessToken = accountAccessToken;
1337
- currentAccountSubject = canonicalAccountSubject(accountAccessToken);
1338
- };
1339
- const keepAccountLoadingLocked = (wallet) => {
1340
- clearCurrentAccount();
1341
- void controller.restore({ wallet, account: null });
1342
- controller.beginRestore();
1343
- };
1344
- const clearProofExpiryTimer = () => {
1345
- if (proofExpiryTimer !== null) clearTimeout(proofExpiryTimer);
1346
- proofExpiryTimer = null;
1347
- };
1348
- const scheduleProofExpiry = () => {
1349
- clearProofExpiryTimer();
1350
- const active = getActiveWallet();
1351
- if (!active) return;
1352
- const session = proofStore.load(active.handle);
1353
- if (!session) return;
1354
- const remainingMs = Math.max(0, session.expiresAt * 1e3 - Date.now());
1355
- const delayMs = Math.min(remainingMs, 2147e6);
1356
- proofExpiryTimer = setTimeout(() => {
1357
- proofExpiryTimer = null;
1358
- if (Date.now() < session.expiresAt * 1e3) {
1359
- scheduleProofExpiry();
1360
- return;
1361
- }
1362
- void controller.setWallet(currentWallet());
1363
- scheduleProofExpiry();
1364
- }, delayMs);
1365
- };
1366
- const start = () => {
1367
- if (started || disposed) return;
1368
- started = true;
1369
- unsubscribeWallet = subscribe((event) => {
1370
- if (disposed || !event.invalidatesAccountBinding) return;
1371
- scheduleProofExpiry();
1372
- const wallet = currentWallet();
1373
- if (accountLoading) {
1374
- keepAccountLoadingLocked(wallet);
1375
- return;
1376
- }
1377
- invalidatedAccountSubject = currentAccountSubject ?? invalidatedAccountSubject;
1378
- clearCurrentAccount();
1379
- void controller.restore({ wallet, account: null });
1380
- });
1381
- unsubscribeProof = proofStore.subscribe((event) => {
1382
- if (disposed) return;
1383
- const active = getActiveWallet();
1384
- if (!active) return;
1385
- if (event.handle !== null && event.handle !== active.handle) return;
1386
- scheduleProofExpiry();
1387
- const wallet = walletCandidate(active, proofStore);
1388
- if (accountLoading) {
1389
- keepAccountLoadingLocked(wallet);
1390
- return;
1391
- }
1392
- void controller.setWallet(wallet);
1393
- });
1394
- scheduleProofExpiry();
1395
- };
1396
- const restore = (accountAccessToken) => {
1397
- start();
1398
- accountLoading = false;
1399
- invalidatedAccountSubject = null;
1400
- allowedAccountAccessToken = null;
1401
- if (accountAccessToken) setCurrentAccount(accountAccessToken);
1402
- else clearCurrentAccount();
1403
- return controller.restore({
1404
- wallet: currentWallet(),
1405
- account: currentAccount
1406
- });
1407
- };
1408
- const setAccountSession = (accountAccessToken) => {
1409
- start();
1410
- const wasAccountLoading = accountLoading;
1411
- accountLoading = false;
1412
- if (accountAccessToken) {
1413
- if (accountAccessToken === currentAccountAccessToken && !wasAccountLoading) {
1414
- return pendingAccountSettlement?.accessToken === accountAccessToken ? pendingAccountSettlement.promise : Promise.resolve(controller.getSnapshot());
1415
- }
1416
- const nextSubject = canonicalAccountSubject(accountAccessToken);
1417
- const allowed = accountAccessToken === allowedAccountAccessToken;
1418
- if (nextSubject === null || !allowed && invalidatedAccountSubject !== null && nextSubject === invalidatedAccountSubject) {
1419
- clearCurrentAccount();
1420
- return controller.setAccount(null);
1421
- }
1422
- allowedAccountAccessToken = null;
1423
- invalidatedAccountSubject = null;
1424
- setCurrentAccount(accountAccessToken);
1425
- } else {
1426
- allowedAccountAccessToken = null;
1427
- clearCurrentAccount();
1428
- }
1429
- const settlement = controller.setAccount(currentAccount);
1430
- if (accountAccessToken) {
1431
- const tracked = { accessToken: accountAccessToken, promise: settlement };
1432
- pendingAccountSettlement = tracked;
1433
- const clearTrackedSettlement = () => {
1434
- if (pendingAccountSettlement === tracked) {
1435
- pendingAccountSettlement = null;
1436
- }
1437
- };
1438
- void settlement.then(clearTrackedSettlement, clearTrackedSettlement);
1439
- } else {
1440
- pendingAccountSettlement = null;
1441
- }
1442
- return settlement;
1443
- };
1444
- return Object.freeze({
1445
- getSnapshot: () => controller.getSnapshot(),
1446
- subscribe: (listener) => controller.subscribe(listener),
1447
- restore,
1448
- setAccountSession,
1449
- setAccountLoading: () => {
1450
- start();
1451
- accountLoading = true;
1452
- controller.beginRestore();
1453
- },
1454
- allowAccountSession: (accountAccessToken) => {
1455
- if (canonicalAccountSubject(accountAccessToken) === null) {
1456
- throw new ConnectError("invalid_account_access_token");
1457
- }
1458
- allowedAccountAccessToken = accountAccessToken;
1459
- },
1460
- retry: () => {
1461
- start();
1462
- return controller.retry();
1463
- },
1464
- dispose: () => {
1465
- if (disposed) return;
1466
- disposed = true;
1467
- clearProofExpiryTimer();
1468
- unsubscribeWallet?.();
1469
- unsubscribeProof?.();
1470
- controller.dispose();
1471
- }
1472
- });
1473
- }
1474
-
1475
1550
  // src/relay.ts
1476
- import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1551
+ import { startAuthentication as startAuthentication2, browserSupportsWebAuthn } from "@simplewebauthn/browser";
1477
1552
 
1478
1553
  // src/immediate.ts
1479
1554
  var immediateCapPromise = null;
@@ -1482,9 +1557,9 @@ function immediateGetSupported() {
1482
1557
  immediateCapPromise = (async () => {
1483
1558
  try {
1484
1559
  if (typeof window === "undefined") return false;
1485
- const pkc2 = window.PublicKeyCredential;
1486
- if (!pkc2 || typeof pkc2.getClientCapabilities !== "function") return false;
1487
- const caps = await pkc2.getClientCapabilities.call(pkc2);
1560
+ const pkc = window.PublicKeyCredential;
1561
+ if (!pkc || typeof pkc.getClientCapabilities !== "function") return false;
1562
+ const caps = await pkc.getClientCapabilities.call(pkc);
1488
1563
  return caps?.immediateGet === true;
1489
1564
  } catch {
1490
1565
  return false;
@@ -1561,7 +1636,7 @@ async function passkeyLogin(config = {}, onPhase) {
1561
1636
  onPhase?.("passkey");
1562
1637
  let response;
1563
1638
  try {
1564
- response = await startAuthentication({ optionsJSON: options });
1639
+ response = await startAuthentication2({ optionsJSON: options });
1565
1640
  } catch (err) {
1566
1641
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1567
1642
  }
@@ -1570,8 +1645,81 @@ async function passkeyLogin(config = {}, onPhase) {
1570
1645
  if (walletStore === "commit") {
1571
1646
  activateConnectVault(result.vault, result.walletIdentityProof);
1572
1647
  }
1648
+ clearPendingCreation(result.vault.credentialId);
1573
1649
  return result;
1574
1650
  }
1651
+ async function continueWithDexter(config = {}, onPhase) {
1652
+ const walletStore = resolveWalletStoreMode(config.walletStore);
1653
+ const agentDelegation = resolveAgentDelegationMode(
1654
+ config.agentDelegation ?? (config.spendPolicy ? "configure-now" : void 0)
1655
+ );
1656
+ const hasExplicitCreationChoice = config.agentDelegation !== void 0 || Boolean(config.spendPolicy);
1657
+ resolveDexterApiBase(config.apiBase);
1658
+ if (agentDelegation === "deferred" && config.spendPolicy) {
1659
+ throw new ConnectError(
1660
+ "conflicting_agent_delegation",
1661
+ "agentDelegation deferred cannot include a spendPolicy"
1662
+ );
1663
+ }
1664
+ if (shouldUsePopup(config.transport)) {
1665
+ const popupResult = await openCeremonyPopup("continue", {
1666
+ connectHost: config.connectHost,
1667
+ name: config.name,
1668
+ ...walletStore === "provisional" ? { walletStore } : {},
1669
+ agentDelegation
1670
+ });
1671
+ const result = popupResult.kind === "signin" ? { kind: "signin", ...normalizeSignInResult(popupResult) } : popupResult.kind === "create" ? {
1672
+ ...popupResult,
1673
+ walletIdentityProof: parseWalletIdentityProof(
1674
+ popupResult.walletIdentityProof
1675
+ )
1676
+ } : popupResult;
1677
+ if (walletStore === "commit") {
1678
+ if (result.kind === "create") {
1679
+ activateConnectVault(result.vault, result.walletIdentityProof);
1680
+ } else if (result.kind === "signin") {
1681
+ activateConnectVault(result.vault, result.walletIdentityProof);
1682
+ }
1683
+ }
1684
+ return result;
1685
+ }
1686
+ if (await immediateGetSupported()) {
1687
+ const probe = await immediatePasskeyLogin(config, onPhase, walletStore);
1688
+ if (probe.outcome === "signin") return { kind: "signin", ...probe.result };
1689
+ if (probe.outcome === "cancelled") return { kind: "cancelled" };
1690
+ if (!hasExplicitCreationChoice) {
1691
+ return { kind: "needs_create" };
1692
+ }
1693
+ const created = await createWallet({ ...config, onPhase });
1694
+ return { kind: "create", ...created };
1695
+ }
1696
+ if (getActiveHandle()) {
1697
+ const result = await passkeyLogin(config, onPhase);
1698
+ return { kind: "signin", ...result };
1699
+ }
1700
+ return { kind: "needs_choice" };
1701
+ }
1702
+ async function immediatePasskeyLogin(config, onPhase, walletStore = "commit") {
1703
+ const apiBase = resolveDexterApiBase(config.apiBase);
1704
+ onPhase?.("challenge");
1705
+ const options = await fetchLoginChallenge(apiBase);
1706
+ onPhase?.("passkey");
1707
+ let response;
1708
+ try {
1709
+ response = await immediateAuthentication(options);
1710
+ } catch (err) {
1711
+ if (classifyWebAuthnRejection(err)) {
1712
+ return { outcome: "no_credential" };
1713
+ }
1714
+ throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1715
+ }
1716
+ onPhase?.("verifying");
1717
+ const result = await submitLogin(apiBase, response);
1718
+ if (walletStore === "commit") {
1719
+ activateConnectVault(result.vault, result.walletIdentityProof);
1720
+ }
1721
+ return { outcome: "signin", result };
1722
+ }
1575
1723
  async function fetchLoginChallenge(apiBase) {
1576
1724
  const res = await fetch(`${apiBase}${ANON_SIGN_BASE}/login-challenge`, {
1577
1725
  method: "POST",
@@ -1627,213 +1775,25 @@ function normalizeSignInResult(value) {
1627
1775
  };
1628
1776
  }
1629
1777
 
1630
- // src/identityTransition.ts
1631
- function restoreWallet(previousWallet) {
1632
- if (previousWallet) {
1633
- return setActiveWallet(previousWallet);
1634
- }
1635
- return getActiveWallet() === null || disconnectActiveWallet();
1636
- }
1637
- async function connectDexterIdentity(config, onPhase) {
1638
- const {
1639
- installAccountSession,
1640
- bindingFetch,
1641
- ...passkeyConfig
1642
- } = config;
1643
- const previousWallet = getActiveWallet();
1644
- const result = await passkeyLogin(
1645
- { ...passkeyConfig, walletStore: "provisional" },
1646
- onPhase
1647
- );
1648
- const bindingClient = createWalletAccountBindingClient({
1649
- ...passkeyConfig.apiBase ? { apiBase: passkeyConfig.apiBase } : {},
1650
- ...bindingFetch ? { fetch: bindingFetch } : {}
1651
- });
1652
- const resolution = await bindingClient.resolve({
1653
- wallet: walletBindingCandidate(result.walletIdentityProof.token, {
1654
- userHandle: result.vault.userHandle,
1655
- vaultPda: result.vault.vaultPda
1656
- }),
1657
- account: accountBindingCandidate(result.session.accessToken)
1658
- });
1659
- if (!resolution.ok) {
1660
- throw new ConnectError(
1661
- resolution.reason === "expired" ? `identity_${resolution.subject}_expired` : resolution.reason === "offline" ? "identity_binding_offline" : resolution.code
1662
- );
1663
- }
1664
- if (resolution.relation !== "bound") {
1665
- throw new ConnectError("identity_binding_conflict");
1666
- }
1667
- if (!activateConnectVault(result.vault, result.walletIdentityProof)) {
1668
- throw new ConnectError("wallet_activation_failed");
1669
- }
1670
- try {
1671
- await installAccountSession(result.session);
1672
- } catch (cause) {
1673
- if (!restoreWallet(previousWallet)) {
1674
- throw new ConnectError(
1675
- "identity_rollback_failed",
1676
- "The previous Wallet could not be restored after account installation failed."
1677
- );
1678
- }
1679
- if (cause instanceof ConnectError) throw cause;
1680
- throw new ConnectError(
1681
- "account_session_install_failed",
1682
- cause instanceof Error ? cause.message : String(cause)
1683
- );
1684
- }
1685
- return result;
1686
- }
1687
- async function disconnectDexterIdentity(config) {
1688
- const previousWallet = getActiveWallet();
1689
- if (previousWallet && !disconnectActiveWallet()) {
1690
- throw new ConnectError("identity_wallet_disconnect_failed");
1691
- }
1692
- try {
1693
- await config.clearAccountSession();
1694
- } catch (cause) {
1695
- if (!restoreWallet(previousWallet)) {
1696
- throw new ConnectError(
1697
- "identity_rollback_failed",
1698
- "The previous Wallet could not be restored after account sign-out failed."
1699
- );
1700
- }
1701
- throw new ConnectError(
1702
- "account_session_clear_failed",
1703
- cause instanceof Error ? cause.message : String(cause)
1704
- );
1705
- }
1706
- return true;
1707
- }
1708
-
1709
- // src/connectionContract.ts
1710
- var CAPABILITIES = Object.freeze({
1711
- identity: Object.freeze(["identity"]),
1712
- wallet: Object.freeze(["identity", "wallet.read", "wallet.use"]),
1713
- agent: Object.freeze(["identity", "wallet.read", "agent.authority"])
1714
- });
1715
- function stageFor(relation, intent) {
1716
- if (relation.runtime.phase === "hydrating" || relation.runtime.phase === "checking") {
1717
- return "checking";
1718
- }
1719
- if (relation.runtime.phase === "offline") return "offline";
1720
- if (relation.runtime.phase === "error") return "error";
1721
- if (relation.runtime.phase === "expired" || relation.relation === "conflict") {
1722
- return "repair";
1723
- }
1724
- if (relation.relation === "none") return "connect";
1725
- if (relation.relation === "bound") return "ready";
1726
- if (relation.relation === "wallet_only" && intent === "wallet") return "ready";
1727
- return "repair";
1728
- }
1729
- function primaryActionFor(stage) {
1730
- if (stage === "connect") return "connect";
1731
- if (stage === "ready") return "use_another_wallet";
1732
- if (stage === "repair") return "repair";
1733
- return "retry";
1734
- }
1735
- function createDexterControlModel(intent, relation) {
1736
- const stage = stageFor(relation, intent);
1737
- const ready = relation.runtime.phase === "ready";
1738
- const bound = ready && relation.relation === "bound" && relation.privateAccountAccess;
1739
- const ownerWalletReady = intent === "wallet" && ready && relation.walletPresent && (relation.relation === "wallet_only" || bound);
1740
- return Object.freeze({
1741
- intent,
1742
- stage,
1743
- primaryAction: primaryActionFor(stage),
1744
- permissions: Object.freeze({
1745
- capabilities: CAPABILITIES[intent],
1746
- walletIdentityVisible: ready && relation.walletPresent && relation.relation !== "conflict",
1747
- walletDataVisible: ownerWalletReady || bound && intent === "agent",
1748
- ownerWalletUseEnabled: ownerWalletReady,
1749
- accountContentVisible: bound,
1750
- agentAuthorityVisible: bound && intent === "agent"
1751
- })
1752
- });
1753
- }
1754
-
1755
- // src/phase.ts
1756
- var PHASE_LABEL = {
1757
- challenge: "Preparing\u2026",
1758
- passkey: "Waiting for your passkey\u2026",
1759
- verifying: "Verifying\u2026",
1760
- finalizing: "Finishing\u2026"
1761
- };
1762
- function ceremonyPhaseLabel(phase) {
1763
- return PHASE_LABEL[phase];
1764
- }
1765
-
1766
- // src/signals.ts
1767
- function pkc() {
1768
- if (typeof window === "undefined") return null;
1769
- const g = globalThis.PublicKeyCredential;
1770
- return g ?? null;
1771
- }
1772
- function defaultRpId() {
1773
- return typeof window !== "undefined" ? window.location.hostname : "";
1774
- }
1775
- function passkeySignalSupport() {
1776
- const p = pkc();
1777
- return {
1778
- rename: typeof p?.signalCurrentUserDetails === "function",
1779
- prune: typeof p?.signalUnknownCredential === "function",
1780
- syncAccepted: typeof p?.signalAllAcceptedCredentials === "function"
1781
- };
1782
- }
1783
- async function renamePasskey(args) {
1784
- const p = pkc();
1785
- if (typeof p?.signalCurrentUserDetails !== "function") return false;
1786
- try {
1787
- await p.signalCurrentUserDetails({
1788
- rpId: args.rpId ?? defaultRpId(),
1789
- userId: args.userId,
1790
- name: args.name,
1791
- displayName: args.displayName ?? args.name
1792
- });
1793
- return true;
1794
- } catch {
1795
- return false;
1796
- }
1797
- }
1798
- async function prunePasskey(args) {
1799
- const p = pkc();
1800
- if (typeof p?.signalUnknownCredential !== "function") return false;
1801
- try {
1802
- await p.signalUnknownCredential({
1803
- rpId: args.rpId ?? defaultRpId(),
1804
- credentialId: args.credentialId
1805
- });
1806
- return true;
1807
- } catch {
1808
- return false;
1809
- }
1810
- }
1811
- async function syncAcceptedPasskeys(args) {
1812
- const p = pkc();
1813
- if (typeof p?.signalAllAcceptedCredentials !== "function") return false;
1814
- try {
1815
- await p.signalAllAcceptedCredentials({
1816
- rpId: args.rpId ?? defaultRpId(),
1817
- userId: args.userId,
1818
- allAcceptedCredentialIds: args.acceptedCredentialIds
1819
- });
1820
- return true;
1821
- } catch {
1822
- return false;
1823
- }
1824
- }
1825
-
1826
1778
  export {
1827
1779
  resolveWalletStoreMode,
1780
+ resolveAgentDelegationMode,
1828
1781
  ConnectError,
1829
1782
  parseWalletIdentityProof,
1830
1783
  readErrorCode,
1784
+ DEXTER_API_BASE,
1831
1785
  resolveDexterApiBase,
1786
+ resolveDexterConnectHost,
1832
1787
  resolveDexterRpId,
1833
1788
  bytesEqual,
1789
+ normalizeMissingVaultRecoveryOptions,
1790
+ parseMissingVaultRecoveryChallenge,
1791
+ validateMissingVaultRecoveryAssertion,
1792
+ parseMissingVaultRecoveryResult,
1834
1793
  shouldUsePopup,
1835
1794
  openCeremonyPopup,
1836
1795
  getActiveHandle,
1796
+ getActiveWallet,
1837
1797
  setActiveWallet,
1838
1798
  setActiveHandle,
1839
1799
  disconnectActiveWallet,
@@ -1846,27 +1806,22 @@ export {
1846
1806
  WALLET_ACCOUNT_BINDING_PATH,
1847
1807
  walletBindingCandidate,
1848
1808
  accountBindingCandidate,
1809
+ fetchWithWalletIdentity,
1849
1810
  createWalletAccountBindingClient,
1850
1811
  WALLET_PROOF_SESSION_STORAGE_PREFIX,
1851
1812
  createWalletProofSessionStore,
1852
1813
  walletProofSessionStore,
1814
+ activateConnectVault,
1853
1815
  activateRecoveredVault,
1854
1816
  SESSION_TTL_30D,
1855
1817
  usdToAtomic,
1856
1818
  authoredPolicy,
1819
+ clearPendingCreation,
1857
1820
  createWallet,
1858
1821
  immediateGetSupported,
1859
1822
  primeImmediateSupport,
1860
1823
  immediateAuthentication,
1861
1824
  classifyWebAuthnRejection,
1862
- WalletAccountRelationController,
1863
- createDexterIdentityCoordinator,
1864
- connectDexterIdentity,
1865
- disconnectDexterIdentity,
1866
- createDexterControlModel,
1867
- ceremonyPhaseLabel,
1868
- passkeySignalSupport,
1869
- renamePasskey,
1870
- prunePasskey,
1871
- syncAcceptedPasskeys
1825
+ passkeyLogin,
1826
+ continueWithDexter
1872
1827
  };