@dexterai/connect 0.26.3 → 0.29.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 +185 -188
- package/dist/chunk-EMCGL64H.js +59 -0
- package/dist/{chunk-TLCQSAE5.js → chunk-T62F36N2.js} +2 -2
- package/dist/chunk-XKOVUW5P.js +1872 -0
- package/dist/connectionContract-QGRidIHM.d.ts +470 -0
- package/dist/index.d.ts +434 -10
- package/dist/index.js +816 -39
- package/dist/react.d.ts +69 -191
- package/dist/react.js +551 -490
- package/dist/server.d.ts +2 -1
- package/dist/server.js +80 -5
- package/dist/worldid.d.ts +2 -4
- package/dist/worldid.js +1 -1
- package/package.json +3 -2
- package/dist/chunk-XQ7RKJMI.js +0 -1126
- package/dist/signals-Dx090EYY.d.ts +0 -375
package/dist/index.js
CHANGED
|
@@ -1,41 +1,382 @@
|
|
|
1
1
|
import {
|
|
2
|
-
ACTIVE_WALLET_STORAGE_KEY,
|
|
3
2
|
ConnectError,
|
|
4
3
|
SESSION_TTL_30D,
|
|
4
|
+
WALLET_ACCOUNT_BINDING_PATH,
|
|
5
|
+
WALLET_PROOF_SESSION_STORAGE_PREFIX,
|
|
6
|
+
WalletAccountRelationController,
|
|
7
|
+
accountBindingCandidate,
|
|
8
|
+
activateRecoveredVault,
|
|
5
9
|
authoredPolicy,
|
|
6
|
-
base64urlToBytes,
|
|
7
10
|
bytesEqual,
|
|
8
|
-
bytesToBase64,
|
|
9
|
-
bytesToBase64url,
|
|
10
11
|
ceremonyPhaseLabel,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
classifyWebAuthnRejection,
|
|
13
|
+
connectDexterIdentity,
|
|
14
|
+
createDexterControlModel,
|
|
15
|
+
createDexterIdentityCoordinator,
|
|
14
16
|
createWallet,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
createWalletAccountBindingClient,
|
|
18
|
+
createWalletProofSessionStore,
|
|
19
|
+
disconnectDexterIdentity,
|
|
20
|
+
immediateAuthentication,
|
|
21
|
+
immediateGetSupported,
|
|
22
|
+
openCeremonyPopup,
|
|
23
|
+
parseWalletIdentityProof,
|
|
21
24
|
passkeySignalSupport,
|
|
25
|
+
primeImmediateSupport,
|
|
22
26
|
prunePasskey,
|
|
23
|
-
|
|
27
|
+
readErrorCode,
|
|
24
28
|
renamePasskey,
|
|
25
29
|
resolveDexterApiBase,
|
|
26
30
|
resolveDexterRpId,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
subscribe,
|
|
30
|
-
switchWallet,
|
|
31
|
+
resolveWalletStoreMode,
|
|
32
|
+
shouldUsePopup,
|
|
31
33
|
syncAcceptedPasskeys,
|
|
32
|
-
usdToAtomic
|
|
33
|
-
|
|
34
|
+
usdToAtomic,
|
|
35
|
+
walletBindingCandidate,
|
|
36
|
+
walletProofSessionStore
|
|
37
|
+
} from "./chunk-XKOVUW5P.js";
|
|
38
|
+
import {
|
|
39
|
+
base64ToBytes,
|
|
40
|
+
base64urlToBytes,
|
|
41
|
+
bytesToBase64,
|
|
42
|
+
bytesToBase64url,
|
|
43
|
+
compactSignatureToDer
|
|
44
|
+
} from "./chunk-EMCGL64H.js";
|
|
34
45
|
|
|
35
|
-
// src/
|
|
46
|
+
// src/anon-policy.ts
|
|
47
|
+
var ANON_SIGN_BASE = "/api/passkey-anon/sign";
|
|
48
|
+
function createAnonServerPolicy(apiBase) {
|
|
49
|
+
const base = resolveDexterApiBase(apiBase);
|
|
50
|
+
return {
|
|
51
|
+
async issueChallenge({ userHandle, operationMessage, operationHash }) {
|
|
52
|
+
const res = await fetch(`${base}${ANON_SIGN_BASE}/challenge`, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { "content-type": "application/json" },
|
|
55
|
+
body: JSON.stringify({
|
|
56
|
+
userHandle: bytesToBase64url(userHandle),
|
|
57
|
+
operationHash: bytesToBase64url(operationHash),
|
|
58
|
+
operationMessage: bytesToBase64url(operationMessage),
|
|
59
|
+
operation: "vault_operation"
|
|
60
|
+
})
|
|
61
|
+
});
|
|
62
|
+
if (!res.ok) throw new ConnectError(await readErrorCode(res), `challenge ${res.status}`);
|
|
63
|
+
const data = await res.json();
|
|
64
|
+
const options = data?.options;
|
|
65
|
+
if (!options?.challenge) {
|
|
66
|
+
throw new ConnectError("challenge_malformed", "no challenge in response");
|
|
67
|
+
}
|
|
68
|
+
const challenge = base64urlToBytes(options.challenge);
|
|
69
|
+
const cred = options.allowCredentials?.[0];
|
|
70
|
+
if (!cred?.id) {
|
|
71
|
+
throw new ConnectError("no_credential", "no allow-listed credential for this userHandle");
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
challenge,
|
|
75
|
+
credentialId: base64urlToBytes(cred.id),
|
|
76
|
+
rpId: resolveDexterRpId(options.rpId),
|
|
77
|
+
transports: cred.transports
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
async verify({ userHandle, credentialId, signature, clientDataJSON, authenticatorData }) {
|
|
81
|
+
const credential = {
|
|
82
|
+
id: bytesToBase64url(credentialId),
|
|
83
|
+
rawId: bytesToBase64url(credentialId),
|
|
84
|
+
type: "public-key",
|
|
85
|
+
response: {
|
|
86
|
+
clientDataJSON: bytesToBase64url(clientDataJSON),
|
|
87
|
+
authenticatorData: bytesToBase64url(authenticatorData),
|
|
88
|
+
// The SDK passes the COMPACT sig; dexter-api's verifier wants DER.
|
|
89
|
+
signature: bytesToBase64url(compactSignatureToDer(signature)),
|
|
90
|
+
userHandle: null
|
|
91
|
+
},
|
|
92
|
+
clientExtensionResults: {},
|
|
93
|
+
authenticatorAttachment: null
|
|
94
|
+
};
|
|
95
|
+
const res = await fetch(`${base}${ANON_SIGN_BASE}/verify`, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
headers: { "content-type": "application/json" },
|
|
98
|
+
body: JSON.stringify({ credential, userHandle: bytesToBase64url(userHandle) })
|
|
99
|
+
});
|
|
100
|
+
if (!res.ok) throw new ConnectError(await readErrorCode(res), `verify ${res.status}`);
|
|
101
|
+
const data = await res.json();
|
|
102
|
+
if (data?.verified !== true) {
|
|
103
|
+
throw new ConnectError("verification_failed", "server did not return verified=true");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/signer.ts
|
|
110
|
+
import { DexterApiBrowserPasskeySigner } from "@dexterai/vault/signers/browser";
|
|
111
|
+
import {
|
|
112
|
+
parseStrictCollectedClientData,
|
|
113
|
+
validatePasskeyAuthorizationChallenge
|
|
114
|
+
} from "@dexterai/vault";
|
|
36
115
|
import { PublicKey } from "@solana/web3.js";
|
|
116
|
+
var HostedPopupPasskeySigner = class {
|
|
117
|
+
constructor(vault, expectedVault, connectHost) {
|
|
118
|
+
this.expectedVault = expectedVault;
|
|
119
|
+
this.connectHost = connectHost;
|
|
120
|
+
this.vault = { ...vault };
|
|
121
|
+
this.credentialId = base64urlToBytes(vault.credentialId);
|
|
122
|
+
this.publicKey = base64ToBytes(vault.publicKey);
|
|
123
|
+
}
|
|
124
|
+
expectedVault;
|
|
125
|
+
connectHost;
|
|
126
|
+
credentialId;
|
|
127
|
+
publicKey;
|
|
128
|
+
vault;
|
|
129
|
+
async signOperation(operationMessage) {
|
|
130
|
+
if (!(operationMessage instanceof Uint8Array) || operationMessage.length === 0) {
|
|
131
|
+
throw new ConnectError("invalid_operation", "signOperation requires non-empty bytes");
|
|
132
|
+
}
|
|
133
|
+
const exactOperationMessage = new Uint8Array(operationMessage);
|
|
134
|
+
const result = await openCeremonyPopup("sign", {
|
|
135
|
+
...this.connectHost ? { connectHost: this.connectHost } : {},
|
|
136
|
+
signRequest: {
|
|
137
|
+
operationMessage: exactOperationMessage,
|
|
138
|
+
vault: {
|
|
139
|
+
vaultPda: this.vault.vaultPda,
|
|
140
|
+
publicKey: this.vault.publicKey,
|
|
141
|
+
userHandle: this.vault.userHandle,
|
|
142
|
+
credentialId: this.vault.credentialId,
|
|
143
|
+
...this.vault.walletLabel !== void 0 ? { walletLabel: this.vault.walletLabel } : {}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
return validateHostedSignResult(result, exactOperationMessage, this.expectedVault);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
function createPasskeySigner(vault, apiBase, opts = {}) {
|
|
151
|
+
resolveDexterApiBase(apiBase);
|
|
152
|
+
const expectedVault = new PublicKey(vault.vaultPda);
|
|
153
|
+
if (shouldUsePopup()) {
|
|
154
|
+
return new HostedPopupPasskeySigner(vault, expectedVault, opts.connectHost);
|
|
155
|
+
}
|
|
156
|
+
return new DexterApiBrowserPasskeySigner({
|
|
157
|
+
identity: { kind: "guest", userHandle: base64urlToBytes(vault.userHandle) },
|
|
158
|
+
publicKey: base64ToBytes(vault.publicKey),
|
|
159
|
+
anonPolicy: createAnonServerPolicy(apiBase),
|
|
160
|
+
// The API resolves the authorization envelope, but this browser still
|
|
161
|
+
// knows which connected vault the caller selected. Pin that exact PDA so a
|
|
162
|
+
// valid Dexter envelope for another vault cannot reach WebAuthn.
|
|
163
|
+
expectedVault,
|
|
164
|
+
...opts.__assertion ? { __assertion: opts.__assertion } : {}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async function validateHostedSignResult(result, operationMessage, expectedVault) {
|
|
168
|
+
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) {
|
|
169
|
+
throw new ConnectError("popup_result_malformed", "hosted signer returned malformed assertion bytes");
|
|
170
|
+
}
|
|
171
|
+
let clientData;
|
|
172
|
+
try {
|
|
173
|
+
clientData = parseStrictCollectedClientData(result.clientDataJSON);
|
|
174
|
+
} catch {
|
|
175
|
+
throw new ConnectError("popup_result_malformed", "hosted signer returned invalid clientDataJSON");
|
|
176
|
+
}
|
|
177
|
+
if (clientData.type !== "webauthn.get" || clientData.origin !== "https://dexter.cash" || clientData.crossOrigin !== false || !/^[A-Za-z0-9_-]+$/.test(clientData.challenge)) {
|
|
178
|
+
throw new ConnectError("popup_result_malformed", "hosted signer returned invalid WebAuthn client data");
|
|
179
|
+
}
|
|
180
|
+
const expectedRpHash = new Uint8Array(
|
|
181
|
+
await crypto.subtle.digest("SHA-256", new TextEncoder().encode("dexter.cash"))
|
|
182
|
+
);
|
|
183
|
+
const flags = result.authenticatorData[32] ?? 0;
|
|
184
|
+
if (!bytesEqual(result.authenticatorData.subarray(0, 32), expectedRpHash) || (flags & 1) === 0 || (flags & 4) === 0) {
|
|
185
|
+
throw new ConnectError("popup_result_malformed", "hosted signer returned invalid authenticator context");
|
|
186
|
+
}
|
|
187
|
+
let challenge;
|
|
188
|
+
try {
|
|
189
|
+
challenge = base64urlToBytes(clientData.challenge);
|
|
190
|
+
if (bytesToBase64url(challenge) !== clientData.challenge) throw new Error("non-canonical");
|
|
191
|
+
} catch {
|
|
192
|
+
throw new ConnectError("popup_result_malformed", "hosted signer returned an invalid challenge encoding");
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
const operationHash = new Uint8Array(
|
|
196
|
+
await crypto.subtle.digest("SHA-256", new Uint8Array(operationMessage))
|
|
197
|
+
);
|
|
198
|
+
validatePasskeyAuthorizationChallenge({ challenge, operationHash, expectedVault });
|
|
199
|
+
} catch {
|
|
200
|
+
throw new ConnectError(
|
|
201
|
+
"popup_result_unbound",
|
|
202
|
+
"hosted signer returned an assertion for a different operation or vault"
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
signature: new Uint8Array(result.signature),
|
|
207
|
+
clientDataJSON: new Uint8Array(result.clientDataJSON),
|
|
208
|
+
authenticatorData: new Uint8Array(result.authenticatorData)
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/recover.ts
|
|
213
|
+
import { startAuthentication, browserSupportsWebAuthn } from "@simplewebauthn/browser";
|
|
214
|
+
var ANON_SIGN_BASE2 = "/api/passkey-anon/sign";
|
|
215
|
+
primeImmediateSupport();
|
|
216
|
+
async function recoverWallet(config = {}) {
|
|
217
|
+
let apiBase;
|
|
218
|
+
let walletStore;
|
|
219
|
+
try {
|
|
220
|
+
apiBase = resolveDexterApiBase(config.apiBase);
|
|
221
|
+
} catch (err) {
|
|
222
|
+
return netError("untrusted_api_base", err);
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
walletStore = resolveWalletStoreMode(config.walletStore);
|
|
226
|
+
} catch (err) {
|
|
227
|
+
return {
|
|
228
|
+
ok: false,
|
|
229
|
+
reason: "error",
|
|
230
|
+
error: err instanceof ConnectError ? err : new ConnectError("invalid_wallet_store_mode")
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
if (shouldUsePopup(config.transport)) {
|
|
234
|
+
let outcome;
|
|
235
|
+
try {
|
|
236
|
+
outcome = await openCeremonyPopup("recover", {
|
|
237
|
+
connectHost: config.connectHost,
|
|
238
|
+
preferImmediate: config.preferImmediate,
|
|
239
|
+
...walletStore === "provisional" ? { walletStore } : {}
|
|
240
|
+
});
|
|
241
|
+
} catch (err) {
|
|
242
|
+
const ce = err instanceof ConnectError ? err : new ConnectError("popup_failed", err instanceof Error ? err.message : String(err));
|
|
243
|
+
if (ce.code === "popup_closed") return { ok: false, reason: "cancelled" };
|
|
244
|
+
return { ok: false, reason: "error", error: ce };
|
|
245
|
+
}
|
|
246
|
+
if (outcome.ok) {
|
|
247
|
+
try {
|
|
248
|
+
outcome = {
|
|
249
|
+
...outcome,
|
|
250
|
+
walletIdentityProof: parseWalletIdentityProof(
|
|
251
|
+
outcome.walletIdentityProof
|
|
252
|
+
)
|
|
253
|
+
};
|
|
254
|
+
} catch (err) {
|
|
255
|
+
return netError("wallet_identity_proof_malformed", err);
|
|
256
|
+
}
|
|
257
|
+
if (walletStore === "commit") {
|
|
258
|
+
activateRecoveredVault(
|
|
259
|
+
outcome.userHandle,
|
|
260
|
+
outcome.credentialId,
|
|
261
|
+
outcome.vault,
|
|
262
|
+
outcome.walletIdentityProof
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return outcome;
|
|
267
|
+
}
|
|
268
|
+
if (typeof navigator === "undefined" || !browserSupportsWebAuthn()) {
|
|
269
|
+
return {
|
|
270
|
+
ok: false,
|
|
271
|
+
reason: "error",
|
|
272
|
+
error: new ConnectError("webauthn_unsupported", "WebAuthn unavailable in this environment")
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
const onPhase = config.onPhase;
|
|
276
|
+
onPhase?.("challenge");
|
|
277
|
+
let options;
|
|
278
|
+
try {
|
|
279
|
+
const res = await fetch(`${apiBase}${ANON_SIGN_BASE2}/recover-challenge`, {
|
|
280
|
+
method: "POST",
|
|
281
|
+
headers: { "content-type": "application/json" },
|
|
282
|
+
body: "{}"
|
|
283
|
+
});
|
|
284
|
+
if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
|
|
285
|
+
const serverOptions = (await res.json()).options;
|
|
286
|
+
if (!serverOptions?.challenge) {
|
|
287
|
+
return {
|
|
288
|
+
ok: false,
|
|
289
|
+
reason: "error",
|
|
290
|
+
error: new ConnectError("recover_challenge_malformed", "no challenge in response")
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
options = { ...serverOptions, rpId: resolveDexterRpId(serverOptions.rpId) };
|
|
294
|
+
} catch (err) {
|
|
295
|
+
if (err instanceof ConnectError && err.code === "untrusted_rp_id") {
|
|
296
|
+
return { ok: false, reason: "error", error: err };
|
|
297
|
+
}
|
|
298
|
+
return netError("recover_challenge_failed", err);
|
|
299
|
+
}
|
|
300
|
+
onPhase?.("passkey");
|
|
301
|
+
const useImmediate = Boolean(config.preferImmediate) && await immediateGetSupported();
|
|
302
|
+
let credential;
|
|
303
|
+
try {
|
|
304
|
+
credential = useImmediate ? await immediateAuthentication(options) : await startAuthentication({ optionsJSON: options });
|
|
305
|
+
} catch (err) {
|
|
306
|
+
if (classifyWebAuthnRejection(err)) {
|
|
307
|
+
return { ok: false, reason: useImmediate ? "no_credential" : "cancelled" };
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
ok: false,
|
|
311
|
+
reason: "error",
|
|
312
|
+
error: new ConnectError("webauthn_failed", err instanceof Error ? err.message : String(err))
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
onPhase?.("verifying");
|
|
316
|
+
let userHandle;
|
|
317
|
+
let credentialId;
|
|
318
|
+
let walletIdentityProof;
|
|
319
|
+
try {
|
|
320
|
+
const res = await fetch(`${apiBase}${ANON_SIGN_BASE2}/recover-verify`, {
|
|
321
|
+
method: "POST",
|
|
322
|
+
headers: { "content-type": "application/json" },
|
|
323
|
+
body: JSON.stringify({ credential })
|
|
324
|
+
});
|
|
325
|
+
if (res.status === 404) return { ok: false, reason: "no_credential" };
|
|
326
|
+
if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
|
|
327
|
+
const data = await res.json();
|
|
328
|
+
userHandle = data.userHandle;
|
|
329
|
+
credentialId = data.credentialId;
|
|
330
|
+
walletIdentityProof = parseWalletIdentityProof(data.walletIdentityProof);
|
|
331
|
+
} catch (err) {
|
|
332
|
+
return netError("recover_verify_failed", err);
|
|
333
|
+
}
|
|
334
|
+
let vault;
|
|
335
|
+
try {
|
|
336
|
+
const res = await fetch(
|
|
337
|
+
`${apiBase}/api/passkey-vault-anon/status?user_handle=${encodeURIComponent(userHandle)}`
|
|
338
|
+
);
|
|
339
|
+
if (!res.ok) return { ok: false, reason: "error", error: new ConnectError(await readErrorCode(res)) };
|
|
340
|
+
const data = await res.json();
|
|
341
|
+
if (!data.hasVault || !data.vault) {
|
|
342
|
+
return {
|
|
343
|
+
ok: false,
|
|
344
|
+
reason: "error",
|
|
345
|
+
error: new ConnectError("vault_not_found", "this sign-in key has no wallet attached")
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
vault = {
|
|
349
|
+
vaultPda: data.vault.vaultPda,
|
|
350
|
+
swigAddress: data.vault.swigAddress,
|
|
351
|
+
receiveAddress: data.vault.receiveAddress ?? null,
|
|
352
|
+
isActivated: Boolean(data.vault.isActivated),
|
|
353
|
+
walletLabel: data.vault.walletLabel ?? null
|
|
354
|
+
};
|
|
355
|
+
} catch (err) {
|
|
356
|
+
return netError("vault_status_failed", err);
|
|
357
|
+
}
|
|
358
|
+
if (walletStore === "commit") {
|
|
359
|
+
activateRecoveredVault(
|
|
360
|
+
userHandle,
|
|
361
|
+
credentialId,
|
|
362
|
+
vault,
|
|
363
|
+
walletIdentityProof
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
return { ok: true, userHandle, credentialId, vault, walletIdentityProof };
|
|
367
|
+
}
|
|
368
|
+
function netError(code, err) {
|
|
369
|
+
return {
|
|
370
|
+
ok: false,
|
|
371
|
+
reason: "error",
|
|
372
|
+
error: new ConnectError(code, err instanceof Error ? err.message : String(err))
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// src/agentSpend.ts
|
|
377
|
+
import { PublicKey as PublicKey2 } from "@solana/web3.js";
|
|
37
378
|
import { WebAuthnAssertion } from "@dexterai/vault/signers/browser";
|
|
38
|
-
import { validatePasskeyAuthorizationChallenge } from "@dexterai/vault";
|
|
379
|
+
import { validatePasskeyAuthorizationChallenge as validatePasskeyAuthorizationChallenge2 } from "@dexterai/vault";
|
|
39
380
|
import { enableAgentSpendMessage, revokeAgentSpendV2Message } from "@dexterai/vault/messages";
|
|
40
381
|
import { DEXTER_VAULT_PROGRAM_ID } from "@dexterai/vault/constants";
|
|
41
382
|
function shortCounterparty(a) {
|
|
@@ -114,7 +455,7 @@ async function agentSpendError(res) {
|
|
|
114
455
|
return new AgentSpendError(code, `agent-spend ${res.status}: ${code}`);
|
|
115
456
|
}
|
|
116
457
|
function assertDexterWallet(id) {
|
|
117
|
-
if (id.kind !== "
|
|
458
|
+
if (id.kind !== "wallet_only" && id.kind !== "bound") {
|
|
118
459
|
throw new AgentSpendError("not_guest", "agent-spend off/on switch is Dexter Wallet only");
|
|
119
460
|
}
|
|
120
461
|
}
|
|
@@ -175,7 +516,7 @@ async function assertCanonicalOperationInline(messageBytes, userHandle, expected
|
|
|
175
516
|
}
|
|
176
517
|
const challenge = base64urlToBytes(options.challenge);
|
|
177
518
|
try {
|
|
178
|
-
|
|
519
|
+
validatePasskeyAuthorizationChallenge2({
|
|
179
520
|
challenge,
|
|
180
521
|
operationHash,
|
|
181
522
|
expectedVault
|
|
@@ -245,7 +586,7 @@ async function revokeAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
|
|
|
245
586
|
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
587
|
throw new AgentSpendError("challenge_malformed", "Dexter returned an incomplete revoke intent");
|
|
247
588
|
}
|
|
248
|
-
const expectedVault = new
|
|
589
|
+
const expectedVault = new PublicKey2(vaultPda);
|
|
249
590
|
const message = revokeAgentSpendV2Message({
|
|
250
591
|
programId: DEXTER_VAULT_PROGRAM_ID,
|
|
251
592
|
vaultPda: expectedVault,
|
|
@@ -299,7 +640,7 @@ async function enableAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
|
|
|
299
640
|
throw new AgentSpendError("challenge_malformed", "Dexter returned an incomplete enable intent");
|
|
300
641
|
}
|
|
301
642
|
const { nonce, expiry } = challenge;
|
|
302
|
-
const expectedVault = new
|
|
643
|
+
const expectedVault = new PublicKey2(vaultPda);
|
|
303
644
|
const message = enableAgentSpendMessage({
|
|
304
645
|
programId: DEXTER_VAULT_PROGRAM_ID,
|
|
305
646
|
vaultPda: expectedVault,
|
|
@@ -334,35 +675,471 @@ async function enableAgentSpend(id, vaultPda, apiOrigin, credentialId, signer) {
|
|
|
334
675
|
if (!verifyRes.ok) throw await agentSpendError(verifyRes);
|
|
335
676
|
return await verifyRes.json();
|
|
336
677
|
}
|
|
678
|
+
|
|
679
|
+
// src/agentAuthority.ts
|
|
680
|
+
var AGENT_AUTHORITY_NAMESPACE = "dexter-governed-agent-surface-selection/v2";
|
|
681
|
+
var AGENT_AUTHORITY_STATUS_NAMESPACE = "dexter-governed-agent-surface-authority/v2";
|
|
682
|
+
var X402_PROTOCOL_ID = "x402";
|
|
683
|
+
var X402_PROTOCOL_VERSION = 2;
|
|
684
|
+
var X402_ALLOWED_SCHEMES = Object.freeze(["exact", "tab"]);
|
|
685
|
+
var X402_ASSET = "usdc";
|
|
686
|
+
var X402_COUNTERPARTY_SCOPE = "any-valid-x402-seller";
|
|
687
|
+
var MAX_AUTHORITY_AMOUNT_ATOMIC = "18446744073709551615";
|
|
688
|
+
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}$/;
|
|
689
|
+
var DIGEST = /^[0-9a-f]{64}$/;
|
|
690
|
+
var IDENTIFIER = /^[a-z0-9][a-z0-9._:-]{0,127}$/;
|
|
691
|
+
var POSITIVE_ATOMIC = /^[1-9][0-9]{0,19}$/;
|
|
692
|
+
var NON_NEGATIVE_ATOMIC = /^(0|[1-9][0-9]{0,19})$/;
|
|
693
|
+
var U64_MAX_ATOMIC = BigInt(MAX_AUTHORITY_AMOUNT_ATOMIC);
|
|
694
|
+
var OAUTH_REQUEST_ID = /^[A-Za-z0-9_-]{16,64}$/;
|
|
695
|
+
var DEVICE_USER_CODE = /^[A-Z0-9-]{6,32}$/;
|
|
696
|
+
var USDC_DECIMAL = /^(0|[1-9][0-9]*)(?:\.([0-9]{1,6}))?$/;
|
|
697
|
+
var NO_CUSTOM_LIMIT_TTL_DAYS = 365;
|
|
698
|
+
var AgentAuthorityError = class extends Error {
|
|
699
|
+
constructor(code, message, status = null, serverCode = null) {
|
|
700
|
+
super(message);
|
|
701
|
+
this.code = code;
|
|
702
|
+
this.status = status;
|
|
703
|
+
this.serverCode = serverCode;
|
|
704
|
+
this.name = "AgentAuthorityError";
|
|
705
|
+
}
|
|
706
|
+
code;
|
|
707
|
+
status;
|
|
708
|
+
serverCode;
|
|
709
|
+
};
|
|
710
|
+
function isRecord(value) {
|
|
711
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
712
|
+
}
|
|
713
|
+
function isIsoDate(value) {
|
|
714
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
715
|
+
}
|
|
716
|
+
function exactTarget(value, expected) {
|
|
717
|
+
if (!isRecord(value) || value.kind !== expected.kind) return false;
|
|
718
|
+
return expected.kind === "oauth-code" ? value.requestId === expected.requestId && Object.keys(value).length === 2 : value.userCode === expected.userCode && Object.keys(value).length === 2;
|
|
719
|
+
}
|
|
720
|
+
function validTarget(target) {
|
|
721
|
+
return target.kind === "oauth-code" ? OAUTH_REQUEST_ID.test(target.requestId) : DEVICE_USER_CODE.test(target.userCode);
|
|
722
|
+
}
|
|
723
|
+
function validAtomic(value) {
|
|
724
|
+
if (!POSITIVE_ATOMIC.test(value)) return false;
|
|
725
|
+
try {
|
|
726
|
+
return BigInt(value) <= U64_MAX_ATOMIC;
|
|
727
|
+
} catch {
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
function validReasons(reasons) {
|
|
732
|
+
return reasons.length <= 32 && reasons.every(
|
|
733
|
+
(reason) => /^[a-z0-9][a-z0-9._:-]{0,63}$/.test(reason)
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
function validRule(rule) {
|
|
737
|
+
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);
|
|
738
|
+
if (!base) return false;
|
|
739
|
+
if (rule.action === "pay") {
|
|
740
|
+
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;
|
|
741
|
+
}
|
|
742
|
+
return Number.isInteger(rule.maxSlippageBps) && rule.maxSlippageBps >= 0 && rule.maxSlippageBps <= 1e4 && Number.isInteger(rule.maxPriceImpactBps) && rule.maxPriceImpactBps >= 0 && rule.maxPriceImpactBps <= 1e4;
|
|
743
|
+
}
|
|
744
|
+
function sameArray(actual, expected) {
|
|
745
|
+
return Array.isArray(actual) && actual.length === expected.length && actual.every((value, index) => value === expected[index]);
|
|
746
|
+
}
|
|
747
|
+
function exactRule(value, expected) {
|
|
748
|
+
if (!isRecord(value) || typeof value.id !== "string" || !UUID.test(value.id)) {
|
|
749
|
+
return false;
|
|
750
|
+
}
|
|
751
|
+
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);
|
|
752
|
+
if (!common) return false;
|
|
753
|
+
if (expected.action === "pay") {
|
|
754
|
+
return value.protocolId === expected.protocolId && value.protocolVersion === expected.protocolVersion && sameArray(value.allowedSchemes, expected.allowedSchemes) && value.counterpartyScope === expected.counterpartyScope;
|
|
755
|
+
}
|
|
756
|
+
return value.maxSlippageBps === expected.maxSlippageBps && value.maxPriceImpactBps === expected.maxPriceImpactBps;
|
|
757
|
+
}
|
|
758
|
+
function exactRules(value, expected) {
|
|
759
|
+
return Array.isArray(value) && value.length === expected.length && value.every((rule, index) => exactRule(rule, expected[index]));
|
|
760
|
+
}
|
|
761
|
+
async function refusal(response) {
|
|
762
|
+
const payload = await response.json().catch(() => null);
|
|
763
|
+
const serverCode = isRecord(payload) ? typeof payload.code === "string" ? payload.code : typeof payload.error === "string" ? payload.error : null : null;
|
|
764
|
+
if (response.status === 401) {
|
|
765
|
+
throw new AgentAuthorityError(
|
|
766
|
+
"owner_required",
|
|
767
|
+
"Sign in as this wallet owner before granting agent authority.",
|
|
768
|
+
response.status,
|
|
769
|
+
serverCode
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
throw new AgentAuthorityError(
|
|
773
|
+
"request_refused",
|
|
774
|
+
serverCode ?? `agent_authority_${response.status}`,
|
|
775
|
+
response.status,
|
|
776
|
+
serverCode
|
|
777
|
+
);
|
|
778
|
+
}
|
|
779
|
+
function usdcAtomic(value) {
|
|
780
|
+
const trimmed = value.trim();
|
|
781
|
+
const match = USDC_DECIMAL.exec(trimmed);
|
|
782
|
+
if (!match) return null;
|
|
783
|
+
const [whole = "0"] = trimmed.split(".");
|
|
784
|
+
const fraction = (match[2] ?? "").padEnd(6, "0");
|
|
785
|
+
const atomic = BigInt(whole) * 1000000n + BigInt(fraction || "0");
|
|
786
|
+
return atomic > 0n ? atomic.toString() : null;
|
|
787
|
+
}
|
|
788
|
+
function noCustomX402Limits(nowUnixMs = Date.now()) {
|
|
789
|
+
if (!Number.isSafeInteger(nowUnixMs) || nowUnixMs < 0) {
|
|
790
|
+
throw new AgentAuthorityError("invalid_input", "The current time is invalid.");
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
perPaymentAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
|
|
794
|
+
dailyAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
|
|
795
|
+
aggregateAtomic: MAX_AUTHORITY_AMOUNT_ATOMIC,
|
|
796
|
+
expiresAt: new Date(
|
|
797
|
+
nowUnixMs + NO_CUSTOM_LIMIT_TTL_DAYS * 864e5
|
|
798
|
+
).toISOString()
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
function validateBoundedX402Draft(draft, nowUnixMs = Date.now()) {
|
|
802
|
+
const perPaymentAtomic = usdcAtomic(draft.perPaymentUsd);
|
|
803
|
+
if (!perPaymentAtomic || BigInt(perPaymentAtomic) > U64_MAX_ATOMIC) {
|
|
804
|
+
return {
|
|
805
|
+
ok: false,
|
|
806
|
+
field: "perPaymentUsd",
|
|
807
|
+
message: "Enter a valid per-payment limit with no more than 6 decimal places."
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
const dailyAtomic = usdcAtomic(draft.dailyUsd);
|
|
811
|
+
if (!dailyAtomic || BigInt(dailyAtomic) > U64_MAX_ATOMIC) {
|
|
812
|
+
return {
|
|
813
|
+
ok: false,
|
|
814
|
+
field: "dailyUsd",
|
|
815
|
+
message: "Enter a valid daily limit with no more than 6 decimal places."
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
const aggregateAtomic = usdcAtomic(draft.aggregateUsd);
|
|
819
|
+
if (!aggregateAtomic || BigInt(aggregateAtomic) > U64_MAX_ATOMIC) {
|
|
820
|
+
return {
|
|
821
|
+
ok: false,
|
|
822
|
+
field: "aggregateUsd",
|
|
823
|
+
message: "Enter a valid total limit with no more than 6 decimal places."
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
if (BigInt(perPaymentAtomic) > BigInt(dailyAtomic)) {
|
|
827
|
+
return {
|
|
828
|
+
ok: false,
|
|
829
|
+
field: "perPaymentUsd",
|
|
830
|
+
message: "The per-payment limit cannot exceed the daily limit."
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
if (BigInt(dailyAtomic) > BigInt(aggregateAtomic)) {
|
|
834
|
+
return {
|
|
835
|
+
ok: false,
|
|
836
|
+
field: "dailyUsd",
|
|
837
|
+
message: "The daily limit cannot exceed the total limit."
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
const expiresInDays = Number(draft.expiresInDays);
|
|
841
|
+
if (!/^\d{1,3}$/.test(draft.expiresInDays) || !Number.isInteger(expiresInDays) || expiresInDays < 1 || expiresInDays > 366) {
|
|
842
|
+
return {
|
|
843
|
+
ok: false,
|
|
844
|
+
field: "expiresInDays",
|
|
845
|
+
message: "Choose an expiry between 1 and 366 days."
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
if (!Number.isSafeInteger(nowUnixMs) || nowUnixMs < 0) {
|
|
849
|
+
throw new AgentAuthorityError("invalid_input", "The current time is invalid.");
|
|
850
|
+
}
|
|
851
|
+
return {
|
|
852
|
+
ok: true,
|
|
853
|
+
limits: {
|
|
854
|
+
perPaymentAtomic,
|
|
855
|
+
dailyAtomic,
|
|
856
|
+
aggregateAtomic,
|
|
857
|
+
expiresAt: new Date(nowUnixMs + expiresInDays * 864e5).toISOString()
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
function buildX402PaymentRule(limits, approval = {}) {
|
|
862
|
+
const rule = {
|
|
863
|
+
assetId: X402_ASSET,
|
|
864
|
+
action: "pay",
|
|
865
|
+
protocolId: X402_PROTOCOL_ID,
|
|
866
|
+
protocolVersion: X402_PROTOCOL_VERSION,
|
|
867
|
+
allowedSchemes: X402_ALLOWED_SCHEMES,
|
|
868
|
+
counterpartyScope: X402_COUNTERPARTY_SCOPE,
|
|
869
|
+
maxAmountAtomic: limits.perPaymentAtomic,
|
|
870
|
+
maxDailyAmountAtomic: limits.dailyAtomic,
|
|
871
|
+
maxAggregateAmountAtomic: limits.aggregateAtomic,
|
|
872
|
+
approvalMode: approval.mode ?? "never",
|
|
873
|
+
approvalThresholdAtomic: approval.thresholdAtomic ?? null,
|
|
874
|
+
approvalEscalationReasons: approval.escalationReasons ?? [],
|
|
875
|
+
blockedEscalationReasons: approval.blockedReasons ?? []
|
|
876
|
+
};
|
|
877
|
+
if (!validRule(rule)) {
|
|
878
|
+
throw new AgentAuthorityError("invalid_input", "The x402 authority rule is invalid.");
|
|
879
|
+
}
|
|
880
|
+
return Object.freeze(rule);
|
|
881
|
+
}
|
|
882
|
+
function buildAgentAuthorityRequest(input) {
|
|
883
|
+
const agentLabel = input.agentLabel === void 0 ? null : input.agentLabel;
|
|
884
|
+
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)) {
|
|
885
|
+
throw new AgentAuthorityError("invalid_input", "The agent authority request is invalid.");
|
|
886
|
+
}
|
|
887
|
+
return Object.freeze({
|
|
888
|
+
expectedVaultPda: input.expectedVaultPda,
|
|
889
|
+
target: input.target,
|
|
890
|
+
agentLabel,
|
|
891
|
+
grantExpiresAt: input.grantExpiresAt,
|
|
892
|
+
rules: Object.freeze([...input.rules])
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
function buildBoundedX402BootstrapRequest(input) {
|
|
896
|
+
return buildAgentAuthorityRequest({
|
|
897
|
+
target: { kind: "oauth-code", requestId: input.requestId },
|
|
898
|
+
expectedVaultPda: input.expectedVaultPda,
|
|
899
|
+
agentLabel: input.agentLabel.trim(),
|
|
900
|
+
grantExpiresAt: input.limits.expiresAt,
|
|
901
|
+
rules: [buildX402PaymentRule(input.limits)]
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
async function beginAgentAuthority(input) {
|
|
905
|
+
if (!input.ownerAccessToken || !UUID.test(input.operationId)) {
|
|
906
|
+
throw new AgentAuthorityError(
|
|
907
|
+
"invalid_input",
|
|
908
|
+
"An owner session and operation id are required."
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
const request = buildAgentAuthorityRequest(input.request);
|
|
912
|
+
const response = await (input.fetchImpl ?? fetch)(
|
|
913
|
+
`${resolveDexterApiBase(input.apiBase)}/api/passkey-vault/governed-assets/agent/mandates/bootstrap`,
|
|
914
|
+
{
|
|
915
|
+
method: "POST",
|
|
916
|
+
headers: {
|
|
917
|
+
authorization: `Bearer ${input.ownerAccessToken}`,
|
|
918
|
+
"content-type": "application/json",
|
|
919
|
+
"idempotency-key": input.operationId
|
|
920
|
+
},
|
|
921
|
+
body: JSON.stringify(request),
|
|
922
|
+
cache: "no-store"
|
|
923
|
+
}
|
|
924
|
+
);
|
|
925
|
+
if (!response.ok) return refusal(response);
|
|
926
|
+
const payload = await response.json();
|
|
927
|
+
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)) {
|
|
928
|
+
throw new AgentAuthorityError(
|
|
929
|
+
"invalid_response",
|
|
930
|
+
"Dexter returned an invalid agent-authority challenge."
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
return {
|
|
934
|
+
namespace: AGENT_AUTHORITY_NAMESPACE,
|
|
935
|
+
status: "owner_authorization_required",
|
|
936
|
+
selectionId: payload.selectionId,
|
|
937
|
+
operationId: input.operationId,
|
|
938
|
+
ownerVaultPda: payload.ownerVaultPda,
|
|
939
|
+
target: payload.target,
|
|
940
|
+
agentId: payload.agentId,
|
|
941
|
+
grantId: payload.grantId,
|
|
942
|
+
validFrom: payload.validFrom,
|
|
943
|
+
grantExpiresAt: payload.grantExpiresAt,
|
|
944
|
+
rules: payload.rules,
|
|
945
|
+
rulesDigest: payload.rulesDigest,
|
|
946
|
+
authorizationId: payload.authorizationId,
|
|
947
|
+
authorizationExpiresAt: payload.authorizationExpiresAt,
|
|
948
|
+
authorizationOptions: payload.authorizationOptions,
|
|
949
|
+
selectionDigest: payload.selectionDigest,
|
|
950
|
+
request
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
async function stageAgentAuthority(input) {
|
|
954
|
+
if (!input.ownerAccessToken || !isRecord(input.credential)) {
|
|
955
|
+
throw new AgentAuthorityError(
|
|
956
|
+
"invalid_input",
|
|
957
|
+
"The owner authorization result is missing."
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
const response = await (input.fetchImpl ?? fetch)(
|
|
961
|
+
`${resolveDexterApiBase(input.apiBase)}/api/passkey-vault/governed-assets/agent/mandates/bootstrap/${input.authorization.selectionId}/complete`,
|
|
962
|
+
{
|
|
963
|
+
method: "POST",
|
|
964
|
+
headers: {
|
|
965
|
+
authorization: `Bearer ${input.ownerAccessToken}`,
|
|
966
|
+
"content-type": "application/json"
|
|
967
|
+
},
|
|
968
|
+
body: JSON.stringify({
|
|
969
|
+
authorizationId: input.authorization.authorizationId,
|
|
970
|
+
credential: input.credential
|
|
971
|
+
}),
|
|
972
|
+
cache: "no-store"
|
|
973
|
+
}
|
|
974
|
+
);
|
|
975
|
+
if (!response.ok) return refusal(response);
|
|
976
|
+
const payload = await response.json();
|
|
977
|
+
const authorization = input.authorization;
|
|
978
|
+
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) {
|
|
979
|
+
throw new AgentAuthorityError(
|
|
980
|
+
"invalid_response",
|
|
981
|
+
"Dexter returned an invalid staged agent-authority receipt."
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
return payload;
|
|
985
|
+
}
|
|
986
|
+
async function beginBoundedX402Authority(input) {
|
|
987
|
+
return beginAgentAuthority({
|
|
988
|
+
ownerAccessToken: input.accessToken,
|
|
989
|
+
operationId: input.operationId,
|
|
990
|
+
request: input.request,
|
|
991
|
+
apiBase: input.apiBase,
|
|
992
|
+
fetchImpl: input.fetchImpl
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
async function stageBoundedX402Authority(input) {
|
|
996
|
+
return stageAgentAuthority({
|
|
997
|
+
ownerAccessToken: input.accessToken,
|
|
998
|
+
authorization: input.authorization,
|
|
999
|
+
credential: input.credential,
|
|
1000
|
+
apiBase: input.apiBase,
|
|
1001
|
+
fetchImpl: input.fetchImpl
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
function exactAgentAuthorityApprovalRedirect(value, expectedGrantId) {
|
|
1005
|
+
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) {
|
|
1006
|
+
throw new AgentAuthorityError(
|
|
1007
|
+
"invalid_response",
|
|
1008
|
+
"Dexter did not return the exact activated agent authority."
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
return value.redirect_url;
|
|
1012
|
+
}
|
|
1013
|
+
function exactBoundedX402ApprovalRedirect(value, expectedGrantId) {
|
|
1014
|
+
try {
|
|
1015
|
+
return exactAgentAuthorityApprovalRedirect(value, expectedGrantId);
|
|
1016
|
+
} catch (error) {
|
|
1017
|
+
if (error instanceof AgentAuthorityError) {
|
|
1018
|
+
throw new AgentAuthorityError(
|
|
1019
|
+
error.code,
|
|
1020
|
+
"Dexter did not return the exact activated payment authority.",
|
|
1021
|
+
error.status,
|
|
1022
|
+
error.serverCode
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
throw error;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
function validAuthorityStatus(value) {
|
|
1029
|
+
if (!isRecord(value) || value.namespace !== AGENT_AUTHORITY_STATUS_NAMESPACE || !["view_only", "bounded_payment_authority", "unavailable"].includes(
|
|
1030
|
+
String(value.mode)
|
|
1031
|
+
) || 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)) {
|
|
1032
|
+
return false;
|
|
1033
|
+
}
|
|
1034
|
+
if (value.principal !== null) {
|
|
1035
|
+
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;
|
|
1036
|
+
}
|
|
1037
|
+
const activeRole = value.activeRole;
|
|
1038
|
+
if (activeRole.status === "active") {
|
|
1039
|
+
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;
|
|
1040
|
+
} else if (!["not-applicable", "unavailable"].includes(String(activeRole.status)) || typeof activeRole.reason !== "string") {
|
|
1041
|
+
return false;
|
|
1042
|
+
}
|
|
1043
|
+
if (value.scopes !== null) {
|
|
1044
|
+
const scopes = value.scopes;
|
|
1045
|
+
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;
|
|
1046
|
+
}
|
|
1047
|
+
if (value.capacity !== null) {
|
|
1048
|
+
const capacity = value.capacity;
|
|
1049
|
+
if (!isRecord(capacity)) return false;
|
|
1050
|
+
const amounts = [
|
|
1051
|
+
capacity.maximumPerCallAmountAtomic,
|
|
1052
|
+
capacity.remainingPerCallAmountAtomic,
|
|
1053
|
+
capacity.maximumDailyAmountAtomic,
|
|
1054
|
+
capacity.usedDailyAmountAtomic,
|
|
1055
|
+
capacity.remainingDailyAmountAtomic,
|
|
1056
|
+
capacity.maximumAggregateAmountAtomic,
|
|
1057
|
+
capacity.usedAggregateAmountAtomic,
|
|
1058
|
+
capacity.remainingAggregateAmountAtomic
|
|
1059
|
+
];
|
|
1060
|
+
if (!amounts.every(
|
|
1061
|
+
(amount) => typeof amount === "string" && NON_NEGATIVE_ATOMIC.test(amount)
|
|
1062
|
+
) || !isIsoDate(capacity.evaluatedAt) || typeof capacity.snapshotDigest !== "string" || !DIGEST.test(capacity.snapshotDigest)) return false;
|
|
1063
|
+
}
|
|
1064
|
+
if (value.mode === "bounded_payment_authority") {
|
|
1065
|
+
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") {
|
|
1066
|
+
return false;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
return true;
|
|
1070
|
+
}
|
|
1071
|
+
async function readAgentAuthority(input) {
|
|
1072
|
+
if (!input.accessToken) {
|
|
1073
|
+
throw new AgentAuthorityError("invalid_input", "An OpenDexter access token is required.");
|
|
1074
|
+
}
|
|
1075
|
+
const response = await (input.fetchImpl ?? fetch)(
|
|
1076
|
+
`${resolveDexterApiBase(input.apiBase)}/api/connector/oauth/authority`,
|
|
1077
|
+
{
|
|
1078
|
+
headers: { authorization: `Bearer ${input.accessToken}` },
|
|
1079
|
+
cache: "no-store"
|
|
1080
|
+
}
|
|
1081
|
+
);
|
|
1082
|
+
if (!response.ok) return refusal(response);
|
|
1083
|
+
const payload = await response.json();
|
|
1084
|
+
if (!validAuthorityStatus(payload)) {
|
|
1085
|
+
throw new AgentAuthorityError(
|
|
1086
|
+
"invalid_response",
|
|
1087
|
+
"Dexter returned an invalid agent-authority status."
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
return payload;
|
|
1091
|
+
}
|
|
337
1092
|
export {
|
|
338
|
-
|
|
1093
|
+
AGENT_AUTHORITY_NAMESPACE,
|
|
1094
|
+
AGENT_AUTHORITY_STATUS_NAMESPACE,
|
|
1095
|
+
AgentAuthorityError,
|
|
339
1096
|
AgentSpendError,
|
|
1097
|
+
AgentAuthorityError as BoundedX402AuthorityError,
|
|
340
1098
|
ConnectError,
|
|
1099
|
+
MAX_AUTHORITY_AMOUNT_ATOMIC,
|
|
341
1100
|
SESSION_TTL_30D,
|
|
1101
|
+
WALLET_ACCOUNT_BINDING_PATH,
|
|
1102
|
+
WALLET_PROOF_SESSION_STORAGE_PREFIX,
|
|
1103
|
+
WalletAccountRelationController,
|
|
1104
|
+
X402_ALLOWED_SCHEMES,
|
|
1105
|
+
X402_ASSET,
|
|
1106
|
+
X402_COUNTERPARTY_SCOPE,
|
|
1107
|
+
X402_PROTOCOL_ID,
|
|
1108
|
+
X402_PROTOCOL_VERSION,
|
|
1109
|
+
accountBindingCandidate,
|
|
342
1110
|
assembleAgentSpendStatus,
|
|
343
1111
|
authoredPolicy,
|
|
1112
|
+
beginAgentAuthority,
|
|
1113
|
+
beginBoundedX402Authority,
|
|
1114
|
+
buildAgentAuthorityRequest,
|
|
1115
|
+
buildBoundedX402BootstrapRequest,
|
|
1116
|
+
buildX402PaymentRule,
|
|
344
1117
|
ceremonyPhaseLabel,
|
|
345
|
-
|
|
1118
|
+
connectDexterIdentity,
|
|
346
1119
|
createAnonServerPolicy,
|
|
1120
|
+
createDexterControlModel,
|
|
1121
|
+
createDexterIdentityCoordinator,
|
|
347
1122
|
createPasskeySigner,
|
|
348
1123
|
createWallet,
|
|
1124
|
+
createWalletAccountBindingClient,
|
|
1125
|
+
createWalletProofSessionStore,
|
|
349
1126
|
describeAgentSpendError,
|
|
350
|
-
|
|
1127
|
+
disconnectDexterIdentity,
|
|
351
1128
|
enableAgentSpend,
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
listWallets,
|
|
356
|
-
passkeyLogin,
|
|
1129
|
+
exactAgentAuthorityApprovalRedirect,
|
|
1130
|
+
exactBoundedX402ApprovalRedirect,
|
|
1131
|
+
noCustomX402Limits,
|
|
357
1132
|
passkeySignalSupport,
|
|
358
1133
|
prunePasskey,
|
|
1134
|
+
readAgentAuthority,
|
|
359
1135
|
recoverWallet,
|
|
360
1136
|
renamePasskey,
|
|
361
|
-
resolveIdentity,
|
|
362
1137
|
revokeAgentSpend,
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
switchWallet,
|
|
1138
|
+
stageAgentAuthority,
|
|
1139
|
+
stageBoundedX402Authority,
|
|
366
1140
|
syncAcceptedPasskeys,
|
|
367
|
-
usdToAtomic
|
|
1141
|
+
usdToAtomic,
|
|
1142
|
+
validateBoundedX402Draft,
|
|
1143
|
+
walletBindingCandidate,
|
|
1144
|
+
walletProofSessionStore
|
|
368
1145
|
};
|