@dexterai/connect 0.31.3 → 0.33.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.
package/dist/hosted.js CHANGED
@@ -1,22 +1,40 @@
1
1
  import {
2
2
  recoverWallet,
3
3
  runHostedMissingVaultRecoveryProof
4
- } from "./chunk-GIEQOIYI.js";
4
+ } from "./chunk-3SBEND6T.js";
5
5
  import {
6
6
  ConnectError,
7
7
  DEXTER_API_BASE,
8
8
  continueWithDexter,
9
9
  createWallet,
10
+ enrollAccountIdentity,
10
11
  passkeyLogin,
11
12
  resolveAgentDelegationMode,
12
- resolveWalletStoreMode
13
- } from "./chunk-IPEINLMT.js";
13
+ resolveWalletStoreMode,
14
+ signInAccountIdentity
15
+ } from "./chunk-Q7HTBUJF.js";
14
16
  import "./chunk-EMCGL64H.js";
15
17
 
16
18
  // src/hosted.ts
17
19
  var DEXTER_HOSTED_CEREMONY_ORIGIN = "https://dexter.cash";
18
20
  async function runHostedCeremony(request) {
19
21
  assertHostedCeremonyOrigin();
22
+ if (request.operation === "account-signin") {
23
+ return signInAccountIdentity({
24
+ apiBase: DEXTER_API_BASE,
25
+ transport: "inline",
26
+ ...request.targetUserHandle === void 0 ? {} : { targetUserHandle: request.targetUserHandle },
27
+ ...request.onPhase === void 0 ? {} : { onPhase: request.onPhase }
28
+ });
29
+ }
30
+ if (request.operation === "account-enroll") {
31
+ return enrollAccountIdentity({
32
+ apiBase: DEXTER_API_BASE,
33
+ transport: "inline",
34
+ ...request.name === void 0 ? {} : { name: request.name },
35
+ ...request.onPhase === void 0 ? {} : { onPhase: request.onPhase }
36
+ });
37
+ }
20
38
  const walletStore = resolveWalletStoreMode(request.walletStore);
21
39
  assertHostedDelegationChoice(request);
22
40
  const persistence = walletStore === "provisional" ? { walletStore } : {};
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { M as MissingVaultRecoveryConfig, c as MissingVaultRecoveryResult, d as ConnectVault, e as RecoverWalletConfig, R as RecoverOutcome, f as WalletIdentityProof, a as CeremonyPhase } from './enroll-Cqou8Pbi.js';
2
- export { A as AgentDelegationMode, g as CeremonyOperation, h as ConnectError, i as CreateWalletConfig, C as CreateWalletResult, D as DexterConnectConfig, H as HostedSignRequestPayload, j as HostedSignResult, k as HostedSignVaultIdentity, l as MissingVaultRecoveryAccount, m as MissingVaultRecoveryVault, P as PasskeyLoginTokens, n as RecoverVault, o as SESSION_TTL_30D, S as SignInResult, b as SpendPolicy, p as authoredPolicy, q as createWallet, u as usdToAtomic } from './enroll-Cqou8Pbi.js';
1
+ import { M as MissingVaultRecoveryConfig, c as MissingVaultRecoveryResult, d as ConnectVault, e as RecoverWalletConfig, R as RecoverOutcome, A as AccountIdentityResult, f as ConnectError, g as WalletIdentityProof, a as CeremonyPhase } from './accountIdentity-DQ_C-WAi.js';
2
+ export { h as ACCOUNT_IDENTITY_API_PATH, i as AccountAccessResult, j as AccountIdentityCredential, k as AccountIdentitySession, l as AccountRefusalRequest, m as AgentDelegationMode, n as CeremonyOperation, o as CreateWalletConfig, C as CreateWalletResult, D as DexterConnectConfig, E as EnrollAccountIdentityConfig, H as HostedSignRequestPayload, p as HostedSignResult, q as HostedSignVaultIdentity, r as MissingVaultRecoveryAccount, s as MissingVaultRecoveryVault, P as PasskeyLoginTokens, t as RecoverVault, u as SESSION_TTL_30D, v as SignInAccountIdentityConfig, S as SignInResult, b as SpendPolicy, w as authoredPolicy, x as createWallet, y as enrollAccountAccess, z as enrollAccountIdentity, B as signInAccountAccess, F as signInAccountIdentity, G as usdToAtomic } from './accountIdentity-DQ_C-WAi.js';
3
3
  import { PasskeySignerWithPublicKey } from '@dexterai/vault/signers';
4
- import { A as ActiveWalletBindingIdentity, W as WalletBindingCandidate, a as WalletAccountRelationSnapshot, B as BindingFetch, b as WalletAccountBindingClient } from './connectionContract-BgecDiDk.js';
5
- export { c as AccountBindingCandidate, d as AccountSessionClearer, e as AccountSessionInstaller, f as BindingResolutionResult, C as ConnectDexterIdentityConfig, D as DexterConnectionCapability, g as DexterConnectionIntent, h as DexterConnectionPermissions, i as DexterControlModel, j as DexterControlPrimaryAction, k as DexterControlStage, l as DisconnectDexterIdentityConfig, R as RelationCandidates, m as RelationCheckReason, n as RelationRuntime, o as ResolveWalletAccountBindingInput, p as ResolvedWalletAccountRelation, S as ServerRelationVerificationRequest, q as ServerRelationVerificationResult, r as ServerRelationVerifier, s as WALLET_ACCOUNT_BINDING_PATH, t as WalletAccountBindingClientConfig, u as WalletAccountRelation, v as WalletAccountRelationController, w as WalletAccountRelationControllerOptions, x as WalletIdentityFetchInput, y as accountBindingCandidate, z as connectDexterIdentity, E as createDexterControlModel, F as createWalletAccountBindingClient, G as disconnectDexterIdentity, H as fetchWithWalletIdentity, I as walletBindingCandidate } from './connectionContract-BgecDiDk.js';
4
+ import { A as ActiveWalletBindingIdentity, W as WalletBindingCandidate, a as WalletAccountRelationSnapshot, B as BindingFetch, b as WalletAccountBindingClient } from './connectionContract-BA03zq2D.js';
5
+ export { c as AccountBindingCandidate, d as AccountSessionClearer, e as AccountSessionInstaller, f as BindingResolutionResult, C as ConnectDexterIdentityConfig, D as DexterConnectionCapability, g as DexterConnectionIntent, h as DexterConnectionPermissions, i as DexterControlModel, j as DexterControlPrimaryAction, k as DexterControlStage, l as DisconnectDexterIdentityConfig, R as RelationCandidates, m as RelationCheckReason, n as RelationRuntime, o as ResolveWalletAccountBindingInput, p as ResolvedWalletAccountRelation, S as ServerRelationVerificationRequest, q as ServerRelationVerificationResult, r as ServerRelationVerifier, s as WALLET_ACCOUNT_BINDING_PATH, t as WalletAccountBindingClientConfig, u as WalletAccountRelation, v as WalletAccountRelationController, w as WalletAccountRelationControllerOptions, x as WalletIdentityFetchInput, y as accountBindingCandidate, z as connectDexterIdentity, E as createDexterControlModel, F as createWalletAccountBindingClient, G as disconnectDexterIdentity, H as fetchWithWalletIdentity, I as walletBindingCandidate } from './connectionContract-BA03zq2D.js';
6
6
  import { PublicKeyCredentialRequestOptionsJSON, AuthenticationResponseJSON } from '@simplewebauthn/browser';
7
7
 
8
8
  /**
@@ -82,6 +82,163 @@ declare function createPasskeySigner(vault: ConnectVault, apiBase?: string, opts
82
82
 
83
83
  declare function recoverWallet(config?: RecoverWalletConfig): Promise<RecoverOutcome>;
84
84
 
85
+ declare const ACCOUNT_API_PATH = "/api/account/v1";
86
+ interface DexterAccount {
87
+ readonly principal: string;
88
+ readonly wallet: string | null;
89
+ readonly status: 'ready' | 'setting-up';
90
+ readonly nextStep: string | null;
91
+ }
92
+ /** The passkey the session is bound to, as its owner would recognise it. */
93
+ interface AccountPasskey {
94
+ /** The label given when the passkey was created, if one was stored. */
95
+ readonly name: string | null;
96
+ /** ISO time the passkey was created. */
97
+ readonly createdAt: string | null;
98
+ }
99
+ /** An operation whose last step was approved and whose outcome the API does not know yet. */
100
+ interface AccountUnsettled {
101
+ readonly operationId: string;
102
+ readonly flow: 'setup' | 'send';
103
+ readonly step: string;
104
+ }
105
+ interface AccountOverview {
106
+ readonly account: DexterAccount | null;
107
+ /**
108
+ * Set while an approved step may still land. Offer no new send until it is
109
+ * settled: read it with `getAccountOperation`.
110
+ */
111
+ readonly unsettled: AccountUnsettled | null;
112
+ /** Which chain the API is using. Anything but `mainnet` is a rehearsal and must be shown as one. */
113
+ readonly network: 'mainnet' | 'test' | null;
114
+ readonly passkey: AccountPasskey | null;
115
+ }
116
+ interface AccountTokenBalance {
117
+ readonly mint: string;
118
+ readonly symbol: string | null;
119
+ readonly decimals: number;
120
+ /** Smallest unit, as a decimal string. */
121
+ readonly amount: string;
122
+ }
123
+ interface AccountBalances {
124
+ readonly wallet: string;
125
+ readonly sol: {
126
+ readonly lamports: string;
127
+ };
128
+ readonly tokens: readonly AccountTokenBalance[];
129
+ readonly slot: number;
130
+ readonly commitment: string;
131
+ }
132
+ interface AccountSendRequest {
133
+ /** A mint address, or `SOL`. */
134
+ readonly mint: string;
135
+ /** Smallest unit, as a decimal string. */
136
+ readonly amount: string;
137
+ readonly to: string;
138
+ }
139
+ /**
140
+ * What the API actually prepared. Shown to the owner before the prompt.
141
+ * `approve-send` carries the amount and recipient; `prepare-token`, the
142
+ * one-time setup of a token for sending, carries the token only.
143
+ */
144
+ interface AccountOperationDetails {
145
+ readonly mint: string;
146
+ readonly symbol: string | null;
147
+ readonly decimals: number;
148
+ readonly amount: string | null;
149
+ readonly to: string | null;
150
+ }
151
+ type AccountStepPhase = 'preparing' | 'ready' | 'passkey' | 'sending' | 'confirmed';
152
+ /** One approval, as the page should show it. */
153
+ interface AccountStepView {
154
+ /** The API's name for the step. The page words the steps it knows. */
155
+ readonly step: string;
156
+ /** The API's wording, for a step the page does not know yet. */
157
+ readonly summary: string;
158
+ /** The kit's own text for what the passkey signs, when the API sends it. */
159
+ readonly statement: string | null;
160
+ readonly stepsRemaining: number | null;
161
+ readonly details: AccountOperationDetails | null;
162
+ readonly phase: AccountStepPhase;
163
+ /** Set once the step is confirmed. */
164
+ readonly signature: string | null;
165
+ }
166
+ interface AccountOperationConfig {
167
+ /** The Account session from `enrollAccountIdentity` or `signInAccountIdentity`. */
168
+ readonly identity: AccountIdentityResult;
169
+ readonly onStep?: (view: AccountStepView) => void;
170
+ /**
171
+ * Hold each prepared step until the owner taps. Resolve it inside the tap's
172
+ * own handler: browsers that require a user gesture for a passkey prompt
173
+ * then see the prompt as coming from that tap. Reject to cancel. Without
174
+ * it, the prompt follows the prepare directly.
175
+ */
176
+ readonly confirmStep?: (view: AccountStepView) => Promise<void>;
177
+ readonly signal?: AbortSignal;
178
+ }
179
+ interface AccountFlowResult {
180
+ /** Transaction signatures, one per approved step, in order. */
181
+ readonly signatures: readonly string[];
182
+ }
183
+ /**
184
+ * Where one operation stands, from the API's own record and the chain.
185
+ * `failed` means none of its transactions landed or can still land;
186
+ * `sending` means that is not known yet.
187
+ */
188
+ type AccountOperationStatus = 'prepared' | 'sending' | 'confirmed' | 'failed' | 'expired';
189
+ interface AccountOperationState {
190
+ readonly operationId: string;
191
+ readonly flow: 'setup' | 'send';
192
+ readonly step: string;
193
+ readonly status: AccountOperationStatus;
194
+ readonly signature: string | null;
195
+ readonly next: string | null;
196
+ }
197
+ /**
198
+ * An approved step whose outcome is not known: the reply was lost, slow, or
199
+ * the API could not say. Its transaction may still land, so the page must not
200
+ * say nothing was sent, and must not offer the same send again until
201
+ * `getAccountOperation` settles it.
202
+ */
203
+ declare class AccountOperationUnsettledError extends ConnectError {
204
+ readonly operationId: string;
205
+ readonly flow: 'setup' | 'send';
206
+ readonly step: string;
207
+ constructor(operationId: string, flow: 'setup' | 'send', step: string);
208
+ }
209
+ /** Read the signed-in owner's Account, or `null` when none is open yet. */
210
+ declare function getAccount(config: Pick<AccountOperationConfig, 'identity' | 'signal'>): Promise<DexterAccount | null>;
211
+ /**
212
+ * Read the Account together with what the owner should see around it: the
213
+ * chain in use and the passkey that owns, or is about to own, the Account.
214
+ * Fields the API does not send come back as `null`.
215
+ */
216
+ declare function getAccountOverview(config: Pick<AccountOperationConfig, 'identity' | 'signal'>): Promise<AccountOverview>;
217
+ /** Read where one operation stands. See `AccountOperationUnsettledError`. */
218
+ declare function getAccountOperation(config: Pick<AccountOperationConfig, 'identity' | 'signal'> & {
219
+ readonly operationId: string;
220
+ }): Promise<AccountOperationState>;
221
+ /** Read the Account wallet's balances. Amounts are smallest-unit strings. */
222
+ declare function getAccountBalances(config: Pick<AccountOperationConfig, 'identity' | 'signal'>): Promise<AccountBalances>;
223
+ /**
224
+ * Open the owner's Account, or finish opening it. Each step the API asks for
225
+ * is one passkey approval; the API decides how many there are. Resolves with
226
+ * the Account once it is ready. Safe to call again after an interruption.
227
+ */
228
+ declare function openAccount(config: AccountOperationConfig): Promise<DexterAccount>;
229
+ /**
230
+ * Send from the Account wallet. The owner approves one exact amount and
231
+ * recipient (`approve-send`). The first send of a token is preceded by its
232
+ * one-time setup (`prepare-token`), which is its own approval.
233
+ */
234
+ declare function sendFromAccount(config: AccountOperationConfig & {
235
+ readonly send: AccountSendRequest;
236
+ }): Promise<AccountFlowResult>;
237
+ /** Turn a smallest-unit amount into a plain decimal string, without rounding. */
238
+ declare function formatAccountAmount(amount: string, decimals: number): string;
239
+ /** Turn what a person typed ("2.5") into a smallest-unit string, or `null` if it is not an amount. */
240
+ declare function parseAccountAmount(input: string, decimals: number): string | null;
241
+
85
242
  /** One localStorage entry per Wallet keeps inactive Wallet proofs independent. */
86
243
  declare const WALLET_PROOF_SESSION_STORAGE_PREFIX: "dexter:wallet-identity-proof-session:";
87
244
  declare const walletProofSessionBrand: unique symbol;
@@ -651,4 +808,4 @@ declare function readAgentAuthority(input: {
651
808
  fetchImpl?: typeof fetch;
652
809
  }): Promise<AgentAuthorityStatus>;
653
810
 
654
- export { AGENT_AUTHORITY_NAMESPACE, AGENT_AUTHORITY_STATUS_NAMESPACE, type AgentAuthorityActiveRole, type AgentAuthorityApprovalMode, type AgentAuthorityAuthorization, type AgentAuthorityBootstrapRequest, type AgentAuthorityCapacity, AgentAuthorityError, type AgentAuthorityRule, type AgentAuthorityRuleBase, type AgentAuthorityStagedReceipt, type AgentAuthorityStatus, type AgentAuthorityTarget, AgentSpendError, type AgentSpendIdentity, type AgentSpendStatus, type AgentSpendTab, type AnonChallengeResult, type AnonServerPolicy, type AutomaticAgentSpend, BindingFetch, AgentAuthorityError as BoundedX402AuthorityError, type BoundedX402Authorization, type BoundedX402BootstrapRequest, type BoundedX402Draft, type BoundedX402Limits, type BoundedX402Rule, type BoundedX402StagedReceipt, type BoundedX402Validation, CeremonyPhase, ConnectVault, type CreatePasskeySignerOptions, type DexterIdentityCoordinator, type DexterIdentityCoordinatorOptions, type EnableAgentSpendResult, MAX_AUTHORITY_AMOUNT_ATOMIC, MissingVaultRecoveryConfig, MissingVaultRecoveryResult, type PasskeySignalSupport, type RawAgentSpendSession, type RawAgentSpendStatus, RecoverOutcome, RecoverWalletConfig, type RevokeAgentSpendResult, type StagedAgentAuthorityRule, type TradeAuthorityRule, WALLET_PROOF_SESSION_STORAGE_PREFIX, WalletAccountBindingClient, WalletAccountRelationSnapshot, WalletBindingCandidate, WalletIdentityProof, type WalletProofLifecycleEvent, type WalletProofSession, type WalletProofSessionEvent, type WalletProofSessionOperation, type WalletProofSessionStorage, type WalletProofSessionStore, type WalletProofSessionStoreOptions, type WalletProofStorageEvent, type WalletProofStorageEventSource, type X402LimitDraft, type X402LimitValidation, type X402Limits, type X402PaymentAuthorityRule, X402_ALLOWED_SCHEMES, X402_ASSET, X402_COUNTERPARTY_SCOPE, X402_PROTOCOL_ID, X402_PROTOCOL_VERSION, assembleAgentSpendStatus, beginAgentAuthority, beginBoundedX402Authority, buildAgentAuthorityRequest, buildBoundedX402BootstrapRequest, buildX402PaymentRule, ceremonyPhaseLabel, createAnonServerPolicy, createDexterIdentityCoordinator, createPasskeySigner, createWalletProofSessionStore, describeAgentSpendError, enableAgentSpend, exactAgentAuthorityApprovalRedirect, exactBoundedX402ApprovalRedirect, noCustomX402Limits, passkeySignalSupport, prunePasskey, readAgentAuthority, recoverMissingVaultForAccount, recoverWallet, renamePasskey, revokeAgentSpend, stageAgentAuthority, stageBoundedX402Authority, syncAcceptedPasskeys, validateBoundedX402Draft, walletProofSessionStore };
811
+ export { ACCOUNT_API_PATH, AGENT_AUTHORITY_NAMESPACE, AGENT_AUTHORITY_STATUS_NAMESPACE, type AccountBalances, type AccountFlowResult, AccountIdentityResult, type AccountOperationConfig, type AccountOperationDetails, type AccountOperationState, type AccountOperationStatus, AccountOperationUnsettledError, type AccountOverview, type AccountPasskey, type AccountSendRequest, type AccountStepPhase, type AccountStepView, type AccountTokenBalance, type AccountUnsettled, type AgentAuthorityActiveRole, type AgentAuthorityApprovalMode, type AgentAuthorityAuthorization, type AgentAuthorityBootstrapRequest, type AgentAuthorityCapacity, AgentAuthorityError, type AgentAuthorityRule, type AgentAuthorityRuleBase, type AgentAuthorityStagedReceipt, type AgentAuthorityStatus, type AgentAuthorityTarget, AgentSpendError, type AgentSpendIdentity, type AgentSpendStatus, type AgentSpendTab, type AnonChallengeResult, type AnonServerPolicy, type AutomaticAgentSpend, BindingFetch, AgentAuthorityError as BoundedX402AuthorityError, type BoundedX402Authorization, type BoundedX402BootstrapRequest, type BoundedX402Draft, type BoundedX402Limits, type BoundedX402Rule, type BoundedX402StagedReceipt, type BoundedX402Validation, CeremonyPhase, ConnectError, ConnectVault, type CreatePasskeySignerOptions, type DexterAccount, type DexterIdentityCoordinator, type DexterIdentityCoordinatorOptions, type EnableAgentSpendResult, MAX_AUTHORITY_AMOUNT_ATOMIC, MissingVaultRecoveryConfig, MissingVaultRecoveryResult, type PasskeySignalSupport, type RawAgentSpendSession, type RawAgentSpendStatus, RecoverOutcome, RecoverWalletConfig, type RevokeAgentSpendResult, type StagedAgentAuthorityRule, type TradeAuthorityRule, WALLET_PROOF_SESSION_STORAGE_PREFIX, WalletAccountBindingClient, WalletAccountRelationSnapshot, WalletBindingCandidate, WalletIdentityProof, type WalletProofLifecycleEvent, type WalletProofSession, type WalletProofSessionEvent, type WalletProofSessionOperation, type WalletProofSessionStorage, type WalletProofSessionStore, type WalletProofSessionStoreOptions, type WalletProofStorageEvent, type WalletProofStorageEventSource, type X402LimitDraft, type X402LimitValidation, type X402Limits, type X402PaymentAuthorityRule, X402_ALLOWED_SCHEMES, X402_ASSET, X402_COUNTERPARTY_SCOPE, X402_PROTOCOL_ID, X402_PROTOCOL_VERSION, assembleAgentSpendStatus, beginAgentAuthority, beginBoundedX402Authority, buildAgentAuthorityRequest, buildBoundedX402BootstrapRequest, buildX402PaymentRule, ceremonyPhaseLabel, createAnonServerPolicy, createDexterIdentityCoordinator, createPasskeySigner, createWalletProofSessionStore, describeAgentSpendError, enableAgentSpend, exactAgentAuthorityApprovalRedirect, exactBoundedX402ApprovalRedirect, formatAccountAmount, getAccount, getAccountBalances, getAccountOperation, getAccountOverview, noCustomX402Limits, openAccount, parseAccountAmount, passkeySignalSupport, prunePasskey, readAgentAuthority, recoverMissingVaultForAccount, recoverWallet, renamePasskey, revokeAgentSpend, sendFromAccount, stageAgentAuthority, stageBoundedX402Authority, syncAcceptedPasskeys, validateBoundedX402Draft, walletProofSessionStore };
package/dist/index.js CHANGED
@@ -9,13 +9,16 @@ import {
9
9
  prunePasskey,
10
10
  renamePasskey,
11
11
  syncAcceptedPasskeys
12
- } from "./chunk-UQE76AJW.js";
12
+ } from "./chunk-SLI2QCWN.js";
13
13
  import {
14
14
  recoverMissingVaultForAccount,
15
15
  recoverWallet
16
- } from "./chunk-GIEQOIYI.js";
16
+ } from "./chunk-3SBEND6T.js";
17
17
  import {
18
+ ACCOUNT_IDENTITY_API_PATH,
18
19
  ConnectError,
20
+ DEXTER_API_BASE,
21
+ DEXTER_RP_ID,
19
22
  SESSION_TTL_30D,
20
23
  WALLET_ACCOUNT_BINDING_PATH,
21
24
  WALLET_PROOF_SESSION_STORAGE_PREFIX,
@@ -25,16 +28,20 @@ import {
25
28
  createWallet,
26
29
  createWalletAccountBindingClient,
27
30
  createWalletProofSessionStore,
31
+ enrollAccountAccess,
32
+ enrollAccountIdentity,
28
33
  fetchWithWalletIdentity,
29
34
  openCeremonyPopup,
30
35
  readErrorCode,
31
36
  resolveDexterApiBase,
32
37
  resolveDexterRpId,
33
38
  shouldUsePopup,
39
+ signInAccountAccess,
40
+ signInAccountIdentity,
34
41
  usdToAtomic,
35
42
  walletBindingCandidate,
36
43
  walletProofSessionStore
37
- } from "./chunk-IPEINLMT.js";
44
+ } from "./chunk-Q7HTBUJF.js";
38
45
  import {
39
46
  base64ToBytes,
40
47
  base64urlToBytes,
@@ -209,6 +216,351 @@ async function validateHostedSignResult(result, operationMessage, expectedVault)
209
216
  };
