@dexterai/connect 0.35.0 → 0.36.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/README.md CHANGED
@@ -92,6 +92,27 @@ await sendFromAccount({ identity, send: { mint, amount: '2500000', to } });
92
92
  - With lazy opening, sign-up's approvals are checked and held, not sent. Each setup step can be confirmed with `signature: null`, and the Account's status is then `held`: its address takes money at once and it opens on the chain by itself on the first money or the first action. Show a `held` Account exactly like a `ready` one; `openAccount` returns it without prompting. A send is never taken as confirmed without the signature of what it sent.
93
93
  - The first action on a held Account finishes the opening inside that request, so it can take a minute. Connect sets no timeout of its own on these requests.
94
94
 
95
+ ### Agent connections
96
+
97
+ An agent asks through OAuth to pay on the owner's behalf. The owner reviews the request and approves one exact spending permission with their passkey, through the same approval step as setup and send.
98
+
99
+ ```ts
100
+ import { getConnectionRequest, grantConnection, listConnections, revokeConnection } from '@dexterai/connect';
101
+
102
+ const review = await getConnectionRequest({ identity, requestId }); // client, limits, payee: show them as sent
103
+ const { redirectUrl } = await grantConnection({ identity, request: review, confirmStep, onStep });
104
+ window.location.assign(redirectUrl); // only ever on review.client.redirectHost
105
+
106
+ const connections = await listConnections({ identity });
107
+ await revokeConnection({ identity, connectionId, confirmStep, onStep });
108
+ ```
109
+
110
+ - The API holds every figure (per payment, per 30 days, how long). Show what it returns, and write no amount into a page.
111
+ - `grantConnection` refuses to prompt for anything but `grant-permission`, and refuses a redirect to any host but the one the request named (`connection_redirect_refused`).
112
+ - A connection is `pending` (an approval that didn't finish; stop it to abandon it), `active`, `stopped` or `revoked`.
113
+ - `revokeConnection`: Dexter's servers stop signing for the connection when the stop is prepared (`connection.state` is `stopped` in the step view). The passkey approval then revokes the permission on chain, and the result's state is `revoked`.
114
+ - A lost reply leaves the step unsettled with `flow: 'connection'`, the same as a send.
115
+
95
116
  ## Interrupted wallet setup
96
117
 
97
118
  `createWallet()` retains the original passkey when setup is interrupted. Calling
package/dist/index.d.ts CHANGED
@@ -103,7 +103,7 @@ interface AccountPasskey {
103
103
  /** An operation whose last step was approved and whose outcome the API does not know yet. */
104
104
  interface AccountUnsettled {
105
105
  readonly operationId: string;
106
- readonly flow: 'setup' | 'send';
106
+ readonly flow: AccountFlowName;
107
107
  readonly step: string;
108
108
  }
109
109
  interface AccountOverview {
@@ -153,6 +153,36 @@ interface AccountOperationDetails {
153
153
  readonly to: string | null;
154
154
  }
155
155
  type AccountStepPhase = 'preparing' | 'ready' | 'passkey' | 'sending' | 'confirmed';
156
+ /** The operations an Account approval belongs to. */
157
+ type AccountFlowName = 'setup' | 'send' | 'connection';
158
+ /** An amount in a token's smallest unit, with what it takes to show it. */
159
+ interface AccountAmount {
160
+ readonly amount: string;
161
+ readonly mint: string;
162
+ readonly decimals: number;
163
+ readonly symbol: string | null;
164
+ }
165
+ /** What an agent connection may spend. The API decides the figures; pages only show them. */
166
+ interface AccountConnectionLimits {
167
+ readonly perPayment: AccountAmount;
168
+ readonly per30Days: AccountAmount;
169
+ readonly days: number;
170
+ }
171
+ interface AccountConnectionClient {
172
+ readonly name: string;
173
+ readonly kind: 'chatgpt' | 'claude' | 'other';
174
+ }
175
+ /** What a connection approval or stop is about, as the API prepared it. */
176
+ interface AccountConnectionDetails {
177
+ readonly connectionId: string;
178
+ readonly limits: AccountConnectionLimits | null;
179
+ readonly payee: {
180
+ readonly name: string | null;
181
+ readonly address: string;
182
+ } | null;
183
+ readonly client: AccountConnectionClient | null;
184
+ readonly state: 'pending' | 'active' | 'stopped' | 'revoked' | null;
185
+ }
156
186
  /** One approval, as the page should show it. */
157
187
  interface AccountStepView {
158
188
  /** The API's name for the step. The page words the steps it knows. */
@@ -163,6 +193,8 @@ interface AccountStepView {
163
193
  readonly statement: string | null;
164
194
  readonly stepsRemaining: number | null;
165
195
  readonly details: AccountOperationDetails | null;
196
+ /** Set for a connection's approval or stop. */
197
+ readonly connection: AccountConnectionDetails | null;
166
198
  readonly phase: AccountStepPhase;
167
199
  /** Set once the step is confirmed. */
168
200
  readonly signature: string | null;
@@ -183,6 +215,8 @@ interface AccountOperationConfig {
183
215
  interface AccountFlowResult {
184
216
  /** Signatures of the transactions the flow sent, in order. A held setup step sends none. */
185
217
  readonly signatures: readonly string[];
218
+ /** The last step's own answer, for flows that return more than a signature. */
219
+ readonly outcome: Readonly<Record<string, string>>;
186
220
  }
187
221
  /**
188
222
  * Where one operation stands, from the API's own record and the chain.
@@ -192,11 +226,13 @@ interface AccountFlowResult {
192
226
  type AccountOperationStatus = 'prepared' | 'sending' | 'confirmed' | 'failed' | 'expired';
193
227
  interface AccountOperationState {
194
228
  readonly operationId: string;
195
- readonly flow: 'setup' | 'send';
229
+ readonly flow: AccountFlowName;
196
230
  readonly step: string;
197
231
  readonly status: AccountOperationStatus;
198
232
  readonly signature: string | null;
199
233
  readonly next: string | null;
234
+ /** A connection's id, state or redirect, when the operation's answer carries them. */
235
+ readonly outcome: Readonly<Record<string, string>>;
200
236
  }
201
237
  /**
202
238
  * An approved step whose outcome is not known: the reply was lost, slow, or
@@ -206,9 +242,9 @@ interface AccountOperationState {
206
242
  */
207
243
  declare class AccountOperationUnsettledError extends ConnectError {
208
244
  readonly operationId: string;
209
- readonly flow: 'setup' | 'send';
245
+ readonly flow: AccountFlowName;
210
246
  readonly step: string;
211
- constructor(operationId: string, flow: 'setup' | 'send', step: string);
247
+ constructor(operationId: string, flow: AccountFlowName, step: string);
212
248
  }
213
249
  /** Read the signed-in owner's Account, or `null` when none is open yet. */
214
250
  declare function getAccount(config: Pick<AccountOperationConfig, 'identity' | 'signal'>): Promise<DexterAccount | null>;
@@ -242,6 +278,62 @@ declare function sendFromAccount(config: AccountOperationConfig & {
242
278
  declare function formatAccountAmount(amount: string, decimals: number): string;
243
279
  /** Turn what a person typed ("2.5") into a smallest-unit string, or `null` if it is not an amount. */
244
280
  declare function parseAccountAmount(input: string, decimals: number): string | null;
281
+ /** An OAuth request for an agent connection, as the owner reviews it. */
282
+ interface AccountConnectionReview {
283
+ readonly requestId: string;
284
+ readonly client: AccountConnectionClient & {
285
+ readonly redirectHost: string;
286
+ };
287
+ readonly scope: string;
288
+ readonly limits: AccountConnectionLimits;
289
+ readonly payee: AccountConnectionDetails['payee'];
290
+ readonly expiresAt: string | null;
291
+ }
292
+ /** An agent connection on the owner's Account. */
293
+ interface AccountConnection {
294
+ readonly connectionId: string;
295
+ readonly client: AccountConnectionClient;
296
+ readonly limits: AccountConnectionLimits;
297
+ readonly spent30Days: AccountAmount | null;
298
+ /**
299
+ * `pending`: an approval that did not finish (stop it to abandon it); `stopped`: Dexter's servers no
300
+ * longer sign for it; `revoked`: the permission is gone on chain.
301
+ */
302
+ readonly state: 'pending' | 'active' | 'stopped' | 'revoked';
303
+ readonly createdAt: string | null;
304
+ readonly stoppedAt: string | null;
305
+ readonly revokedAt: string | null;
306
+ }
307
+ /** Read an agent's OAuth request so the owner can review it before approving. */
308
+ declare function getConnectionRequest(config: Pick<AccountOperationConfig, 'identity' | 'signal'> & {
309
+ readonly requestId: string;
310
+ }): Promise<AccountConnectionReview>;
311
+ /** List the owner's agent connections. */
312
+ declare function listConnections(config: Pick<AccountOperationConfig, 'identity' | 'signal'>): Promise<readonly AccountConnection[]>;
313
+ /** Read one of the owner's agent connections. */
314
+ declare function getConnection(config: Pick<AccountOperationConfig, 'identity' | 'signal'> & {
315
+ readonly connectionId: string;
316
+ }): Promise<AccountConnection>;
317
+ /**
318
+ * Approve an agent's spending permission with the owner's passkey. Resolves
319
+ * with the new connection and the address to return the person to, which must
320
+ * be on the host the reviewed request named.
321
+ */
322
+ declare function grantConnection(config: AccountOperationConfig & {
323
+ readonly request: Pick<AccountConnectionReview, 'requestId' | 'client'>;
324
+ }): Promise<AccountFlowResult & {
325
+ readonly connectionId: string;
326
+ readonly redirectUrl: string;
327
+ }>;
328
+ /**
329
+ * Stop an agent connection. Dexter's servers stop signing for it when the stop
330
+ * is prepared; the owner's passkey then revokes the permission on chain.
331
+ */
332
+ declare function revokeConnection(config: AccountOperationConfig & {
333
+ readonly connectionId: string;
334
+ }): Promise<AccountFlowResult & {
335
+ readonly state: 'revoked';
336
+ }>;
245
337
 
246
338
  /** One localStorage entry per Wallet keeps inactive Wallet proofs independent. */
247
339
  declare const WALLET_PROOF_SESSION_STORAGE_PREFIX: "dexter:wallet-identity-proof-session:";
@@ -862,4 +954,4 @@ type SignAccountChallengeResult = {
862
954
  };
863
955
  declare function signAccountChallenge(config: SignAccountChallengeConfig): Promise<SignAccountChallengeResult>;
864
956
 
865
- export { ACCOUNT_API_PATH, AGENT_AUTHORITY_NAMESPACE, AGENT_AUTHORITY_STATUS_NAMESPACE, type AccountBalances, type AccountChallengeAssertion, type AccountConnectionRequest, type AccountFlowResult, AccountIdentityResult, type AccountOperationConfig, type AccountOperationDetails, type AccountOperationState, type AccountOperationStatus, AccountOperationUnsettledError, type AccountOverview, type AccountPasskey, type AccountPrincipalContext, 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 SignAccountChallengeConfig, type SignAccountChallengeResult, 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, signAccountChallenge, stageAgentAuthority, stageBoundedX402Authority, syncAcceptedPasskeys, validateBoundedX402Draft, walletProofSessionStore };
957
+ export { ACCOUNT_API_PATH, AGENT_AUTHORITY_NAMESPACE, AGENT_AUTHORITY_STATUS_NAMESPACE, type AccountAmount, type AccountBalances, type AccountChallengeAssertion, type AccountConnection, type AccountConnectionClient, type AccountConnectionDetails, type AccountConnectionLimits, type AccountConnectionRequest, type AccountConnectionReview, type AccountFlowName, type AccountFlowResult, AccountIdentityResult, type AccountOperationConfig, type AccountOperationDetails, type AccountOperationState, type AccountOperationStatus, AccountOperationUnsettledError, type AccountOverview, type AccountPasskey, type AccountPrincipalContext, 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 SignAccountChallengeConfig, type SignAccountChallengeResult, 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, getConnection, getConnectionRequest, grantConnection, listConnections, noCustomX402Limits, openAccount, parseAccountAmount, passkeySignalSupport, prunePasskey, readAgentAuthority, recoverMissingVaultForAccount, recoverWallet, renamePasskey, revokeAgentSpend, revokeConnection, sendFromAccount, signAccountChallenge, stageAgentAuthority, stageBoundedX402Authority, syncAcceptedPasskeys, validateBoundedX402Draft, walletProofSessionStore };
package/dist/index.js CHANGED
@@ -233,6 +233,8 @@ var AccountOperationUnsettledError = class extends ConnectError {
233
233
  this.step = step;
234
234
  }
235
235
  };
236
+ var SETUP_ROUTE = { flow: "setup", prepare: "/setup/prepare", complete: "/setup/complete" };
237
+ var SEND_ROUTE = { flow: "send", prepare: "/send/prepare", complete: "/send/complete" };
236
238
  function record(value) {
237
239
  return value !== null && typeof value === "object" && !Array.isArray(value);
238
240
  }
@@ -311,7 +313,44 @@ function detailsFrom(value) {
311
313
  to: value.to ?? null
312
314
  });
313
315
  }
314
- function preparedFrom(value, identity) {
316
+ var isFlowName = (value) => value === "setup" || value === "send" || value === "connection";
317
+ var connectionKey = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
318
+ function amountFrom(value) {
319
+ if (!record(value) || !units(value.amount) || !address(value.mint) || 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();
320
+ return Object.freeze({
321
+ amount: value.amount,
322
+ mint: value.mint,
323
+ decimals: value.decimals,
324
+ symbol: value.symbol ?? null
325
+ });
326
+ }
327
+ function limitsFrom(value) {
328
+ if (!record(value) || typeof value.days !== "number" || !Number.isInteger(value.days) || value.days < 1 || value.days > 3660) malformed();
329
+ return Object.freeze({ perPayment: amountFrom(value.perPayment), per30Days: amountFrom(value.per30Days), days: value.days });
330
+ }
331
+ function clientFrom(value) {
332
+ if (!record(value) || !text(value.name, 80)) malformed();
333
+ const kind = value.kind === "chatgpt" || value.kind === "claude" ? value.kind : "other";
334
+ return Object.freeze({ name: value.name, kind });
335
+ }
336
+ function payeeFrom(value) {
337
+ if (value === null || value === void 0) return null;
338
+ if (!record(value) || !address(value.address) || value.name !== null && value.name !== void 0 && !text(value.name, 80)) malformed();
339
+ return Object.freeze({ name: value.name ?? null, address: value.address });
340
+ }
341
+ var CONNECTION_STATES = ["pending", "active", "stopped", "revoked"];
342
+ var connectionState = (value) => CONNECTION_STATES.includes(value) ? value : null;
343
+ function connectionDetailsFrom(value) {
344
+ if (!record(value) || !connectionKey(value.connectionId)) malformed();
345
+ return Object.freeze({
346
+ connectionId: value.connectionId,
347
+ limits: value.limits === void 0 || value.limits === null ? null : limitsFrom(value.limits),
348
+ payee: payeeFrom(value.payee),
349
+ client: value.client === void 0 || value.client === null ? null : clientFrom(value.client),
350
+ state: connectionState(value.state)
351
+ });
352
+ }
353
+ function preparedFrom(value, identity, flow) {
315
354
  if (record(value) && value.status === "complete" && (value.next === null || value.next === void 0)) return null;
316
355
  if (!record(value) || !text(value.operationId) || !text(value.step, 80) || typeof value.summary !== "string" || value.summary.length > 300 || !record(value.publicKey)) malformed();
317
356
  const options = value.publicKey;
@@ -333,7 +372,8 @@ function preparedFrom(value, identity) {
333
372
  summary: value.summary,
334
373
  statement: text(value.statement, 1e3) ? value.statement : null,
335
374
  stepsRemaining: typeof remaining === "number" && Number.isInteger(remaining) && remaining >= 0 ? remaining : null,
336
- details: detailsFrom(value.details),
375
+ details: flow === "connection" ? null : detailsFrom(value.details),
376
+ connection: flow === "connection" ? connectionDetailsFrom(value.details) : null,
337
377
  publicKey: Object.freeze({
338
378
  challenge: options.challenge,
339
379
  rpId: DEXTER_RP_ID,
@@ -350,12 +390,13 @@ function assertApprovalContext() {
350
390
  if (!browserSupportsWebAuthn()) throw new ConnectError("webauthn_unsupported");
351
391
  }
352
392
  var approvalInProgress = false;
353
- async function prepare(config, flow, body) {
393
+ async function prepare(config, route, body) {
354
394
  for (let attempt = 0; ; attempt += 1) {
355
395
  try {
356
396
  return preparedFrom(
357
- await call(config.identity, "POST", `/${flow}/prepare`, body, false, config.signal),
358
- config.identity
397
+ await call(config.identity, "POST", route.prepare, body, false, config.signal),
398
+ config.identity,
399
+ route.flow
359
400
  );
360
401
  } catch (cause) {
361
402
  if (!(cause instanceof ConnectError) || cause.code !== "chain_not_ready" || attempt >= NOT_READY_RETRIES) throw cause;
@@ -363,20 +404,31 @@ async function prepare(config, flow, body) {
363
404
  }
364
405
  }
365
406
  }
366
- async function complete(config, flow, body) {
407
+ async function complete(config, route, body) {
367
408
  try {
368
- return await call(config.identity, "POST", `/${flow}/complete`, body, true);
409
+ return await call(config.identity, "POST", route.complete, body, true);
369
410
  } catch (cause) {
370
411
  if (!(cause instanceof ConnectError) || cause.code !== "account_operation_uncertain") throw cause;
371
- return call(config.identity, "POST", `/${flow}/complete`, body, true);
412
+ return call(config.identity, "POST", route.complete, body, true);
372
413
  }
373
414
  }
415
+ function outcomeFrom(value) {
416
+ const outcome = {};
417
+ for (const key of ["connectionId", "state", "redirectUrl"]) {
418
+ if (text(value[key], 2048)) outcome[key] = value[key];
419
+ }
420
+ return Object.freeze(outcome);
421
+ }
374
422
  function confirmedFrom(value, flow) {
375
423
  if (!record(value) || value.status !== "confirmed") malformed();
376
424
  const held = flow === "setup" && (value.signature === null || value.signature === void 0);
377
425
  if (!held && !text(value.signature)) malformed();
378
426
  if (value.next !== null && value.next !== void 0 && !text(value.next, 80)) malformed();
379
- return { signature: held ? null : value.signature, next: value.next ?? null };
427
+ return {
428
+ signature: held ? null : value.signature,
429
+ next: value.next ?? null,
430
+ outcome: outcomeFrom(value)
431
+ };
380
432
  }
381
433
  async function settle(config, flow, step, operationId, cause) {
382
434
  let state;
@@ -385,13 +437,16 @@ async function settle(config, flow, step, operationId, cause) {
385
437
  } catch {
386
438
  throw new AccountOperationUnsettledError(operationId, flow, step);
387
439
  }
388
- if (state.status === "confirmed" && (state.signature || flow === "setup")) return { signature: state.signature, next: state.next };
440
+ if (state.status === "confirmed" && (state.signature || flow === "setup")) {
441
+ return { signature: state.signature, next: state.next, outcome: state.outcome };
442
+ }
389
443
  if (state.status === "failed" || state.status === "prepared" || state.status === "expired") {
390
444
  throw cause instanceof ConnectError && cause.code !== "account_operation_uncertain" ? cause : new ConnectError("account_operation_failed");
391
445
  }
392
446
  throw new AccountOperationUnsettledError(operationId, flow, step);
393
447
  }
394
- async function runFlow(config, flow, body, check) {
448
+ async function runFlow(config, route, body, check) {
449
+ const { flow } = route;
395
450
  assertApprovalContext();
396
451
  if (approvalInProgress) throw new ConnectError("account_operation_in_progress");
397
452
  approvalInProgress = true;
@@ -399,15 +454,16 @@ async function runFlow(config, flow, body, check) {
399
454
  try {
400
455
  for (let count = 0; count < MAX_STEPS; count += 1) {
401
456
  cancelled(config.signal);
402
- const prepared = await prepare(config, flow, body);
403
- if (prepared === null) return Object.freeze({ signatures: Object.freeze(signatures) });
404
- check?.(prepared.step, prepared.details);
457
+ const prepared = await prepare(config, route, body);
458
+ if (prepared === null) return Object.freeze({ signatures: Object.freeze(signatures), outcome: Object.freeze({}) });
459
+ check?.(prepared.step, { details: prepared.details, connection: prepared.connection });
405
460
  const view = {
406
461
  step: prepared.step,
407
462
  summary: prepared.summary,
408
463
  statement: prepared.statement,
409
464
  stepsRemaining: prepared.stepsRemaining,
410
465
  details: prepared.details,
466
+ connection: prepared.connection,
411
467
  signature: null
412
468
  };
413
469
  if (config.confirmStep) {
@@ -433,7 +489,7 @@ async function runFlow(config, flow, body, check) {
433
489
  config.onStep?.({ ...view, phase: "sending" });
434
490
  let result;
435
491
  try {
436
- result = confirmedFrom(await complete(config, flow, {
492
+ result = confirmedFrom(await complete(config, route, {
437
493
  operationId: prepared.operationId,
438
494
  assertion: {
439
495
  credentialId: credential.id,
@@ -449,13 +505,14 @@ async function runFlow(config, flow, body, check) {
449
505
  if (result.signature) signatures.push(result.signature);
450
506
  config.onStep?.({ ...view, phase: "confirmed", signature: result.signature });
451
507
  const next = result.next;
452
- if (next === null) return Object.freeze({ signatures: Object.freeze(signatures) });
508
+ if (next === null) return Object.freeze({ signatures: Object.freeze(signatures), outcome: result.outcome });
453
509
  config.onStep?.({
454
510
  step: next,
455
511
  summary: "",
456
512
  statement: null,
457
513
  stepsRemaining: null,
458
514
  details: null,
515
+ connection: null,
459
516
  signature: null,
460
517
  phase: "preparing"
461
518
  });
@@ -477,21 +534,22 @@ async function getAccountOverview(config) {
477
534
  const created = record(raw) && text(raw.createdAt, 40) && !Number.isNaN(Date.parse(raw.createdAt)) ? raw.createdAt : null;
478
535
  const passkey = record(raw) ? Object.freeze({ name: text(raw.name, 80) ? raw.name : null, createdAt: created }) : null;
479
536
  const pending = body.unsettled;
480
- 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;
537
+ const unsettled = record(pending) && text(pending.operationId) && isFlowName(pending.flow) && text(pending.step, 80) ? Object.freeze({ operationId: pending.operationId, flow: pending.flow, step: pending.step }) : null;
481
538
  return Object.freeze({ account, network, passkey, unsettled });
482
539
  }
483
540
  async function getAccountOperation(config) {
484
541
  if (!text(config.operationId) || !/^[A-Za-z0-9_-]+$/.test(config.operationId)) throw new ConnectError("invalid_account_operation");
485
542
  const value = await call(config.identity, "GET", `/operations/${config.operationId}`, void 0, false, config.signal);
486
543
  const statuses = ["prepared", "sending", "confirmed", "failed", "expired"];
487
- 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" && value.flow === "send" && !text(value.signature)) malformed();
544
+ if (!record(value) || value.operationId !== config.operationId || !isFlowName(value.flow) || !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" && value.flow !== "setup" && !text(value.signature)) malformed();
488
545
  return Object.freeze({
489
546
  operationId: value.operationId,
490
547
  flow: value.flow,
491
548
  step: value.step,
492
549
  status: value.status,
493
550
  signature: value.signature ?? null,
494
- next: value.next ?? null
551
+ next: value.next ?? null,
552
+ outcome: outcomeFrom(value)
495
553
  });
496
554
  }
497
555
  async function getAccountBalances(config) {
@@ -523,10 +581,11 @@ async function openAccount(config) {
523
581
  statement: null,
524
582
  stepsRemaining: null,
525
583
  details: null,
584
+ connection: null,
526
585
  signature: null,
527
586
  phase: "preparing"
528
587
  });
529
- await runFlow(config, "setup", {});
588
+ await runFlow(config, SETUP_ROUTE, {});
530
589
  const account = await getAccount(config);
531
590
  if (!account) malformed();
532
591
  return account;
@@ -537,7 +596,7 @@ async function sendFromAccount(config) {
537
596
  throw new ConnectError("invalid_account_send");
538
597
  }
539
598
  const request = { mint: send.mint, amount: send.amount, to: send.to };
540
- return runFlow(config, "send", request, (step, details) => {
599
+ return runFlow(config, SEND_ROUTE, request, (step, { details }) => {
541
600
  const sameToken = details !== null && details.mint === request.mint;
542
601
  if (step === "prepare-token" ? !sameToken || details.amount !== null || details.to !== null : !sameToken || details.amount !== request.amount || details.to !== request.to) {
543
602
  throw new ConnectError("account_operation_mismatch");
@@ -562,6 +621,94 @@ function parseAccountAmount(input, decimals) {
562
621
  const value = BigInt(`${match[1] || "0"}${fraction.padEnd(decimals, "0")}`);
563
622
  return value > 0n && value < 1n << 64n ? value.toString() : null;
564
623
  }
624
+ var hostName = (value) => typeof value === "string" && /^[a-z0-9.-]{1,253}(:[0-9]{1,5})?$/i.test(value);
625
+ var time = (value) => text(value, 40) && !Number.isNaN(Date.parse(value)) ? value : null;
626
+ function connectionFrom(value) {
627
+ if (!record(value) || !connectionKey(value.connectionId)) malformed();
628
+ const state = connectionState(value.state);
629
+ if (state === null) malformed();
630
+ return Object.freeze({
631
+ connectionId: value.connectionId,
632
+ client: clientFrom(value.client),
633
+ limits: limitsFrom(value.limits),
634
+ spent30Days: value.spent30Days === null || value.spent30Days === void 0 ? null : amountFrom(value.spent30Days),
635
+ state,
636
+ createdAt: time(value.createdAt),
637
+ stoppedAt: time(value.stoppedAt),
638
+ revokedAt: time(value.revokedAt)
639
+ });
640
+ }
641
+ async function getConnectionRequest(config) {
642
+ if (!connectionKey(config.requestId)) throw new ConnectError("invalid_connection_request");
643
+ const value = await call(config.identity, "GET", `/connections/requests/${config.requestId}`, void 0, false, config.signal);
644
+ if (!record(value) || value.requestId !== config.requestId || !record(value.client) || !hostName(value.client.redirectHost) || !text(value.scope, 80)) malformed();
645
+ return Object.freeze({
646
+ requestId: value.requestId,
647
+ client: Object.freeze({ ...clientFrom(value.client), redirectHost: value.client.redirectHost.toLowerCase() }),
648
+ scope: value.scope,
649
+ limits: limitsFrom(value.limits),
650
+ payee: payeeFrom(value.payee),
651
+ expiresAt: time(value.expiresAt)
652
+ });
653
+ }
654
+ async function listConnections(config) {
655
+ const value = await call(config.identity, "GET", "/connections", void 0, false, config.signal);
656
+ if (!record(value) || !Array.isArray(value.connections)) malformed();
657
+ return Object.freeze(value.connections.map(connectionFrom));
658
+ }
659
+ async function getConnection(config) {
660
+ if (!connectionKey(config.connectionId)) throw new ConnectError("invalid_connection");
661
+ const value = connectionFrom(await call(config.identity, "GET", `/connections/${config.connectionId}`, void 0, false, config.signal));
662
+ if (value.connectionId !== config.connectionId) malformed();
663
+ return value;
664
+ }
665
+ async function grantConnection(config) {
666
+ const { request } = config;
667
+ if (!record(request) || !connectionKey(request.requestId) || !record(request.client) || !hostName(request.client.redirectHost)) {
668
+ throw new ConnectError("invalid_connection_request");
669
+ }
670
+ let promised = null;
671
+ const result = await runFlow(
672
+ config,
673
+ { flow: "connection", prepare: "/connections/grant/prepare", complete: "/connections/grant/complete" },
674
+ { requestId: request.requestId },
675
+ (step, { connection }) => {
676
+ if (step !== "grant-permission" || connection === null || promised !== null && connection.connectionId !== promised) {
677
+ throw new ConnectError("account_operation_mismatch");
678
+ }
679
+ promised = connection.connectionId;
680
+ }
681
+ );
682
+ const connectionId = result.outcome.connectionId;
683
+ const redirectUrl = result.outcome.redirectUrl;
684
+ if (!connectionKey(connectionId) || promised !== null && connectionId !== promised || !text(redirectUrl, 2048)) malformed();
685
+ let target;
686
+ try {
687
+ target = new URL(redirectUrl);
688
+ } catch {
689
+ throw new ConnectError("connection_redirect_refused");
690
+ }
691
+ if (target.protocol !== "https:" || target.host.toLowerCase() !== request.client.redirectHost.toLowerCase()) {
692
+ throw new ConnectError("connection_redirect_refused");
693
+ }
694
+ return Object.freeze({ ...result, connectionId, redirectUrl: target.toString() });
695
+ }
696
+ async function revokeConnection(config) {
697
+ const { connectionId } = config;
698
+ if (!connectionKey(connectionId)) throw new ConnectError("invalid_connection");
699
+ const result = await runFlow(
700
+ config,
701
+ { flow: "connection", prepare: `/connections/${connectionId}/revoke/prepare`, complete: "/connections/revoke/complete" },
702
+ {},
703
+ (step, { connection }) => {
704
+ if (step !== "revoke-permission" || connection?.connectionId !== connectionId) {
705
+ throw new ConnectError("account_operation_mismatch");
706
+ }
707
+ }
708
+ );
709
+ if (result.outcome.connectionId !== connectionId || result.outcome.state !== "revoked") malformed();
710
+ return Object.freeze({ ...result, state: "revoked" });
711
+ }
565
712
 
566
713
  // src/agentSpend.ts
567
714
  import { PublicKey as PublicKey2 } from "@solana/web3.js";
@@ -1373,6 +1520,10 @@ export {
1373
1520
  getAccountBalances,
1374
1521
  getAccountOperation,
1375
1522
  getAccountOverview,
1523
+ getConnection,
1524
+ getConnectionRequest,
1525
+ grantConnection,
1526
+ listConnections,
1376
1527
  noCustomX402Limits,
1377
1528
  openAccount,
1378
1529
  parseAccountAmount,
@@ -1383,6 +1534,7 @@ export {
1383
1534
  recoverWallet,
1384
1535
  renamePasskey,
1385
1536
  revokeAgentSpend,
1537
+ revokeConnection,
1386
1538
  sendFromAccount,
1387
1539
  signAccountChallenge,
1388
1540
  signInAccountAccess,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dexterai/connect",
3
- "version": "0.35.0",
3
+ "version": "0.36.0",
4
4
  "description": "Connect apps and agents to a self-custodial Dexter Wallet with passkey identity, governed authority, hosted signing, and verifiable sessions.",
5
5
  "repository": {
6
6
  "type": "git",