@dexterai/connect 0.34.0 → 0.35.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.
@@ -84,6 +84,14 @@ function bytesEqual(a, b) {
84
84
  return difference === 0;
85
85
  }
86
86
 
87
+ // src/enroll.ts
88
+ var DEXTER_WALLET_CLOSED_CODE = "dexter_wallet_closed";
89
+ var DEXTER_WALLET_CLOSED_MESSAGE = "Dexter Wallet is now Dexter Account. Your Account works at dexter.cash; this app can't use it yet.";
90
+ async function createWallet(config = {}) {
91
+ void config;
92
+ throw new ConnectError(DEXTER_WALLET_CLOSED_CODE, DEXTER_WALLET_CLOSED_MESSAGE);
93
+ }
94
+
87
95
  // src/bindingResolver.ts
88
96
  import { PublicKey } from "@solana/web3.js";
89
97
  var WALLET_ACCOUNT_BINDING_PATH = "/api/passkey-anon/binding/resolve";
@@ -506,468 +514,191 @@ function createWalletProofSessionStore(options = {}) {
506
514
  }
507
515
  var walletProofSessionStore = createWalletProofSessionStore();
508
516
 
509
- // src/policy.ts
510
- var SESSION_TTL_30D = "2592000";
511
- function usdToAtomic(input) {
512
- const cleaned = input.trim().replace(/^\$/, "").replace(/,/g, "");
513
- if (!/^\d+(\.\d{1,6})?$/.test(cleaned)) return null;
514
- const [whole, frac = ""] = cleaned.split(".");
517
+ // src/accountIdentity.ts
518
+ import {
519
+ browserSupportsWebAuthn,
520
+ startAuthentication,
521
+ startRegistration
522
+ } from "@simplewebauthn/browser";
523
+
524
+ // src/httpError.ts
525
+ async function readErrorCode(res) {
515
526
  try {
516
- return BigInt(whole) * 1000000n + BigInt((frac + "000000").slice(0, 6));
527
+ const body = await res.json();
528
+ if (body?.error) return body.error;
517
529
  } catch {
518
- return null;
519
530
  }
520
- }
521
- function authoredPolicy(usdInput) {
522
- const atomic = usdToAtomic(usdInput);
523
- if (atomic === null || atomic <= 0n) return null;
524
- return { spendLimitAtomic: atomic.toString(), sessionTtlSeconds: SESSION_TTL_30D };
531
+ return `http_${res.status}`;
525
532
  }
526
533
 
527
- // src/enroll.ts
528
- import { startRegistration, startAuthentication } from "@simplewebauthn/browser";
529
-
530
- // src/walletStore.ts
531
- var ACTIVE_HANDLE_KEY = "dexter:passkey:userHandle";
532
- var ROSTER_KEY = "dexter:passkey:wallets";
533
- var DEVICE_WALLET_REMOVAL_CONFIRMATION = "remove-wallet-from-device";
534
- var listeners = /* @__PURE__ */ new Set();
535
- var lastObservedActiveWallet = null;
536
- function hasStorage() {
537
- try {
538
- return typeof window !== "undefined" && !!window.localStorage;
539
- } catch {
540
- return false;
534
+ // src/missingVaultRecoveryContract.ts
535
+ var DEXTER_ORIGIN = "https://dexter.cash";
536
+ var MIN_CHALLENGE_BYTES = 16;
537
+ var MAX_CHALLENGE_BYTES = 128;
538
+ function normalizeMissingVaultRecoveryOptions(value) {
539
+ if (!value || typeof value !== "object") {
540
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
541
+ }
542
+ const options = value;
543
+ const challenge = canonicalBase64url(
544
+ options.challenge,
545
+ MIN_CHALLENGE_BYTES,
546
+ MAX_CHALLENGE_BYTES,
547
+ "missing_vault_recovery_challenge_malformed"
548
+ );
549
+ const challengeBytes = base64urlToBytes(challenge);
550
+ 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)) {
551
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
552
+ }
553
+ if (options.timeout !== void 0 && (typeof options.timeout !== "number" || !Number.isFinite(options.timeout) || options.timeout <= 0 || options.timeout > 3e5)) {
554
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
541
555
  }
542
- }
543
- function optionalString(value) {
544
- return typeof value === "string" && value.length > 0 ? value : void 0;
545
- }
546
- function normalizeWallet(value, migrateHistoricalRow = true) {
547
- if (!value || typeof value !== "object") return null;
548
- const raw = value;
549
- const handle = optionalString(raw.handle);
550
- if (!handle) return null;
551
- const rosterState = raw.rosterState === "unavailable" || raw.rosterState === "known" ? raw.rosterState : migrateHistoricalRow ? "known" : void 0;
552
- const verificationState = raw.verificationState === "verified" || raw.verificationState === "quarantined" || raw.verificationState === "unverified" ? raw.verificationState : migrateHistoricalRow ? "unverified" : void 0;
553
556
  return {
554
- handle,
555
- ...optionalString(raw.label) ? { label: optionalString(raw.label) } : {},
556
- ...optionalString(raw.credentialId) ? { credentialId: optionalString(raw.credentialId) } : {},
557
- ...optionalString(raw.vaultPda) ? { vaultPda: optionalString(raw.vaultPda) } : {},
558
- ...optionalString(raw.swigAddress) ? { swigAddress: optionalString(raw.swigAddress) } : {},
559
- ...optionalString(raw.walletAddress) ? { walletAddress: optionalString(raw.walletAddress) } : {},
560
- ...raw.receiveAddress === null ? { receiveAddress: null } : optionalString(raw.receiveAddress) ? { receiveAddress: optionalString(raw.receiveAddress) } : {},
561
- ...optionalString(raw.network) ? { network: optionalString(raw.network) } : {},
562
- ...rosterState ? { rosterState } : {},
563
- ...verificationState ? { verificationState } : {},
564
- ...typeof raw.lastUsedAt === "number" && Number.isFinite(raw.lastUsedAt) ? { lastUsedAt: raw.lastUsedAt } : {}
557
+ challenge,
558
+ rpId: DEXTER_RP_ID,
559
+ userVerification: "required",
560
+ ...typeof options.timeout === "number" ? { timeout: options.timeout } : {}
565
561
  };
566
562
  }
567
- function readRoster() {
568
- if (!hasStorage()) return [];
569
- try {
570
- const raw = window.localStorage.getItem(ROSTER_KEY);
571
- if (!raw) return [];
572
- const parsed = JSON.parse(raw);
573
- if (!Array.isArray(parsed)) return [];
574
- const wallets = /* @__PURE__ */ new Map();
575
- for (const value of parsed) {
576
- const wallet = normalizeWallet(value);
577
- if (wallet) wallets.set(wallet.handle, wallet);
578
- }
579
- return [...wallets.values()];
580
- } catch {
581
- return [];
563
+ function parseMissingVaultRecoveryChallenge(value) {
564
+ if (!value || typeof value !== "object") {
565
+ throw new ConnectError("missing_vault_recovery_challenge_malformed");
566
+ }
567
+ const envelope = value;
568
+ if (envelope.operation !== "vault_missing_recovery") {
569
+ throw new ConnectError("missing_vault_recovery_operation_mismatch");
582
570
  }
571
+ return {
572
+ options: normalizeMissingVaultRecoveryOptions(envelope.options),
573
+ account: parseMissingVaultRecoveryAccount(envelope.account)
574
+ };
583
575
  }
584
- function writeRoster(wallets) {
585
- if (!hasStorage()) return false;
576
+ async function validateMissingVaultRecoveryAssertion(value, expectedChallenge) {
577
+ if (!value || typeof value !== "object") {
578
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
579
+ }
580
+ const credential = value;
581
+ const response = credential.response;
582
+ if (!response || typeof response !== "object") {
583
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
584
+ }
585
+ const assertion = response;
586
+ const id = canonicalBase64url(
587
+ credential.id,
588
+ 1,
589
+ 1024,
590
+ "missing_vault_recovery_assertion_malformed"
591
+ );
592
+ const rawId = canonicalBase64url(
593
+ credential.rawId,
594
+ 1,
595
+ 1024,
596
+ "missing_vault_recovery_assertion_malformed"
597
+ );
598
+ if (!bytesEqual(base64urlToBytes(id), base64urlToBytes(rawId)) || credential.type !== "public-key" || !isPlainObject(credential.clientExtensionResults) || Object.keys(credential.clientExtensionResults).length !== 0) {
599
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
600
+ }
601
+ const clientDataJSON = canonicalBase64url(
602
+ assertion.clientDataJSON,
603
+ 1,
604
+ 8192,
605
+ "missing_vault_recovery_assertion_malformed"
606
+ );
607
+ const authenticatorData = canonicalBase64url(
608
+ assertion.authenticatorData,
609
+ 37,
610
+ 4096,
611
+ "missing_vault_recovery_assertion_malformed"
612
+ );
613
+ const signature = canonicalBase64url(
614
+ assertion.signature,
615
+ 1,
616
+ 1024,
617
+ "missing_vault_recovery_assertion_malformed"
618
+ );
619
+ const userHandle = assertion.userHandle === void 0 || assertion.userHandle === null ? void 0 : canonicalBase64url(
620
+ assertion.userHandle,
621
+ 1,
622
+ 1024,
623
+ "missing_vault_recovery_assertion_malformed"
624
+ );
625
+ let clientData;
586
626
  try {
587
- window.localStorage.setItem(ROSTER_KEY, JSON.stringify(wallets));
588
- return true;
627
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(
628
+ base64urlToBytes(clientDataJSON)
629
+ );
630
+ clientData = JSON.parse(decoded);
589
631
  } catch {
590
- return false;
632
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
591
633
  }
592
- }
593
- function walletForHandle(handle, roster = readRoster()) {
594
- if (!handle) return null;
595
- return roster.find((wallet) => wallet.handle === handle) ?? {
596
- handle,
597
- rosterState: "known",
598
- verificationState: "unverified"
634
+ if (clientData.type !== "webauthn.get" || clientData.challenge !== expectedChallenge || clientData.origin !== DEXTER_ORIGIN || clientData.crossOrigin !== false) {
635
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
636
+ }
637
+ const authData = base64urlToBytes(authenticatorData);
638
+ const expectedRpHash = new Uint8Array(
639
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(DEXTER_RP_ID))
640
+ );
641
+ const flags = authData[32] ?? 0;
642
+ if (!bytesEqual(authData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
643
+ throw new ConnectError("missing_vault_recovery_assertion_unbound");
644
+ }
645
+ const authenticatorAttachment = credential.authenticatorAttachment;
646
+ if (authenticatorAttachment !== void 0 && authenticatorAttachment !== "platform" && authenticatorAttachment !== "cross-platform") {
647
+ throw new ConnectError("missing_vault_recovery_assertion_malformed");
648
+ }
649
+ return {
650
+ id,
651
+ rawId,
652
+ type: "public-key",
653
+ response: {
654
+ clientDataJSON,
655
+ authenticatorData,
656
+ signature,
657
+ ...userHandle ? { userHandle } : {}
658
+ },
659
+ clientExtensionResults: {},
660
+ ...authenticatorAttachment ? { authenticatorAttachment } : {}
599
661
  };
600
662
  }
601
- function emit(event) {
602
- lastObservedActiveWallet = event.activeWallet;
603
- for (const listener of listeners) {
604
- try {
605
- listener(event);
606
- } catch {
607
- }
663
+ function parseMissingVaultRecoveryResult(value, credential, expectedAccount) {
664
+ if (!value || typeof value !== "object") {
665
+ throw new ConnectError("missing_vault_recovery_result_malformed");
666
+ }
667
+ const result = value;
668
+ const vault = result.vault;
669
+ if (result.recovered !== true || typeof result.alreadyRecovered !== "boolean" || result.relation !== "bound" || !vault || typeof vault !== "object") {
670
+ throw new ConnectError("missing_vault_recovery_result_malformed");
671
+ }
672
+ const row = vault;
673
+ const account = parseMissingVaultRecoveryAccount(result.account);
674
+ const credentialId = canonicalBase64url(
675
+ row.credentialId,
676
+ 1,
677
+ 1024,
678
+ "missing_vault_recovery_result_malformed"
679
+ );
680
+ const userHandle = canonicalBase64url(
681
+ row.userHandle,
682
+ 1,
683
+ 1024,
684
+ "missing_vault_recovery_result_malformed"
685
+ );
686
+ 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") {
687
+ throw new ConnectError("missing_vault_recovery_result_malformed");
608
688
  }
609
- }
610
- function mutationEvent(operation, previousActiveWallet, activeWallet, wallet) {
611
- const activeIdentityFactsChanged = previousActiveWallet?.handle === activeWallet?.handle && (previousActiveWallet?.vaultPda !== activeWallet?.vaultPda || previousActiveWallet?.credentialId !== activeWallet?.credentialId);
612
689
  return {
613
- operation,
614
- previousActiveWallet,
615
- activeWallet,
616
- wallet,
617
- invalidatesAccountBinding: previousActiveWallet?.handle !== activeWallet?.handle || activeIdentityFactsChanged
618
- };
619
- }
620
- function mergeDefinedWallet(existing, incoming) {
621
- const base = existing ?? {
622
- handle: incoming.handle,
623
- rosterState: "known",
624
- verificationState: "unverified"
625
- };
626
- return {
627
- ...base,
628
- handle: incoming.handle,
629
- ...incoming.label !== void 0 ? { label: incoming.label } : {},
630
- ...incoming.credentialId !== void 0 ? { credentialId: incoming.credentialId } : {},
631
- ...incoming.vaultPda !== void 0 ? { vaultPda: incoming.vaultPda } : {},
632
- ...incoming.swigAddress !== void 0 ? { swigAddress: incoming.swigAddress } : {},
633
- ...incoming.walletAddress !== void 0 ? { walletAddress: incoming.walletAddress } : {},
634
- ...incoming.receiveAddress !== void 0 ? { receiveAddress: incoming.receiveAddress } : {},
635
- ...incoming.network !== void 0 ? { network: incoming.network } : {},
636
- ...incoming.rosterState !== void 0 ? { rosterState: incoming.rosterState } : {},
637
- ...incoming.verificationState !== void 0 ? { verificationState: incoming.verificationState } : {},
638
- rosterState: incoming.rosterState || base.rosterState || "known",
639
- verificationState: incoming.verificationState || base.verificationState || "unverified",
640
- lastUsedAt: Date.now()
641
- };
642
- }
643
- function activateWallet(wallet, requestedOperation) {
644
- if (!hasStorage()) return false;
645
- const normalized = normalizeWallet(wallet, false);
646
- if (!normalized) return false;
647
- const roster = readRoster();
648
- const previousActiveWallet = walletForHandle(getActiveHandle(), roster);
649
- const existingIndex = roster.findIndex((row) => row.handle === normalized.handle);
650
- const nextWallet = mergeDefinedWallet(
651
- existingIndex >= 0 ? roster[existingIndex] : void 0,
652
- normalized
653
- );
654
- if (existingIndex >= 0) roster[existingIndex] = nextWallet;
655
- else roster.push(nextWallet);
656
- const previousRoster = readRoster();
657
- if (!writeRoster(roster)) return false;
658
- try {
659
- window.localStorage.setItem(ACTIVE_HANDLE_KEY, normalized.handle);
660
- } catch {
661
- writeRoster(previousRoster);
662
- return false;
663
- }
664
- const changedHandle = previousActiveWallet?.handle !== normalized.handle;
665
- const operation = changedHandle ? requestedOperation ?? (previousActiveWallet ? "switch" : "activate") : "update";
666
- emit(mutationEvent(operation, previousActiveWallet, nextWallet, nextWallet));
667
- return true;
668
- }
669
- function removeRosterWallet(handle, operation) {
670
- if (!hasStorage() || !handle) return null;
671
- const roster = readRoster();
672
- const removedWallet = roster.find((wallet) => wallet.handle === handle) ?? null;
673
- if (!removedWallet) return null;
674
- const previousActiveWallet = walletForHandle(getActiveHandle(), roster);
675
- const wasActive = previousActiveWallet?.handle === handle;
676
- const nextRoster = roster.filter((wallet) => wallet.handle !== handle);
677
- if (!writeRoster(nextRoster)) return null;
678
- if (wasActive) {
679
- try {
680
- window.localStorage.removeItem(ACTIVE_HANDLE_KEY);
681
- } catch {
682
- writeRoster(roster);
683
- return null;
684
- }
685
- }
686
- const activeWallet = wasActive ? null : previousActiveWallet;
687
- emit(mutationEvent(operation, previousActiveWallet, activeWallet, removedWallet));
688
- return removedWallet;
689
- }
690
- function getActiveHandle() {
691
- if (!hasStorage()) return null;
692
- try {
693
- return window.localStorage.getItem(ACTIVE_HANDLE_KEY);
694
- } catch {
695
- return null;
696
- }
697
- }
698
- function getActiveWallet() {
699
- return walletForHandle(getActiveHandle());
700
- }
701
- function setActiveWallet(wallet) {
702
- return activateWallet(wallet);
703
- }
704
- function setActiveHandle(handle, label, credentialId) {
705
- activateWallet({ handle, label, credentialId });
706
- }
707
- function getCredentialId(handle) {
708
- return readRoster().find((wallet) => wallet.handle === handle)?.credentialId;
709
- }
710
- function disconnectActiveWallet() {
711
- if (!hasStorage()) return false;
712
- const previousActiveWallet = getActiveWallet();
713
- if (!previousActiveWallet) return false;
714
- try {
715
- window.localStorage.removeItem(ACTIVE_HANDLE_KEY);
716
- } catch {
717
- return false;
718
- }
719
- emit(mutationEvent("disconnect", previousActiveWallet, null, previousActiveWallet));
720
- return true;
721
- }
722
- function ejectActiveWallet(opts) {
723
- const handle = getActiveHandle();
724
- if (opts?.forget && handle) {
725
- forgetWallet(handle);
726
- return;
727
- }
728
- disconnectActiveWallet();
729
- }
730
- function listWallets() {
731
- return readRoster().sort((a, b) => (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0));
732
- }
733
- function switchWallet(handle) {
734
- const wallet = readRoster().find((row) => row.handle === handle);
735
- if (!wallet) return false;
736
- return activateWallet(wallet, "switch");
737
- }
738
- function forgetWallet(handle) {
739
- removeRosterWallet(handle, "forget");
740
- }
741
- function removeWalletFromDeviceRoster(handle, confirmation) {
742
- if (confirmation !== DEVICE_WALLET_REMOVAL_CONFIRMATION) return null;
743
- return removeRosterWallet(handle, "remove-device");
744
- }
745
- function subscribe(listener) {
746
- listeners.add(listener);
747
- if (hasStorage() && listeners.size === 1) {
748
- lastObservedActiveWallet = getActiveWallet();
749
- window.addEventListener("storage", onStorageEvent);
750
- }
751
- return () => {
752
- listeners.delete(listener);
753
- if (hasStorage() && listeners.size === 0) {
754
- window.removeEventListener("storage", onStorageEvent);
755
- }
756
- };
757
- }
758
- function onStorageEvent(event) {
759
- if (event.key !== ACTIVE_HANDLE_KEY && event.key !== ROSTER_KEY && event.key !== null) return;
760
- const previousActiveWallet = lastObservedActiveWallet;
761
- const activeWallet = getActiveWallet();
762
- emit(mutationEvent("external", previousActiveWallet, activeWallet, activeWallet));
763
- }
764
-
765
- // src/walletActivation.ts
766
- function activateConnectVault(vault, walletIdentityProof) {
767
- const proof = parseWalletIdentityProof(walletIdentityProof);
768
- const proofSession = walletProofSessionStore.save(vault.userHandle, proof);
769
- if (!proofSession) return false;
770
- const activated = setActiveWallet({
771
- handle: vault.userHandle,
772
- label: vault.walletLabel ?? void 0,
773
- credentialId: vault.credentialId,
774
- vaultPda: vault.vaultPda,
775
- swigAddress: vault.swigAddress,
776
- walletAddress: vault.swigAddress,
777
- receiveAddress: vault.receiveAddress,
778
- network: "solana-mainnet",
779
- verificationState: "unverified"
780
- });
781
- if (!activated) walletProofSessionStore.clear(vault.userHandle);
782
- return activated;
783
- }
784
- function activateRecoveredVault(userHandle, credentialId, vault, walletIdentityProof) {
785
- const proof = parseWalletIdentityProof(walletIdentityProof);
786
- const proofSession = walletProofSessionStore.save(userHandle, proof);
787
- if (!proofSession) return false;
788
- const activated = setActiveWallet({
789
- handle: userHandle,
790
- label: vault.walletLabel ?? void 0,
791
- credentialId,
792
- vaultPda: vault.vaultPda,
793
- swigAddress: vault.swigAddress,
794
- walletAddress: vault.swigAddress,
795
- receiveAddress: vault.receiveAddress,
796
- network: "solana-mainnet",
797
- verificationState: "unverified"
798
- });
799
- if (!activated) walletProofSessionStore.clear(userHandle);
800
- return activated;
801
- }
802
-
803
- // src/missingVaultRecoveryContract.ts
804
- var DEXTER_ORIGIN = "https://dexter.cash";
805
- var MIN_CHALLENGE_BYTES = 16;
806
- var MAX_CHALLENGE_BYTES = 128;
807
- function normalizeMissingVaultRecoveryOptions(value) {
808
- if (!value || typeof value !== "object") {
809
- throw new ConnectError("missing_vault_recovery_challenge_malformed");
810
- }
811
- const options = value;
812
- const challenge = canonicalBase64url(
813
- options.challenge,
814
- MIN_CHALLENGE_BYTES,
815
- MAX_CHALLENGE_BYTES,
816
- "missing_vault_recovery_challenge_malformed"
817
- );
818
- const challengeBytes = base64urlToBytes(challenge);
819
- 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)) {
820
- throw new ConnectError("missing_vault_recovery_challenge_malformed");
821
- }
822
- if (options.timeout !== void 0 && (typeof options.timeout !== "number" || !Number.isFinite(options.timeout) || options.timeout <= 0 || options.timeout > 3e5)) {
823
- throw new ConnectError("missing_vault_recovery_challenge_malformed");
824
- }
825
- return {
826
- challenge,
827
- rpId: DEXTER_RP_ID,
828
- userVerification: "required",
829
- ...typeof options.timeout === "number" ? { timeout: options.timeout } : {}
830
- };
831
- }
832
- function parseMissingVaultRecoveryChallenge(value) {
833
- if (!value || typeof value !== "object") {
834
- throw new ConnectError("missing_vault_recovery_challenge_malformed");
835
- }
836
- const envelope = value;
837
- if (envelope.operation !== "vault_missing_recovery") {
838
- throw new ConnectError("missing_vault_recovery_operation_mismatch");
839
- }
840
- return {
841
- options: normalizeMissingVaultRecoveryOptions(envelope.options),
842
- account: parseMissingVaultRecoveryAccount(envelope.account)
843
- };
844
- }
845
- async function validateMissingVaultRecoveryAssertion(value, expectedChallenge) {
846
- if (!value || typeof value !== "object") {
847
- throw new ConnectError("missing_vault_recovery_assertion_malformed");
848
- }
849
- const credential = value;
850
- const response = credential.response;
851
- if (!response || typeof response !== "object") {
852
- throw new ConnectError("missing_vault_recovery_assertion_malformed");
853
- }
854
- const assertion = response;
855
- const id = canonicalBase64url(
856
- credential.id,
857
- 1,
858
- 1024,
859
- "missing_vault_recovery_assertion_malformed"
860
- );
861
- const rawId = canonicalBase64url(
862
- credential.rawId,
863
- 1,
864
- 1024,
865
- "missing_vault_recovery_assertion_malformed"
866
- );
867
- if (!bytesEqual(base64urlToBytes(id), base64urlToBytes(rawId)) || credential.type !== "public-key" || !isPlainObject(credential.clientExtensionResults) || Object.keys(credential.clientExtensionResults).length !== 0) {
868
- throw new ConnectError("missing_vault_recovery_assertion_malformed");
869
- }
870
- const clientDataJSON = canonicalBase64url(
871
- assertion.clientDataJSON,
872
- 1,
873
- 8192,
874
- "missing_vault_recovery_assertion_malformed"
875
- );
876
- const authenticatorData = canonicalBase64url(
877
- assertion.authenticatorData,
878
- 37,
879
- 4096,
880
- "missing_vault_recovery_assertion_malformed"
881
- );
882
- const signature = canonicalBase64url(
883
- assertion.signature,
884
- 1,
885
- 1024,
886
- "missing_vault_recovery_assertion_malformed"
887
- );
888
- const userHandle = assertion.userHandle === void 0 || assertion.userHandle === null ? void 0 : canonicalBase64url(
889
- assertion.userHandle,
890
- 1,
891
- 1024,
892
- "missing_vault_recovery_assertion_malformed"
893
- );
894
- let clientData;
895
- try {
896
- const decoded = new TextDecoder("utf-8", { fatal: true }).decode(
897
- base64urlToBytes(clientDataJSON)
898
- );
899
- clientData = JSON.parse(decoded);
900
- } catch {
901
- throw new ConnectError("missing_vault_recovery_assertion_malformed");
902
- }
903
- if (clientData.type !== "webauthn.get" || clientData.challenge !== expectedChallenge || clientData.origin !== DEXTER_ORIGIN || clientData.crossOrigin !== false) {
904
- throw new ConnectError("missing_vault_recovery_assertion_unbound");
905
- }
906
- const authData = base64urlToBytes(authenticatorData);
907
- const expectedRpHash = new Uint8Array(
908
- await crypto.subtle.digest("SHA-256", new TextEncoder().encode(DEXTER_RP_ID))
909
- );
910
- const flags = authData[32] ?? 0;
911
- if (!bytesEqual(authData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
912
- throw new ConnectError("missing_vault_recovery_assertion_unbound");
913
- }
914
- const authenticatorAttachment = credential.authenticatorAttachment;
915
- if (authenticatorAttachment !== void 0 && authenticatorAttachment !== "platform" && authenticatorAttachment !== "cross-platform") {
916
- throw new ConnectError("missing_vault_recovery_assertion_malformed");
917
- }
918
- return {
919
- id,
920
- rawId,
921
- type: "public-key",
922
- response: {
923
- clientDataJSON,
924
- authenticatorData,
925
- signature,
926
- ...userHandle ? { userHandle } : {}
927
- },
928
- clientExtensionResults: {},
929
- ...authenticatorAttachment ? { authenticatorAttachment } : {}
930
- };
931
- }
932
- function parseMissingVaultRecoveryResult(value, credential, expectedAccount) {
933
- if (!value || typeof value !== "object") {
934
- throw new ConnectError("missing_vault_recovery_result_malformed");
935
- }
936
- const result = value;
937
- const vault = result.vault;
938
- if (result.recovered !== true || typeof result.alreadyRecovered !== "boolean" || result.relation !== "bound" || !vault || typeof vault !== "object") {
939
- throw new ConnectError("missing_vault_recovery_result_malformed");
940
- }
941
- const row = vault;
942
- const account = parseMissingVaultRecoveryAccount(result.account);
943
- const credentialId = canonicalBase64url(
944
- row.credentialId,
945
- 1,
946
- 1024,
947
- "missing_vault_recovery_result_malformed"
948
- );
949
- const userHandle = canonicalBase64url(
950
- row.userHandle,
951
- 1,
952
- 1024,
953
- "missing_vault_recovery_result_malformed"
954
- );
955
- 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") {
956
- throw new ConnectError("missing_vault_recovery_result_malformed");
957
- }
958
- return {
959
- recovered: true,
960
- alreadyRecovered: result.alreadyRecovered,
961
- relation: "bound",
962
- account,
963
- vault: {
964
- vaultPda: row.vaultPda,
965
- swigAddress: row.swigAddress,
966
- receiveAddress: row.receiveAddress,
967
- userHandle,
968
- credentialId,
969
- state: "initialized"
970
- }
690
+ recovered: true,
691
+ alreadyRecovered: result.alreadyRecovered,
692
+ relation: "bound",
693
+ account,
694
+ vault: {
695
+ vaultPda: row.vaultPda,
696
+ swigAddress: row.swigAddress,
697
+ receiveAddress: row.receiveAddress,
698
+ userHandle,
699
+ credentialId,
700
+ state: "initialized"
701
+ }
971
702
  };
972
703
  }
973
704
  function parseMissingVaultRecoveryAccount(value) {
@@ -1263,575 +994,542 @@ function makeNonce() {
1263
994
  return `rid-${new URL(location.href).searchParams.get("v") ?? ""}-${typeof performance !== "undefined" ? performance.now() : 0}`;
1264
995
  }
1265
996
 
1266
- // src/httpError.ts
1267
- async function readErrorCode(res) {
997
+ // src/accountIdentity.ts
998
+ var ACCOUNT_IDENTITY_API_PATH = "/api/connect/account-identity";
999
+ function record(value) {
1000
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1001
+ }
1002
+ function canonicalBase64url2(value, exactLength) {
1003
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value) || value.length > 1400) return false;
1268
1004
  try {
1269
- const body = await res.json();
1270
- if (body?.error) return body.error;
1005
+ const bytes = base64urlToBytes(value);
1006
+ return bytes.length > 0 && bytes.length <= 1024 && (exactLength === void 0 || bytes.length === exactLength) && bytesToBase64url(bytes) === value;
1271
1007
  } catch {
1008
+ return false;
1272
1009
  }
1273
- return `http_${res.status}`;
1274
1010
  }
1275
-
1276
- // src/pendingCreation.ts
1277
- var KEY = "dexter:pending-wallet-creation:v1";
1278
- var retained = null;
1279
- function storage() {
1011
+ function validPublicKey(value) {
1012
+ if (typeof value !== "string" || value.length !== 44) return false;
1280
1013
  try {
1281
- return typeof window === "undefined" ? null : window.localStorage;
1014
+ const bytes = base64ToBytes(value);
1015
+ return bytes.length === 33 && (bytes[0] === 2 || bytes[0] === 3) && bytesToBase64(bytes) === value;
1282
1016
  } catch {
1283
- return null;
1017
+ return false;
1018
+ }
1019
+ }
1020
+ function positiveInteger(value) {
1021
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1022
+ }
1023
+ function normalizeSession(session) {
1024
+ if (!record(session) || typeof session.accessToken !== "string" || session.accessToken.length === 0 || /\s/.test(session.accessToken) || session.tokenType !== "Bearer" || !positiveInteger(session.expiresAt) || !positiveInteger(session.expiresIn) || session.expiresIn > 30 * 24 * 60 * 60) {
1025
+ throw new ConnectError("account_identity_result_malformed");
1026
+ }
1027
+ return Object.freeze({
1028
+ accessToken: session.accessToken,
1029
+ expiresAt: session.expiresAt,
1030
+ expiresIn: session.expiresIn,
1031
+ tokenType: "Bearer"
1032
+ });
1033
+ }
1034
+ function normalizeResult(value) {
1035
+ if (!record(value) || value.profile !== "account-identity-v1" || !record(value.credential)) {
1036
+ throw new ConnectError("account_identity_result_malformed");
1037
+ }
1038
+ const { credential } = value;
1039
+ if (!canonicalBase64url2(credential.userHandle, 16) || !canonicalBase64url2(credential.credentialId) || !validPublicKey(credential.publicKey)) {
1040
+ throw new ConnectError("account_identity_result_malformed");
1041
+ }
1042
+ return Object.freeze({
1043
+ profile: "account-identity-v1",
1044
+ session: normalizeSession(value.session),
1045
+ credential: Object.freeze({
1046
+ userHandle: credential.userHandle,
1047
+ credentialId: credential.credentialId,
1048
+ publicKey: credential.publicKey
1049
+ })
1050
+ });
1051
+ }
1052
+ function normalizeAccessResult(value) {
1053
+ const identity = normalizeResult(value);
1054
+ const refusalProof = normalizeSession(record(value) ? value.refusalProof : void 0);
1055
+ if (refusalProof.accessToken === identity.session.accessToken) {
1056
+ throw new ConnectError("account_identity_result_malformed");
1057
+ }
1058
+ return Object.freeze({ ...identity, refusalProof });
1059
+ }
1060
+ function bindRefusalRequest(request) {
1061
+ assertInlineOrigin();
1062
+ if (window.top !== window || window.location.pathname !== "/tabs/setup" || !record(request) || typeof request.request_id !== "string" || typeof request.decline_token !== "string" || !/^vpair_[a-f0-9]{1,80}$/.test(request.request_id) || !/^[a-f0-9]{64}$/.test(request.decline_token) || new URL(window.location.href).searchParams.get("request_id") !== request.request_id) {
1063
+ throw new ConnectError("account_request_mismatch");
1284
1064
  }
1065
+ return Object.freeze({ request_id: request.request_id, decline_token: request.decline_token });
1285
1066
  }
1286
- function readPendingCreation() {
1287
- const store = storage();
1288
- if (!store) return retained;
1289
- let raw;
1067
+ async function post(apiBase, endpoint, body) {
1068
+ let response;
1290
1069
  try {
1291
- raw = store.getItem(KEY);
1070
+ response = await fetch(`${apiBase}${ACCOUNT_IDENTITY_API_PATH}/${endpoint}`, {
1071
+ method: "POST",
1072
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
1073
+ body: JSON.stringify(body),
1074
+ credentials: "omit",
1075
+ cache: "no-store",
1076
+ redirect: "error"
1077
+ });
1292
1078
  } catch {
1293
- return retained;
1079
+ throw new ConnectError(endpoint === "login" || endpoint === "enroll" ? "account_identity_request_uncertain" : "account_identity_unavailable");
1294
1080
  }
1295
- if (!raw) return retained = null;
1296
- try {
1297
- const value = JSON.parse(raw);
1298
- if (value.version !== 1 || !value.credentialId || typeof value.name !== "string" || value.registration?.id !== value.credentialId) throw new Error();
1299
- if (value.enrolled) {
1300
- if (value.enrolled.credentialId !== value.credentialId || !value.enrolled.userHandle || !value.enrolled.publicKey) throw new Error();
1301
- value.enrolled.walletIdentityProof = parseWalletIdentityProof(value.enrolled.walletIdentityProof);
1081
+ if (!response.ok) {
1082
+ const code = await readErrorCode(response);
1083
+ if (endpoint === "enroll" && !(response.status === 400 && code === "account_identity_verification_failed" || response.status === 409 && ["challenge_unavailable", "credential_exists", "credential_changed"].includes(code))) {
1084
+ throw new ConnectError("account_identity_request_uncertain");
1302
1085
  }
1303
- return retained = value;
1304
- } catch {
1305
- throw new ConnectError("pending_creation_invalid", "Sign in with your saved passkey to finish setting up your wallet.");
1086
+ throw new ConnectError(code);
1306
1087
  }
1307
- }
1308
- function savePendingCreation(value) {
1309
- retained = value;
1310
1088
  try {
1311
- storage()?.setItem(KEY, JSON.stringify(value));
1089
+ return await response.json();
1312
1090
  } catch {
1091
+ throw new ConnectError(endpoint === "enroll" ? "account_identity_request_uncertain" : "account_identity_result_malformed");
1313
1092
  }
1314
1093
  }
1315
- function clearPendingCreation(credentialId) {
1316
- let current;
1094
+ function enrollmentResult(value, decode, expected) {
1317
1095
  try {
1318
- current = readPendingCreation();
1096
+ const result = decode(value);
1097
+ if (expected && (result.credential.credentialId !== expected.credentialId || result.credential.userHandle !== expected.userHandle)) {
1098
+ throw new ConnectError("account_identity_credential_mismatch");
1099
+ }
1100
+ return result;
1319
1101
  } catch {
1320
- return;
1102
+ throw new ConnectError("account_identity_request_uncertain");
1321
1103
  }
1322
- if (current?.credentialId !== credentialId) return;
1323
- retained = null;
1324
- try {
1325
- storage()?.removeItem(KEY);
1326
- } catch {
1104
+ }
1105
+ function assertInlineOrigin() {
1106
+ if (typeof window === "undefined" || window.location.origin !== "https://dexter.cash") {
1107
+ throw new ConnectError("hosted_ceremony_origin_required");
1327
1108
  }
1109
+ if (!browserSupportsWebAuthn()) throw new ConnectError("webauthn_unsupported");
1328
1110
  }
1329
-
1330
- // src/enroll.ts
1331
- var DEFAULT_WALLET_NAME = "Dexter Wallet";
1332
- var creationInProgress = false;
1333
- async function createWallet(config = {}) {
1334
- if (creationInProgress) throw new ConnectError("wallet_creation_in_progress");
1335
- creationInProgress = true;
1111
+ function loginOptions(value) {
1112
+ if (!record(value) || !record(value.options)) throw new ConnectError("account_identity_challenge_malformed");
1113
+ const options = value.options;
1114
+ if (!canonicalBase64url2(options.challenge) || base64urlToBytes(options.challenge).length < 16 || options.rpId !== DEXTER_RP_ID || options.userVerification !== "required") {
1115
+ throw new ConnectError("account_identity_challenge_malformed");
1116
+ }
1117
+ return options;
1118
+ }
1119
+ function enrollmentOptions(value) {
1120
+ if (!record(value) || !record(value.options)) throw new ConnectError("account_identity_challenge_malformed");
1121
+ const options = value.options;
1122
+ if (!canonicalBase64url2(options.challenge) || base64urlToBytes(options.challenge).length < 16 || !record(options.rp) || options.rp.id !== DEXTER_RP_ID || !record(options.user) || !canonicalBase64url2(options.user.id, 16) || !record(options.authenticatorSelection) || options.authenticatorSelection.userVerification !== "required" || options.authenticatorSelection.residentKey !== "required" || !Array.isArray(options.pubKeyCredParams) || options.pubKeyCredParams.length !== 1 || !record(options.pubKeyCredParams[0]) || options.pubKeyCredParams[0].type !== "public-key" || options.pubKeyCredParams[0].alg !== -7) {
1123
+ throw new ConnectError("account_identity_challenge_malformed");
1124
+ }
1125
+ return options;
1126
+ }
1127
+ function ceremonyError(cause) {
1128
+ if (cause instanceof Error && (cause.name === "NotAllowedError" || cause.name === "AbortError")) {
1129
+ return new ConnectError("user_cancelled");
1130
+ }
1131
+ return new ConnectError("webauthn_failed");
1132
+ }
1133
+ var ceremonyInProgress = false;
1134
+ async function serializeCeremony(run) {
1135
+ if (ceremonyInProgress) throw new ConnectError("account_identity_ceremony_in_progress");
1136
+ ceremonyInProgress = true;
1336
1137
  try {
1337
- return await createWalletOperation(config);
1138
+ return await run();
1338
1139
  } finally {
1339
- creationInProgress = false;
1140
+ ceremonyInProgress = false;
1340
1141
  }
1341
1142
  }
1342
- async function createWalletOperation(config = {}) {
1343
- const walletStore = resolveWalletStoreMode(config.walletStore);
1344
- const agentDelegation = resolveAgentDelegationMode(
1345
- config.agentDelegation ?? (config.spendPolicy ? "configure-now" : void 0)
1143
+ async function signInAccountIdentity(config = {}) {
1144
+ return signIn(config, normalizeResult);
1145
+ }
1146
+ async function signInAccountAccess(config) {
1147
+ return signIn(
1148
+ { targetUserHandle: config.targetUserHandle, onPhase: config.onPhase, transport: "inline" },
1149
+ normalizeAccessResult,
1150
+ bindRefusalRequest(config.accountRequest)
1346
1151
  );
1152
+ }
1153
+ async function signIn(config, decode, accountRequest) {
1154
+ const context = accountRequest ? { accountRequest } : {};
1155
+ const { targetUserHandle, transport, onPhase } = config;
1347
1156
  const apiBase = resolveDexterApiBase(config.apiBase);
1348
- resolveDexterRpId(config.rpId);
1349
- if (agentDelegation === "deferred" && config.spendPolicy) {
1350
- throw new ConnectError(
1351
- "conflicting_agent_delegation",
1352
- "agentDelegation deferred cannot include a spendPolicy"
1353
- );
1157
+ const connectHost = resolveDexterConnectHost(config.connectHost);
1158
+ if (targetUserHandle !== void 0 && !canonicalBase64url2(targetUserHandle, 16)) {
1159
+ throw new ConnectError("invalid_target_account");
1354
1160
  }
1355
- if (shouldUsePopup(config.transport)) {
1356
- const popupResult = await openCeremonyPopup("create", {
1357
- connectHost: config.connectHost,
1358
- name: config.name,
1359
- ...walletStore === "provisional" ? { walletStore } : {},
1360
- agentDelegation
1361
- });
1362
- if (!popupResult?.vault) {
1363
- throw new ConnectError("wallet_create_vault_missing");
1161
+ return serializeCeremony(async () => {
1162
+ let result;
1163
+ if (shouldUsePopup(transport)) {
1164
+ result = decode(await openCeremonyPopup("account-signin", {
1165
+ connectHost,
1166
+ ...targetUserHandle === void 0 ? {} : { targetUserHandle }
1167
+ }));
1168
+ } else {
1169
+ assertInlineOrigin();
1170
+ onPhase?.("challenge");
1171
+ const optionsJSON = loginOptions(await post(apiBase, "login-challenge", context));
1172
+ onPhase?.("passkey");
1173
+ let credential;
1174
+ try {
1175
+ credential = await startAuthentication({ optionsJSON });
1176
+ } catch (cause) {
1177
+ throw ceremonyError(cause);
1178
+ }
1179
+ onPhase?.("verifying");
1180
+ result = decode(await post(apiBase, "login", { credential, ...context }));
1181
+ if (result.credential.credentialId !== credential.id || credential.response.userHandle && result.credential.userHandle !== credential.response.userHandle) {
1182
+ throw new ConnectError("account_identity_credential_mismatch");
1183
+ }
1364
1184
  }
1365
- const result = {
1366
- ...popupResult,
1367
- walletIdentityProof: parseWalletIdentityProof(
1368
- popupResult.walletIdentityProof
1369
- )
1370
- };
1371
- if (walletStore === "commit") {
1372
- activateConnectVault(result.vault, result.walletIdentityProof);
1185
+ if (targetUserHandle !== void 0 && result.credential.userHandle !== targetUserHandle) {
1186
+ throw new ConnectError("target_account_mismatch");
1373
1187
  }
1374
1188
  return result;
1189
+ });
1190
+ }
1191
+ async function enrollAccountIdentity(config = {}) {
1192
+ return enroll(config, normalizeResult);
1193
+ }
1194
+ async function enrollAccountAccess(config) {
1195
+ return enroll(
1196
+ { name: config.name, onPhase: config.onPhase, transport: "inline" },
1197
+ normalizeAccessResult,
1198
+ bindRefusalRequest(config.accountRequest)
1199
+ );
1200
+ }
1201
+ async function enroll(config, decode, accountRequest) {
1202
+ const context = accountRequest ? { accountRequest } : {};
1203
+ const { transport, onPhase } = config;
1204
+ const apiBase = resolveDexterApiBase(config.apiBase);
1205
+ const connectHost = resolveDexterConnectHost(config.connectHost);
1206
+ if (config.name !== void 0 && (typeof config.name !== "string" || config.name.trim().length > 80)) {
1207
+ throw new ConnectError("invalid_account_identity_name");
1375
1208
  }
1376
- if (typeof navigator === "undefined" || !navigator.credentials) {
1377
- throw new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment");
1378
- }
1379
- const pending = readPendingCreation();
1380
- if (pending && config.agentDelegation === "deferred" && pending.spendPolicy !== void 0) {
1381
- throw new ConnectError(
1382
- "pending_creation_has_spend_policy",
1383
- "Finish the account setup that included a spending allowance before continuing."
1384
- );
1385
- }
1386
- if (pending) return resumeCreation(apiBase, pending, walletStore, config.onPhase);
1387
- const name = config.name && config.name.trim() || DEFAULT_WALLET_NAME;
1388
- config.onPhase?.("challenge");
1389
- const options = await fetchEnrollChallenge(apiBase);
1390
- config.onPhase?.("passkey");
1391
- const optionsJSON = {
1392
- ...options,
1393
- rp: { ...options.rp, id: DEXTER_RP_ID, name: "Dexter" },
1394
- user: { ...options.user, name, displayName: name }
1395
- };
1396
- let regResponse;
1397
- try {
1398
- regResponse = await startRegistration({ optionsJSON });
1399
- } catch (err) {
1400
- throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1401
- }
1402
- const checkpoint = {
1403
- version: 1,
1404
- credentialId: regResponse.id,
1405
- registration: regResponse,
1406
- name: config.name?.trim() || "",
1407
- ...config.spendPolicy ? { spendPolicy: { ...config.spendPolicy } } : {}
1408
- };
1409
- savePendingCreation(checkpoint);
1410
- config.onPhase?.("verifying");
1411
- const enrolled = await submitEnrollComplete(apiBase, regResponse);
1412
- checkpoint.enrolled = enrolled;
1413
- savePendingCreation(checkpoint);
1414
- return finishCreation(apiBase, checkpoint, enrolled, walletStore, config.onPhase);
1415
- }
1416
- async function resumeCreation(apiBase, checkpoint, walletStore, onPhase) {
1417
- let enrolled;
1418
- if (!checkpoint.enrolled) {
1419
- try {
1420
- onPhase?.("verifying");
1421
- enrolled = await submitEnrollComplete(apiBase, checkpoint.registration);
1422
- checkpoint.enrolled = enrolled;
1423
- savePendingCreation(checkpoint);
1424
- return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1425
- } catch (error) {
1426
- if (!(error instanceof ConnectError) || !["challenge_replayed", "verification_failed"].includes(error.code)) throw error;
1209
+ const name = config.name?.trim() || "Dexter";
1210
+ return serializeCeremony(async () => {
1211
+ if (shouldUsePopup(transport)) {
1212
+ let value;
1213
+ try {
1214
+ value = await openCeremonyPopup("account-enroll", { connectHost, name });
1215
+ } catch (cause) {
1216
+ if (cause instanceof ConnectError && [
1217
+ "popup_blocked",
1218
+ "not_browser",
1219
+ "user_cancelled",
1220
+ "account_identity_verification_failed",
1221
+ "challenge_unavailable",
1222
+ "credential_exists",
1223
+ "credential_changed",
1224
+ "account_identity_unavailable",
1225
+ "account_identity_challenge_malformed",
1226
+ "webauthn_unsupported",
1227
+ "webauthn_failed"
1228
+ ].includes(cause.code)) throw cause;
1229
+ throw new ConnectError("account_identity_request_uncertain");
1230
+ }
1231
+ return enrollmentResult(value, decode);
1427
1232
  }
1428
- }
1429
- onPhase?.("challenge");
1430
- const challenge = await fetch(`${apiBase}/api/passkey-anon/sign/recover-challenge`, {
1431
- method: "POST",
1432
- headers: { "content-type": "application/json" },
1433
- body: "{}"
1434
- });
1435
- if (!challenge.ok) throw new ConnectError(await readErrorCode(challenge));
1436
- const { options } = await challenge.json();
1437
- resolveDexterRpId(options?.rpId);
1438
- onPhase?.("passkey");
1439
- let credential;
1440
- try {
1441
- credential = await startAuthentication({ optionsJSON: {
1233
+ assertInlineOrigin();
1234
+ onPhase?.("challenge");
1235
+ const options = enrollmentOptions(await post(apiBase, "enroll-challenge", context));
1236
+ const expectedUserHandle = options.user.id;
1237
+ const optionsJSON = {
1442
1238
  ...options,
1443
- allowCredentials: [{ id: checkpoint.credentialId, type: "public-key" }]
1444
- } });
1445
- } catch (error) {
1446
- throw new ConnectError("webauthn_failed", error instanceof Error ? error.message : String(error));
1447
- }
1448
- if (credential.id !== checkpoint.credentialId) throw new ConnectError("creation_credential_mismatch");
1449
- onPhase?.("verifying");
1450
- const verification = await fetch(`${apiBase}/api/passkey-anon/sign/recover-verify`, {
1451
- method: "POST",
1452
- headers: { "content-type": "application/json" },
1453
- body: JSON.stringify({ credential })
1454
- });
1455
- if (!verification.ok) {
1456
- const code = await readErrorCode(verification);
1457
- if (verification.status === 404 && code === "credential_not_found") {
1458
- clearPendingCreation(checkpoint.credentialId);
1459
- throw new ConnectError(
1460
- "enrollment_not_saved",
1461
- "Wallet setup was not saved. Start again to create your wallet."
1462
- );
1239
+ rp: { ...options.rp, name: "Dexter" },
1240
+ user: { ...options.user, name, displayName: name }
1241
+ };
1242
+ onPhase?.("passkey");
1243
+ let credential;
1244
+ try {
1245
+ credential = await startRegistration({ optionsJSON });
1246
+ } catch (cause) {
1247
+ throw ceremonyError(cause);
1463
1248
  }
1464
- throw new ConnectError(code);
1465
- }
1466
- const verified = await verification.json();
1467
- if (verified.verified !== true || verified.credentialId !== checkpoint.credentialId || checkpoint.enrolled && verified.userHandle !== checkpoint.enrolled.userHandle) {
1468
- throw new ConnectError("creation_credential_mismatch");
1469
- }
1470
- enrolled = {
1471
- userHandle: verified.userHandle,
1472
- credentialId: verified.credentialId,
1473
- publicKey: verified.publicKey ?? checkpoint.enrolled?.publicKey,
1474
- walletIdentityProof: parseWalletIdentityProof(verified.walletIdentityProof)
1475
- };
1476
- if (!enrolled.publicKey || !enrolled.userHandle) throw new ConnectError("recover_verify_malformed");
1477
- checkpoint.enrolled = enrolled;
1478
- savePendingCreation(checkpoint);
1479
- return finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase);
1480
- }
1481
- async function finishCreation(apiBase, checkpoint, enrolled, walletStore, onPhase) {
1482
- onPhase?.("finalizing");
1483
- let init;
1249
+ onPhase?.("verifying");
1250
+ return enrollmentResult(await post(apiBase, "enroll", { credential, ...context }), decode, {
1251
+ credentialId: credential.id,
1252
+ userHandle: expectedUserHandle
1253
+ });
1254
+ });
1255
+ }
1256
+
1257
+ // src/relay.ts
1258
+ import { startAuthentication as startAuthentication2, browserSupportsWebAuthn as browserSupportsWebAuthn2 } from "@simplewebauthn/browser";
1259
+
1260
+ // src/walletStore.ts
1261
+ var ACTIVE_HANDLE_KEY = "dexter:passkey:userHandle";
1262
+ var ROSTER_KEY = "dexter:passkey:wallets";
1263
+ var DEVICE_WALLET_REMOVAL_CONFIRMATION = "remove-wallet-from-device";
1264
+ var listeners = /* @__PURE__ */ new Set();
1265
+ var lastObservedActiveWallet = null;
1266
+ function hasStorage() {
1484
1267
  try {
1485
- init = await initializeVault(
1486
- apiBase,
1487
- enrolled.userHandle,
1488
- enrolled.credentialId,
1489
- checkpoint.spendPolicy,
1490
- checkpoint.name || void 0,
1491
- enrolled.walletIdentityProof
1492
- );
1493
- } catch (error) {
1494
- throw new ConnectError(
1495
- error instanceof ConnectError ? error.code : "initialize_failed",
1496
- "Your passkey is saved. Retry to finish setting up this wallet."
1497
- );
1268
+ return typeof window !== "undefined" && !!window.localStorage;
1269
+ } catch {
1270
+ return false;
1498
1271
  }
1499
- const vault = {
1500
- vaultPda: init.vaultPda,
1501
- swigAddress: init.swigStateAddress,
1502
- receiveAddress: init.receiveAddress ?? null,
1503
- usdcAta: null,
1504
- publicKey: enrolled.publicKey,
1505
- userHandle: enrolled.userHandle,
1506
- credentialId: enrolled.credentialId,
1507
- walletLabel: init.walletLabel ?? (checkpoint.name || null)
1508
- };
1509
- if (walletStore === "commit") activateConnectVault(vault, enrolled.walletIdentityProof);
1510
- clearPendingCreation(enrolled.credentialId);
1511
- return {
1512
- handle: enrolled.userHandle,
1513
- credentialId: enrolled.credentialId,
1514
- vault,
1515
- label: vault.walletLabel ?? null,
1516
- walletIdentityProof: enrolled.walletIdentityProof
1517
- };
1518
1272
  }
1519
- async function fetchEnrollChallenge(apiBase) {
1520
- const res = await fetch(`${apiBase}/api/passkey-anon/enroll/challenge`, {
1521
- method: "POST",
1522
- headers: { "content-type": "application/json" },
1523
- body: "{}"
1524
- });
1525
- if (!res.ok) throw new ConnectError("enroll_challenge_failed", `enroll/challenge ${res.status}`);
1526
- const data = await res.json();
1527
- if (!data?.options?.challenge) {
1528
- throw new ConnectError("enroll_challenge_malformed", "no creation options in response");
1529
- }
1530
- resolveDexterRpId(data.options.rp?.id);
1531
- return data.options;
1273
+ function optionalString(value) {
1274
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1532
1275
  }
1533
- async function submitEnrollComplete(apiBase, response) {
1534
- const res = await fetch(`${apiBase}/api/passkey-anon/enroll/complete`, {
1535
- method: "POST",
1536
- headers: { "content-type": "application/json" },
1537
- body: JSON.stringify({ credential: response })
1538
- });
1539
- if (!res.ok) throw new ConnectError(await readErrorCode(res), `enroll/complete ${res.status}`);
1540
- const data = await res.json();
1541
- if (data.credentialId !== response.id || typeof data.userHandle !== "string" || !data.userHandle || typeof data.publicKey !== "string" || !data.publicKey) {
1542
- throw new ConnectError("enroll_complete_malformed");
1543
- }
1276
+ function normalizeWallet(value, migrateHistoricalRow = true) {
1277
+ if (!value || typeof value !== "object") return null;
1278
+ const raw = value;
1279
+ const handle = optionalString(raw.handle);
1280
+ if (!handle) return null;
1281
+ const rosterState = raw.rosterState === "unavailable" || raw.rosterState === "known" ? raw.rosterState : migrateHistoricalRow ? "known" : void 0;
1282
+ const verificationState = raw.verificationState === "verified" || raw.verificationState === "quarantined" || raw.verificationState === "unverified" ? raw.verificationState : migrateHistoricalRow ? "unverified" : void 0;
1544
1283
  return {
1545
- credentialId: data.credentialId,
1546
- publicKey: data.publicKey,
1547
- userHandle: data.userHandle,
1548
- walletIdentityProof: parseWalletIdentityProof(data.walletIdentityProof)
1284
+ handle,
1285
+ ...optionalString(raw.label) ? { label: optionalString(raw.label) } : {},
1286
+ ...optionalString(raw.credentialId) ? { credentialId: optionalString(raw.credentialId) } : {},
1287
+ ...optionalString(raw.vaultPda) ? { vaultPda: optionalString(raw.vaultPda) } : {},
1288
+ ...optionalString(raw.swigAddress) ? { swigAddress: optionalString(raw.swigAddress) } : {},
1289
+ ...optionalString(raw.walletAddress) ? { walletAddress: optionalString(raw.walletAddress) } : {},
1290
+ ...raw.receiveAddress === null ? { receiveAddress: null } : optionalString(raw.receiveAddress) ? { receiveAddress: optionalString(raw.receiveAddress) } : {},
1291
+ ...optionalString(raw.network) ? { network: optionalString(raw.network) } : {},
1292
+ ...rosterState ? { rosterState } : {},
1293
+ ...verificationState ? { verificationState } : {},
1294
+ ...typeof raw.lastUsedAt === "number" && Number.isFinite(raw.lastUsedAt) ? { lastUsedAt: raw.lastUsedAt } : {}
1549
1295
  };
1550
1296
  }
1551
- async function initializeVault(apiBase, userHandle, credentialId, spendPolicy, label, walletIdentityProof) {
1552
- const body = { userHandle, credentialId, coolingOffSeconds: 0 };
1553
- if (label) body.label = label;
1554
- if (spendPolicy) {
1555
- body.spendLimitAtomic = spendPolicy.spendLimitAtomic;
1556
- body.sessionTtlSeconds = SESSION_TTL_30D;
1557
- }
1558
- const res = await fetch(`${apiBase}/api/passkey-vault-anon/initialize`, {
1559
- method: "POST",
1560
- headers: { "content-type": "application/json", ...walletIdentityProof ? { authorization: `Bearer ${walletIdentityProof.token}` } : {} },
1561
- body: JSON.stringify(body)
1562
- });
1563
- if (!res.ok) throw new ConnectError(await readErrorCode(res), `initialize ${res.status}`);
1564
- return await res.json();
1565
- }
1566
-
1567
- // src/accountIdentity.ts
1568
- import {
1569
- browserSupportsWebAuthn,
1570
- startAuthentication as startAuthentication2,
1571
- startRegistration as startRegistration2
1572
- } from "@simplewebauthn/browser";
1573
- var ACCOUNT_IDENTITY_API_PATH = "/api/connect/account-identity";
1574
- function record(value) {
1575
- return value !== null && typeof value === "object" && !Array.isArray(value);
1576
- }
1577
- function canonicalBase64url2(value, exactLength) {
1578
- if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value) || value.length > 1400) return false;
1297
+ function readRoster() {
1298
+ if (!hasStorage()) return [];
1579
1299
  try {
1580
- const bytes = base64urlToBytes(value);
1581
- return bytes.length > 0 && bytes.length <= 1024 && (exactLength === void 0 || bytes.length === exactLength) && bytesToBase64url(bytes) === value;
1300
+ const raw = window.localStorage.getItem(ROSTER_KEY);
1301
+ if (!raw) return [];
1302
+ const parsed = JSON.parse(raw);
1303
+ if (!Array.isArray(parsed)) return [];
1304
+ const wallets = /* @__PURE__ */ new Map();
1305
+ for (const value of parsed) {
1306
+ const wallet = normalizeWallet(value);
1307
+ if (wallet) wallets.set(wallet.handle, wallet);
1308
+ }
1309
+ return [...wallets.values()];
1582
1310
  } catch {
1583
- return false;
1311
+ return [];
1584
1312
  }
1585
1313
  }
1586
- function validPublicKey(value) {
1587
- if (typeof value !== "string" || value.length !== 44) return false;
1314
+ function writeRoster(wallets) {
1315
+ if (!hasStorage()) return false;
1588
1316
  try {
1589
- const bytes = base64ToBytes(value);
1590
- return bytes.length === 33 && (bytes[0] === 2 || bytes[0] === 3) && bytesToBase64(bytes) === value;
1317
+ window.localStorage.setItem(ROSTER_KEY, JSON.stringify(wallets));
1318
+ return true;
1591
1319
  } catch {
1592
1320
  return false;
1593
1321
  }
1594
1322
  }
1595
- function positiveInteger(value) {
1596
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1597
- }
1598
- function normalizeSession(session) {
1599
- if (!record(session) || typeof session.accessToken !== "string" || session.accessToken.length === 0 || /\s/.test(session.accessToken) || session.tokenType !== "Bearer" || !positiveInteger(session.expiresAt) || !positiveInteger(session.expiresIn) || session.expiresIn > 30 * 24 * 60 * 60) {
1600
- throw new ConnectError("account_identity_result_malformed");
1601
- }
1602
- return Object.freeze({
1603
- accessToken: session.accessToken,
1604
- expiresAt: session.expiresAt,
1605
- expiresIn: session.expiresIn,
1606
- tokenType: "Bearer"
1607
- });
1323
+ function walletForHandle(handle, roster = readRoster()) {
1324
+ if (!handle) return null;
1325
+ return roster.find((wallet) => wallet.handle === handle) ?? {
1326
+ handle,
1327
+ rosterState: "known",
1328
+ verificationState: "unverified"
1329
+ };
1608
1330
  }
1609
- function normalizeResult(value) {
1610
- if (!record(value) || value.profile !== "account-identity-v1" || !record(value.credential)) {
1611
- throw new ConnectError("account_identity_result_malformed");
1612
- }
1613
- const { credential } = value;
1614
- if (!canonicalBase64url2(credential.userHandle, 16) || !canonicalBase64url2(credential.credentialId) || !validPublicKey(credential.publicKey)) {
1615
- throw new ConnectError("account_identity_result_malformed");
1331
+ function emit(event) {
1332
+ lastObservedActiveWallet = event.activeWallet;
1333
+ for (const listener of listeners) {
1334
+ try {
1335
+ listener(event);
1336
+ } catch {
1337
+ }
1616
1338
  }
1617
- return Object.freeze({
1618
- profile: "account-identity-v1",
1619
- session: normalizeSession(value.session),
1620
- credential: Object.freeze({
1621
- userHandle: credential.userHandle,
1622
- credentialId: credential.credentialId,
1623
- publicKey: credential.publicKey
1624
- })
1625
- });
1626
1339
  }
1627
- function normalizeAccessResult(value) {
1628
- const identity = normalizeResult(value);
1629
- const refusalProof = normalizeSession(record(value) ? value.refusalProof : void 0);
1630
- if (refusalProof.accessToken === identity.session.accessToken) {
1631
- throw new ConnectError("account_identity_result_malformed");
1632
- }
1633
- return Object.freeze({ ...identity, refusalProof });
1340
+ function mutationEvent(operation, previousActiveWallet, activeWallet, wallet) {
1341
+ const activeIdentityFactsChanged = previousActiveWallet?.handle === activeWallet?.handle && (previousActiveWallet?.vaultPda !== activeWallet?.vaultPda || previousActiveWallet?.credentialId !== activeWallet?.credentialId);
1342
+ return {
1343
+ operation,
1344
+ previousActiveWallet,
1345
+ activeWallet,
1346
+ wallet,
1347
+ invalidatesAccountBinding: previousActiveWallet?.handle !== activeWallet?.handle || activeIdentityFactsChanged
1348
+ };
1634
1349
  }
1635
- function bindRefusalRequest(request) {
1636
- assertInlineOrigin();
1637
- if (window.top !== window || window.location.pathname !== "/tabs/setup" || !record(request) || typeof request.request_id !== "string" || typeof request.decline_token !== "string" || !/^vpair_[a-f0-9]{1,80}$/.test(request.request_id) || !/^[a-f0-9]{64}$/.test(request.decline_token) || new URL(window.location.href).searchParams.get("request_id") !== request.request_id) {
1638
- throw new ConnectError("account_request_mismatch");
1639
- }
1640
- return Object.freeze({ request_id: request.request_id, decline_token: request.decline_token });
1350
+ function mergeDefinedWallet(existing, incoming) {
1351
+ const base = existing ?? {
1352
+ handle: incoming.handle,
1353
+ rosterState: "known",
1354
+ verificationState: "unverified"
1355
+ };
1356
+ return {
1357
+ ...base,
1358
+ handle: incoming.handle,
1359
+ ...incoming.label !== void 0 ? { label: incoming.label } : {},
1360
+ ...incoming.credentialId !== void 0 ? { credentialId: incoming.credentialId } : {},
1361
+ ...incoming.vaultPda !== void 0 ? { vaultPda: incoming.vaultPda } : {},
1362
+ ...incoming.swigAddress !== void 0 ? { swigAddress: incoming.swigAddress } : {},
1363
+ ...incoming.walletAddress !== void 0 ? { walletAddress: incoming.walletAddress } : {},
1364
+ ...incoming.receiveAddress !== void 0 ? { receiveAddress: incoming.receiveAddress } : {},
1365
+ ...incoming.network !== void 0 ? { network: incoming.network } : {},
1366
+ ...incoming.rosterState !== void 0 ? { rosterState: incoming.rosterState } : {},
1367
+ ...incoming.verificationState !== void 0 ? { verificationState: incoming.verificationState } : {},
1368
+ rosterState: incoming.rosterState || base.rosterState || "known",
1369
+ verificationState: incoming.verificationState || base.verificationState || "unverified",
1370
+ lastUsedAt: Date.now()
1371
+ };
1641
1372
  }
1642
- async function post(apiBase, endpoint, body) {
1643
- let response;
1373
+ function activateWallet(wallet, requestedOperation) {
1374
+ if (!hasStorage()) return false;
1375
+ const normalized = normalizeWallet(wallet, false);
1376
+ if (!normalized) return false;
1377
+ const roster = readRoster();
1378
+ const previousActiveWallet = walletForHandle(getActiveHandle(), roster);
1379
+ const existingIndex = roster.findIndex((row) => row.handle === normalized.handle);
1380
+ const nextWallet = mergeDefinedWallet(
1381
+ existingIndex >= 0 ? roster[existingIndex] : void 0,
1382
+ normalized
1383
+ );
1384
+ if (existingIndex >= 0) roster[existingIndex] = nextWallet;
1385
+ else roster.push(nextWallet);
1386
+ const previousRoster = readRoster();
1387
+ if (!writeRoster(roster)) return false;
1644
1388
  try {
1645
- response = await fetch(`${apiBase}${ACCOUNT_IDENTITY_API_PATH}/${endpoint}`, {
1646
- method: "POST",
1647
- headers: { "Content-Type": "application/json", Accept: "application/json" },
1648
- body: JSON.stringify(body),
1649
- credentials: "omit",
1650
- cache: "no-store",
1651
- redirect: "error"
1652
- });
1389
+ window.localStorage.setItem(ACTIVE_HANDLE_KEY, normalized.handle);
1653
1390
  } catch {
1654
- throw new ConnectError(endpoint === "login" || endpoint === "enroll" ? "account_identity_request_uncertain" : "account_identity_unavailable");
1391
+ writeRoster(previousRoster);
1392
+ return false;
1655
1393
  }
1656
- if (!response.ok) {
1657
- const code = await readErrorCode(response);
1658
- if (endpoint === "enroll" && !(response.status === 400 && code === "account_identity_verification_failed" || response.status === 409 && ["challenge_unavailable", "credential_exists", "credential_changed"].includes(code))) {
1659
- throw new ConnectError("account_identity_request_uncertain");
1394
+ const changedHandle = previousActiveWallet?.handle !== normalized.handle;
1395
+ const operation = changedHandle ? requestedOperation ?? (previousActiveWallet ? "switch" : "activate") : "update";
1396
+ emit(mutationEvent(operation, previousActiveWallet, nextWallet, nextWallet));
1397
+ return true;
1398
+ }
1399
+ function removeRosterWallet(handle, operation) {
1400
+ if (!hasStorage() || !handle) return null;
1401
+ const roster = readRoster();
1402
+ const removedWallet = roster.find((wallet) => wallet.handle === handle) ?? null;
1403
+ if (!removedWallet) return null;
1404
+ const previousActiveWallet = walletForHandle(getActiveHandle(), roster);
1405
+ const wasActive = previousActiveWallet?.handle === handle;
1406
+ const nextRoster = roster.filter((wallet) => wallet.handle !== handle);
1407
+ if (!writeRoster(nextRoster)) return null;
1408
+ if (wasActive) {
1409
+ try {
1410
+ window.localStorage.removeItem(ACTIVE_HANDLE_KEY);
1411
+ } catch {
1412
+ writeRoster(roster);
1413
+ return null;
1660
1414
  }
1661
- throw new ConnectError(code);
1662
- }
1663
- try {
1664
- return await response.json();
1665
- } catch {
1666
- throw new ConnectError(endpoint === "enroll" ? "account_identity_request_uncertain" : "account_identity_result_malformed");
1667
1415
  }
1416
+ const activeWallet = wasActive ? null : previousActiveWallet;
1417
+ emit(mutationEvent(operation, previousActiveWallet, activeWallet, removedWallet));
1418
+ return removedWallet;
1668
1419
  }
1669
- function enrollmentResult(value, decode, expected) {
1420
+ function getActiveHandle() {
1421
+ if (!hasStorage()) return null;
1670
1422
  try {
1671
- const result = decode(value);
1672
- if (expected && (result.credential.credentialId !== expected.credentialId || result.credential.userHandle !== expected.userHandle)) {
1673
- throw new ConnectError("account_identity_credential_mismatch");
1674
- }
1675
- return result;
1423
+ return window.localStorage.getItem(ACTIVE_HANDLE_KEY);
1676
1424
  } catch {
1677
- throw new ConnectError("account_identity_request_uncertain");
1425
+ return null;
1678
1426
  }
1679
1427
  }
1680
- function assertInlineOrigin() {
1681
- if (typeof window === "undefined" || window.location.origin !== "https://dexter.cash") {
1682
- throw new ConnectError("hosted_ceremony_origin_required");
1683
- }
1684
- if (!browserSupportsWebAuthn()) throw new ConnectError("webauthn_unsupported");
1428
+ function getActiveWallet() {
1429
+ return walletForHandle(getActiveHandle());
1685
1430
  }
1686
- function loginOptions(value) {
1687
- if (!record(value) || !record(value.options)) throw new ConnectError("account_identity_challenge_malformed");
1688
- const options = value.options;
1689
- if (!canonicalBase64url2(options.challenge) || base64urlToBytes(options.challenge).length < 16 || options.rpId !== DEXTER_RP_ID || options.userVerification !== "required") {
1690
- throw new ConnectError("account_identity_challenge_malformed");
1691
- }
1692
- return options;
1431
+ function setActiveWallet(wallet) {
1432
+ return activateWallet(wallet);
1433
+ }
1434
+ function setActiveHandle(handle, label, credentialId) {
1435
+ activateWallet({ handle, label, credentialId });
1693
1436
  }
1694
- function enrollmentOptions(value) {
1695
- if (!record(value) || !record(value.options)) throw new ConnectError("account_identity_challenge_malformed");
1696
- const options = value.options;
1697
- if (!canonicalBase64url2(options.challenge) || base64urlToBytes(options.challenge).length < 16 || !record(options.rp) || options.rp.id !== DEXTER_RP_ID || !record(options.user) || !canonicalBase64url2(options.user.id, 16) || !record(options.authenticatorSelection) || options.authenticatorSelection.userVerification !== "required" || options.authenticatorSelection.residentKey !== "required" || !Array.isArray(options.pubKeyCredParams) || options.pubKeyCredParams.length !== 1 || !record(options.pubKeyCredParams[0]) || options.pubKeyCredParams[0].type !== "public-key" || options.pubKeyCredParams[0].alg !== -7) {
1698
- throw new ConnectError("account_identity_challenge_malformed");
1699
- }
1700
- return options;
1437
+ function getCredentialId(handle) {
1438
+ return readRoster().find((wallet) => wallet.handle === handle)?.credentialId;
1701
1439
  }
1702
- function ceremonyError(cause) {
1703
- if (cause instanceof Error && (cause.name === "NotAllowedError" || cause.name === "AbortError")) {
1704
- return new ConnectError("user_cancelled");
1440
+ function disconnectActiveWallet() {
1441
+ if (!hasStorage()) return false;
1442
+ const previousActiveWallet = getActiveWallet();
1443
+ if (!previousActiveWallet) return false;
1444
+ try {
1445
+ window.localStorage.removeItem(ACTIVE_HANDLE_KEY);
1446
+ } catch {
1447
+ return false;
1705
1448
  }
1706
- return new ConnectError("webauthn_failed");
1449
+ emit(mutationEvent("disconnect", previousActiveWallet, null, previousActiveWallet));
1450
+ return true;
1707
1451
  }
1708
- var ceremonyInProgress = false;
1709
- async function serializeCeremony(run) {
1710
- if (ceremonyInProgress) throw new ConnectError("account_identity_ceremony_in_progress");
1711
- ceremonyInProgress = true;
1712
- try {
1713
- return await run();
1714
- } finally {
1715
- ceremonyInProgress = false;
1452
+ function ejectActiveWallet(opts) {
1453
+ const handle = getActiveHandle();
1454
+ if (opts?.forget && handle) {
1455
+ forgetWallet(handle);
1456
+ return;
1716
1457
  }
1458
+ disconnectActiveWallet();
1717
1459
  }
1718
- async function signInAccountIdentity(config = {}) {
1719
- return signIn(config, normalizeResult);
1460
+ function listWallets() {
1461
+ return readRoster().sort((a, b) => (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0));
1720
1462
  }
1721
- async function signInAccountAccess(config) {
1722
- return signIn(
1723
- { targetUserHandle: config.targetUserHandle, onPhase: config.onPhase, transport: "inline" },
1724
- normalizeAccessResult,
1725
- bindRefusalRequest(config.accountRequest)
1726
- );
1463
+ function switchWallet(handle) {
1464
+ const wallet = readRoster().find((row) => row.handle === handle);
1465
+ if (!wallet) return false;
1466
+ return activateWallet(wallet, "switch");
1727
1467
  }
1728
- async function signIn(config, decode, accountRequest) {
1729
- const context = accountRequest ? { accountRequest } : {};
1730
- const { targetUserHandle, transport, onPhase } = config;
1731
- const apiBase = resolveDexterApiBase(config.apiBase);
1732
- const connectHost = resolveDexterConnectHost(config.connectHost);
1733
- if (targetUserHandle !== void 0 && !canonicalBase64url2(targetUserHandle, 16)) {
1734
- throw new ConnectError("invalid_target_account");
1468
+ function forgetWallet(handle) {
1469
+ removeRosterWallet(handle, "forget");
1470
+ }
1471
+ function removeWalletFromDeviceRoster(handle, confirmation) {
1472
+ if (confirmation !== DEVICE_WALLET_REMOVAL_CONFIRMATION) return null;
1473
+ return removeRosterWallet(handle, "remove-device");
1474
+ }
1475
+ function subscribe(listener) {
1476
+ listeners.add(listener);
1477
+ if (hasStorage() && listeners.size === 1) {
1478
+ lastObservedActiveWallet = getActiveWallet();
1479
+ window.addEventListener("storage", onStorageEvent);
1735
1480
  }
1736
- return serializeCeremony(async () => {
1737
- let result;
1738
- if (shouldUsePopup(transport)) {
1739
- result = decode(await openCeremonyPopup("account-signin", {
1740
- connectHost,
1741
- ...targetUserHandle === void 0 ? {} : { targetUserHandle }
1742
- }));
1743
- } else {
1744
- assertInlineOrigin();
1745
- onPhase?.("challenge");
1746
- const optionsJSON = loginOptions(await post(apiBase, "login-challenge", context));
1747
- onPhase?.("passkey");
1748
- let credential;
1749
- try {
1750
- credential = await startAuthentication2({ optionsJSON });
1751
- } catch (cause) {
1752
- throw ceremonyError(cause);
1753
- }
1754
- onPhase?.("verifying");
1755
- result = decode(await post(apiBase, "login", { credential, ...context }));
1756
- if (result.credential.credentialId !== credential.id || credential.response.userHandle && result.credential.userHandle !== credential.response.userHandle) {
1757
- throw new ConnectError("account_identity_credential_mismatch");
1758
- }
1759
- }
1760
- if (targetUserHandle !== void 0 && result.credential.userHandle !== targetUserHandle) {
1761
- throw new ConnectError("target_account_mismatch");
1481
+ return () => {
1482
+ listeners.delete(listener);
1483
+ if (hasStorage() && listeners.size === 0) {
1484
+ window.removeEventListener("storage", onStorageEvent);
1762
1485
  }
1763
- return result;
1764
- });
1486
+ };
1765
1487
  }
1766
- async function enrollAccountIdentity(config = {}) {
1767
- return enroll(config, normalizeResult);
1488
+ function onStorageEvent(event) {
1489
+ if (event.key !== ACTIVE_HANDLE_KEY && event.key !== ROSTER_KEY && event.key !== null) return;
1490
+ const previousActiveWallet = lastObservedActiveWallet;
1491
+ const activeWallet = getActiveWallet();
1492
+ emit(mutationEvent("external", previousActiveWallet, activeWallet, activeWallet));
1768
1493
  }
1769
- async function enrollAccountAccess(config) {
1770
- return enroll(
1771
- { name: config.name, onPhase: config.onPhase, transport: "inline" },
1772
- normalizeAccessResult,
1773
- bindRefusalRequest(config.accountRequest)
1774
- );
1494
+
1495
+ // src/walletActivation.ts
1496
+ function activateConnectVault(vault, walletIdentityProof) {
1497
+ const proof = parseWalletIdentityProof(walletIdentityProof);
1498
+ const proofSession = walletProofSessionStore.save(vault.userHandle, proof);
1499
+ if (!proofSession) return false;
1500
+ const activated = setActiveWallet({
1501
+ handle: vault.userHandle,
1502
+ label: vault.walletLabel ?? void 0,
1503
+ credentialId: vault.credentialId,
1504
+ vaultPda: vault.vaultPda,
1505
+ swigAddress: vault.swigAddress,
1506
+ walletAddress: vault.swigAddress,
1507
+ receiveAddress: vault.receiveAddress,
1508
+ network: "solana-mainnet",
1509
+ verificationState: "unverified"
1510
+ });
1511
+ if (!activated) walletProofSessionStore.clear(vault.userHandle);
1512
+ return activated;
1775
1513
  }
1776
- async function enroll(config, decode, accountRequest) {
1777
- const context = accountRequest ? { accountRequest } : {};
1778
- const { transport, onPhase } = config;
1779
- const apiBase = resolveDexterApiBase(config.apiBase);
1780
- const connectHost = resolveDexterConnectHost(config.connectHost);
1781
- if (config.name !== void 0 && (typeof config.name !== "string" || config.name.trim().length > 80)) {
1782
- throw new ConnectError("invalid_account_identity_name");
1783
- }
1784
- const name = config.name?.trim() || "Dexter";
1785
- return serializeCeremony(async () => {
1786
- if (shouldUsePopup(transport)) {
1787
- let value;
1788
- try {
1789
- value = await openCeremonyPopup("account-enroll", { connectHost, name });
1790
- } catch (cause) {
1791
- if (cause instanceof ConnectError && [
1792
- "popup_blocked",
1793
- "not_browser",
1794
- "user_cancelled",
1795
- "account_identity_verification_failed",
1796
- "challenge_unavailable",
1797
- "credential_exists",
1798
- "credential_changed",
1799
- "account_identity_unavailable",
1800
- "account_identity_challenge_malformed",
1801
- "webauthn_unsupported",
1802
- "webauthn_failed"
1803
- ].includes(cause.code)) throw cause;
1804
- throw new ConnectError("account_identity_request_uncertain");
1805
- }
1806
- return enrollmentResult(value, decode);
1807
- }
1808
- assertInlineOrigin();
1809
- onPhase?.("challenge");
1810
- const options = enrollmentOptions(await post(apiBase, "enroll-challenge", context));
1811
- const expectedUserHandle = options.user.id;
1812
- const optionsJSON = {
1813
- ...options,
1814
- rp: { ...options.rp, name: "Dexter" },
1815
- user: { ...options.user, name, displayName: name }
1816
- };
1817
- onPhase?.("passkey");
1818
- let credential;
1819
- try {
1820
- credential = await startRegistration2({ optionsJSON });
1821
- } catch (cause) {
1822
- throw ceremonyError(cause);
1823
- }
1824
- onPhase?.("verifying");
1825
- return enrollmentResult(await post(apiBase, "enroll", { credential, ...context }), decode, {
1826
- credentialId: credential.id,
1827
- userHandle: expectedUserHandle
1828
- });
1514
+ function activateRecoveredVault(userHandle, credentialId, vault, walletIdentityProof) {
1515
+ const proof = parseWalletIdentityProof(walletIdentityProof);
1516
+ const proofSession = walletProofSessionStore.save(userHandle, proof);
1517
+ if (!proofSession) return false;
1518
+ const activated = setActiveWallet({
1519
+ handle: userHandle,
1520
+ label: vault.walletLabel ?? void 0,
1521
+ credentialId,
1522
+ vaultPda: vault.vaultPda,
1523
+ swigAddress: vault.swigAddress,
1524
+ walletAddress: vault.swigAddress,
1525
+ receiveAddress: vault.receiveAddress,
1526
+ network: "solana-mainnet",
1527
+ verificationState: "unverified"
1829
1528
  });
1529
+ if (!activated) walletProofSessionStore.clear(userHandle);
1530
+ return activated;
1830
1531
  }
1831
1532
 
1832
- // src/relay.ts
1833
- import { startAuthentication as startAuthentication3, browserSupportsWebAuthn as browserSupportsWebAuthn2 } from "@simplewebauthn/browser";
1834
-
1835
1533
  // src/immediate.ts
1836
1534
  var immediateCapPromise = null;
1837
1535
  function immediateGetSupported() {
@@ -1892,6 +1590,53 @@ function classifyWebAuthnRejection(err) {
1892
1590
  return /notallowed|not ?allowed|abort|cancel|timed out|timeout|denied|ceremony/.test(blob);
1893
1591
  }
1894
1592
 
1593
+ // src/pendingCreation.ts
1594
+ var KEY = "dexter:pending-wallet-creation:v1";
1595
+ var retained = null;
1596
+ function storage() {
1597
+ try {
1598
+ return typeof window === "undefined" ? null : window.localStorage;
1599
+ } catch {
1600
+ return null;
1601
+ }
1602
+ }
1603
+ function readPendingCreation() {
1604
+ const store = storage();
1605
+ if (!store) return retained;
1606
+ let raw;
1607
+ try {
1608
+ raw = store.getItem(KEY);
1609
+ } catch {
1610
+ return retained;
1611
+ }
1612
+ if (!raw) return retained = null;
1613
+ try {
1614
+ const value = JSON.parse(raw);
1615
+ if (value.version !== 1 || !value.credentialId || typeof value.name !== "string" || value.registration?.id !== value.credentialId) throw new Error();
1616
+ if (value.enrolled) {
1617
+ if (value.enrolled.credentialId !== value.credentialId || !value.enrolled.userHandle || !value.enrolled.publicKey) throw new Error();
1618
+ value.enrolled.walletIdentityProof = parseWalletIdentityProof(value.enrolled.walletIdentityProof);
1619
+ }
1620
+ return retained = value;
1621
+ } catch {
1622
+ throw new ConnectError("pending_creation_invalid", "Sign in with your saved passkey to finish setting up your wallet.");
1623
+ }
1624
+ }
1625
+ function clearPendingCreation(credentialId) {
1626
+ let current;
1627
+ try {
1628
+ current = readPendingCreation();
1629
+ } catch {
1630
+ return;
1631
+ }
1632
+ if (current?.credentialId !== credentialId) return;
1633
+ retained = null;
1634
+ try {
1635
+ storage()?.removeItem(KEY);
1636
+ } catch {
1637
+ }
1638
+ }
1639
+
1895
1640
  // src/relay.ts
1896
1641
  var ANON_SIGN_BASE = "/api/passkey-anon/sign";
1897
1642
  primeImmediateSupport();
@@ -1923,7 +1668,7 @@ async function passkeyLogin(config = {}, onPhase) {
1923
1668
  onPhase?.("passkey");
1924
1669
  let response;
1925
1670
  try {
1926
- response = await startAuthentication3({ optionsJSON: targetedOptions });
1671
+ response = await startAuthentication2({ optionsJSON: targetedOptions });
1927
1672
  } catch (err) {
1928
1673
  throw new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err));
1929
1674
  }
@@ -2086,6 +1831,9 @@ export {
2086
1831
  parseMissingVaultRecoveryResult,
2087
1832
  shouldUsePopup,
2088
1833
  openCeremonyPopup,
1834
+ DEXTER_WALLET_CLOSED_CODE,
1835
+ DEXTER_WALLET_CLOSED_MESSAGE,
1836
+ createWallet,
2089
1837
  getActiveHandle,
2090
1838
  getActiveWallet,
2091
1839
  setActiveWallet,
@@ -2107,15 +1855,11 @@ export {
2107
1855
  walletProofSessionStore,
2108
1856
  activateConnectVault,
2109
1857
  activateRecoveredVault,
2110
- SESSION_TTL_30D,
2111
- usdToAtomic,
2112
- authoredPolicy,
2113
- clearPendingCreation,
2114
- createWallet,
2115
1858
  immediateGetSupported,
2116
1859
  primeImmediateSupport,
2117
1860
  immediateAuthentication,
2118
1861
  classifyWebAuthnRejection,
1862
+ clearPendingCreation,
2119
1863
  ACCOUNT_IDENTITY_API_PATH,
2120
1864
  signInAccountIdentity,
2121
1865
  signInAccountAccess,