@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.
package/dist/index.js CHANGED
@@ -1,41 +1,216 @@
1
1
  import {
2
- ACTIVE_WALLET_STORAGE_KEY,
2
+ WalletAccountRelationController,
3
+ ceremonyPhaseLabel,
4
+ connectDexterIdentity,
5
+ createDexterControlModel,
6
+ createDexterIdentityCoordinator,
7
+ disconnectDexterIdentity,
8
+ passkeySignalSupport,
9
+ prunePasskey,
10
+ renamePasskey,
11
+ syncAcceptedPasskeys
12
+ } from "./chunk-2BTS6DCR.js";
13
+ import {
14
+ recoverWallet
15
+ } from "./chunk-LHYU2EZQ.js";
16
+ import {
3
17
  ConnectError,
4
18
  SESSION_TTL_30D,
19
+ WALLET_ACCOUNT_BINDING_PATH,
20
+ WALLET_PROOF_SESSION_STORAGE_PREFIX,
21
+ accountBindingCandidate,
5
22
  authoredPolicy,
6
- base64urlToBytes,
7
23
  bytesEqual,
8
- bytesToBase64,
9
- bytesToBase64url,
10
- ceremonyPhaseLabel,
11
- continueWithDexter,
12
- createAnonServerPolicy,
13
- createPasskeySigner,
14
24
  createWallet,
15
- ejectActiveWallet,
16
- forgetWallet,
17
- getActiveHandle,
18
- getCredentialId,
19
- listWallets,
20
- passkeyLogin,
21
- passkeySignalSupport,
22
- prunePasskey,
23
- recoverWallet,
24
- renamePasskey,
25
+ createWalletAccountBindingClient,
26
+ createWalletProofSessionStore,
27
+ openCeremonyPopup,
28
+ readErrorCode,
25
29
  resolveDexterApiBase,
26
30
  resolveDexterRpId,
27
- resolveIdentity,
28
- setActiveHandle,
29
- subscribe,
30
- switchWallet,
31
- syncAcceptedPasskeys,
32
- usdToAtomic
33
- } from "./chunk-H3NXC4S5.js";
31
+ shouldUsePopup,
32
+ usdToAtomic,
33
+ walletBindingCandidate,
34
+ walletProofSessionStore
35
+ } from "./chunk-CZL7NGVV.js";
36
+ import {
37
+ base64ToBytes,
38
+ base64urlToBytes,
39
+ bytesToBase64,
40
+ bytesToBase64url,
41
+ compactSignatureToDer
42
+ } from "./chunk-EMCGL64H.js";
34
43
 
35
- // src/agentSpend.ts
44
+ // src/anon-policy.ts
45
+ var ANON_SIGN_BASE = "/api/passkey-anon/sign";
46
+ function createAnonServerPolicy(apiBase) {
47
+ const base = resolveDexterApiBase(apiBase);
48
+ return {
49
+ async issueChallenge({ userHandle, operationMessage, operationHash }) {
50
+ const res = await fetch(`${base}${ANON_SIGN_BASE}/challenge`, {
51
+ method: "POST",
52
+ headers: { "content-type": "application/json" },
53
+ body: JSON.stringify({
54
+ userHandle: bytesToBase64url(userHandle),
55
+ operationHash: bytesToBase64url(operationHash),
56
+ operationMessage: bytesToBase64url(operationMessage),
57
+ operation: "vault_operation"
58
+ })
59
+ });
60
+ if (!res.ok) throw new ConnectError(await readErrorCode(res), `challenge ${res.status}`);
61
+ const data = await res.json();
62
+ const options = data?.options;
63
+ if (!options?.challenge) {
64
+ throw new ConnectError("challenge_malformed", "no challenge in response");
65
+ }
66
+ const challenge = base64urlToBytes(options.challenge);
67
+ const cred = options.allowCredentials?.[0];
68
+ if (!cred?.id) {
69
+ throw new ConnectError("no_credential", "no allow-listed credential for this userHandle");
70
+ }
71
+ return {
72
+ challenge,
73
+ credentialId: base64urlToBytes(cred.id),
74
+ rpId: resolveDexterRpId(options.rpId),
75
+ transports: cred.transports
76
+ };
77
+ },
78
+ async verify({ userHandle, credentialId, signature, clientDataJSON, authenticatorData }) {
79
+ const credential = {
80
+ id: bytesToBase64url(credentialId),
81
+ rawId: bytesToBase64url(credentialId),
82
+ type: "public-key",
83
+ response: {
84
+ clientDataJSON: bytesToBase64url(clientDataJSON),
85
+ authenticatorData: bytesToBase64url(authenticatorData),
86
+ // The SDK passes the COMPACT sig; dexter-api's verifier wants DER.
87
+ signature: bytesToBase64url(compactSignatureToDer(signature)),
88
+ userHandle: null
89
+ },
90
+ clientExtensionResults: {},
91
+ authenticatorAttachment: null
92
+ };
93
+ const res = await fetch(`${base}${ANON_SIGN_BASE}/verify`, {
94
+ method: "POST",
95
+ headers: { "content-type": "application/json" },
96
+ body: JSON.stringify({ credential, userHandle: bytesToBase64url(userHandle) })
97
+ });
98
+ if (!res.ok) throw new ConnectError(await readErrorCode(res), `verify ${res.status}`);
99
+ const data = await res.json();
100
+ if (data?.verified !== true) {
101
+ throw new ConnectError("verification_failed", "server did not return verified=true");
102
+ }
103
+ }
104
+ };
105
+ }
106
+
107
+ // src/signer.ts
108
+ import { DexterApiBrowserPasskeySigner } from "@dexterai/vault/signers/browser";
109
+ import {
110
+ parseStrictCollectedClientData,
111
+ validatePasskeyAuthorizationChallenge
112
+ } from "@dexterai/vault";
36
113
  import { PublicKey } from "@solana/web3.js";
