@dexterai/connect 0.26.4 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ // src/base64.ts
2
+ function base64ToBytes(s) {
3
+ const bin = atob(s);
4
+ const out = new Uint8Array(bin.length);
5
+ for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);
6
+ return out;
7
+ }
8
+ function base64urlToBytes(s) {
9
+ const pad = s.length % 4 === 0 ? "" : "=".repeat(4 - s.length % 4);
10
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + pad;
11
+ return base64ToBytes(b64);
12
+ }
13
+ function bytesToBase64(bytes) {
14
+ let bin = "";
15
+ for (let i = 0; i < bytes.length; i += 1) bin += String.fromCharCode(bytes[i]);
16
+ return btoa(bin);
17
+ }
18
+ function bytesToBase64url(bytes) {
19
+ return bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
20
+ }
21
+ function compactSignatureToDer(compact) {
22
+ if (compact.length !== 64) {
23
+ throw new Error(`expected 64-byte compact signature, got ${compact.length}`);
24
+ }
25
+ const r = derInteger(compact.subarray(0, 32));
26
+ const s = derInteger(compact.subarray(32, 64));
27
+ const body = new Uint8Array(r.length + s.length);
28
+ body.set(r, 0);
29
+ body.set(s, r.length);
30
+ const out = new Uint8Array(2 + body.length);
31
+ out[0] = 48;
32
+ out[1] = body.length;
33
+ out.set(body, 2);
34
+ return out;
35
+ }
36
+ function derInteger(component) {
37
+ let start = 0;
38
+ while (start < component.length - 1 && component[start] === 0) start += 1;
39
+ let content = component.subarray(start);
40
+ if (content[0] & 128) {
41
+ const padded = new Uint8Array(content.length + 1);
42
+ padded[0] = 0;
43
+ padded.set(content, 1);
44
+ content = padded;
45
+ }
46
+ const out = new Uint8Array(2 + content.length);
47
+ out[0] = 2;
48
+ out[1] = content.length;
49
+ out.set(content, 2);
50
+ return out;
51
+ }
52
+
53
+ export {
54
+ base64ToBytes,
55
+ base64urlToBytes,
56
+ bytesToBase64,
57
+ bytesToBase64url,
58
+ compactSignatureToDer
59
+ };
@@ -0,0 +1,183 @@
1
+ import {
2
+ ConnectError,
3
+ activateRecoveredVault,
4
+ classifyWebAuthnRejection,
5
+ immediateAuthentication,
6
+ immediateGetSupported,
7
+ openCeremonyPopup,
8
+ parseWalletIdentityProof,
9
+ primeImmediateSupport,
10
+ readErrorCode,
11
+ resolveDexterApiBase,
12
+ resolveDexterRpId,
13
+ resolveWalletStoreMode,
14
+ shouldUsePopup
15
+ } from "./chunk-CZL7NGVV.js";
16
+
17
+ // src/recover.ts
18
+ import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
19
+ var ANON_SIGN_BASE = "/api/passkey-anon/sign";
20
+ primeImmediateSupport();
21
+ async function recoverWallet(config = {}) {
22
+ let apiBase;
23
+ let walletStore;
24
+ try {
25
+ apiBase = resolveDexterApiBase(config.apiBase);
26
+ } catch (err) {
27
+ return netError("untrusted_api_base", err);
28
+ }
29
+ try {
30
+ walletStore = resolveWalletStoreMode(config.walletStore);
31
+ } catch (err) {
32
+ return {
33
+ ok: false,
34
+ reason: "error",
35
+ error: err instanceof ConnectError ? err : new ConnectError("invalid_wallet_store_mode")
36
+ };
37
+ }
38
+ if (shouldUsePopup(config.transport)) {
39
+ let outcome;
40
+ try {
41
+ outcome = await openCeremonyPopup("recover", {
42
+ connectHost: config.connectHost,
43
+ preferImmediate: config.preferImmediate,
44
+ ...walletStore === "provisional" ? { walletStore } : {}
45
+ });
46
+ } catch (err) {
47
+ const ce = err instanceof ConnectError ? err : new ConnectError("popup_failed", err instanceof Error ? err.message : String(err));
48
+ if (ce.code === "popup_closed") return { ok: false, reason: "cancelled" };
49
+ return { ok: false, reason: "error", error: ce };
50
+ }
51
+ if (outcome.ok) {
52
+ try {
53
+ outcome = {
54
+ ...outcome,
55
+ walletIdentityProof: parseWalletIdentityProof(
56
+ outcome.walletIdentityProof
57
+ )
58
+ };
59
+ } catch (err) {
60
+ return netError("wallet_identity_proof_malformed", err);
61
+ }
62
+ if (walletStore === "commit") {
63
+ activateRecoveredVault(
64
+ outcome.userHandle,
65
+ outcome.credentialId,
66
+ outcome.vault,
67
+ outcome.walletIdentityProof
68
+ );
69
+ }
70
+ }
71
+ return outcome;
72
+ }
73
+ if (typeof navigator === "undefined" || !browserSupportsWebAuthn()) {
74
+ return {
75
+ ok: false,
76
+ reason: "error",
77
+ error: new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment")
78
+ };
79
+ }
80
+ const onPhase = config.onPhase;
81
+ onPhase?.("challenge");
82
+ let options;
83
+ try {
84
+ const res = await fetch(`${apiBase}${ANON_SIGN_BASE}/recover-challenge`, {
85
+ method: "POST",
86
+ headers: { "content-type": "application/json" },
87
+ body: "{}"
88
+ });
89
+ if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
90
+ const serverOptions = (await res.json()).options;
91
+ if (!serverOptions?.challenge) {
92
+ return {
93
+ ok: false,
94
+ reason: "error",
95
+ error: new ConnectError("recover_challenge_malformed", "no challenge in response")
96
+ };
97
+ }
98
+ options = { ...serverOptions, rpId: resolveDexterRpId(serverOptions.rpId) };
99
+ } catch (err) {
100
+ if (err instanceof ConnectError && err.code === "untrusted_rp_id") {
101
+ return { ok: false, reason: "error", error: err };
102
+ }
103
+ return netError("recover_challenge_failed", err);
104
+ }
105
+ onPhase?.("passkey");
106
+ const useImmediate = Boolean(config.preferImmediate) && await immediateGetSupported();
107
+ let credential;
108
+ try {
109
+ credential = useImmediate ? await immediateAuthentication(options) : await startAuthentication({ optionsJSON: options });
110
+ } catch (err) {
111
+ if (classifyWebAuthnRejection(err)) {
112
+ return { ok: false, reason: useImmediate ? "no_credential" : "cancelled" };
113
+ }
114
+ return {
115
+ ok: false,
116
+ reason: "error",
117
+ error: new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err))
118
+ };
119
+ }
120
+ onPhase?.("verifying");
121
+ let userHandle;
122
+ let credentialId;
123
+ let walletIdentityProof;
124
+ try {
125
+ const res = await fetch(`${apiBase}${ANON_SIGN_BASE}/recover-verify`, {
126
+ method: "POST",
127
+ headers: { "content-type": "application/json" },
128
+ body: JSON.stringify({ credential })
129
+ });
130
+ if (res.status === 404) return { ok: false, reason: "no_credential" };
131
+ if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
132
+ const data = await res.json();
133
+ userHandle = data.userHandle;
134
+ credentialId = data.credentialId;
135
+ walletIdentityProof = parseWalletIdentityProof(data.walletIdentityProof);
136
+ } catch (err) {
137
+ return netError("recover_verify_failed", err);
138
+ }
139
+ let vault;
140
+ try {
141
+ const res = await fetch(
142
+ `${apiBase}/api/passkey-vault-anon/status?user_handle=${encodeURIComponent(userHandle)}`
143
+ );
144
+ if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
145
+ const data = await res.json();
146
+ if (!data.hasVault || !data.vault) {
147
+ return {
148
+ ok: false,
149
+ reason: "error",
150
+ error: new ConnectError("vault_not_found", "this sign-in key has no wallet attached")
151
+ };
152
+ }
153
+ vault = {
154
+ vaultPda: data.vault.vaultPda,
155
+ swigAddress: data.vault.swigAddress,
156
+ receiveAddress: data.vault.receiveAddress ?? null,
157
+ isActivated: Boolean(data.vault.isActivated),
158
+ walletLabel: data.vault.walletLabel ?? null
159
+ };
160
+ } catch (err) {
161
+ return netError("vault_status_failed", err);
162
+ }
163
+ if (walletStore === "commit") {
164
+ activateRecoveredVault(
165
+ userHandle,
166
+ credentialId,
167
+ vault,
168
+ walletIdentityProof
169
+ );
170
+ }
171
+ return { ok: true, userHandle, credentialId, vault, walletIdentityProof };
172
+ }
173
+ function netError(code, err) {
174
+ return {
175
+ ok: false,
176
+ reason: "error",
177
+ error: new ConnectError(code, err instanceof Error ? err.message : String(err))
178
+ };
179
+ }
180
+
181
+ export {
182
+ recoverWallet
183
+ };
@@ -10,7 +10,7 @@ var BUTTON_CSS = `
10
10
  min-height:48px; padding:11px 22px; border:1px solid color-mix(in srgb,var(--dx-ember,#f26c18) 55%,transparent);
11
11
  border-radius:var(--dx-radius,0px);
12
12
  background:linear-gradient(135deg,var(--dx-ember,#f26c18),var(--dx-ember-2,#ba3a00));
13
- color:var(--dx-fg,#fff4ea); font:inherit; font-weight:600; font-size:.78rem; letter-spacing:.12em;
13
+ color:var(--dx-fg,#fff4ea); font:inherit; font-weight:600; font-size:.875rem; letter-spacing:.1em;
14
14
  text-transform:uppercase; cursor:pointer; -webkit-tap-highlight-color:transparent;
15
15
  box-shadow:0 14px 26px color-mix(in srgb,var(--dx-ember,#f26c18) 24%,transparent);
16
16
  transition:transform .16s ease, box-shadow .16s ease, filter .16s ease, background .16s ease;
@@ -50,7 +50,7 @@ var BUTTON_CSS = `
50
50
  .dx-btn--sm:hover{ box-shadow:0 12px 22px color-mix(in srgb,var(--dx-ember,#f26c18) 26%,transparent); }
51
51
  .dx-btn--sm .dx-btn__mark{ width:14px; height:14px; }
52
52
  .dx-btn--sm .dx-btn__spin{ width:12px; height:12px; }
53
- .dx-btn__mark{ flex-shrink:0; }
53
+ .dx-btn__mark{ width:20px; height:20px; flex-shrink:0; }
54
54
  .dx-btn__spin{ width:15px; height:15px; flex-shrink:0; border-radius:50%;
55
55
  border:2px solid color-mix(in srgb,currentColor 30%,transparent); border-top-color:currentColor;
56
56
  animation:dx-spin .7s linear infinite; }
@@ -0,0 +1,228 @@
1
+ import { P as PasskeyLoginTokens, o as PasskeyLoginConfig, a as CeremonyPhase, S as SignInResult } from './enroll-DrgEW0X8.js';
2
+
3
+ /**
4
+ * Framework-neutral Wallet/account relationship controller.
5
+ *
6
+ * Browser presence is insufficient to establish a bound identity. The injected
7
+ * verifier is the only path to `bound` or `conflict`; every local identity
8
+ * change immediately falls back to a provisional relation while verification
9
+ * runs. Candidate objects should be immutable for the duration of a check.
10
+ */
11
+ type WalletAccountRelation = 'none' | 'wallet_only' | 'account_only' | 'bound' | 'conflict';
12
+ type RelationCheckReason = 'restore' | 'wallet_change' | 'account_change' | 'retry';
13
+ type RelationRuntime = {
14
+ readonly phase: 'hydrating';
15
+ } | {
16
+ readonly phase: 'checking';
17
+ readonly reason: RelationCheckReason;
18
+ } | {
19
+ readonly phase: 'ready';
20
+ } | {
21
+ readonly phase: 'offline';
22
+ } | {
23
+ readonly phase: 'expired';
24
+ readonly subject: 'wallet' | 'account' | 'both';
25
+ } | {
26
+ readonly phase: 'error';
27
+ readonly code: string;
28
+ };
29
+ interface WalletAccountRelationSnapshot {
30
+ readonly relation: WalletAccountRelation;
31
+ readonly runtime: RelationRuntime;
32
+ readonly walletPresent: boolean;
33
+ readonly accountPresent: boolean;
34
+ /** Account-scoped data and actions stay locked unless the server verified the pair. */
35
+ readonly privateAccountAccess: boolean;
36
+ /** A verified mismatch. Consumers should expose only their repair path. */
37
+ readonly quarantined: boolean;
38
+ readonly verifiedAt: number | null;
39
+ readonly revision: number;
40
+ }
41
+ type ServerRelationVerificationResult = {
42
+ readonly ok: true;
43
+ readonly relation: 'bound' | 'conflict';
44
+ readonly verifiedAt?: number;
45
+ } | {
46
+ readonly ok: false;
47
+ readonly reason: 'offline';
48
+ } | {
49
+ readonly ok: false;
50
+ readonly reason: 'expired';
51
+ readonly subject: 'wallet' | 'account' | 'both';
52
+ } | {
53
+ readonly ok: false;
54
+ readonly reason: 'error';
55
+ readonly code: string;
56
+ };
57
+ interface ServerRelationVerificationRequest<TWallet, TAccount> {
58
+ readonly wallet: TWallet;
59
+ readonly account: TAccount;
60
+ readonly reason: RelationCheckReason;
61
+ readonly signal: AbortSignal;
62
+ }
63
+ type ServerRelationVerifier<TWallet, TAccount> = (request: ServerRelationVerificationRequest<TWallet, TAccount>) => Promise<ServerRelationVerificationResult>;
64
+ interface WalletAccountRelationControllerOptions<TWallet, TAccount> {
65
+ /**
66
+ * Call the Dexter API with proof for both candidates. Local equality checks
67
+ * are not verification and must not be substituted here.
68
+ */
69
+ readonly verify: ServerRelationVerifier<TWallet, TAccount>;
70
+ readonly now?: () => number;
71
+ }
72
+ interface RelationCandidates<TWallet, TAccount> {
73
+ readonly wallet: TWallet | null;
74
+ readonly account: TAccount | null;
75
+ }
76
+ type Listener = (snapshot: WalletAccountRelationSnapshot) => void;
77
+ /**
78
+ * Owns relationship state without owning storage, HTTP, React, or credentials.
79
+ * Consumers feed it Wallet/account candidates and provide the API verifier.
80
+ */
81
+ declare class WalletAccountRelationController<TWallet, TAccount> {
82
+ private wallet;
83
+ private account;
84
+ private revision;
85
+ private activeCheck;
86
+ private readonly listeners;
87
+ private readonly verify;
88
+ private readonly now;
89
+ private snapshot;
90
+ constructor(options: WalletAccountRelationControllerOptions<TWallet, TAccount>);
91
+ getSnapshot(): WalletAccountRelationSnapshot;
92
+ subscribe(listener: Listener): () => void;
93
+ /** Restore cached candidates, then verify the exact pair before unlocking account access. */
94
+ restore(candidates: RelationCandidates<TWallet, TAccount>): Promise<WalletAccountRelationSnapshot>;
95
+ /** Lock account-owned data while the host restores its account session. */
96
+ beginRestore(): void;
97
+ /** An explicit Wallet event always invalidates prior binding, even for the same object. */
98
+ setWallet(wallet: TWallet | null): Promise<WalletAccountRelationSnapshot>;
99
+ /** An explicit account event always invalidates prior binding, even for the same object. */
100
+ setAccount(account: TAccount | null): Promise<WalletAccountRelationSnapshot>;
101
+ retry(): Promise<WalletAccountRelationSnapshot>;
102
+ dispose(): void;
103
+ private runtimeAfterChange;
104
+ private replaceCandidates;
105
+ private invalidate;
106
+ private settle;
107
+ private runCheck;
108
+ private isCurrentCheck;
109
+ private publish;
110
+ }
111
+
112
+ declare const WALLET_ACCOUNT_BINDING_PATH = "/api/passkey-anon/binding/resolve";
113
+ type ResolvedWalletAccountRelation = 'wallet_only' | 'account_only' | 'bound' | 'conflict';
114
+ declare const walletBindingCandidateBrand: unique symbol;
115
+ declare const accountBindingCandidateBrand: unique symbol;
116
+ /** Opaque bearer for a server-issued Dexter Wallet identity proof. */
117
+ interface WalletBindingCandidate {
118
+ readonly kind: 'dexter_wallet_identity_proof';
119
+ readonly [walletBindingCandidateBrand]: true;
120
+ }
121
+ /** The exact active Wallet selected by the consumer for this relation check. */
122
+ interface ActiveWalletBindingIdentity {
123
+ readonly userHandle: string;
124
+ readonly vaultPda: string;
125
+ }
126
+ /** Opaque bearer for an authenticated Dexter account session. */
127
+ interface AccountBindingCandidate {
128
+ readonly kind: 'dexter_account_session';
129
+ readonly [accountBindingCandidateBrand]: true;
130
+ }
131
+ /**
132
+ * Wrap a Wallet proof before giving it to the relationship controller. The
133
+ * proof stays outside enumerable object properties, JSON, and snapshots.
134
+ */
135
+ declare function walletBindingCandidate(identityProof: string, activeWallet: ActiveWalletBindingIdentity): WalletBindingCandidate;
136
+ /**
137
+ * Wrap an account access token before giving it to the relationship controller.
138
+ * The token stays outside enumerable object properties, JSON, and snapshots.
139
+ */
140
+ declare function accountBindingCandidate(accessToken: string): AccountBindingCandidate;
141
+ type BindingResolutionResult = {
142
+ readonly ok: true;
143
+ readonly relation: ResolvedWalletAccountRelation;
144
+ } | {
145
+ readonly ok: false;
146
+ readonly reason: 'offline';
147
+ } | {
148
+ readonly ok: false;
149
+ readonly reason: 'expired';
150
+ readonly subject: 'wallet' | 'account' | 'both';
151
+ } | {
152
+ readonly ok: false;
153
+ readonly reason: 'error';
154
+ readonly code: string;
155
+ };
156
+ interface ResolveWalletAccountBindingInput {
157
+ readonly wallet?: WalletBindingCandidate | null;
158
+ readonly account?: AccountBindingCandidate | null;
159
+ readonly signal?: AbortSignal;
160
+ }
161
+ type BindingFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
162
+ interface WalletAccountBindingClientConfig {
163
+ /** Compatibility option; only the canonical Dexter API origin is accepted. */
164
+ readonly apiBase?: string;
165
+ /** Injectable for tests, edge runtimes, and hosts with a custom fetch adapter. */
166
+ readonly fetch?: BindingFetch;
167
+ }
168
+ interface WalletAccountBindingClient {
169
+ resolve(input: ResolveWalletAccountBindingInput): Promise<BindingResolutionResult>;
170
+ readonly verify: ServerRelationVerifier<WalletBindingCandidate, AccountBindingCandidate>;
171
+ }
172
+ /**
173
+ * Create the API adapter that resolves Wallet/account relation from two
174
+ * independently issued proofs. It never compares browser identifiers.
175
+ */
176
+ declare function createWalletAccountBindingClient(config?: WalletAccountBindingClientConfig): WalletAccountBindingClient;
177
+
178
+ type AccountSessionInstaller = (session: PasskeyLoginTokens) => void | Promise<void>;
179
+ type AccountSessionClearer = () => void | Promise<void>;
180
+ interface ConnectDexterIdentityConfig extends Omit<PasskeyLoginConfig, 'walletStore'> {
181
+ /**
182
+ * Install the account session returned by the same passkey ceremony. Reject
183
+ * without publishing a replacement session if installation fails.
184
+ */
185
+ readonly installAccountSession: AccountSessionInstaller;
186
+ /** Injectable binding fetch for tests and non-browser hosts. */
187
+ readonly bindingFetch?: BindingFetch;
188
+ }
189
+ interface DisconnectDexterIdentityConfig {
190
+ /** Clear the host account session after Connect drops the active Wallet. */
191
+ readonly clearAccountSession: AccountSessionClearer;
192
+ }
193
+ /**
194
+ * Complete a full Dexter identity transition from one passkey result.
195
+ *
196
+ * The candidate Wallet and account are verified as an exact pair before local
197
+ * state changes. Connect then publishes the Wallet and asks the host to install
198
+ * the matching account session. A rejected install restores the prior Wallet.
199
+ */
200
+ declare function connectDexterIdentity(config: ConnectDexterIdentityConfig, onPhase?: (phase: CeremonyPhase) => void): Promise<SignInResult>;
201
+ /** Clear the complete browser identity while retaining its device passkey. */
202
+ declare function disconnectDexterIdentity(config: DisconnectDexterIdentityConfig): Promise<boolean>;
203
+
204
+ type DexterConnectionIntent = 'identity' | 'wallet' | 'agent';
205
+ type DexterConnectionCapability = 'identity' | 'wallet.read' | 'wallet.use' | 'agent.authority';
206
+ type DexterControlStage = 'connect' | 'checking' | 'ready' | 'repair' | 'offline' | 'error';
207
+ type DexterControlPrimaryAction = 'connect' | 'use_another_wallet' | 'retry' | 'repair';
208
+ interface DexterConnectionPermissions {
209
+ readonly capabilities: readonly DexterConnectionCapability[];
210
+ readonly walletIdentityVisible: boolean;
211
+ readonly walletDataVisible: boolean;
212
+ readonly ownerWalletUseEnabled: boolean;
213
+ readonly accountContentVisible: boolean;
214
+ readonly agentAuthorityVisible: boolean;
215
+ }
216
+ interface DexterControlModel {
217
+ readonly intent: DexterConnectionIntent;
218
+ readonly stage: DexterControlStage;
219
+ readonly primaryAction: DexterControlPrimaryAction;
220
+ readonly permissions: DexterConnectionPermissions;
221
+ }
222
+ /**
223
+ * Produce the display and permission contract for the canonical Dexter control.
224
+ * Account-owned content is available only after the API verifies `bound`.
225
+ */
226
+ declare function createDexterControlModel(intent: DexterConnectionIntent, relation: WalletAccountRelationSnapshot): DexterControlModel;
227
+
228
+ export { type ActiveWalletBindingIdentity as A, type BindingFetch as B, type ConnectDexterIdentityConfig as C, type DexterConnectionCapability as D, createWalletAccountBindingClient as E, disconnectDexterIdentity as F, walletBindingCandidate as G, type RelationCandidates as R, type ServerRelationVerificationRequest as S, type WalletBindingCandidate as W, type WalletAccountRelationSnapshot as a, type WalletAccountBindingClient as b, type AccountBindingCandidate as c, type AccountSessionClearer as d, type AccountSessionInstaller as e, type BindingResolutionResult as f, type DexterConnectionIntent as g, type DexterConnectionPermissions as h, type DexterControlModel as i, type DexterControlPrimaryAction as j, type DexterControlStage as k, type DisconnectDexterIdentityConfig as l, type RelationCheckReason as m, type RelationRuntime as n, type ResolveWalletAccountBindingInput as o, type ResolvedWalletAccountRelation as p, type ServerRelationVerificationResult as q, type ServerRelationVerifier as r, WALLET_ACCOUNT_BINDING_PATH as s, type WalletAccountBindingClientConfig as t, type WalletAccountRelation as u, WalletAccountRelationController as v, type WalletAccountRelationControllerOptions as w, accountBindingCandidate as x, connectDexterIdentity as y, createDexterControlModel as z };