210
217
  }
211
218
 
219
+ // src/accountOperations.ts
220
+ import { browserSupportsWebAuthn, startAuthentication } from "@simplewebauthn/browser";
221
+ var ACCOUNT_API_PATH = "/api/account/v1";
222
+ var MAX_STEPS = 8;
223
+ var NOT_READY_RETRIES = 2;
224
+ var AccountOperationUnsettledError = class extends ConnectError {
225
+ operationId;
226
+ flow;
227
+ step;
228
+ constructor(operationId, flow, step) {
229
+ super("account_operation_unsettled");
230
+ this.name = "AccountOperationUnsettledError";
231
+ this.operationId = operationId;
232
+ this.flow = flow;
233
+ this.step = step;
234
+ }
235
+ };
236
+ function record(value) {
237
+ return value !== null && typeof value === "object" && !Array.isArray(value);
238
+ }
239
+ var text = (value, max = 200) => typeof value === "string" && value.length > 0 && value.length <= max;
240
+ var address = (value) => typeof value === "string" && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(value);
241
+ var units = (value) => typeof value === "string" && /^(0|[1-9][0-9]{0,19})$/.test(value);
242
+ function malformed() {
243
+ throw new ConnectError("account_response_malformed");
244
+ }
245
+ function bearer(identity) {
246
+ const session = identity?.session;
247
+ if (!session || session.tokenType !== "Bearer" || !text(session.accessToken, 8192)) {
248
+ throw new ConnectError("account_session_required");
249
+ }
250
+ if (session.expiresAt * 1e3 <= Date.now()) throw new ConnectError("account_session_expired");
251
+ return session.accessToken;
252
+ }
253
+ function cancelled(signal) {
254
+ if (signal?.aborted) throw new ConnectError("user_cancelled");
255
+ }
256
+ async function call(identity, method, path, body, uncertain, signal) {
257
+ const token = bearer(identity);
258
+ let response;
259
+ try {
260
+ response = await fetch(`${DEXTER_API_BASE}${ACCOUNT_API_PATH}${path}`, {
261
+ method,
262
+ headers: {
263
+ Accept: "application/json",
264
+ Authorization: `Bearer ${token}`,
265
+ ...method === "POST" ? { "Content-Type": "application/json" } : {}
266
+ },
267
+ ...method === "POST" ? { body: JSON.stringify(body) } : {},
268
+ credentials: "omit",
269
+ cache: "no-store",
270
+ redirect: "error",
271
+ signal
272
+ });
273
+ } catch {
274
+ cancelled(signal);
275
+ throw new ConnectError(uncertain ? "account_operation_uncertain" : "account_unavailable");
276
+ }
277
+ let parsed;
278
+ try {
279
+ parsed = await response.json();
280
+ } catch {
281
+ throw new ConnectError(response.ok ? uncertain ? "account_operation_uncertain" : "account_response_malformed" : `http_${response.status}`);
282
+ }
283
+ if (!response.ok) {
284
+ const code = record(parsed) && text(parsed.error, 80) ? parsed.error : `http_${response.status}`;
285
+ const message = record(parsed) && text(parsed.message, 400) ? parsed.message : void 0;
286
+ throw new ConnectError(code, message);
287
+ }
288
+ return parsed;
289
+ }
290
+ function accountFrom(value) {
291
+ if (!record(value) || !("account" in value)) malformed();
292
+ const account = value.account;
293
+ if (account === null) return null;
294
+ if (!record(account) || !address(account.principal) || account.wallet !== null && account.wallet !== void 0 && !address(account.wallet) || account.status !== "ready" && account.status !== "setting-up" || account.nextStep !== null && account.nextStep !== void 0 && !text(account.nextStep, 80)) malformed();
295
+ return Object.freeze({
296
+ principal: account.principal,
297
+ wallet: account.wallet ?? null,
298
+ status: account.status,
299
+ nextStep: account.nextStep ?? null
300
+ });
301
+ }
302
+ function detailsFrom(value) {
303
+ if (value === void 0 || value === null) return null;
304
+ const absent = (field) => field === void 0 || field === null;
305
+ if (!record(value) || !(value.mint === "SOL" || address(value.mint)) || !(absent(value.amount) || units(value.amount)) || !(absent(value.to) || address(value.to)) || typeof value.decimals !== "number" || !Number.isInteger(value.decimals) || value.decimals < 0 || value.decimals > 18 || value.symbol !== null && value.symbol !== void 0 && !text(value.symbol, 20)) malformed();
306
+ return Object.freeze({
307
+ mint: value.mint,
308
+ symbol: value.symbol ?? null,
309
+ decimals: value.decimals,
310
+ amount: value.amount ?? null,
311
+ to: value.to ?? null
312
+ });
313
+ }
314
+ function preparedFrom(value, identity) {
315
+ if (record(value) && value.status === "complete" && (value.next === null || value.next === void 0)) return null;
316
+ if (!record(value) || !text(value.operationId) || !text(value.step, 80) || typeof value.summary !== "string" || value.summary.length > 300 || !record(value.publicKey)) malformed();
317
+ const options = value.publicKey;
318
+ let challenge;
319
+ try {
320
+ challenge = base64urlToBytes(String(options.challenge));
321
+ } catch {
322
+ malformed();
323
+ }
324
+ const allowed = options.allowCredentials;
325
+ if (challenge.length !== 32 || bytesToBase64url(challenge) !== options.challenge || options.rpId !== DEXTER_RP_ID || options.userVerification !== "required" || !Array.isArray(allowed) || allowed.length !== 1 || !record(allowed[0]) || allowed[0].type !== "public-key" || allowed[0].id !== identity.credential.credentialId) {
326
+ throw new ConnectError("account_challenge_refused");
327
+ }
328
+ const timeout = typeof options.timeout === "number" && options.timeout >= 1e4 && options.timeout <= 6e5 ? options.timeout : 12e4;
329
+ const remaining = value.stepsRemaining;
330
+ return Object.freeze({
331
+ operationId: value.operationId,
332
+ step: value.step,
333
+ summary: value.summary,
334
+ statement: text(value.statement, 1e3) ? value.statement : null,
335
+ stepsRemaining: typeof remaining === "number" && Number.isInteger(remaining) && remaining >= 0 ? remaining : null,
336
+ details: detailsFrom(value.details),
337
+ publicKey: Object.freeze({
338
+ challenge: options.challenge,
339
+ rpId: DEXTER_RP_ID,
340
+ allowCredentials: [{ type: "public-key", id: identity.credential.credentialId }],
341
+ userVerification: "required",
342
+ timeout
343
+ })
344
+ });
345
+ }
346
+ function assertApprovalContext() {
347
+ if (typeof window === "undefined" || window.top !== window.self || window.location.origin !== "https://dexter.cash") {
348
+ throw new ConnectError("hosted_ceremony_origin_required");
349
+ }
350
+ if (!browserSupportsWebAuthn()) throw new ConnectError("webauthn_unsupported");
351
+ }
352
+ var approvalInProgress = false;
353
+ async function prepare(config, flow, body) {
354
+ for (let attempt = 0; ; attempt += 1) {
355
+ try {
356
+ return preparedFrom(
357
+ await call(config.identity, "POST", `/${flow}/prepare`, body, false, config.signal),
358
+ config.identity
359
+ );
360
+ } catch (cause) {
361
+ if (!(cause instanceof ConnectError) || cause.code !== "chain_not_ready" || attempt >= NOT_READY_RETRIES) throw cause;
362
+ cancelled(config.signal);
363
+ }
364
+ }
365
+ }
366
+ async function complete(config, flow, body) {
367
+ try {
368
+ return await call(config.identity, "POST", `/${flow}/complete`, body, true);
369
+ } catch (cause) {
370
+ if (!(cause instanceof ConnectError) || cause.code !== "account_operation_uncertain") throw cause;
371
+ return call(config.identity, "POST", `/${flow}/complete`, body, true);
372
+ }
373
+ }
374
+ function confirmedFrom(value) {
375
+ if (!record(value) || value.status !== "confirmed" || !text(value.signature)) malformed();
376
+ if (value.next !== null && value.next !== void 0 && !text(value.next, 80)) malformed();
377
+ return { signature: value.signature, next: value.next ?? null };
378
+ }
379
+ async function settle(config, flow, step, operationId, cause) {
380
+ let state;
381
+ try {
382
+ state = await getAccountOperation({ identity: config.identity, operationId });
383
+ } catch {
384
+ throw new AccountOperationUnsettledError(operationId, flow, step);
385
+ }
386
+ if (state.status === "confirmed" && state.signature) return { signature: state.signature, next: state.next };
387
+ if (state.status === "failed" || state.status === "prepared" || state.status === "expired") {
388
+ throw cause instanceof ConnectError && cause.code !== "account_operation_uncertain" ? cause : new ConnectError("account_operation_failed");
389
+ }
390
+ throw new AccountOperationUnsettledError(operationId, flow, step);
391
+ }
392
+ async function runFlow(config, flow, body, check) {
393
+ assertApprovalContext();
394
+ if (approvalInProgress) throw new ConnectError("account_operation_in_progress");
395
+ approvalInProgress = true;
396
+ const signatures = [];
397
+ try {
398
+ for (let count = 0; count < MAX_STEPS; count += 1) {
399
+ cancelled(config.signal);
400
+ const prepared = await prepare(config, flow, body);
401
+ if (prepared === null) return Object.freeze({ signatures: Object.freeze(signatures) });
402
+ check?.(prepared.step, prepared.details);
403
+ const view = {
404
+ step: prepared.step,
405
+ summary: prepared.summary,
406
+ statement: prepared.statement,
407
+ stepsRemaining: prepared.stepsRemaining,
408
+ details: prepared.details,
409
+ signature: null
410
+ };
411
+ if (config.confirmStep) {
412
+ config.onStep?.({ ...view, phase: "ready" });
413
+ try {
414
+ await config.confirmStep({ ...view, phase: "ready" });
415
+ } catch {
416
+ throw new ConnectError("user_cancelled");
417
+ }
418
+ cancelled(config.signal);
419
+ }
420
+ config.onStep?.({ ...view, phase: "passkey" });
421
+ let credential;
422
+ try {
423
+ credential = await startAuthentication({ optionsJSON: { ...prepared.publicKey, allowCredentials: [...prepared.publicKey.allowCredentials] } });
424
+ } catch (cause) {
425
+ throw new ConnectError(cause instanceof Error && (cause.name === "NotAllowedError" || cause.name === "AbortError") ? "user_cancelled" : "webauthn_failed");
426
+ }
427
+ if (credential.id !== config.identity.credential.credentialId) {
428
+ throw new ConnectError("account_credential_mismatch");
429
+ }
430
+ cancelled(config.signal);
431
+ config.onStep?.({ ...view, phase: "sending" });
432
+ let result;
433
+ try {
434
+ result = confirmedFrom(await complete(config, flow, {
435
+ operationId: prepared.operationId,
436
+ assertion: {
437
+ credentialId: credential.id,
438
+ authenticatorData: credential.response.authenticatorData,
439
+ clientDataJSON: credential.response.clientDataJSON,
440
+ signature: credential.response.signature,
441
+ userHandle: credential.response.userHandle ?? null
442
+ }
443
+ }));
444
+ } catch (cause) {
445
+ result = await settle(config, flow, prepared.step, prepared.operationId, cause);
446
+ }
447
+ signatures.push(result.signature);
448
+ config.onStep?.({ ...view, phase: "confirmed", signature: result.signature });
449
+ const next = result.next;
450
+ if (next === null) return Object.freeze({ signatures: Object.freeze(signatures) });
451
+ config.onStep?.({
452
+ step: next,
453
+ summary: "",
454
+ statement: null,
455
+ stepsRemaining: null,
456
+ details: null,
457
+ signature: null,
458
+ phase: "preparing"
459
+ });
460
+ }
461
+ throw new ConnectError("account_flow_too_long");
462
+ } finally {
463
+ approvalInProgress = false;
464
+ }
465
+ }
466
+ async function getAccount(config) {
467
+ return accountFrom(await call(config.identity, "GET", "/me", void 0, false, config.signal));
468
+ }
469
+ async function getAccountOverview(config) {
470
+ const value = await call(config.identity, "GET", "/me", void 0, false, config.signal);
471
+ const account = accountFrom(value);
472
+ const body = value;
473
+ const network = body.network === "mainnet" ? "mainnet" : text(body.network, 40) ? "test" : null;
474
+ const raw = body.passkey;
475
+ const created = record(raw) && text(raw.createdAt, 40) && !Number.isNaN(Date.parse(raw.createdAt)) ? raw.createdAt : null;
476
+ const passkey = record(raw) ? Object.freeze({ name: text(raw.name, 80) ? raw.name : null, createdAt: created }) : null;
477
+ const pending = body.unsettled;
478
+ const unsettled = record(pending) && text(pending.operationId) && (pending.flow === "setup" || pending.flow === "send") && text(pending.step, 80) ? Object.freeze({ operationId: pending.operationId, flow: pending.flow, step: pending.step }) : null;
479
+ return Object.freeze({ account, network, passkey, unsettled });
480
+ }
481
+ async function getAccountOperation(config) {
482
+ if (!text(config.operationId) || !/^[A-Za-z0-9_-]+$/.test(config.operationId)) throw new ConnectError("invalid_account_operation");
483
+ const value = await call(config.identity, "GET", `/operations/${config.operationId}`, void 0, false, config.signal);
484
+ const statuses = ["prepared", "sending", "confirmed", "failed", "expired"];
485
+ if (!record(value) || value.operationId !== config.operationId || value.flow !== "setup" && value.flow !== "send" || !text(value.step, 80) || typeof value.status !== "string" || !statuses.includes(value.status) || value.signature !== null && value.signature !== void 0 && !text(value.signature) || value.next !== null && value.next !== void 0 && !text(value.next, 80) || value.status === "confirmed" && !text(value.signature)) malformed();
486
+ return Object.freeze({
487
+ operationId: value.operationId,
488
+ flow: value.flow,
489
+ step: value.step,
490
+ status: value.status,
491
+ signature: value.signature ?? null,
492
+ next: value.next ?? null
493
+ });
494
+ }
495
+ async function getAccountBalances(config) {
496
+ const value = await call(config.identity, "GET", "/balances", void 0, false, config.signal);
497
+ if (!record(value) || !address(value.wallet) || !record(value.sol) || !units(value.sol.lamports) || !Array.isArray(value.tokens) || typeof value.slot !== "number" || typeof value.commitment !== "string") malformed();
498
+ const tokens = value.tokens.map((token) => {
499
+ if (!record(token) || !address(token.mint) || !units(token.amount) || typeof token.decimals !== "number" || !Number.isInteger(token.decimals) || token.decimals < 0 || token.decimals > 18 || token.symbol !== null && token.symbol !== void 0 && !text(token.symbol, 20)) malformed();
500
+ return Object.freeze({
501
+ mint: token.mint,
502
+ symbol: token.symbol ?? null,
503
+ decimals: token.decimals,
504
+ amount: token.amount
505
+ });
506
+ });
507
+ return Object.freeze({
508
+ wallet: value.wallet,
509
+ sol: Object.freeze({ lamports: value.sol.lamports }),
510
+ tokens: Object.freeze(tokens),
511
+ slot: value.slot,
512
+ commitment: value.commitment
513
+ });
514
+ }
515
+ async function openAccount(config) {
516
+ const existing = await getAccount(config);
517
+ if (existing?.status === "ready") return existing;
518
+ config.onStep?.({
519
+ step: existing?.nextStep ?? "create-account",
520
+ summary: "",
521
+ statement: null,
522
+ stepsRemaining: null,
523
+ details: null,
524
+ signature: null,
525
+ phase: "preparing"
526
+ });
527
+ await runFlow(config, "setup", {});
528
+ const account = await getAccount(config);
529
+ if (!account) malformed();
530
+ return account;
531
+ }
532
+ async function sendFromAccount(config) {
533
+ const { send } = config;
534
+ if (!record(send) || !(send.mint === "SOL" || address(send.mint)) || !units(send.amount) || send.amount === "0" || !address(send.to)) {
535
+ throw new ConnectError("invalid_account_send");
536
+ }
537
+ const request = { mint: send.mint, amount: send.amount, to: send.to };
538
+ return runFlow(config, "send", request, (step, details) => {
539
+ const sameToken = details !== null && details.mint === request.mint;
540
+ if (step === "prepare-token" ? !sameToken || details.amount !== null || details.to !== null : !sameToken || details.amount !== request.amount || details.to !== request.to) {
541
+ throw new ConnectError("account_operation_mismatch");
542
+ }
543
+ });
544
+ }
545
+ function formatAccountAmount(amount, decimals) {
546
+ if (!units(amount) || !Number.isInteger(decimals) || decimals < 0 || decimals > 18) {
547
+ throw new ConnectError("invalid_account_amount");
548
+ }
549
+ if (decimals === 0) return amount;
550
+ const padded = amount.padStart(decimals + 1, "0");
551
+ const fraction = padded.slice(-decimals).replace(/0+$/, "");
552
+ return fraction ? `${padded.slice(0, -decimals)}.${fraction}` : padded.slice(0, -decimals);
553
+ }
554
+ function parseAccountAmount(input, decimals) {
555
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18) return null;
556
+ const match = /^([0-9]{0,20})(?:\.([0-9]*))?$/.exec(typeof input === "string" ? input.trim() : "");
557
+ if (!match || match[1] === "" && !match[2]) return null;
558
+ const fraction = match[2] ?? "";
559
+ if (fraction.length > decimals) return null;
560
+ const value = BigInt(`${match[1] || "0"}${fraction.padEnd(decimals, "0")}`);
561
+ return value > 0n && value < 1n << 64n ? value.toString() : null;
562
+ }
563
+
212
564
  // src/agentSpend.ts