114
+ var HostedPopupPasskeySigner = class {
115
+ constructor(vault, expectedVault, connectHost) {
116
+ this.expectedVault = expectedVault;
117
+ this.connectHost = connectHost;
118
+ this.vault = { ...vault };
119
+ this.credentialId = base64urlToBytes(vault.credentialId);
120
+ this.publicKey = base64ToBytes(vault.publicKey);
121
+ }
122
+ expectedVault;
123
+ connectHost;
124
+ credentialId;
125
+ publicKey;
126
+ vault;
127
+ async signOperation(operationMessage) {
128
+ if (!(operationMessage instanceof Uint8Array) || operationMessage.length === 0) {
129
+ throw new ConnectError("invalid_operation", "signOperation requires non-empty bytes");
130
+ }
131
+ const exactOperationMessage = new Uint8Array(operationMessage);
132
+ const result = await openCeremonyPopup("sign", {
133
+ ...this.connectHost ? { connectHost: this.connectHost } : {},
134
+ signRequest: {
135
+ operationMessage: exactOperationMessage,
136
+ vault: {
137
+ vaultPda: this.vault.vaultPda,
138
+ publicKey: this.vault.publicKey,
139
+ userHandle: this.vault.userHandle,
140
+ credentialId: this.vault.credentialId,
141
+ ...this.vault.walletLabel !== void 0 ? { walletLabel: this.vault.walletLabel } : {}
142
+ }
143
+ }
144
+ });
145
+ return validateHostedSignResult(result, exactOperationMessage, this.expectedVault);
146
+ }
147
+ };
148
+ function createPasskeySigner(vault, apiBase, opts = {}) {
149
+ resolveDexterApiBase(apiBase);
150
+ const expectedVault = new PublicKey(vault.vaultPda);
151
+ if (shouldUsePopup()) {
152
+ return new HostedPopupPasskeySigner(vault, expectedVault, opts.connectHost);
153
+ }
154
+ return new DexterApiBrowserPasskeySigner({
155
+ identity: { kind: "guest", userHandle: base64urlToBytes(vault.userHandle) },
156
+ publicKey: base64ToBytes(vault.publicKey),
157
+ anonPolicy: createAnonServerPolicy(apiBase),
158
+ // The API resolves the authorization envelope, but this browser still
159
+ // knows which connected vault the caller selected. Pin that exact PDA so a
160
+ // valid Dexter envelope for another vault cannot reach WebAuthn.
161
+ expectedVault,
162
+ ...opts.__assertion ? { __assertion: opts.__assertion } : {}
163
+ });
164
+ }
165
+ async function validateHostedSignResult(result, operationMessage, expectedVault) {
166
+ if (!result || !(result.signature instanceof Uint8Array) || result.signature.length !== 64 || !(result.clientDataJSON instanceof Uint8Array) || result.clientDataJSON.length === 0 || !(result.authenticatorData instanceof Uint8Array) || result.authenticatorData.length < 37) {
167
+ throw new ConnectError("popup_result_malformed", "hosted signer returned malformed assertion bytes");
168
+ }
169
+ let clientData;
170
+ try {
171
+ clientData = parseStrictCollectedClientData(result.clientDataJSON);
172
+ } catch {
173
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid clientDataJSON");
174
+ }
175
+ if (clientData.type !== "webauthn.get" || clientData.origin !== "https://dexter.cash" || clientData.crossOrigin !== false || !/^[A-Za-z0-9_-]+$/.test(clientData.challenge)) {
176
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid WebAuthn client data");
177
+ }
178
+ const expectedRpHash = new Uint8Array(
179
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode("dexter.cash"))
180
+ );
181
+ const flags = result.authenticatorData[32] ?? 0;
182
+ if (!bytesEqual(result.authenticatorData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
183
+ throw new ConnectError("popup_result_malformed", "hosted signer returned invalid authenticator context");
184
+ }
185
+ let challenge;
186
+ try {
187
+ challenge = base64urlToBytes(clientData.challenge);
188
+ if (bytesToBase64url(challenge) !== clientData.challenge) throw new Error("non-canonical");
189
+ } catch {
190
+ throw new ConnectError("popup_result_malformed", "hosted signer returned an invalid challenge encoding");
191
+ }
192
+ try {
193
+ const operationHash = new Uint8Array(
194
+ await crypto.subtle.digest("SHA-256", new Uint8Array(operationMessage))
195
+ );
196
+ validatePasskeyAuthorizationChallenge({ challenge, operationHash, expectedVault });
197
+ } catch {
198
+ throw new ConnectError(
199
+ "popup_result_unbound",
200
+ "hosted signer returned an assertion for a different operation or vault"
201
+ );
202
+ }
203
+ return {
204
+ signature: new Uint8Array(result.signature),
205
+ clientDataJSON: new Uint8Array(result.clientDataJSON),
206
+ authenticatorData: new Uint8Array(result.authenticatorData)
207
+ };
208
+ }
209
+
210
+ // src/agentSpend.ts
211
+ import { PublicKey as PublicKey2 } from "@solana/web3.js";
37
212
  import { WebAuthnAssertion } from "@dexterai/vault/signers/browser";
38
- import { validatePasskeyAuthorizationChallenge } from "@dexterai/vault";
213
+ import { validatePasskeyAuthorizationChallenge as validatePasskeyAuthorizationChallenge2 } from "@dexterai/vault";
39
214
  import { enableAgentSpendMessage, revokeAgentSpendV2Message } from "@dexterai/vault/messages";
40
215
  import { DEXTER_VAULT_PROGRAM_ID } from "@dexterai/vault/constants";
41
216
  function shortCounterparty(a) {
@@ -114,7 +289,7 @@ async function agentSpendError(res) {
114
289
  return new AgentSpendError(code, `agent-spend ${res.status}: ${code}`);
115
290
  }
116
291
  function assertDexterWallet(id) {
117
- if (id.kind !== "passkey-vault") {
292
+ if (id.kind !== "wallet_only" && id.kind !== "bound") {
118
293
  throw new AgentSpendError("not_guest", "agent-spend off/on switch is Dexter Wallet only");
119
294
  }
120
295
  }
@@ -175,7 +350,7 @@ async function assertCanonicalOperationInline(messageBytes, userHandle, expected
175
350
  }
176
351
  const challenge = base64urlToBytes(options.challenge);
177
352
  try {
178
- validatePasskeyAuthorizationChallenge({
353
+ validatePasskeyAuthorizationChallenge2({
179
354
  challenge,
180
355
  operationHash,
181
356
  expectedVault
@@ -245,7 +420,7 @@ async function revokeAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
245
420
  if (typeof challenge.nonce !== "string" || !/^(0|[1-9][0-9]*)$/.test(challenge.nonce) || typeof challenge.expiry !== "number" || !Number.isSafeInteger(challenge.expiry) || typeof challenge.operationMessage !== "string") {
246
421
  throw new AgentSpendError("challenge_malformed", "Dexter returned an incomplete revoke intent");
247
422
  }
248
- const expectedVault = new PublicKey(vaultPda);
423
+ const expectedVault = new PublicKey2(vaultPda);
249
424
  const message = revokeAgentSpendV2Message({
250
425
  programId: DEXTER_VAULT_PROGRAM_ID,
251
426
  vaultPda: expectedVault,
@@ -299,7 +474,7 @@ async function enableAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
299
474
  throw new AgentSpendError("challenge_malformed", "Dexter returned an incomplete enable intent");
300
475
  }
301
476
  const { nonce, expiry } = challenge;
302
- const expectedVault = new PublicKey(vaultPda);
477
+ const expectedVault = new PublicKey2(vaultPda);
303
478
  const message = enableAgentSpendMessage({
304
479
  programId: DEXTER_VAULT_PROGRAM_ID,
305
480
  vaultPda: expectedVault,
@@ -334,35 +509,471 @@ async function enableAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
334
509
  if (!verifyRes.ok) throw await agentSpendError(verifyRes);
335
510
  return await verifyRes.json();
336
511
  }
512
+
513
+ // src/agentAuthority.ts
514
+ var AGENT_AUTHORITY_NAMESPACE = "dexter-governed-agent-surface-selection/v2";
515
+ var AGENT_AUTHORITY_STATUS_NAMESPACE = "dexter-governed-agent-surface-authority/v2";
516
+ var X402_PROTOCOL_ID = "x402";
517
+ var X402_PROTOCOL_VERSION = 2;
518
+ var X402_ALLOWED_SCHEMES = Object.freeze(["exact", "tab"]);
519
+ var X402_ASSET = "usdc";
520
+ var X402_COUNTERPARTY_SCOPE = "any-valid-x402-seller";
521
+ var MAX_AUTHORITY_AMOUNT_ATOMIC = "18446744073709551615";
522
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
523
+ var DIGEST = /^[0-9a-f]{64}$/;
524
+ var IDENTIFIER = /^[a-z0-9][a-z0-9._:-]{0,127}$/;
525
+ var POSITIVE_ATOMIC = /^[1-9][0-9]{0,19}$/;
526
+ var NON_NEGATIVE_ATOMIC = /^(0|[1-9][0-9]{0,19})$/;
527
+ var U64_MAX_ATOMIC = BigInt(MAX_AUTHORITY_AMOUNT_ATOMIC);
528
+ var OAUTH_REQUEST_ID = /^[A-Za-z0-9_-]{16,64}$/;
529
+ var DEVICE_USER_CODE = /^[A-Z0-9-]{6,32}$/;
530
+ var USDC_DECIMAL = /^(0|[1-9][0-9]*)(?:\.([0-9]{1,6}))?$/;
531
+ var NO_CUSTOM_LIMIT_TTL_DAYS = 365;
532
+ var AgentAuthorityError = class extends Error {
533
+ constructor(code, message, status = null, serverCode = null) {
534
+ super(message);
535
+ this.code = code;
536
+ this.status = status;
537
+ this.serverCode = serverCode;
538
+ this.name = "AgentAuthorityError";
539
+ }
540
+ code;
541
+ status;
542
+ serverCode;
543
+ };
544
+ function isRecord(value) {
545
+ return typeof value === "object" && value !== null && !Array.isArray(value);
546
+ }
547
+ function isIsoDate(value) {
548
+ return typeof value === "string" && Number.isFinite(Date.parse(value));
549
+ }
550
+ function exactTarget(value, expected) {
551
+ if (!isRecord(value) || value.kind !== expected.kind) return false;
552
+ return expected.kind === "oauth-code" ? value.requestId === expected.requestId && Object.keys(value).length === 2 : value.userCode === expected.userCode && Object.keys(value).length === 2;
553
+ }
554
+ function validTarget(target) {
555
+ return target.kind === "oauth-code" ? OAUTH_REQUEST_ID.test(target.requestId) : DEVICE_USER_CODE.test(target.userCode);
556
+ }
557
+ function validAtomic(value) {
558
+ if (!POSITIVE_ATOMIC.test(value)) return false;
559
+ try {
560
+ return BigInt(value) <= U64_MAX_ATOMIC;
561
+ } catch {
562
+ return false;
563
+ }
564
+ }
565
+ function validReasons(reasons) {
566
+ return reasons.length <= 32 && reasons.every(
567
+ (reason) => /^[a-z0-9][a-z0-9._:-]{0,63}$/.test(reason)
568
+ );
569
+ }
570
+ function validRule(rule) {
571
+ const base = IDENTIFIER.test(rule.assetId) && validAtomic(rule.maxAmountAtomic) && validAtomic(rule.maxDailyAmountAtomic) && validAtomic(rule.maxAggregateAmountAtomic) && BigInt(rule.maxAmountAtomic) <= BigInt(rule.maxDailyAmountAtomic) && BigInt(rule.maxDailyAmountAtomic) <= BigInt(rule.maxAggregateAmountAtomic) && ["never", "always", "amount_or_risk"].includes(rule.approvalMode) && (rule.approvalThresholdAtomic === null || validAtomic(rule.approvalThresholdAtomic)) && validReasons(rule.approvalEscalationReasons) && validReasons(rule.blockedEscalationReasons);
572
+ if (!base) return false;
573
+ if (rule.action === "pay") {
574
+ return rule.assetId === X402_ASSET && rule.protocolId === X402_PROTOCOL_ID && rule.protocolVersion === X402_PROTOCOL_VERSION && rule.allowedSchemes.length === 2 && rule.allowedSchemes[0] === "exact" && rule.allowedSchemes[1] === "tab" && rule.counterpartyScope === X402_COUNTERPARTY_SCOPE;
575
+ }
576
+ return Number.isInteger(rule.maxSlippageBps) && rule.maxSlippageBps >= 0 && rule.maxSlippageBps <= 1e4 && Number.isInteger(rule.maxPriceImpactBps) && rule.maxPriceImpactBps >= 0 && rule.maxPriceImpactBps <= 1e4;
577
+ }
578
+ function sameArray(actual, expected) {
579
+ return Array.isArray(actual) && actual.length === expected.length && actual.every((value, index) => value === expected[index]);
580
+ }
581
+ function exactRule(value, expected) {
582
+ if (!isRecord(value) || typeof value.id !== "string" || !UUID.test(value.id)) {
583
+ return false;
584
+ }
585
+ const common = value.assetId === expected.assetId && value.action === expected.action && value.maxAmountAtomic === expected.maxAmountAtomic && value.maxDailyAmountAtomic === expected.maxDailyAmountAtomic && value.maxAggregateAmountAtomic === expected.maxAggregateAmountAtomic && value.approvalMode === expected.approvalMode && value.approvalThresholdAtomic === expected.approvalThresholdAtomic && sameArray(value.approvalEscalationReasons, expected.approvalEscalationReasons) && sameArray(value.blockedEscalationReasons, expected.blockedEscalationReasons);
586
+ if (!common) return false;
587
+ if (expected.action === "pay") {
588
+ return value.protocolId === expected.protocolId && value.protocolVersion === expected.protocolVersion && sameArray(value.allowedSchemes, expected.allowedSchemes) && value.counterpartyScope === expected.counterpartyScope;
589
+ }
590
+ return value.maxSlippageBps === expected.maxSlippageBps && value.maxPriceImpactBps === expected.maxPriceImpactBps;
591
+ }
592
+ function exactRules(value, expected) {
593
+ return Array.isArray(value) && value.length === expected.length && value.every((rule, index) => exactRule(rule, expected[index]));
594
+ }
595
+ async function refusal(response) {
596
+ const payload = await response.json().catch(() => null);
597
+ const serverCode = isRecord(payload) ? typeof payload.code === "string" ? payload.code : typeof payload.error === "string" ? payload.error : null : null;
598
+ if (response.status === 401) {
599
+ throw new AgentAuthorityError(
600
+ "owner_required",
601
+ "Sign in as this wallet owner before granting agent authority.",
602
+ response.status,
603
+ serverCode
604
+ );
605
+ }
606
+ throw new AgentAuthorityError(
607
+ "request_refused",
608
+ serverCode ?? `agent_authority_${response.status}`,
609
+ response.status,
610
+ serverCode
611
+ );
612
+ }
613
+ function usdcAtomic(value) {
614
+ const trimmed = value.trim();
615
+ const match = USDC_DECIMAL.exec(trimmed);
616
+ if (!match) return null;
617
+ const [whole = "0"] = trimmed.split(".");
618
+ const fraction = (match[2] ?? "").padEnd(6, "0");
619
+ const atomic = BigInt(whole) * 1000000n + BigInt(fraction || "0");
620
+ return atomic > 0n ? atomic.toString() : null;
621
+ }
622
+ function noCustomX402Limits(nowUnixMs = Date.now()) {
623
+ if (!Number.isSafeInteger(nowUnixMs) || nowUnixMs < 0) {
624
+ throw new AgentAuthorityError("invalid_input", "The current time is invalid.");
625
+ }
626
+ return {
627
+ perPaymentAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
628
+ dailyAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
629
+ aggregateAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
630
+ expiresAt: new Date(
631
+ nowUnixMs + NO_CUSTOM_LIMIT_TTL_DAYS * 864e5
632
+ ).toISOString()
633
+ };
634
+ }
635
+ function validateBoundedX402Draft(draft, nowUnixMs = Date.now()) {
636
+ const perPaymentAtomic = usdcAtomic(draft.perPaymentUsd);
637
+ if (!perPaymentAtomic || BigInt(perPaymentAtomic) > U64_MAX_ATOMIC) {
638
+ return {
639
+ ok: false,
640
+ field: "perPaymentUsd",
641
+ message: "Enter a valid per-payment limit with no more than 6 decimal places."
642
+ };
643
+ }
644
+ const dailyAtomic = usdcAtomic(draft.dailyUsd);
645
+ if (!dailyAtomic || BigInt(dailyAtomic) > U64_MAX_ATOMIC) {
646
+ return {
647
+ ok: false,
648
+ field: "dailyUsd",
649
+ message: "Enter a valid daily limit with no more than 6 decimal places."
650
+ };
651
+ }
652
+ const aggregateAtomic = usdcAtomic(draft.aggregateUsd);
653
+ if (!aggregateAtomic || BigInt(aggregateAtomic) > U64_MAX_ATOMIC) {
654
+ return {
655
+ ok: false,
656
+ field: "aggregateUsd",
657
+ message: "Enter a valid total limit with no more than 6 decimal places."
658
+ };
659
+ }
660
+ if (BigInt(perPaymentAtomic) > BigInt(dailyAtomic)) {
661
+ return {
662
+ ok: false,
663
+ field: "perPaymentUsd",
664
+ message: "The per-payment limit cannot exceed the daily limit."
665
+ };
666
+ }
667
+ if (BigInt(dailyAtomic) > BigInt(aggregateAtomic)) {
668
+ return {
669
+ ok: false,
670
+ field: "dailyUsd",
671
+ message: "The daily limit cannot exceed the total limit."
672
+ };
673
+ }
674
+ const expiresInDays = Number(draft.expiresInDays);
675
+ if (!/^\d{1,3}$/.test(draft.expiresInDays) || !Number.isInteger(expiresInDays) || expiresInDays < 1 || expiresInDays > 366) {
676
+ return {
677
+ ok: false,
678
+ field: "expiresInDays",
679
+ message: "Choose an expiry between 1 and 366 days."
680
+ };
681
+ }
682
+ if (!Number.isSafeInteger(nowUnixMs) || nowUnixMs < 0) {
683
+ throw new AgentAuthorityError("invalid_input", "The current time is invalid.");
684
+ }
685
+ return {
686
+ ok: true,
687
+ limits: {
688
+ perPaymentAtomic,
689
+ dailyAtomic,
690
+ aggregateAtomic,
691
+ expiresAt: new Date(nowUnixMs + expiresInDays * 864e5).toISOString()
692
+ }
693
+ };
694
+ }
695
+ function buildX402PaymentRule(limits, approval = {}) {
696
+ const rule = {
697
+ assetId: X402_ASSET,
698
+ action: "pay",
699
+ protocolId: X402_PROTOCOL_ID,
700
+ protocolVersion: X402_PROTOCOL_VERSION,
701
+ allowedSchemes: X402_ALLOWED_SCHEMES,
702
+ counterpartyScope: X402_COUNTERPARTY_SCOPE,
703
+ maxAmountAtomic: limits.perPaymentAtomic,
704
+ maxDailyAmountAtomic: limits.dailyAtomic,
705
+ maxAggregateAmountAtomic: limits.aggregateAtomic,
706
+ approvalMode: approval.mode ?? "never",
707
+ approvalThresholdAtomic: approval.thresholdAtomic ?? null,
708
+ approvalEscalationReasons: approval.escalationReasons ?? [],
709
+ blockedEscalationReasons: approval.blockedReasons ?? []
710
+ };
711
+ if (!validRule(rule)) {
712
+ throw new AgentAuthorityError("invalid_input", "The x402 authority rule is invalid.");
713
+ }
714
+ return Object.freeze(rule);
715
+ }
716
+ function buildAgentAuthorityRequest(input) {
717
+ const agentLabel = input.agentLabel === void 0 ? null : input.agentLabel;
718
+ if (!validTarget(input.target) || input.expectedVaultPda.length < 1 || input.expectedVaultPda.length > 128 || agentLabel !== null && (agentLabel.length < 1 || agentLabel.length > 128 || agentLabel !== agentLabel.trim()) || !isIsoDate(input.grantExpiresAt) || input.rules.length < 1 || input.rules.length > 64 || !input.rules.every(validRule)) {
719
+ throw new AgentAuthorityError("invalid_input", "The agent authority request is invalid.");
720
+ }
721
+ return Object.freeze({
722
+ expectedVaultPda: input.expectedVaultPda,
723
+ target: input.target,
724
+ agentLabel,
725
+ grantExpiresAt: input.grantExpiresAt,
726
+ rules: Object.freeze([...input.rules])
727
+ });
728
+ }
729
+ function buildBoundedX402BootstrapRequest(input) {
730
+ return buildAgentAuthorityRequest({
731
+ target: { kind: "oauth-code", requestId: input.requestId },
732
+ expectedVaultPda: input.expectedVaultPda,
733
+ agentLabel: input.agentLabel.trim(),
734
+ grantExpiresAt: input.limits.expiresAt,
735
+ rules: [buildX402PaymentRule(input.limits)]
736
+ });
737
+ }
738
+ async function beginAgentAuthority(input) {
739
+ if (!input.ownerAccessToken || !UUID.test(input.operationId)) {
740
+ throw new AgentAuthorityError(
741
+ "invalid_input",
742
+ "An owner session and operation id are required."
743
+ );
744
+ }
745
+ const request = buildAgentAuthorityRequest(input.request);
746
+ const response = await (input.fetchImpl ?? fetch)(
747
+ `${resolveDexterApiBase(input.apiBase)}/api/passkey-vault/governed-assets/agent/mandates/bootstrap`,
748
+ {
749
+ method: "POST",
750
+ headers: {
751
+ authorization: `Bearer ${input.ownerAccessToken}`,
752
+ "content-type": "application/json",
753
+ "idempotency-key": input.operationId
754
+ },
755
+ body: JSON.stringify(request),
756
+ cache: "no-store"
757
+ }
758
+ );
759
+ if (!response.ok) return refusal(response);
760
+ const payload = await response.json();
761
+ if (!isRecord(payload) || payload.namespace !== AGENT_AUTHORITY_NAMESPACE || payload.status !== "owner_authorization_required" || !UUID.test(String(payload.selectionId ?? "")) || payload.operationId !== input.operationId || payload.ownerVaultPda !== request.expectedVaultPda || !exactTarget(payload.target, request.target) || !UUID.test(String(payload.agentId ?? "")) || !UUID.test(String(payload.grantId ?? "")) || !isIsoDate(payload.validFrom) || payload.grantExpiresAt !== request.grantExpiresAt || !exactRules(payload.rules, request.rules) || typeof payload.rulesDigest !== "string" || !DIGEST.test(payload.rulesDigest) || !UUID.test(String(payload.authorizationId ?? "")) || !isIsoDate(payload.authorizationExpiresAt) || !isRecord(payload.authorizationOptions) || typeof payload.authorizationOptions.challenge !== "string" || payload.authorizationOptions.challenge.length < 16 || typeof payload.selectionDigest !== "string" || !DIGEST.test(payload.selectionDigest)) {
762
+ throw new AgentAuthorityError(
763
+ "invalid_response",
764
+ "Dexter returned an invalid agent-authority challenge."
765
+ );
766
+ }
767
+ return {
768
+ namespace: AGENT_AUTHORITY_NAMESPACE,
769
+ status: "owner_authorization_required",
770
+ selectionId: payload.selectionId,
771
+ operationId: input.operationId,
772
+ ownerVaultPda: payload.ownerVaultPda,
773
+ target: payload.target,
774
+ agentId: payload.agentId,
775
+ grantId: payload.grantId,
776
+ validFrom: payload.validFrom,
777
+ grantExpiresAt: payload.grantExpiresAt,
778
+ rules: payload.rules,
779
+ rulesDigest: payload.rulesDigest,
780
+ authorizationId: payload.authorizationId,
781
+ authorizationExpiresAt: payload.authorizationExpiresAt,
782
+ authorizationOptions: payload.authorizationOptions,
783
+ selectionDigest: payload.selectionDigest,
784
+ request
785
+ };
786
+ }
787
+ async function stageAgentAuthority(input) {
788
+ if (!input.ownerAccessToken || !isRecord(input.credential)) {
789
+ throw new AgentAuthorityError(
790
+ "invalid_input",
791
+ "The owner authorization result is missing."
792
+ );
793
+ }
794
+ const response = await (input.fetchImpl ?? fetch)(
795
+ `${resolveDexterApiBase(input.apiBase)}/api/passkey-vault/governed-assets/agent/mandates/bootstrap/${input.authorization.selectionId}/complete`,
796
+ {
797
+ method: "POST",
798
+ headers: {
799
+ authorization: `Bearer ${input.ownerAccessToken}`,
800
+ "content-type": "application/json"
801
+ },
802
+ body: JSON.stringify({
803
+ authorizationId: input.authorization.authorizationId,
804
+ credential: input.credential
805
+ }),
806
+ cache: "no-store"
807
+ }
808
+ );
809
+ if (!response.ok) return refusal(response);
810
+ const payload = await response.json();
811
+ const authorization = input.authorization;
812
+ if (!isRecord(payload) || payload.namespace !== AGENT_AUTHORITY_NAMESPACE || payload.status !== "owner_authorized" || payload.selectionId !== authorization.selectionId || payload.operationId !== authorization.operationId || payload.ownerVaultPda !== authorization.ownerVaultPda || !exactTarget(payload.target, authorization.request.target) || payload.agentId !== authorization.agentId || payload.grantId !== authorization.grantId || payload.validFrom !== authorization.validFrom || payload.grantExpiresAt !== authorization.request.grantExpiresAt || !exactRules(payload.rules, authorization.request.rules) || payload.rulesDigest !== authorization.rulesDigest || payload.authorizationId !== authorization.authorizationId || payload.selectionDigest !== authorization.selectionDigest) {
813
+ throw new AgentAuthorityError(
814
+ "invalid_response",
815
+ "Dexter returned an invalid staged agent-authority receipt."
816
+ );
817
+ }
818
+ return payload;
819
+ }
820
+ async function beginBoundedX402Authority(input) {
821
+ return beginAgentAuthority({
822
+ ownerAccessToken: input.accessToken,
823
+ operationId: input.operationId,
824
+ request: input.request,
825
+ apiBase: input.apiBase,
826
+ fetchImpl: input.fetchImpl
827
+ });
828
+ }
829
+ async function stageBoundedX402Authority(input) {
830
+ return stageAgentAuthority({
831
+ ownerAccessToken: input.accessToken,
832
+ authorization: input.authorization,
833
+ credential: input.credential,
834
+ apiBase: input.apiBase,
835
+ fetchImpl: input.fetchImpl
836
+ });
837
+ }
838
+ function exactAgentAuthorityApprovalRedirect(value, expectedGrantId) {
839
+ if (!UUID.test(expectedGrantId) || !isRecord(value) || value.ok !== true || typeof value.redirect_url !== "string" || !isRecord(value.authority) || value.authority.status !== "active" || value.authority.grantId !== expectedGrantId) {
840
+ throw new AgentAuthorityError(
841
+ "invalid_response",
842
+ "Dexter did not return the exact activated agent authority."
843
+ );
844
+ }
845
+ return value.redirect_url;
846
+ }
847
+ function exactBoundedX402ApprovalRedirect(value, expectedGrantId) {
848
+ try {
849
+ return exactAgentAuthorityApprovalRedirect(value, expectedGrantId);
850
+ } catch (error) {
851
+ if (error instanceof AgentAuthorityError) {
852
+ throw new AgentAuthorityError(
853
+ error.code,
854
+ "Dexter did not return the exact activated payment authority.",
855
+ error.status,
856
+ error.serverCode
857
+ );
858
+ }
859
+ throw error;
860
+ }
861
+ }
862
+ function validAuthorityStatus(value) {
863
+ if (!isRecord(value) || value.namespace !== AGENT_AUTHORITY_STATUS_NAMESPACE || !["view_only", "bounded_payment_authority", "unavailable"].includes(
864
+ String(value.mode)
865
+ ) || typeof value.active !== "boolean" || !(value.inactiveReason === null || typeof value.inactiveReason === "string") || typeof value.logicalGrantActive !== "boolean" || !(value.grantId === null || typeof value.grantId === "string" && UUID.test(value.grantId)) || !(value.grantRevision === null || Number.isInteger(value.grantRevision) && Number(value.grantRevision) >= 1) || !(value.expiresAt === null || isIsoDate(value.expiresAt)) || !(value.revoked === null || typeof value.revoked === "boolean") || !(value.source === null || value.source === "mcp-link-token") || value.fallback !== false || !isRecord(value.activeRole)) {
866
+ return false;
867
+ }
868
+ if (value.principal !== null) {
869
+ if (!isRecord(value.principal) || !["owner", "agent"].includes(String(value.principal.actor)) || typeof value.principal.vaultPda !== "string" || typeof value.principal.walletAddress !== "string" || !(value.principal.agentId === null || typeof value.principal.agentId === "string" && UUID.test(value.principal.agentId))) return false;
870
+ }
871
+ const activeRole = value.activeRole;
872
+ if (activeRole.status === "active") {
873
+ if (!Number.isInteger(activeRole.roleId) || Number(activeRole.roleId) < 0 || typeof activeRole.authoritySigner !== "string" || !Number.isInteger(activeRole.sessionExpirySlot) || !Number.isInteger(activeRole.currentSlot) || typeof activeRole.resolutionDigest !== "string" || !DIGEST.test(activeRole.resolutionDigest)) return false;
874
+ } else if (!["not-applicable", "unavailable"].includes(String(activeRole.status)) || typeof activeRole.reason !== "string") {
875
+ return false;
876
+ }
877
+ if (value.scopes !== null) {
878
+ const scopes = value.scopes;
879
+ if (!isRecord(scopes) || scopes.network !== "solana-mainnet" || scopes.assetId !== X402_ASSET || scopes.action !== "pay" || scopes.protocolId !== X402_PROTOCOL_ID || scopes.protocolVersion !== X402_PROTOCOL_VERSION || !sameArray(scopes.allowedSchemes, X402_ALLOWED_SCHEMES) || scopes.counterpartyScope !== X402_COUNTERPARTY_SCOPE) return false;
880
+ }
881
+ if (value.capacity !== null) {
882
+ const capacity = value.capacity;
883
+ if (!isRecord(capacity)) return false;
884
+ const amounts = [
885
+ capacity.maximumPerCallAmountAtomic,
886
+ capacity.remainingPerCallAmountAtomic,
887
+ capacity.maximumDailyAmountAtomic,
888
+ capacity.usedDailyAmountAtomic,
889
+ capacity.remainingDailyAmountAtomic,
890
+ capacity.maximumAggregateAmountAtomic,
891
+ capacity.usedAggregateAmountAtomic,
892
+ capacity.remainingAggregateAmountAtomic
893
+ ];
894
+ if (!amounts.every(
895
+ (amount) => typeof amount === "string" && NON_NEGATIVE_ATOMIC.test(amount)
896
+ ) || !isIsoDate(capacity.evaluatedAt) || typeof capacity.snapshotDigest !== "string" || !DIGEST.test(capacity.snapshotDigest)) return false;
897
+ }
898
+ if (value.mode === "bounded_payment_authority") {
899
+ if (value.principal?.actor !== "agent" || value.source !== "mcp-link-token" || value.grantId === null || value.grantRevision === null || value.expiresAt === null || value.scopes === null || value.capacity === null || value.revoked !== false || activeRole.status !== "active") {
900
+ return false;
901
+ }
902
+ }
903
+ return true;
904
+ }
905
+ async function readAgentAuthority(input) {
906
+ if (!input.accessToken) {
907
+ throw new AgentAuthorityError("invalid_input", "An OpenDexter access token is required.");
908
+ }
909
+ const response = await (input.fetchImpl ?? fetch)(
910
+ `${resolveDexterApiBase(input.apiBase)}/api/connector/oauth/authority`,
911
+ {
912
+ headers: { authorization: `Bearer ${input.accessToken}` },
913
+ cache: "no-store"
914
+ }
915
+ );
916
+ if (!response.ok) return refusal(response);
917
+ const payload = await response.json();
918
+ if (!validAuthorityStatus(payload)) {
919
+ throw new AgentAuthorityError(
920
+ "invalid_response",
921
+ "Dexter returned an invalid agent-authority status."
922
+ );
923
+ }
924
+ return payload;
925
+ }
337
926
  export {
338
- ACTIVE_WALLET_STORAGE_KEY,
927
+ AGENT_AUTHORITY_NAMESPACE,
928
+ AGENT_AUTHORITY_STATUS_NAMESPACE,
929
+ AgentAuthorityError,
339
930
  AgentSpendError,
931
+ AgentAuthorityError as BoundedX402AuthorityError,
340
932
  ConnectError,
933
+ MAX_AUTHORITY_AMOUNT_ATOMIC,
341
934
  SESSION_TTL_30D,
935
+ WALLET_ACCOUNT_BINDING_PATH,
936
+ WALLET_PROOF_SESSION_STORAGE_PREFIX,
937
+ WalletAccountRelationController,
938
+ X402_ALLOWED_SCHEMES,
939
+ X402_ASSET,
940
+ X402_COUNTERPARTY_SCOPE,
941
+ X402_PROTOCOL_ID,
942
+ X402_PROTOCOL_VERSION,
943
+ accountBindingCandidate,
342
944
  assembleAgentSpendStatus,
343
945
  authoredPolicy,
946
+ beginAgentAuthority,
947
+ beginBoundedX402Authority,
948
+ buildAgentAuthorityRequest,
949
+ buildBoundedX402BootstrapRequest,
950
+ buildX402PaymentRule,
344
951
  ceremonyPhaseLabel,
345
- continueWithDexter,
952
+ connectDexterIdentity,
346
953
  createAnonServerPolicy,
954
+ createDexterControlModel,
955
+ createDexterIdentityCoordinator,
347
956
  createPasskeySigner,
348
957
  createWallet,
958
+ createWalletAccountBindingClient,
959
+ createWalletProofSessionStore,
349
960
  describeAgentSpendError,
350
- ejectActiveWallet,
961
+ disconnectDexterIdentity,
351
962
  enableAgentSpend,
352
- forgetWallet,
353
- getActiveHandle,
354
- getCredentialId,
355
- listWallets,
356
- passkeyLogin,
963
+ exactAgentAuthorityApprovalRedirect,
964
+ exactBoundedX402ApprovalRedirect,
965
+ noCustomX402Limits,
357
966
  passkeySignalSupport,
358
967
  prunePasskey,
968
+ readAgentAuthority,
359
969
  recoverWallet,
360
970
  renamePasskey,
361
- resolveIdentity,
362
971
  revokeAgentSpend,
363
- setActiveHandle,
364
- subscribe as subscribeWallet,
365
- switchWallet,
972
+ stageAgentAuthority,
973
+ stageBoundedX402Authority,
366
974
  syncAcceptedPasskeys,
367
- usdToAtomic
975
+ usdToAtomic,
976
+ validateBoundedX402Draft,
977
+ walletBindingCandidate,
978
+ walletProofSessionStore
368
979
  };