213
565
  import { PublicKey as PublicKey2 } from "@solana/web3.js";
214
566
  import { WebAuthnAssertion } from "@dexterai/vault/signers/browser";
@@ -926,8 +1278,11 @@ async function readAgentAuthority(input) {
926
1278
  return payload;
927
1279
  }
928
1280
  export {
1281
+ ACCOUNT_API_PATH,
1282
+ ACCOUNT_IDENTITY_API_PATH,
929
1283
  AGENT_AUTHORITY_NAMESPACE,
930
1284
  AGENT_AUTHORITY_STATUS_NAMESPACE,
1285
+ AccountOperationUnsettledError,
931
1286
  AgentAuthorityError,
932
1287
  AgentSpendError,
933
1288
  AgentAuthorityError as BoundedX402AuthorityError,
@@ -962,10 +1317,19 @@ export {
962
1317
  describeAgentSpendError,
963
1318
  disconnectDexterIdentity,
964
1319
  enableAgentSpend,
1320
+ enrollAccountAccess,
1321
+ enrollAccountIdentity,
965
1322
  exactAgentAuthorityApprovalRedirect,
966
1323
  exactBoundedX402ApprovalRedirect,
967
1324
  fetchWithWalletIdentity,
1325
+ formatAccountAmount,
1326
+ getAccount,
1327
+ getAccountBalances,
1328
+ getAccountOperation,
1329
+ getAccountOverview,
968
1330
  noCustomX402Limits,
1331
+ openAccount,
1332
+ parseAccountAmount,
969
1333
  passkeySignalSupport,
970
1334
  prunePasskey,
971
1335
  readAgentAuthority,
@@ -973,6 +1337,9 @@ export {
973
1337
  recoverWallet,
974
1338
  renamePasskey,
975
1339
  revokeAgentSpend,
1340
+ sendFromAccount,
1341
+ signInAccountAccess,
1342
+ signInAccountIdentity,
976
1343
  stageAgentAuthority,
977
1344
  stageBoundedX402Authority,
978
1345
  syncAcceptedPasskeys,