@muhaven/mcp 0.2.1 → 0.2.3
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/CHANGELOG.md +125 -0
- package/dist/broker.cjs +1092 -149
- package/dist/broker.js +1093 -150
- package/dist/index.cjs +2230 -231
- package/dist/index.d.cts +769 -16
- package/dist/index.d.ts +769 -16
- package/dist/index.js +2216 -220
- package/manifest.json +39 -3
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { unlink, readFile, mkdir, chmod, writeFile, stat } from 'fs/promises';
|
|
1
|
+
import { unlink, readFile, mkdir, chmod, writeFile, rename, readdir, stat } from 'fs/promises';
|
|
2
2
|
import 'fs';
|
|
3
3
|
import { join, dirname } from 'path';
|
|
4
4
|
import { fileURLToPath } from 'url';
|
|
@@ -6,9 +6,13 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
|
6
6
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
7
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
8
8
|
import { z, ZodError } from 'zod';
|
|
9
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
9
10
|
import { platform, homedir } from 'os';
|
|
10
11
|
import { connect, createServer } from 'net';
|
|
11
|
-
import {
|
|
12
|
+
import { setTimeout as setTimeout$1 } from 'timers/promises';
|
|
13
|
+
import { parseAbi, toFunctionSelector, encodeFunctionData, encodePacked, pad, concatHex, decodeAbiParameters } from 'viem';
|
|
14
|
+
import { createHash, randomBytes } from 'crypto';
|
|
15
|
+
import { getUserOperationHash } from 'viem/account-abstraction';
|
|
12
16
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
13
17
|
|
|
14
18
|
// src/server.ts
|
|
@@ -18,6 +22,10 @@ var DEFAULT_REQUEST_TIMEOUT_MS = 15e3;
|
|
|
18
22
|
var DEFAULT_BROKER_TIMEOUT_MS = 5e3;
|
|
19
23
|
var DEFAULT_BROKER_MAX_BYTES = 64 * 1024;
|
|
20
24
|
var DEFAULT_JWT_CACHE_TTL_SEC = 30;
|
|
25
|
+
var DEFAULT_BUNDLER_TIMEOUT_MS = 2e4;
|
|
26
|
+
var DEFAULT_CHAIN_ID = 421614;
|
|
27
|
+
var DEFAULT_ENTRY_POINT_ADDRESS = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
|
|
28
|
+
var ADDRESS_HEX_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
21
29
|
function defaultBrokerEndpoint() {
|
|
22
30
|
if (platform() === "win32") {
|
|
23
31
|
const user = process.env.USERNAME ?? "default";
|
|
@@ -93,6 +101,35 @@ function loadMcpConfig(env = process.env) {
|
|
|
93
101
|
const requestTimeoutMs = readEnvInt("MUHAVEN_REQUEST_TIMEOUT_MS", DEFAULT_REQUEST_TIMEOUT_MS, env);
|
|
94
102
|
const brokerTimeoutMs = readEnvInt("MUHAVEN_BROKER_TIMEOUT_MS", DEFAULT_BROKER_TIMEOUT_MS, env);
|
|
95
103
|
const jwtCacheTtlSec = readEnvInt("MUHAVEN_JWT_CACHE_TTL_SEC", DEFAULT_JWT_CACHE_TTL_SEC, env);
|
|
104
|
+
const bundlerUrlRaw = readEnv("MUHAVEN_BUNDLER_URL", env);
|
|
105
|
+
let bundlerUrl;
|
|
106
|
+
if (bundlerUrlRaw !== void 0) {
|
|
107
|
+
const validationErr = validatePublicUrlEnv("MUHAVEN_BUNDLER_URL", bundlerUrlRaw);
|
|
108
|
+
if (validationErr) throw new Error(validationErr);
|
|
109
|
+
bundlerUrl = trimTrailingSlash(bundlerUrlRaw);
|
|
110
|
+
}
|
|
111
|
+
const bundlerTimeoutMs = readEnvInt("MUHAVEN_BUNDLER_TIMEOUT_MS", DEFAULT_BUNDLER_TIMEOUT_MS, env);
|
|
112
|
+
const chainId = readEnvInt("MUHAVEN_CHAIN_ID", DEFAULT_CHAIN_ID, env);
|
|
113
|
+
const subscriptionAddressRaw = readEnv("MUHAVEN_SUBSCRIPTION_ADDRESS", env);
|
|
114
|
+
let subscriptionAddress;
|
|
115
|
+
if (subscriptionAddressRaw !== void 0) {
|
|
116
|
+
if (!ADDRESS_HEX_RE.test(subscriptionAddressRaw)) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`MUHAVEN_SUBSCRIPTION_ADDRESS must be a 0x-prefixed 20-byte hex string (got ${JSON.stringify(subscriptionAddressRaw)})`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
subscriptionAddress = subscriptionAddressRaw.toLowerCase();
|
|
122
|
+
}
|
|
123
|
+
const entryPointAddressRaw = readEnv("MUHAVEN_ENTRY_POINT", env);
|
|
124
|
+
let entryPointAddress = DEFAULT_ENTRY_POINT_ADDRESS;
|
|
125
|
+
if (entryPointAddressRaw !== void 0) {
|
|
126
|
+
if (!ADDRESS_HEX_RE.test(entryPointAddressRaw)) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`MUHAVEN_ENTRY_POINT must be a 0x-prefixed 20-byte hex string (got ${JSON.stringify(entryPointAddressRaw)})`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
entryPointAddress = entryPointAddressRaw.toLowerCase();
|
|
132
|
+
}
|
|
96
133
|
return {
|
|
97
134
|
backendBaseUrl,
|
|
98
135
|
dashboardBaseUrl,
|
|
@@ -101,7 +138,12 @@ function loadMcpConfig(env = process.env) {
|
|
|
101
138
|
requestTimeoutMs,
|
|
102
139
|
brokerTimeoutMs,
|
|
103
140
|
allowedBackendHosts: deriveAllowedHosts(backendBaseUrl),
|
|
104
|
-
jwtCacheTtlSec
|
|
141
|
+
jwtCacheTtlSec,
|
|
142
|
+
bundlerUrl,
|
|
143
|
+
bundlerTimeoutMs,
|
|
144
|
+
chainId,
|
|
145
|
+
subscriptionAddress,
|
|
146
|
+
entryPointAddress
|
|
105
147
|
};
|
|
106
148
|
}
|
|
107
149
|
var PRIVKEY_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
@@ -136,16 +178,366 @@ function loadBrokerConfig(env = process.env) {
|
|
|
136
178
|
dashboardBaseUrl
|
|
137
179
|
};
|
|
138
180
|
}
|
|
181
|
+
|
|
182
|
+
// src/broker/protocol.ts
|
|
183
|
+
var BROKER_PROTOCOL_VERSION = "0.4.0";
|
|
184
|
+
var HASH_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
185
|
+
var ADDRESS_HEX_RE2 = /^0x[0-9a-fA-F]{40}$/;
|
|
186
|
+
var SELECTOR_HEX_RE = /^0x[0-9a-fA-F]{8}$/;
|
|
187
|
+
var HEX_PREFIXED_RE = /^0x[0-9a-fA-F]*$/;
|
|
188
|
+
var JWT_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
189
|
+
var SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
190
|
+
var UINT256_DEC_RE = /^(0|[1-9][0-9]{0,77})$/;
|
|
191
|
+
var MAX_CALLDATA_HEX_LEN = 2e5;
|
|
192
|
+
function isHashHex(value) {
|
|
193
|
+
return typeof value === "string" && HASH_HEX_RE.test(value);
|
|
194
|
+
}
|
|
195
|
+
function isAddressHex(value) {
|
|
196
|
+
return typeof value === "string" && ADDRESS_HEX_RE2.test(value);
|
|
197
|
+
}
|
|
198
|
+
function isSelectorHex(value) {
|
|
199
|
+
return typeof value === "string" && SELECTOR_HEX_RE.test(value);
|
|
200
|
+
}
|
|
201
|
+
function isHexPrefixed(value) {
|
|
202
|
+
return typeof value === "string" && HEX_PREFIXED_RE.test(value);
|
|
203
|
+
}
|
|
204
|
+
function isJwtShape(value) {
|
|
205
|
+
return typeof value === "string" && value.length <= 8192 && JWT_RE.test(value);
|
|
206
|
+
}
|
|
207
|
+
function isSessionIdShape(value) {
|
|
208
|
+
return typeof value === "string" && SESSION_ID_RE.test(value);
|
|
209
|
+
}
|
|
210
|
+
function isUint256DecString(value) {
|
|
211
|
+
return typeof value === "string" && UINT256_DEC_RE.test(value);
|
|
212
|
+
}
|
|
213
|
+
var UINT256_MAX = (1n << 256n) - 1n;
|
|
214
|
+
function isUint256InRange(value) {
|
|
215
|
+
if (!isUint256DecString(value)) return false;
|
|
216
|
+
return BigInt(value) <= UINT256_MAX;
|
|
217
|
+
}
|
|
218
|
+
function parseSelectorCap(raw) {
|
|
219
|
+
if (typeof raw !== "object" || raw === null) {
|
|
220
|
+
return { error: "selectorCap must be an object" };
|
|
221
|
+
}
|
|
222
|
+
const obj = raw;
|
|
223
|
+
if (!isSelectorHex(obj.selector)) {
|
|
224
|
+
return { error: "selectorCap.selector must be a 4-byte 0x-hex" };
|
|
225
|
+
}
|
|
226
|
+
const capArgIndex = obj.capArgIndex;
|
|
227
|
+
const maxAmount = obj.maxAmount;
|
|
228
|
+
const indexIsNull = capArgIndex === null;
|
|
229
|
+
const amountIsNull = maxAmount === null;
|
|
230
|
+
if (indexIsNull !== amountIsNull) {
|
|
231
|
+
return {
|
|
232
|
+
error: "selectorCap.capArgIndex and selectorCap.maxAmount must both be null or both non-null"
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
if (!indexIsNull) {
|
|
236
|
+
if (typeof capArgIndex !== "number" || !Number.isInteger(capArgIndex) || capArgIndex < 0 || capArgIndex > 31) {
|
|
237
|
+
return {
|
|
238
|
+
error: "selectorCap.capArgIndex must be an integer in [0, 31] (max 32 ABI words)"
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
if (typeof maxAmount !== "string" || !isUint256InRange(maxAmount)) {
|
|
242
|
+
return { error: "selectorCap.maxAmount must be a uint256 decimal string \u2264 2^256-1" };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
selector: obj.selector.toLowerCase(),
|
|
247
|
+
capArgIndex: indexIsNull ? null : capArgIndex,
|
|
248
|
+
maxAmount: indexIsNull ? null : maxAmount
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function isOptionalHash32(value) {
|
|
252
|
+
return value === void 0 || isHashHex(value);
|
|
253
|
+
}
|
|
254
|
+
function isOptionalPermissionId(value) {
|
|
255
|
+
return value === void 0 || isSelectorHex(value);
|
|
256
|
+
}
|
|
257
|
+
function parsePolicySnapshot(raw) {
|
|
258
|
+
if (typeof raw !== "object" || raw === null) {
|
|
259
|
+
return { error: "snapshot must be a JSON object" };
|
|
260
|
+
}
|
|
261
|
+
const obj = raw;
|
|
262
|
+
if (!isSessionIdShape(obj.sessionId)) {
|
|
263
|
+
return { error: "snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]" };
|
|
264
|
+
}
|
|
265
|
+
if (obj.mode !== "scoped") {
|
|
266
|
+
return { error: "snapshot.mode must be 'scoped' (wildcard ships in Slice 4)" };
|
|
267
|
+
}
|
|
268
|
+
if (!isAddressHex(obj.signerAddress)) {
|
|
269
|
+
return { error: "snapshot.signerAddress must be a 0x-prefixed 20-byte hex" };
|
|
270
|
+
}
|
|
271
|
+
const targetContracts = obj.targetContracts;
|
|
272
|
+
if (!Array.isArray(targetContracts) || targetContracts.length === 0 || targetContracts.length > 32 || !targetContracts.every(isAddressHex)) {
|
|
273
|
+
return {
|
|
274
|
+
error: "snapshot.targetContracts must be a 1..32-element array of 0x-addresses"
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
const rawCaps = obj.selectorCaps;
|
|
278
|
+
if (!Array.isArray(rawCaps) || rawCaps.length === 0 || rawCaps.length > 32) {
|
|
279
|
+
return { error: "snapshot.selectorCaps must be a 1..32-element array" };
|
|
280
|
+
}
|
|
281
|
+
const parsedCaps = [];
|
|
282
|
+
const seenSelectors = /* @__PURE__ */ new Set();
|
|
283
|
+
for (const c of rawCaps) {
|
|
284
|
+
const parsed = parseSelectorCap(c);
|
|
285
|
+
if ("error" in parsed) return { error: `selectorCaps: ${parsed.error}` };
|
|
286
|
+
if (seenSelectors.has(parsed.selector)) {
|
|
287
|
+
return { error: `selectorCaps: duplicate selector ${parsed.selector}` };
|
|
288
|
+
}
|
|
289
|
+
seenSelectors.add(parsed.selector);
|
|
290
|
+
parsedCaps.push(parsed);
|
|
291
|
+
}
|
|
292
|
+
if (typeof obj.validUntilSec !== "number" || !Number.isFinite(obj.validUntilSec) || obj.validUntilSec <= 0) {
|
|
293
|
+
return { error: "snapshot.validUntilSec must be a positive number" };
|
|
294
|
+
}
|
|
295
|
+
if (typeof obj.mintedAtSec !== "number" || !Number.isFinite(obj.mintedAtSec) || obj.mintedAtSec <= 0) {
|
|
296
|
+
return { error: "snapshot.mintedAtSec must be a positive number" };
|
|
297
|
+
}
|
|
298
|
+
if (!isOptionalHash32(obj.consentActionHash)) {
|
|
299
|
+
return { error: "snapshot.consentActionHash must be a 0x-prefixed 32-byte hex when provided" };
|
|
300
|
+
}
|
|
301
|
+
if (!isOptionalHash32(obj.consentTextSha256)) {
|
|
302
|
+
return { error: "snapshot.consentTextSha256 must be a 0x-prefixed 32-byte hex when provided" };
|
|
303
|
+
}
|
|
304
|
+
if (!isOptionalPermissionId(obj.permissionId)) {
|
|
305
|
+
return { error: "snapshot.permissionId must be a 0x-prefixed 4-byte hex when provided" };
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
sessionId: obj.sessionId,
|
|
309
|
+
mode: "scoped",
|
|
310
|
+
signerAddress: obj.signerAddress.toLowerCase(),
|
|
311
|
+
targetContracts: targetContracts.map(
|
|
312
|
+
(a) => a.toLowerCase()
|
|
313
|
+
),
|
|
314
|
+
selectorCaps: parsedCaps,
|
|
315
|
+
validUntilSec: obj.validUntilSec,
|
|
316
|
+
mintedAtSec: obj.mintedAtSec,
|
|
317
|
+
...obj.consentActionHash === void 0 ? {} : { consentActionHash: obj.consentActionHash.toLowerCase() },
|
|
318
|
+
...obj.consentTextSha256 === void 0 ? {} : { consentTextSha256: obj.consentTextSha256.toLowerCase() },
|
|
319
|
+
...obj.permissionId === void 0 ? {} : { permissionId: obj.permissionId.toLowerCase() }
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function parseBrokerRequest(line) {
|
|
323
|
+
let parsed;
|
|
324
|
+
try {
|
|
325
|
+
parsed = JSON.parse(line);
|
|
326
|
+
} catch {
|
|
327
|
+
return { type: "error", code: "invalid_request", message: "request is not valid JSON" };
|
|
328
|
+
}
|
|
329
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
330
|
+
return { type: "error", code: "invalid_request", message: "request must be a JSON object" };
|
|
331
|
+
}
|
|
332
|
+
const obj = parsed;
|
|
333
|
+
switch (obj.type) {
|
|
334
|
+
case "hello":
|
|
335
|
+
return { type: "hello" };
|
|
336
|
+
case "sign_hash": {
|
|
337
|
+
const hash = obj.hash;
|
|
338
|
+
if (!isHashHex(hash)) {
|
|
339
|
+
return {
|
|
340
|
+
type: "error",
|
|
341
|
+
code: "invalid_request",
|
|
342
|
+
message: "sign_hash.hash must be a 0x-prefixed 32-byte hex string"
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
const intent = obj.intent;
|
|
346
|
+
const intentValid = intent === void 0 || typeof intent === "object" && intent !== null && typeof intent.tool === "string";
|
|
347
|
+
if (!intentValid) {
|
|
348
|
+
return {
|
|
349
|
+
type: "error",
|
|
350
|
+
code: "invalid_request",
|
|
351
|
+
message: "sign_hash.intent.tool must be a string when provided"
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
type: "sign_hash",
|
|
356
|
+
hash,
|
|
357
|
+
...intent === void 0 ? {} : { intent }
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
case "store_jwt": {
|
|
361
|
+
const jwt = obj.jwt;
|
|
362
|
+
if (!isJwtShape(jwt)) {
|
|
363
|
+
return {
|
|
364
|
+
type: "error",
|
|
365
|
+
code: "invalid_request",
|
|
366
|
+
message: "store_jwt.jwt must be a JWT-shaped string \u22648192 chars"
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
const expiresAtSec = obj.expiresAtSec;
|
|
370
|
+
const expiresValid = expiresAtSec === void 0 || typeof expiresAtSec === "number" && Number.isFinite(expiresAtSec) && expiresAtSec > 0;
|
|
371
|
+
if (!expiresValid) {
|
|
372
|
+
return {
|
|
373
|
+
type: "error",
|
|
374
|
+
code: "invalid_request",
|
|
375
|
+
message: "store_jwt.expiresAtSec must be a positive number when provided"
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
type: "store_jwt",
|
|
380
|
+
jwt,
|
|
381
|
+
...expiresAtSec === void 0 ? {} : { expiresAtSec }
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
case "get_jwt":
|
|
385
|
+
return { type: "get_jwt" };
|
|
386
|
+
case "clear_jwt":
|
|
387
|
+
return { type: "clear_jwt" };
|
|
388
|
+
case "sign_userop": {
|
|
389
|
+
const sessionId = obj.sessionId;
|
|
390
|
+
if (!isSessionIdShape(sessionId)) {
|
|
391
|
+
return {
|
|
392
|
+
type: "error",
|
|
393
|
+
code: "invalid_request",
|
|
394
|
+
message: "sign_userop.sessionId must be 1-128 chars [A-Za-z0-9_-]"
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
const userOpHash = obj.userOpHash;
|
|
398
|
+
if (!isHashHex(userOpHash)) {
|
|
399
|
+
return {
|
|
400
|
+
type: "error",
|
|
401
|
+
code: "invalid_request",
|
|
402
|
+
message: "sign_userop.userOpHash must be a 0x-prefixed 32-byte hex string"
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
const innerCall = obj.innerCall;
|
|
406
|
+
if (typeof innerCall !== "object" || innerCall === null) {
|
|
407
|
+
return {
|
|
408
|
+
type: "error",
|
|
409
|
+
code: "invalid_request",
|
|
410
|
+
message: "sign_userop.innerCall must be an object with { target, callData }"
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
const ic = innerCall;
|
|
414
|
+
if (!isAddressHex(ic.target)) {
|
|
415
|
+
return {
|
|
416
|
+
type: "error",
|
|
417
|
+
code: "invalid_request",
|
|
418
|
+
message: "sign_userop.innerCall.target must be a 0x-prefixed 20-byte hex"
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
if (!isHexPrefixed(ic.callData) || ic.callData.length < 74 || ic.callData.length % 2 !== 0 || ic.callData.length > MAX_CALLDATA_HEX_LEN) {
|
|
422
|
+
return {
|
|
423
|
+
type: "error",
|
|
424
|
+
code: "invalid_request",
|
|
425
|
+
message: "sign_userop.innerCall.callData must be 0x-prefixed even-length hex \u226574 chars (selector + first uint256 arg) and \u2264200000 chars"
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
const intent = obj.intent;
|
|
429
|
+
let safeIntent;
|
|
430
|
+
if (intent !== void 0) {
|
|
431
|
+
if (typeof intent !== "object" || intent === null) {
|
|
432
|
+
return {
|
|
433
|
+
type: "error",
|
|
434
|
+
code: "invalid_request",
|
|
435
|
+
message: "sign_userop.intent must be an object when provided"
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
const intentObj = intent;
|
|
439
|
+
if (typeof intentObj.tool !== "string" || intentObj.tool.length > 64) {
|
|
440
|
+
return {
|
|
441
|
+
type: "error",
|
|
442
|
+
code: "invalid_request",
|
|
443
|
+
message: "sign_userop.intent.tool must be a string \u226464 chars"
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
if (intentObj.summary !== void 0 && (typeof intentObj.summary !== "string" || intentObj.summary.length > 256)) {
|
|
447
|
+
return {
|
|
448
|
+
type: "error",
|
|
449
|
+
code: "invalid_request",
|
|
450
|
+
message: "sign_userop.intent.summary must be a string \u2264256 chars when provided"
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
safeIntent = {
|
|
454
|
+
tool: intentObj.tool,
|
|
455
|
+
...typeof intentObj.summary === "string" ? { summary: intentObj.summary } : {}
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
return {
|
|
459
|
+
type: "sign_userop",
|
|
460
|
+
sessionId,
|
|
461
|
+
userOpHash,
|
|
462
|
+
innerCall: {
|
|
463
|
+
target: ic.target.toLowerCase(),
|
|
464
|
+
callData: ic.callData.toLowerCase()
|
|
465
|
+
},
|
|
466
|
+
...safeIntent === void 0 ? {} : { intent: safeIntent }
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
case "store_policy_snapshot": {
|
|
470
|
+
const parsed2 = parsePolicySnapshot(obj.snapshot);
|
|
471
|
+
if ("error" in parsed2) {
|
|
472
|
+
return { type: "error", code: "invalid_request", message: parsed2.error };
|
|
473
|
+
}
|
|
474
|
+
return { type: "store_policy_snapshot", snapshot: parsed2 };
|
|
475
|
+
}
|
|
476
|
+
case "get_policy_snapshot": {
|
|
477
|
+
if (!isSessionIdShape(obj.sessionId)) {
|
|
478
|
+
return {
|
|
479
|
+
type: "error",
|
|
480
|
+
code: "invalid_request",
|
|
481
|
+
message: "get_policy_snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]"
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
return { type: "get_policy_snapshot", sessionId: obj.sessionId };
|
|
485
|
+
}
|
|
486
|
+
case "clear_policy_snapshot": {
|
|
487
|
+
if (!isSessionIdShape(obj.sessionId)) {
|
|
488
|
+
return {
|
|
489
|
+
type: "error",
|
|
490
|
+
code: "invalid_request",
|
|
491
|
+
message: "clear_policy_snapshot.sessionId must be 1-128 chars [A-Za-z0-9_-]"
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
return { type: "clear_policy_snapshot", sessionId: obj.sessionId };
|
|
495
|
+
}
|
|
496
|
+
case "get_active_session_id":
|
|
497
|
+
return { type: "get_active_session_id" };
|
|
498
|
+
default:
|
|
499
|
+
return {
|
|
500
|
+
type: "error",
|
|
501
|
+
code: "unsupported_type",
|
|
502
|
+
message: `unsupported request type: ${String(obj.type)}`
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function serializeResponse(res) {
|
|
507
|
+
return JSON.stringify(res) + "\n";
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// src/clients/broker-client.ts
|
|
139
511
|
var BrokerClientError = class extends Error {
|
|
140
|
-
constructor(code, message, cause) {
|
|
512
|
+
constructor(code, message, cause, brokerCode) {
|
|
141
513
|
super(message);
|
|
142
514
|
this.code = code;
|
|
143
515
|
this.cause = cause;
|
|
516
|
+
this.brokerCode = brokerCode;
|
|
144
517
|
this.name = "BrokerClientError";
|
|
145
518
|
}
|
|
146
519
|
code;
|
|
147
520
|
cause;
|
|
521
|
+
brokerCode;
|
|
148
522
|
};
|
|
523
|
+
function semverGte(a, b) {
|
|
524
|
+
const re = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
|
525
|
+
const ma = re.exec(a);
|
|
526
|
+
const mb = re.exec(b);
|
|
527
|
+
if (!ma || !mb) {
|
|
528
|
+
throw new BrokerClientError(
|
|
529
|
+
"protocol_error",
|
|
530
|
+
`semverGte: malformed version (got ${JSON.stringify(a)} vs ${JSON.stringify(b)})`
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
for (let i = 1; i <= 3; i++) {
|
|
534
|
+
const ai = Number(ma[i]);
|
|
535
|
+
const bi = Number(mb[i]);
|
|
536
|
+
if (ai > bi) return true;
|
|
537
|
+
if (ai < bi) return false;
|
|
538
|
+
}
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
149
541
|
var BrokerClient = class {
|
|
150
542
|
constructor(options) {
|
|
151
543
|
this.options = options;
|
|
@@ -205,6 +597,109 @@ var BrokerClient = class {
|
|
|
205
597
|
);
|
|
206
598
|
}
|
|
207
599
|
}
|
|
600
|
+
// ── Wave 5 Path D Slice 1 (Commit 3) — policy snapshot CRUD + sign_userop ──
|
|
601
|
+
async signUserOp(args) {
|
|
602
|
+
const res = await this.exchange({
|
|
603
|
+
type: "sign_userop",
|
|
604
|
+
sessionId: args.sessionId,
|
|
605
|
+
userOpHash: args.userOpHash,
|
|
606
|
+
innerCall: args.innerCall,
|
|
607
|
+
...args.intent ? { intent: args.intent } : {}
|
|
608
|
+
});
|
|
609
|
+
if (res.type !== "sign_userop") {
|
|
610
|
+
throw new BrokerClientError(
|
|
611
|
+
"protocol_error",
|
|
612
|
+
`expected sign_userop response, got ${res.type}`
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
return res;
|
|
616
|
+
}
|
|
617
|
+
async storePolicySnapshot(snapshot) {
|
|
618
|
+
const res = await this.exchange({ type: "store_policy_snapshot", snapshot });
|
|
619
|
+
if (res.type !== "store_policy_snapshot") {
|
|
620
|
+
throw new BrokerClientError(
|
|
621
|
+
"protocol_error",
|
|
622
|
+
`expected store_policy_snapshot response, got ${res.type}`
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
return res;
|
|
626
|
+
}
|
|
627
|
+
async getPolicySnapshot(sessionId) {
|
|
628
|
+
const res = await this.exchange({ type: "get_policy_snapshot", sessionId });
|
|
629
|
+
if (res.type !== "get_policy_snapshot") {
|
|
630
|
+
throw new BrokerClientError(
|
|
631
|
+
"protocol_error",
|
|
632
|
+
`expected get_policy_snapshot response, got ${res.type}`
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
return res;
|
|
636
|
+
}
|
|
637
|
+
async clearPolicySnapshot(sessionId) {
|
|
638
|
+
const res = await this.exchange({ type: "clear_policy_snapshot", sessionId });
|
|
639
|
+
if (res.type !== "clear_policy_snapshot") {
|
|
640
|
+
throw new BrokerClientError(
|
|
641
|
+
"protocol_error",
|
|
642
|
+
`expected clear_policy_snapshot response, got ${res.type}`
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
return res;
|
|
646
|
+
}
|
|
647
|
+
async getActiveSessionId() {
|
|
648
|
+
const res = await this.exchange({ type: "get_active_session_id" });
|
|
649
|
+
if (res.type !== "get_active_session_id") {
|
|
650
|
+
throw new BrokerClientError(
|
|
651
|
+
"protocol_error",
|
|
652
|
+
`expected get_active_session_id response, got ${res.type}`
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
return res;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Detect whether the running daemon speaks Path D (protocol 0.4.0+).
|
|
659
|
+
* Wraps `hello()` with a semver-gte comparison so the MCP tool layer
|
|
660
|
+
* can short-circuit to Path C with a clear `version_too_old` reason
|
|
661
|
+
* instead of surfacing the opaque `unsupported_type` error a stale
|
|
662
|
+
* 0.3.0 daemon would emit on `sign_userop` / `get_active_session_id`
|
|
663
|
+
* (Backend Architect H-2, round 2).
|
|
664
|
+
*
|
|
665
|
+
* Returns `{ supported: false }` on broker connect failure too — the
|
|
666
|
+
* caller treats "daemon down" identically to "version too old": Path D
|
|
667
|
+
* not available, fall through to Path C.
|
|
668
|
+
*/
|
|
669
|
+
async preflight() {
|
|
670
|
+
let hello;
|
|
671
|
+
try {
|
|
672
|
+
hello = await this.hello();
|
|
673
|
+
} catch (err2) {
|
|
674
|
+
return {
|
|
675
|
+
supported: false,
|
|
676
|
+
reason: "broker_unreachable",
|
|
677
|
+
message: err2 instanceof BrokerClientError ? `broker.${err2.code}: ${err2.message}` : err2 instanceof Error ? err2.message : "broker unreachable",
|
|
678
|
+
requiredVersion: BROKER_PROTOCOL_VERSION
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
if (!semverGte(hello.version, BROKER_PROTOCOL_VERSION)) {
|
|
682
|
+
return {
|
|
683
|
+
supported: false,
|
|
684
|
+
reason: "version_too_old",
|
|
685
|
+
daemonVersion: hello.version,
|
|
686
|
+
requiredVersion: BROKER_PROTOCOL_VERSION
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
if (hello.hasSessionKey === false) {
|
|
690
|
+
return {
|
|
691
|
+
supported: false,
|
|
692
|
+
reason: "session_key_unavailable",
|
|
693
|
+
daemonVersion: hello.version,
|
|
694
|
+
requiredVersion: BROKER_PROTOCOL_VERSION
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
return {
|
|
698
|
+
supported: true,
|
|
699
|
+
daemonVersion: hello.version,
|
|
700
|
+
signerAddress: hello.sessionKeyAddress
|
|
701
|
+
};
|
|
702
|
+
}
|
|
208
703
|
exchange(request) {
|
|
209
704
|
return new Promise((resolve, reject) => {
|
|
210
705
|
let socket;
|
|
@@ -245,7 +740,12 @@ var BrokerClient = class {
|
|
|
245
740
|
const parsed = JSON.parse(line);
|
|
246
741
|
if (parsed.type === "error") {
|
|
247
742
|
settleErr(
|
|
248
|
-
new BrokerClientError(
|
|
743
|
+
new BrokerClientError(
|
|
744
|
+
"broker_error",
|
|
745
|
+
`${parsed.code}: ${parsed.message}`,
|
|
746
|
+
void 0,
|
|
747
|
+
parsed.code
|
|
748
|
+
)
|
|
249
749
|
);
|
|
250
750
|
return;
|
|
251
751
|
}
|
|
@@ -482,6 +982,414 @@ function mapStatus(status) {
|
|
|
482
982
|
if (status >= 500) return "server_error";
|
|
483
983
|
return "invalid_response";
|
|
484
984
|
}
|
|
985
|
+
var ENTRY_POINT_GET_NONCE_ABI = parseAbi([
|
|
986
|
+
"function getNonce(address sender, uint192 key) view returns (uint256)"
|
|
987
|
+
]);
|
|
988
|
+
var BundlerClientError = class extends Error {
|
|
989
|
+
constructor(code, message, detail) {
|
|
990
|
+
super(message);
|
|
991
|
+
this.code = code;
|
|
992
|
+
this.detail = detail;
|
|
993
|
+
this.name = "BundlerClientError";
|
|
994
|
+
}
|
|
995
|
+
code;
|
|
996
|
+
detail;
|
|
997
|
+
};
|
|
998
|
+
var BundlerClient = class {
|
|
999
|
+
constructor(options) {
|
|
1000
|
+
this.options = options;
|
|
1001
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
1002
|
+
}
|
|
1003
|
+
options;
|
|
1004
|
+
fetchImpl;
|
|
1005
|
+
nextRpcId = 1;
|
|
1006
|
+
/**
|
|
1007
|
+
* Submit a signed UserOperation. Returns the userOpHash the bundler
|
|
1008
|
+
* computed (which must match the hash the broker signed — caller is
|
|
1009
|
+
* responsible for the consistency check; broker policy snapshot
|
|
1010
|
+
* captures the signer-binding piece).
|
|
1011
|
+
*/
|
|
1012
|
+
async sendUserOp(userOp, entryPoint) {
|
|
1013
|
+
const result = await this.rpc("eth_sendUserOperation", [userOp, entryPoint]);
|
|
1014
|
+
if (typeof result !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(result)) {
|
|
1015
|
+
throw new BundlerClientError(
|
|
1016
|
+
"invalid_response",
|
|
1017
|
+
`eth_sendUserOperation returned non-hash result: ${JSON.stringify(result).slice(0, 80)}`
|
|
1018
|
+
);
|
|
1019
|
+
}
|
|
1020
|
+
return result.toLowerCase();
|
|
1021
|
+
}
|
|
1022
|
+
/** Return the receipt for a userOpHash, or null when the UserOp has
|
|
1023
|
+
* not yet been bundled. */
|
|
1024
|
+
async getReceipt(userOpHash) {
|
|
1025
|
+
const result = await this.rpc("eth_getUserOperationReceipt", [userOpHash]);
|
|
1026
|
+
if (result === null || result === void 0) return null;
|
|
1027
|
+
return parseReceipt(result);
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Poll until the bundler returns a receipt, or `timeoutMs` elapses.
|
|
1031
|
+
* Caller decides retry / fallback behaviour on `receipt_timeout`.
|
|
1032
|
+
*
|
|
1033
|
+
* Poll interval grows linearly from `initialIntervalMs` to
|
|
1034
|
+
* `maxIntervalMs` to avoid burning the bundler quota when blocks are
|
|
1035
|
+
* slow. Default tuning: 500ms → 2000ms over the first 6 polls; then
|
|
1036
|
+
* pinned at 2000ms.
|
|
1037
|
+
*/
|
|
1038
|
+
async waitForReceipt(userOpHash, opts) {
|
|
1039
|
+
const clock = opts.clockMs ?? (() => Date.now());
|
|
1040
|
+
const sleep = opts.sleep ?? ((ms) => setTimeout$1(ms));
|
|
1041
|
+
const initial = opts.initialIntervalMs ?? 500;
|
|
1042
|
+
const max = opts.maxIntervalMs ?? 2e3;
|
|
1043
|
+
const deadline = clock() + opts.timeoutMs;
|
|
1044
|
+
let attempt = 0;
|
|
1045
|
+
while (true) {
|
|
1046
|
+
const receipt = await this.getReceipt(userOpHash);
|
|
1047
|
+
if (receipt) return receipt;
|
|
1048
|
+
const now = clock();
|
|
1049
|
+
if (now >= deadline) {
|
|
1050
|
+
throw new BundlerClientError(
|
|
1051
|
+
"receipt_timeout",
|
|
1052
|
+
`no receipt for userOp ${userOpHash} within ${opts.timeoutMs}ms`
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
const interval = Math.min(max, initial + attempt * 250);
|
|
1056
|
+
const remaining = Math.max(0, deadline - now);
|
|
1057
|
+
await sleep(Math.min(interval, remaining));
|
|
1058
|
+
attempt++;
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Wave 5 Path D Slice 1 Commit 3.5 — `pm_sponsorUserOperation`.
|
|
1063
|
+
* ZeroDev's bundler URL serves both bundler RPCs AND paymaster RPCs
|
|
1064
|
+
* at the same endpoint, so we don't need a separate paymaster URL.
|
|
1065
|
+
* Returns the paymaster fields + the gas limits the paymaster's
|
|
1066
|
+
* simulation computed (the caller doesn't need a separate
|
|
1067
|
+
* `estimateUserOpGas` round-trip on the happy path).
|
|
1068
|
+
*/
|
|
1069
|
+
async sponsorUserOp(userOp, entryPoint) {
|
|
1070
|
+
const result = await this.rpc("pm_sponsorUserOperation", [userOp, entryPoint]);
|
|
1071
|
+
return parseSponsoredFields(result);
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Wave 5 Path D Slice 1 Commit 3.5 — `eth_estimateUserOperationGas`.
|
|
1075
|
+
* Not used in the happy path (sponsorship returns gas), but lives as
|
|
1076
|
+
* a fallback for unsponsored flows OR if the operator's paymaster
|
|
1077
|
+
* goes down. Reading gas separately also makes the failure modes
|
|
1078
|
+
* distinguishable for the LLM-facing fallback reasons.
|
|
1079
|
+
*/
|
|
1080
|
+
async estimateUserOpGas(userOp, entryPoint) {
|
|
1081
|
+
const result = await this.rpc("eth_estimateUserOperationGas", [userOp, entryPoint]);
|
|
1082
|
+
if (typeof result !== "object" || result === null) {
|
|
1083
|
+
throw new BundlerClientError(
|
|
1084
|
+
"invalid_response",
|
|
1085
|
+
"eth_estimateUserOperationGas returned non-object"
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
const obj = result;
|
|
1089
|
+
return {
|
|
1090
|
+
callGasLimit: assertHex(obj.callGasLimit, "estimateUserOpGas.callGasLimit"),
|
|
1091
|
+
verificationGasLimit: assertHex(
|
|
1092
|
+
obj.verificationGasLimit,
|
|
1093
|
+
"estimateUserOpGas.verificationGasLimit"
|
|
1094
|
+
),
|
|
1095
|
+
preVerificationGas: assertHex(
|
|
1096
|
+
obj.preVerificationGas,
|
|
1097
|
+
"estimateUserOpGas.preVerificationGas"
|
|
1098
|
+
)
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Wave 5 Path D Slice 1 Commit 3.5 — `eth_call` against the
|
|
1103
|
+
* EntryPoint's `getNonce(sender, key)`. Uses the bundler URL as a
|
|
1104
|
+
* full Arb Sepolia node (ZeroDev's bundler accepts read-side RPCs).
|
|
1105
|
+
*
|
|
1106
|
+
* Pass `key = 0n` for the default nonce key — Path D never uses a
|
|
1107
|
+
* non-default key in Slice 1; reserved for batched UserOps in
|
|
1108
|
+
* later slices.
|
|
1109
|
+
*/
|
|
1110
|
+
async getNonce(sender, entryPoint, key = 0n) {
|
|
1111
|
+
const data = encodeFunctionData({
|
|
1112
|
+
abi: ENTRY_POINT_GET_NONCE_ABI,
|
|
1113
|
+
functionName: "getNonce",
|
|
1114
|
+
args: [sender, key]
|
|
1115
|
+
});
|
|
1116
|
+
const result = await this.rpc("eth_call", [
|
|
1117
|
+
{ to: entryPoint, data },
|
|
1118
|
+
"latest"
|
|
1119
|
+
]);
|
|
1120
|
+
if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result)) {
|
|
1121
|
+
throw new BundlerClientError(
|
|
1122
|
+
"invalid_response",
|
|
1123
|
+
`eth_call returned non-hex: ${JSON.stringify(result).slice(0, 80)}`
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
const [nonce] = decodeAbiParameters([{ type: "uint256" }], result);
|
|
1127
|
+
return nonce;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Wave 5 Path D Slice 1 Commit 3.5 — fetch the fee market via
|
|
1131
|
+
* `eth_gasPrice` (returns a single value the bundler will accept for
|
|
1132
|
+
* both maxFee + maxPriorityFee on Arb Sepolia, which has effectively
|
|
1133
|
+
* no priority-vs-base distinction).
|
|
1134
|
+
*
|
|
1135
|
+
* Simple-on-purpose: a full EIP-1559 fee market read would need two
|
|
1136
|
+
* RPCs (`eth_maxPriorityFeePerGas` + `eth_getBlock`); Arb Sepolia's
|
|
1137
|
+
* fee dynamics don't require that precision and the paymaster pays
|
|
1138
|
+
* either way. A future caller wanting EIP-1559 precision can add a
|
|
1139
|
+
* sibling method.
|
|
1140
|
+
*/
|
|
1141
|
+
async getFeeData() {
|
|
1142
|
+
const result = await this.rpc("eth_gasPrice", []);
|
|
1143
|
+
if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) {
|
|
1144
|
+
throw new BundlerClientError(
|
|
1145
|
+
"invalid_response",
|
|
1146
|
+
`eth_gasPrice returned non-hex: ${JSON.stringify(result).slice(0, 80)}`
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
const base = BigInt(result);
|
|
1150
|
+
const margined = base * 2n;
|
|
1151
|
+
const hex = `0x${margined.toString(16)}`;
|
|
1152
|
+
return { maxFeePerGas: hex, maxPriorityFeePerGas: hex };
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Verify the bundler's reported chainId matches `expectedChainId`. Cheap
|
|
1156
|
+
* to call once at MCP server boot (or lazily before the first send) so
|
|
1157
|
+
* a misconfigured bundler URL surfaces as `chain_mismatch` before any
|
|
1158
|
+
* user-facing send rather than after a guaranteed-failing submit.
|
|
1159
|
+
*
|
|
1160
|
+
* Throws `BundlerClientError(config)` if no `expectedChainId` is set —
|
|
1161
|
+
* caller asked for an assert without configuring the expectation.
|
|
1162
|
+
*/
|
|
1163
|
+
async assertChainId() {
|
|
1164
|
+
if (this.options.expectedChainId === void 0) {
|
|
1165
|
+
throw new BundlerClientError(
|
|
1166
|
+
"config",
|
|
1167
|
+
"assertChainId called without expectedChainId configured"
|
|
1168
|
+
);
|
|
1169
|
+
}
|
|
1170
|
+
const result = await this.rpc("eth_chainId", []);
|
|
1171
|
+
if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) {
|
|
1172
|
+
throw new BundlerClientError(
|
|
1173
|
+
"invalid_response",
|
|
1174
|
+
`eth_chainId returned non-hex result: ${JSON.stringify(result).slice(0, 80)}`
|
|
1175
|
+
);
|
|
1176
|
+
}
|
|
1177
|
+
const reported = Number.parseInt(result, 16);
|
|
1178
|
+
if (reported !== this.options.expectedChainId) {
|
|
1179
|
+
throw new BundlerClientError(
|
|
1180
|
+
"chain_mismatch",
|
|
1181
|
+
`bundler reports chainId ${reported}, MCP expected ${this.options.expectedChainId}`,
|
|
1182
|
+
{ reportedChainId: reported, expectedChainId: this.options.expectedChainId }
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
async rpc(method, params) {
|
|
1187
|
+
const id = this.nextRpcId++;
|
|
1188
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
1189
|
+
const ctrl = new AbortController();
|
|
1190
|
+
const timer = setTimeout(() => ctrl.abort(), this.options.requestTimeoutMs);
|
|
1191
|
+
let res;
|
|
1192
|
+
try {
|
|
1193
|
+
const headers = {
|
|
1194
|
+
"content-type": "application/json",
|
|
1195
|
+
accept: "application/json"
|
|
1196
|
+
};
|
|
1197
|
+
if (this.options.originHeader) {
|
|
1198
|
+
headers["origin"] = this.options.originHeader;
|
|
1199
|
+
}
|
|
1200
|
+
res = await this.fetchImpl(this.options.endpoint, {
|
|
1201
|
+
method: "POST",
|
|
1202
|
+
headers,
|
|
1203
|
+
body,
|
|
1204
|
+
signal: ctrl.signal
|
|
1205
|
+
});
|
|
1206
|
+
} catch (err2) {
|
|
1207
|
+
clearTimeout(timer);
|
|
1208
|
+
if (err2.name === "AbortError") {
|
|
1209
|
+
throw new BundlerClientError("timeout", `bundler ${method} timed out`);
|
|
1210
|
+
}
|
|
1211
|
+
throw new BundlerClientError(
|
|
1212
|
+
"network",
|
|
1213
|
+
`bundler ${method} network error: ${err2 instanceof Error ? err2.message : String(err2)}`,
|
|
1214
|
+
err2
|
|
1215
|
+
);
|
|
1216
|
+
} finally {
|
|
1217
|
+
clearTimeout(timer);
|
|
1218
|
+
}
|
|
1219
|
+
if (!res.ok) {
|
|
1220
|
+
let text = "";
|
|
1221
|
+
try {
|
|
1222
|
+
text = (await res.text()).slice(0, 256);
|
|
1223
|
+
} catch {
|
|
1224
|
+
}
|
|
1225
|
+
throw new BundlerClientError(
|
|
1226
|
+
"http_error",
|
|
1227
|
+
`bundler ${method} \u2192 HTTP ${res.status}: ${text}`
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1230
|
+
let parsed;
|
|
1231
|
+
try {
|
|
1232
|
+
parsed = await res.json();
|
|
1233
|
+
} catch (err2) {
|
|
1234
|
+
throw new BundlerClientError(
|
|
1235
|
+
"invalid_response",
|
|
1236
|
+
`bundler ${method} returned non-JSON: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
1240
|
+
throw new BundlerClientError(
|
|
1241
|
+
"invalid_response",
|
|
1242
|
+
`bundler ${method} returned non-object`
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
const obj = parsed;
|
|
1246
|
+
if (obj.error !== void 0 && obj.error !== null) {
|
|
1247
|
+
const err2 = obj.error;
|
|
1248
|
+
throw new BundlerClientError(
|
|
1249
|
+
"rpc_error",
|
|
1250
|
+
`bundler ${method} rpc error: ${typeof err2.message === "string" ? err2.message : "<no message>"}`,
|
|
1251
|
+
{ code: err2.code, message: err2.message, data: err2.data }
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
return obj.result;
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
function parseReceipt(raw) {
|
|
1258
|
+
if (typeof raw !== "object" || raw === null) {
|
|
1259
|
+
throw new BundlerClientError("invalid_response", "receipt is not an object");
|
|
1260
|
+
}
|
|
1261
|
+
const obj = raw;
|
|
1262
|
+
const userOpHash = obj.userOpHash;
|
|
1263
|
+
if (typeof userOpHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(userOpHash)) {
|
|
1264
|
+
throw new BundlerClientError("invalid_response", "receipt.userOpHash malformed");
|
|
1265
|
+
}
|
|
1266
|
+
const sender = obj.sender;
|
|
1267
|
+
if (typeof sender !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(sender)) {
|
|
1268
|
+
throw new BundlerClientError("invalid_response", "receipt.sender malformed");
|
|
1269
|
+
}
|
|
1270
|
+
if (typeof obj.success !== "boolean") {
|
|
1271
|
+
throw new BundlerClientError("invalid_response", "receipt.success must be a boolean");
|
|
1272
|
+
}
|
|
1273
|
+
const inner = obj.receipt;
|
|
1274
|
+
if (typeof inner !== "object" || inner === null) {
|
|
1275
|
+
throw new BundlerClientError("invalid_response", "receipt.receipt missing");
|
|
1276
|
+
}
|
|
1277
|
+
const innerObj = inner;
|
|
1278
|
+
const txHash = innerObj.transactionHash;
|
|
1279
|
+
if (typeof txHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(txHash)) {
|
|
1280
|
+
throw new BundlerClientError(
|
|
1281
|
+
"invalid_response",
|
|
1282
|
+
"receipt.receipt.transactionHash malformed"
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
const blockNumber = innerObj.blockNumber;
|
|
1286
|
+
if (typeof blockNumber !== "string" || !/^0x[0-9a-fA-F]+$/.test(blockNumber)) {
|
|
1287
|
+
throw new BundlerClientError(
|
|
1288
|
+
"invalid_response",
|
|
1289
|
+
"receipt.receipt.blockNumber malformed"
|
|
1290
|
+
);
|
|
1291
|
+
}
|
|
1292
|
+
const blockHash = innerObj.blockHash;
|
|
1293
|
+
if (typeof blockHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(blockHash)) {
|
|
1294
|
+
throw new BundlerClientError(
|
|
1295
|
+
"invalid_response",
|
|
1296
|
+
"receipt.receipt.blockHash malformed"
|
|
1297
|
+
);
|
|
1298
|
+
}
|
|
1299
|
+
return {
|
|
1300
|
+
userOpHash: userOpHash.toLowerCase(),
|
|
1301
|
+
sender: sender.toLowerCase(),
|
|
1302
|
+
success: obj.success,
|
|
1303
|
+
...typeof obj.reason === "string" ? { reason: obj.reason } : {},
|
|
1304
|
+
receipt: {
|
|
1305
|
+
transactionHash: txHash.toLowerCase(),
|
|
1306
|
+
blockNumber: blockNumber.toLowerCase(),
|
|
1307
|
+
blockHash: blockHash.toLowerCase()
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
function parseSponsoredFields(raw) {
|
|
1312
|
+
if (typeof raw !== "object" || raw === null) {
|
|
1313
|
+
throw new BundlerClientError(
|
|
1314
|
+
"invalid_response",
|
|
1315
|
+
"pm_sponsorUserOperation returned non-object"
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
const obj = raw;
|
|
1319
|
+
return {
|
|
1320
|
+
paymaster: assertHexAddress(obj.paymaster, "sponsoredFields.paymaster"),
|
|
1321
|
+
paymasterVerificationGasLimit: assertHexNonZero(
|
|
1322
|
+
obj.paymasterVerificationGasLimit,
|
|
1323
|
+
"sponsoredFields.paymasterVerificationGasLimit",
|
|
1324
|
+
MAX_PAYMASTER_GAS_LIMIT
|
|
1325
|
+
),
|
|
1326
|
+
paymasterPostOpGasLimit: assertHexNonZero(
|
|
1327
|
+
obj.paymasterPostOpGasLimit,
|
|
1328
|
+
"sponsoredFields.paymasterPostOpGasLimit",
|
|
1329
|
+
MAX_PAYMASTER_GAS_LIMIT
|
|
1330
|
+
),
|
|
1331
|
+
// paymasterData is the only sponsored field that can legitimately
|
|
1332
|
+
// be empty (`0x`) — paymasters with no per-op data return that.
|
|
1333
|
+
paymasterData: assertHex(obj.paymasterData, "sponsoredFields.paymasterData"),
|
|
1334
|
+
callGasLimit: assertHexNonZero(
|
|
1335
|
+
obj.callGasLimit,
|
|
1336
|
+
"sponsoredFields.callGasLimit",
|
|
1337
|
+
MAX_CALL_GAS_LIMIT
|
|
1338
|
+
),
|
|
1339
|
+
verificationGasLimit: assertHexNonZero(
|
|
1340
|
+
obj.verificationGasLimit,
|
|
1341
|
+
"sponsoredFields.verificationGasLimit",
|
|
1342
|
+
MAX_VERIFICATION_GAS_LIMIT
|
|
1343
|
+
),
|
|
1344
|
+
preVerificationGas: assertHexNonZero(
|
|
1345
|
+
obj.preVerificationGas,
|
|
1346
|
+
"sponsoredFields.preVerificationGas",
|
|
1347
|
+
MAX_PRE_VERIFICATION_GAS
|
|
1348
|
+
)
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
function assertHex(value, label) {
|
|
1352
|
+
if (typeof value !== "string" || !/^0x([0-9a-fA-F]{2})*$/.test(value)) {
|
|
1353
|
+
const repr = value === void 0 ? "undefined" : JSON.stringify(value);
|
|
1354
|
+
const safe = typeof repr === "string" ? repr.slice(0, 80) : "unknown";
|
|
1355
|
+
throw new BundlerClientError(
|
|
1356
|
+
"invalid_response",
|
|
1357
|
+
`${label} must be a 0x-prefixed hex string (got ${safe})`
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1360
|
+
return value;
|
|
1361
|
+
}
|
|
1362
|
+
function assertHexNonZero(value, label, maxValue) {
|
|
1363
|
+
const hex = assertHex(value, label);
|
|
1364
|
+
if (hex.length === 2 || BigInt(hex) === 0n) {
|
|
1365
|
+
throw new BundlerClientError(
|
|
1366
|
+
"invalid_response",
|
|
1367
|
+
`${label} must be a non-zero hex value (got "${hex}")`
|
|
1368
|
+
);
|
|
1369
|
+
}
|
|
1370
|
+
if (maxValue !== void 0 && BigInt(hex) > maxValue) {
|
|
1371
|
+
throw new BundlerClientError(
|
|
1372
|
+
"invalid_response",
|
|
1373
|
+
`${label} = ${BigInt(hex)} exceeds plausible ceiling ${maxValue} \u2014 refusing to sign + submit`
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
return hex;
|
|
1377
|
+
}
|
|
1378
|
+
var MAX_CALL_GAS_LIMIT = 20000000n;
|
|
1379
|
+
var MAX_VERIFICATION_GAS_LIMIT = 20000000n;
|
|
1380
|
+
var MAX_PRE_VERIFICATION_GAS = 5000000n;
|
|
1381
|
+
var MAX_PAYMASTER_GAS_LIMIT = 5000000n;
|
|
1382
|
+
function assertHexAddress(value, label) {
|
|
1383
|
+
if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {
|
|
1384
|
+
const repr = value === void 0 ? "undefined" : JSON.stringify(value);
|
|
1385
|
+
const safe = typeof repr === "string" ? repr.slice(0, 80) : "unknown";
|
|
1386
|
+
throw new BundlerClientError(
|
|
1387
|
+
"invalid_response",
|
|
1388
|
+
`${label} must be a 0x-prefixed 20-byte hex address (got ${safe})`
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
return value;
|
|
1392
|
+
}
|
|
485
1393
|
var TOOL_DESCRIPTORS = [
|
|
486
1394
|
{
|
|
487
1395
|
name: "muhaven.read.portfolio",
|
|
@@ -829,6 +1737,119 @@ var GovernanceCastVoteInputSchema = z.object({
|
|
|
829
1737
|
voteYes: z.boolean()
|
|
830
1738
|
}).strict();
|
|
831
1739
|
|
|
1740
|
+
// src/auth/jwt-decode.ts
|
|
1741
|
+
var JwtDecodeError = class extends Error {
|
|
1742
|
+
code;
|
|
1743
|
+
constructor(code, message) {
|
|
1744
|
+
super(message);
|
|
1745
|
+
this.name = "JwtDecodeError";
|
|
1746
|
+
this.code = code;
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
function decodeJwtPayload(jwt) {
|
|
1750
|
+
const segments = jwt.split(".");
|
|
1751
|
+
if (segments.length !== 3) {
|
|
1752
|
+
throw new JwtDecodeError(
|
|
1753
|
+
"malformed_segments",
|
|
1754
|
+
`expected 3 dot-separated segments, got ${segments.length}`
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
const payloadSegment = segments[1];
|
|
1758
|
+
if (payloadSegment === void 0) {
|
|
1759
|
+
throw new JwtDecodeError("malformed_segments", "payload segment missing");
|
|
1760
|
+
}
|
|
1761
|
+
let payloadJson;
|
|
1762
|
+
try {
|
|
1763
|
+
payloadJson = Buffer.from(payloadSegment, "base64url").toString("utf8");
|
|
1764
|
+
} catch (err2) {
|
|
1765
|
+
throw new JwtDecodeError(
|
|
1766
|
+
"malformed_base64",
|
|
1767
|
+
`payload segment is not valid base64url: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
let parsed;
|
|
1771
|
+
try {
|
|
1772
|
+
parsed = JSON.parse(payloadJson);
|
|
1773
|
+
} catch (err2) {
|
|
1774
|
+
throw new JwtDecodeError(
|
|
1775
|
+
"malformed_json",
|
|
1776
|
+
`payload is not valid JSON: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
1777
|
+
);
|
|
1778
|
+
}
|
|
1779
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
1780
|
+
throw new JwtDecodeError(
|
|
1781
|
+
"malformed_json",
|
|
1782
|
+
`payload is not a JSON object (got ${parsed === null ? "null" : typeof parsed})`
|
|
1783
|
+
);
|
|
1784
|
+
}
|
|
1785
|
+
const obj = parsed;
|
|
1786
|
+
return {
|
|
1787
|
+
sub: typeof obj.sub === "string" ? obj.sub : null,
|
|
1788
|
+
scope: Array.isArray(obj.scope) ? obj.scope.filter((s) => typeof s === "string") : [],
|
|
1789
|
+
expSec: typeof obj.exp === "number" ? obj.exp : null,
|
|
1790
|
+
iss: typeof obj.iss === "string" ? obj.iss : null
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
function truncateSubject(sub) {
|
|
1794
|
+
if (!sub) return "(missing)";
|
|
1795
|
+
const sanitized = sub.replace(/[^\x20-\x7e]/g, "?");
|
|
1796
|
+
if (sanitized.length <= 12) return sanitized;
|
|
1797
|
+
return `${sanitized.slice(0, 8)}\u2026${sanitized.slice(-4)}`;
|
|
1798
|
+
}
|
|
1799
|
+
var KERNEL_EXECUTE_ABI = parseAbi([
|
|
1800
|
+
"function execute(bytes32 mode, bytes calldata executionCalldata)"
|
|
1801
|
+
]);
|
|
1802
|
+
var KERNEL_V3_SINGLE_CALL_MODE_DEFAULT = `0x${"00".repeat(32)}`;
|
|
1803
|
+
function encodeKernelExecuteSingleCall(input) {
|
|
1804
|
+
const executionCalldata = encodePacked(
|
|
1805
|
+
["address", "uint256", "bytes"],
|
|
1806
|
+
[input.target, input.value, input.callData]
|
|
1807
|
+
);
|
|
1808
|
+
return encodeFunctionData({
|
|
1809
|
+
abi: KERNEL_EXECUTE_ABI,
|
|
1810
|
+
functionName: "execute",
|
|
1811
|
+
args: [KERNEL_V3_SINGLE_CALL_MODE_DEFAULT, executionCalldata]
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
var ECDSA_SIG_HEX_RE = /^0x[0-9a-fA-F]{130}$/;
|
|
1815
|
+
var PERMISSION_USE_PREFIX = "0xff";
|
|
1816
|
+
function buildKernelSessionKeySignature(input) {
|
|
1817
|
+
if (!ECDSA_SIG_HEX_RE.test(input.ecdsaSignature)) {
|
|
1818
|
+
throw new Error(
|
|
1819
|
+
`buildKernelSessionKeySignature: ecdsaSignature must be a 0x-prefixed 65-byte hex (got ${input.ecdsaSignature.length} chars)`
|
|
1820
|
+
);
|
|
1821
|
+
}
|
|
1822
|
+
return concatHex([PERMISSION_USE_PREFIX, input.ecdsaSignature]);
|
|
1823
|
+
}
|
|
1824
|
+
var VALIDATOR_MODE_DEFAULT = "0x00";
|
|
1825
|
+
var VALIDATOR_TYPE_PERMISSION = "0x02";
|
|
1826
|
+
var PERMISSION_ID_HEX_RE = /^0x[0-9a-fA-F]{8}$/;
|
|
1827
|
+
function composeKernelV3NonceKey(args) {
|
|
1828
|
+
if (!PERMISSION_ID_HEX_RE.test(args.permissionId)) {
|
|
1829
|
+
throw new Error(
|
|
1830
|
+
`composeKernelV3NonceKey: permissionId must be a 0x-prefixed 4-byte hex (got ${args.permissionId.length} chars)`
|
|
1831
|
+
);
|
|
1832
|
+
}
|
|
1833
|
+
const customKey = args.customKey ?? 0n;
|
|
1834
|
+
if (customKey < 0n || customKey > 0xffffn) {
|
|
1835
|
+
throw new Error(
|
|
1836
|
+
`composeKernelV3NonceKey: customKey must fit in 2 bytes (0..0xffff), got ${customKey}`
|
|
1837
|
+
);
|
|
1838
|
+
}
|
|
1839
|
+
const paddedPermissionId = pad(args.permissionId, { size: 20, dir: "right" });
|
|
1840
|
+
const customKeyHex = pad(`0x${customKey.toString(16)}`, { size: 2 });
|
|
1841
|
+
const composite = pad(
|
|
1842
|
+
concatHex([
|
|
1843
|
+
VALIDATOR_MODE_DEFAULT,
|
|
1844
|
+
VALIDATOR_TYPE_PERMISSION,
|
|
1845
|
+
paddedPermissionId,
|
|
1846
|
+
customKeyHex
|
|
1847
|
+
]),
|
|
1848
|
+
{ size: 24 }
|
|
1849
|
+
);
|
|
1850
|
+
return BigInt(composite);
|
|
1851
|
+
}
|
|
1852
|
+
|
|
832
1853
|
// src/tools/auth-required.ts
|
|
833
1854
|
function authRequiredPayload() {
|
|
834
1855
|
return {
|
|
@@ -871,6 +1892,13 @@ function formatUsd6AsDecimal(usd6) {
|
|
|
871
1892
|
}
|
|
872
1893
|
|
|
873
1894
|
// src/tools/handlers.ts
|
|
1895
|
+
var SUBSCRIPTION_PURCHASE_SELECTOR = toFunctionSelector(
|
|
1896
|
+
"function purchase(address,(uint256,uint8,uint8,bytes),uint128,address)"
|
|
1897
|
+
).toLowerCase();
|
|
1898
|
+
var SUBSCRIPTION_PURCHASE_ABI = parseAbi([
|
|
1899
|
+
"function purchase(address token, (uint256 ctHash, uint8 securityZone, uint8 utype, bytes signature) encShares, uint128 maxSharesHint, address ephemeralEOA)"
|
|
1900
|
+
]);
|
|
1901
|
+
var PLACEHOLDER_SIGNATURE = "0x" + "fe".repeat(86);
|
|
874
1902
|
function ok(data) {
|
|
875
1903
|
return { ok: true, data };
|
|
876
1904
|
}
|
|
@@ -882,94 +1910,673 @@ function mapBackendError(e) {
|
|
|
882
1910
|
if (e.code === "unauthorized") return authRequiredPayload();
|
|
883
1911
|
return err(`backend.${e.code}`, e.message);
|
|
884
1912
|
}
|
|
885
|
-
if (e instanceof Error) return err("backend.network", e.message);
|
|
886
|
-
return err("backend.network", "unknown backend error");
|
|
887
|
-
}
|
|
888
|
-
async function readPortfolio(_input, deps) {
|
|
889
|
-
try {
|
|
890
|
-
const data = await deps.backend.get("/api/v1/portfolio");
|
|
891
|
-
return ok(data);
|
|
892
|
-
} catch (e) {
|
|
893
|
-
return mapBackendError(e);
|
|
1913
|
+
if (e instanceof Error) return err("backend.network", e.message);
|
|
1914
|
+
return err("backend.network", "unknown backend error");
|
|
1915
|
+
}
|
|
1916
|
+
async function readPortfolio(_input, deps) {
|
|
1917
|
+
try {
|
|
1918
|
+
const data = await deps.backend.get("/api/v1/portfolio");
|
|
1919
|
+
return ok(data);
|
|
1920
|
+
} catch (e) {
|
|
1921
|
+
return mapBackendError(e);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
async function readYields(input, deps) {
|
|
1925
|
+
try {
|
|
1926
|
+
const data = await deps.backend.get("/api/v1/yields", {
|
|
1927
|
+
token: input.token,
|
|
1928
|
+
limit: input.limit
|
|
1929
|
+
});
|
|
1930
|
+
return ok(data);
|
|
1931
|
+
} catch (e) {
|
|
1932
|
+
return mapBackendError(e);
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
async function readDistribution(input, deps) {
|
|
1936
|
+
try {
|
|
1937
|
+
const data = await deps.backend.get("/api/v1/distributions", {
|
|
1938
|
+
token: input.token,
|
|
1939
|
+
epoch: input.epoch
|
|
1940
|
+
});
|
|
1941
|
+
return ok(data);
|
|
1942
|
+
} catch (e) {
|
|
1943
|
+
return mapBackendError(e);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
async function readTokens(_input, deps) {
|
|
1947
|
+
try {
|
|
1948
|
+
const data = await deps.backend.get("/api/v1/tokens");
|
|
1949
|
+
return ok(data);
|
|
1950
|
+
} catch (e) {
|
|
1951
|
+
return mapBackendError(e);
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
async function readAudit(input, deps) {
|
|
1955
|
+
try {
|
|
1956
|
+
const data = await deps.backend.get("/api/v1/agent/policy/audit", {
|
|
1957
|
+
surface: input.surface,
|
|
1958
|
+
eventTypes: input.eventTypes?.join(","),
|
|
1959
|
+
since: input.since,
|
|
1960
|
+
until: input.until,
|
|
1961
|
+
cursor: input.cursor,
|
|
1962
|
+
limit: input.limit
|
|
1963
|
+
});
|
|
1964
|
+
return ok(data);
|
|
1965
|
+
} catch (e) {
|
|
1966
|
+
return mapBackendError(e);
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
async function readActivity(input, deps) {
|
|
1970
|
+
try {
|
|
1971
|
+
const data = await deps.backend.get("/api/v1/activity", {
|
|
1972
|
+
limit: input.limit,
|
|
1973
|
+
offset: input.offset
|
|
1974
|
+
});
|
|
1975
|
+
return ok(data);
|
|
1976
|
+
} catch (e) {
|
|
1977
|
+
return mapBackendError(e);
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
function buildPositionDeeplink(dashboardBaseUrl, action, params) {
|
|
1981
|
+
const base = dashboardBaseUrl.replace(/\/+$/, "");
|
|
1982
|
+
const path = action === "buy" || action === "sell" ? "/trade" : action === "claim" ? "/yields" : "/cash";
|
|
1983
|
+
const search = new URLSearchParams();
|
|
1984
|
+
if (action === "buy" || action === "sell") search.set("mode", action);
|
|
1985
|
+
for (const [k, v] of Object.entries(params)) search.set(k, v);
|
|
1986
|
+
search.set("from", "mcp");
|
|
1987
|
+
return `${base}${path}?${search.toString()}`;
|
|
1988
|
+
}
|
|
1989
|
+
function resolveDashboardBaseUrl(deps) {
|
|
1990
|
+
return deps.dashboardBaseUrl ?? "https://muhaven.app";
|
|
1991
|
+
}
|
|
1992
|
+
function resolveTokenInCatalog(identifier, catalog) {
|
|
1993
|
+
const needle = identifier.toLowerCase();
|
|
1994
|
+
return catalog.find(
|
|
1995
|
+
(t) => t.address.toLowerCase() === needle || t.symbol.toLowerCase() === needle
|
|
1996
|
+
) ?? null;
|
|
1997
|
+
}
|
|
1998
|
+
function sanitizeSymbolForLlmContext(raw) {
|
|
1999
|
+
const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, "?");
|
|
2000
|
+
return cleaned.length > 16 ? cleaned.slice(0, 16) : cleaned;
|
|
2001
|
+
}
|
|
2002
|
+
function sanitizeRpcMessageForLlmContext(raw) {
|
|
2003
|
+
const cleaned = raw.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/\s+/g, " ").trim();
|
|
2004
|
+
return cleaned.length > 120 ? cleaned.slice(0, 120) + "\u2026" : cleaned;
|
|
2005
|
+
}
|
|
2006
|
+
function mapBrokerCallFailure(err2, verb, defaultReason = "broker_internal") {
|
|
2007
|
+
if (err2 instanceof BrokerClientError && err2.brokerCode === "unsupported_type") {
|
|
2008
|
+
return {
|
|
2009
|
+
kind: "fallback",
|
|
2010
|
+
reason: "version_too_old",
|
|
2011
|
+
message: `broker daemon rejected ${verb} as unsupported_type \u2014 daemon is likely older than protocol 0.4.0; upgrade @muhaven/mcp and restart the broker`
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
return {
|
|
2015
|
+
kind: "fallback",
|
|
2016
|
+
reason: defaultReason,
|
|
2017
|
+
message: `broker rejected ${verb} (${typedErrorCode(err2)})`
|
|
2018
|
+
};
|
|
2019
|
+
}
|
|
2020
|
+
var MCP_HEX_20_BYTE_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
2021
|
+
var MCP_HEX_4_BYTE_RE = /^0x[0-9a-fA-F]{8}$/;
|
|
2022
|
+
var MCP_HEX_32_BYTE_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
2023
|
+
var MCP_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
2024
|
+
var MirrorDtoMalformedError = class extends Error {
|
|
2025
|
+
constructor(message) {
|
|
2026
|
+
super(message);
|
|
2027
|
+
this.name = "MirrorDtoMalformedError";
|
|
2028
|
+
}
|
|
2029
|
+
};
|
|
2030
|
+
function mirrorDtoToPolicySnapshot(dto) {
|
|
2031
|
+
if (dto.mode !== "scoped") {
|
|
2032
|
+
throw new MirrorDtoMalformedError(
|
|
2033
|
+
`mode must be 'scoped' (got ${JSON.stringify(dto.mode)}); wildcard mirror auto-sync ships in Slice 4`
|
|
2034
|
+
);
|
|
2035
|
+
}
|
|
2036
|
+
if (dto.status !== "active") {
|
|
2037
|
+
throw new MirrorDtoMalformedError(
|
|
2038
|
+
`status must be 'active' for auto-sync (got ${JSON.stringify(dto.status)}); backend mirror should have filtered this row out`
|
|
2039
|
+
);
|
|
2040
|
+
}
|
|
2041
|
+
if (typeof dto.sessionId !== "string" || !MCP_SESSION_ID_RE.test(dto.sessionId)) {
|
|
2042
|
+
throw new MirrorDtoMalformedError(
|
|
2043
|
+
`sessionId must match /^[A-Za-z0-9_-]{1,128}$/`
|
|
2044
|
+
);
|
|
2045
|
+
}
|
|
2046
|
+
if (!MCP_HEX_20_BYTE_RE.test(dto.signerAddress)) {
|
|
2047
|
+
throw new MirrorDtoMalformedError(
|
|
2048
|
+
`signerAddress is not a 0x-prefixed 20-byte hex`
|
|
2049
|
+
);
|
|
2050
|
+
}
|
|
2051
|
+
if (!Array.isArray(dto.targetContracts) || dto.targetContracts.length === 0) {
|
|
2052
|
+
throw new MirrorDtoMalformedError(
|
|
2053
|
+
`targetContracts must be a non-empty array`
|
|
2054
|
+
);
|
|
2055
|
+
}
|
|
2056
|
+
for (const t of dto.targetContracts) {
|
|
2057
|
+
if (typeof t !== "string" || !MCP_HEX_20_BYTE_RE.test(t)) {
|
|
2058
|
+
throw new MirrorDtoMalformedError(
|
|
2059
|
+
`targetContracts entry is not a 0x-prefixed 20-byte hex`
|
|
2060
|
+
);
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
if (!Array.isArray(dto.selectorCaps) || dto.selectorCaps.length === 0) {
|
|
2064
|
+
throw new MirrorDtoMalformedError(`selectorCaps must be a non-empty array`);
|
|
2065
|
+
}
|
|
2066
|
+
for (const c of dto.selectorCaps) {
|
|
2067
|
+
if (typeof c?.selector !== "string" || !MCP_HEX_4_BYTE_RE.test(c.selector)) {
|
|
2068
|
+
throw new MirrorDtoMalformedError(
|
|
2069
|
+
`selectorCaps entry has a malformed selector`
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
if (dto.permissionId != null && !MCP_HEX_4_BYTE_RE.test(dto.permissionId)) {
|
|
2074
|
+
throw new MirrorDtoMalformedError(
|
|
2075
|
+
`permissionId is not a 0x-prefixed 4-byte hex`
|
|
2076
|
+
);
|
|
2077
|
+
}
|
|
2078
|
+
if (dto.consentActionHash != null && !MCP_HEX_32_BYTE_RE.test(dto.consentActionHash)) {
|
|
2079
|
+
throw new MirrorDtoMalformedError(
|
|
2080
|
+
`consentActionHash is not a 0x-prefixed 32-byte hex`
|
|
2081
|
+
);
|
|
2082
|
+
}
|
|
2083
|
+
if (dto.consentTextSha256 != null && !MCP_HEX_32_BYTE_RE.test(dto.consentTextSha256)) {
|
|
2084
|
+
throw new MirrorDtoMalformedError(
|
|
2085
|
+
`consentTextSha256 is not a 0x-prefixed 32-byte hex`
|
|
2086
|
+
);
|
|
2087
|
+
}
|
|
2088
|
+
return {
|
|
2089
|
+
sessionId: dto.sessionId,
|
|
2090
|
+
mode: "scoped",
|
|
2091
|
+
signerAddress: dto.signerAddress.toLowerCase(),
|
|
2092
|
+
targetContracts: dto.targetContracts.map(
|
|
2093
|
+
(a) => a.toLowerCase()
|
|
2094
|
+
),
|
|
2095
|
+
selectorCaps: dto.selectorCaps.map((c) => ({
|
|
2096
|
+
selector: c.selector.toLowerCase(),
|
|
2097
|
+
capArgIndex: c.capArgIndex,
|
|
2098
|
+
maxAmount: c.maxAmount
|
|
2099
|
+
})),
|
|
2100
|
+
validUntilSec: dto.validUntilSec,
|
|
2101
|
+
mintedAtSec: dto.mintedAtSec,
|
|
2102
|
+
...dto.consentActionHash ? { consentActionHash: dto.consentActionHash.toLowerCase() } : {},
|
|
2103
|
+
...dto.consentTextSha256 ? { consentTextSha256: dto.consentTextSha256.toLowerCase() } : {},
|
|
2104
|
+
...dto.permissionId ? { permissionId: dto.permissionId.toLowerCase() } : {}
|
|
2105
|
+
};
|
|
2106
|
+
}
|
|
2107
|
+
function typedErrorCode(err2) {
|
|
2108
|
+
if (err2 instanceof BackendError) return `backend.${err2.code}`;
|
|
2109
|
+
if (err2 instanceof BrokerClientError) {
|
|
2110
|
+
return err2.brokerCode ? `broker.${err2.brokerCode}` : `broker.${err2.code}`;
|
|
2111
|
+
}
|
|
2112
|
+
if (err2 instanceof MirrorDtoMalformedError) return "malformed_mirror_row";
|
|
2113
|
+
return "unknown";
|
|
2114
|
+
}
|
|
2115
|
+
async function fetchJwtSubjectHint(deps) {
|
|
2116
|
+
if (!deps.broker) return null;
|
|
2117
|
+
try {
|
|
2118
|
+
const res = await deps.broker.getJwt();
|
|
2119
|
+
if (!res.jwt) return null;
|
|
2120
|
+
const decoded = decodeJwtPayload(res.jwt);
|
|
2121
|
+
return truncateSubject(decoded.sub);
|
|
2122
|
+
} catch {
|
|
2123
|
+
return null;
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
async function syncSnapshotFromMirror(deps, brokerSignerAddress) {
|
|
2127
|
+
if (!deps.broker) {
|
|
2128
|
+
return {
|
|
2129
|
+
kind: "fallback",
|
|
2130
|
+
reason: "mirror_sync_failed",
|
|
2131
|
+
message: "auto-sync invoked without a broker dep \u2014 pipeline bug"
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
let mirror;
|
|
2135
|
+
try {
|
|
2136
|
+
mirror = await deps.backend.get(
|
|
2137
|
+
"/api/v1/agent/policy/scoped-session",
|
|
2138
|
+
{ surface: "mcp" }
|
|
2139
|
+
);
|
|
2140
|
+
} catch (err2) {
|
|
2141
|
+
return {
|
|
2142
|
+
kind: "fallback",
|
|
2143
|
+
reason: "mirror_sync_failed",
|
|
2144
|
+
message: `backend mirror lookup failed (${typedErrorCode(err2)})`
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
if (!mirror || mirror.session == null) {
|
|
2148
|
+
const subjectHint = await fetchJwtSubjectHint(deps);
|
|
2149
|
+
const hintSuffix = subjectHint ? ` (broker JWT subject: ${subjectHint} \u2014 verify this matches the userId of the wallet you used to mint the scoped tier; if not, run \`muhaven-broker logout && muhaven-broker login\` and re-authorize with the correct passkey)` : "";
|
|
2150
|
+
return {
|
|
2151
|
+
kind: "fallback",
|
|
2152
|
+
reason: "no_active_session_key",
|
|
2153
|
+
message: "no active scoped session \u2014 visit /agent/policy/transition to mint one, then retry. (Mirror also empty; nothing to auto-sync.)" + hintSuffix
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
let snapshot;
|
|
2157
|
+
try {
|
|
2158
|
+
snapshot = mirrorDtoToPolicySnapshot(mirror.session);
|
|
2159
|
+
} catch (err2) {
|
|
2160
|
+
return {
|
|
2161
|
+
kind: "fallback",
|
|
2162
|
+
reason: "mirror_sync_failed",
|
|
2163
|
+
message: `mirror returned a malformed scoped-session row (${typedErrorCode(err2)})`
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
if (snapshot.signerAddress.toLowerCase() !== brokerSignerAddress.toLowerCase()) {
|
|
2167
|
+
return {
|
|
2168
|
+
kind: "fallback",
|
|
2169
|
+
reason: "signer_mismatch",
|
|
2170
|
+
message: `mirror snapshot is bound to signer ${snapshot.signerAddress}, broker is currently signing as ${brokerSignerAddress} \u2014 re-mint the scoped tier from the dashboard against the broker's current session key, OR restart the broker with the session key matching the mirror snapshot`
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
try {
|
|
2174
|
+
await deps.broker.storePolicySnapshot(snapshot);
|
|
2175
|
+
} catch (err2) {
|
|
2176
|
+
return {
|
|
2177
|
+
kind: "fallback",
|
|
2178
|
+
reason: "mirror_sync_failed",
|
|
2179
|
+
message: `broker rejected store_policy_snapshot (${typedErrorCode(err2)})`
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
let activeId;
|
|
2183
|
+
try {
|
|
2184
|
+
const res = await deps.broker.getActiveSessionId();
|
|
2185
|
+
activeId = res.sessionId;
|
|
2186
|
+
} catch (err2) {
|
|
2187
|
+
return {
|
|
2188
|
+
kind: "fallback",
|
|
2189
|
+
reason: "mirror_sync_failed",
|
|
2190
|
+
message: `broker re-probe after store_policy_snapshot failed (${typedErrorCode(err2)})`
|
|
2191
|
+
};
|
|
2192
|
+
}
|
|
2193
|
+
if (!activeId) {
|
|
2194
|
+
return {
|
|
2195
|
+
kind: "fallback",
|
|
2196
|
+
reason: "mirror_sync_failed",
|
|
2197
|
+
message: "broker accepted store_policy_snapshot but get_active_session_id returned null \u2014 most likely cause: multiple non-expired snapshots for the same signer collapse to ambiguous. Clear stale snapshots via the muhaven-broker CLI before retrying. (Snapshot signer was pre-validated to match the broker; signer mismatch already filtered upstream.)"
|
|
2198
|
+
};
|
|
2199
|
+
}
|
|
2200
|
+
return { kind: "ok", sessionId: activeId };
|
|
2201
|
+
}
|
|
2202
|
+
async function attemptPathD(args, deps) {
|
|
2203
|
+
const { shares, tokenAddress, tokenSymbol } = args;
|
|
2204
|
+
if (!deps.broker || !deps.bundler) {
|
|
2205
|
+
return { kind: "unconfigured" };
|
|
2206
|
+
}
|
|
2207
|
+
if (!deps.subscriptionAddress) {
|
|
2208
|
+
return {
|
|
2209
|
+
kind: "fallback",
|
|
2210
|
+
reason: "subscription_address_unset",
|
|
2211
|
+
message: "MUHAVEN_SUBSCRIPTION_ADDRESS not configured \u2014 Path D autonomous-buy disabled until the operator sets it in the MCP env"
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
if (!deps.entryPointAddress) {
|
|
2215
|
+
return {
|
|
2216
|
+
kind: "fallback",
|
|
2217
|
+
reason: "entry_point_unset",
|
|
2218
|
+
message: "MUHAVEN_ENTRY_POINT resolved to undefined \u2014 Path D requires the EntryPoint v0.7 address"
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
if (typeof deps.chainId !== "number") {
|
|
2222
|
+
return {
|
|
2223
|
+
kind: "fallback",
|
|
2224
|
+
reason: "chain_id_unset",
|
|
2225
|
+
message: "MUHAVEN_CHAIN_ID not configured \u2014 Path D autonomous-buy requires a chain id for userOpHash"
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
const subscriptionAddress = deps.subscriptionAddress;
|
|
2229
|
+
const entryPointAddress = deps.entryPointAddress;
|
|
2230
|
+
const chainId = deps.chainId;
|
|
2231
|
+
const preflight = await deps.broker.preflight();
|
|
2232
|
+
if (!preflight.supported) {
|
|
2233
|
+
if (preflight.reason === "broker_unreachable") {
|
|
2234
|
+
return {
|
|
2235
|
+
kind: "fallback",
|
|
2236
|
+
reason: "broker_unreachable",
|
|
2237
|
+
message: `broker daemon not reachable (${preflight.message}) \u2014 falling back to Path C dashboard deep-link`
|
|
2238
|
+
};
|
|
2239
|
+
}
|
|
2240
|
+
if (preflight.reason === "version_too_old") {
|
|
2241
|
+
return {
|
|
2242
|
+
kind: "fallback",
|
|
2243
|
+
reason: "version_too_old",
|
|
2244
|
+
message: `broker speaks ${preflight.daemonVersion}, Path D requires \u2265${preflight.requiredVersion} \u2014 upgrade @muhaven/mcp and restart the broker`
|
|
2245
|
+
};
|
|
2246
|
+
}
|
|
2247
|
+
return {
|
|
2248
|
+
kind: "fallback",
|
|
2249
|
+
reason: "session_key_unavailable",
|
|
2250
|
+
message: "broker is running in read-only posture (no MUHAVEN_BROKER_SESSION_KEY set) \u2014 Path D requires a loaded session key"
|
|
2251
|
+
};
|
|
2252
|
+
}
|
|
2253
|
+
let activeId;
|
|
2254
|
+
try {
|
|
2255
|
+
const res = await deps.broker.getActiveSessionId();
|
|
2256
|
+
activeId = res.sessionId;
|
|
2257
|
+
} catch (err2) {
|
|
2258
|
+
return mapBrokerCallFailure(err2, "get_active_session_id");
|
|
2259
|
+
}
|
|
2260
|
+
if (!activeId) {
|
|
2261
|
+
const synced = await syncSnapshotFromMirror(deps, preflight.signerAddress);
|
|
2262
|
+
if (synced.kind === "fallback") {
|
|
2263
|
+
return synced;
|
|
2264
|
+
}
|
|
2265
|
+
activeId = synced.sessionId;
|
|
2266
|
+
}
|
|
2267
|
+
let snapshot;
|
|
2268
|
+
try {
|
|
2269
|
+
const res = await deps.broker.getPolicySnapshot(activeId);
|
|
2270
|
+
snapshot = res.snapshot;
|
|
2271
|
+
} catch (err2) {
|
|
2272
|
+
return mapBrokerCallFailure(err2, "get_policy_snapshot", "snapshot_lookup_failed");
|
|
2273
|
+
}
|
|
2274
|
+
if (!snapshot) {
|
|
2275
|
+
return {
|
|
2276
|
+
kind: "fallback",
|
|
2277
|
+
reason: "no_active_snapshot",
|
|
2278
|
+
message: `broker reported session ${activeId} active but get_policy_snapshot returned null (race? \u2014 refresh tier from dashboard)`
|
|
2279
|
+
};
|
|
2280
|
+
}
|
|
2281
|
+
if (snapshot.signerAddress.toLowerCase() !== preflight.signerAddress.toLowerCase()) {
|
|
2282
|
+
return {
|
|
2283
|
+
kind: "fallback",
|
|
2284
|
+
reason: "signer_mismatch",
|
|
2285
|
+
message: `snapshot ${activeId} is bound to signer ${snapshot.signerAddress}, broker is currently signing as ${preflight.signerAddress} \u2014 broker session-key likely rotated mid-flight; re-mint the scoped tier from the dashboard`
|
|
2286
|
+
};
|
|
2287
|
+
}
|
|
2288
|
+
const purchaseCap = snapshot.selectorCaps.find(
|
|
2289
|
+
(c) => c.selector.toLowerCase() === SUBSCRIPTION_PURCHASE_SELECTOR
|
|
2290
|
+
);
|
|
2291
|
+
if (!purchaseCap) {
|
|
2292
|
+
return {
|
|
2293
|
+
kind: "fallback",
|
|
2294
|
+
reason: "selector_not_in_snapshot",
|
|
2295
|
+
message: "active scoped session does not authorize subscription.purchase \u2014 re-mint the session with a purchase cap"
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
if (purchaseCap.maxAmount === null) {
|
|
2299
|
+
return {
|
|
2300
|
+
kind: "fallback",
|
|
2301
|
+
reason: "selector_uncapped",
|
|
2302
|
+
message: "active scoped session lists subscription.purchase but with no per-op cap (capArgIndex/maxAmount both null) \u2014 Slice 1 refuses to autonomy-buy without an explicit ceiling; re-mint with a maxAmount"
|
|
2303
|
+
};
|
|
2304
|
+
}
|
|
2305
|
+
const maxShares = BigInt(purchaseCap.maxAmount);
|
|
2306
|
+
if (shares > maxShares) {
|
|
2307
|
+
return {
|
|
2308
|
+
kind: "fallback",
|
|
2309
|
+
reason: "out_of_scope",
|
|
2310
|
+
message: `requested ${shares} shares exceeds the active session's per-op cap of ${maxShares} shares \u2014 fall back to Path C dashboard deep-link for this larger buy`
|
|
2311
|
+
};
|
|
894
2312
|
}
|
|
895
|
-
|
|
896
|
-
|
|
2313
|
+
if (!snapshot.targetContracts.some(
|
|
2314
|
+
(t) => t.toLowerCase() === subscriptionAddress.toLowerCase()
|
|
2315
|
+
)) {
|
|
2316
|
+
return {
|
|
2317
|
+
kind: "fallback",
|
|
2318
|
+
reason: "target_not_in_snapshot",
|
|
2319
|
+
message: `subscription target ${subscriptionAddress} not in active session's target allowlist \u2014 re-mint the session with subscription in scope`
|
|
2320
|
+
};
|
|
2321
|
+
}
|
|
2322
|
+
let accountAddress;
|
|
897
2323
|
try {
|
|
898
|
-
const
|
|
899
|
-
|
|
900
|
-
limit: input.limit
|
|
2324
|
+
const stateDto = await deps.backend.get("/api/v1/agent/policy/state", {
|
|
2325
|
+
surface: "mcp"
|
|
901
2326
|
});
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
2327
|
+
if (!stateDto.accountAddress || !/^0x[0-9a-fA-F]{40}$/.test(stateDto.accountAddress)) {
|
|
2328
|
+
return {
|
|
2329
|
+
kind: "fallback",
|
|
2330
|
+
reason: "no_validator_registered",
|
|
2331
|
+
message: "backend /agent/policy/state returned no accountAddress \u2014 re-login the MCP"
|
|
2332
|
+
};
|
|
2333
|
+
}
|
|
2334
|
+
accountAddress = stateDto.accountAddress.toLowerCase();
|
|
2335
|
+
} catch (err2) {
|
|
2336
|
+
return {
|
|
2337
|
+
kind: "fallback",
|
|
2338
|
+
reason: "no_validator_registered",
|
|
2339
|
+
message: `backend /agent/policy/state lookup failed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
2340
|
+
};
|
|
905
2341
|
}
|
|
906
|
-
|
|
907
|
-
|
|
2342
|
+
if (!snapshot.permissionId) {
|
|
2343
|
+
return {
|
|
2344
|
+
kind: "fallback",
|
|
2345
|
+
reason: "no_permission_id_in_snapshot",
|
|
2346
|
+
message: "active scoped session snapshot lacks permissionId \u2014 frontend storePolicySnapshot wire-up is a Slice 2 prerequisite; falling back to Path C"
|
|
2347
|
+
};
|
|
2348
|
+
}
|
|
2349
|
+
const permissionId = snapshot.permissionId;
|
|
2350
|
+
let encShares;
|
|
2351
|
+
let ephemeralEOA;
|
|
908
2352
|
try {
|
|
909
|
-
const
|
|
910
|
-
|
|
911
|
-
|
|
2353
|
+
const enc = await deps.backend.post("/api/v1/agent/path-d/encrypt-shares", {
|
|
2354
|
+
tokenAddress,
|
|
2355
|
+
sharesAmount: shares.toString()
|
|
912
2356
|
});
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
2357
|
+
if (!enc.encShares || typeof enc.encShares.ctHash !== "string" || typeof enc.encShares.securityZone !== "number" || typeof enc.encShares.utype !== "number" || typeof enc.encShares.signature !== "string" || typeof enc.ephemeralEOA !== "string") {
|
|
2358
|
+
return {
|
|
2359
|
+
kind: "fallback",
|
|
2360
|
+
reason: "encrypt_shares_server_error",
|
|
2361
|
+
message: "backend /agent/path-d/encrypt-shares returned malformed payload"
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
encShares = {
|
|
2365
|
+
ctHash: enc.encShares.ctHash,
|
|
2366
|
+
securityZone: enc.encShares.securityZone,
|
|
2367
|
+
utype: enc.encShares.utype,
|
|
2368
|
+
signature: enc.encShares.signature
|
|
2369
|
+
};
|
|
2370
|
+
ephemeralEOA = enc.ephemeralEOA;
|
|
2371
|
+
} catch (err2) {
|
|
2372
|
+
if (err2 instanceof BackendError) {
|
|
2373
|
+
const is4xx = typeof err2.status === "number" && err2.status < 500;
|
|
2374
|
+
return {
|
|
2375
|
+
kind: "fallback",
|
|
2376
|
+
reason: is4xx ? "encrypt_shares_rejected" : "encrypt_shares_server_error",
|
|
2377
|
+
message: `backend rejected encrypt-shares (backend.${err2.code})`
|
|
2378
|
+
};
|
|
2379
|
+
}
|
|
2380
|
+
return {
|
|
2381
|
+
kind: "fallback",
|
|
2382
|
+
reason: "encrypt_shares_server_error",
|
|
2383
|
+
message: `backend /agent/path-d/encrypt-shares failed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
2384
|
+
};
|
|
916
2385
|
}
|
|
917
|
-
|
|
918
|
-
|
|
2386
|
+
const innerCallData = encodeFunctionData({
|
|
2387
|
+
abi: SUBSCRIPTION_PURCHASE_ABI,
|
|
2388
|
+
functionName: "purchase",
|
|
2389
|
+
args: [
|
|
2390
|
+
tokenAddress,
|
|
2391
|
+
{
|
|
2392
|
+
ctHash: BigInt(encShares.ctHash),
|
|
2393
|
+
securityZone: encShares.securityZone,
|
|
2394
|
+
utype: encShares.utype,
|
|
2395
|
+
signature: encShares.signature
|
|
2396
|
+
},
|
|
2397
|
+
shares,
|
|
2398
|
+
// maxSharesHint — tight per spec
|
|
2399
|
+
ephemeralEOA
|
|
2400
|
+
]
|
|
2401
|
+
});
|
|
2402
|
+
const kernelCallData = encodeKernelExecuteSingleCall({
|
|
2403
|
+
target: subscriptionAddress,
|
|
2404
|
+
value: 0n,
|
|
2405
|
+
callData: innerCallData
|
|
2406
|
+
});
|
|
2407
|
+
let nonce;
|
|
2408
|
+
let feeData;
|
|
919
2409
|
try {
|
|
920
|
-
const
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
2410
|
+
const nonceKey = composeKernelV3NonceKey({ permissionId });
|
|
2411
|
+
nonce = await deps.bundler.getNonce(accountAddress, entryPointAddress, nonceKey);
|
|
2412
|
+
feeData = await deps.bundler.getFeeData();
|
|
2413
|
+
} catch (err2) {
|
|
2414
|
+
return {
|
|
2415
|
+
kind: "fallback",
|
|
2416
|
+
reason: "bundler_setup_failed",
|
|
2417
|
+
message: `bundler bootstrap failed: ${err2 instanceof BundlerClientError ? `${err2.code}: ${err2.message}` : String(err2)}`
|
|
2418
|
+
};
|
|
924
2419
|
}
|
|
925
|
-
|
|
926
|
-
|
|
2420
|
+
const partial = {
|
|
2421
|
+
sender: accountAddress,
|
|
2422
|
+
nonce: `0x${nonce.toString(16)}`,
|
|
2423
|
+
callData: kernelCallData,
|
|
2424
|
+
maxFeePerGas: feeData.maxFeePerGas,
|
|
2425
|
+
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
|
|
2426
|
+
signature: PLACEHOLDER_SIGNATURE
|
|
2427
|
+
};
|
|
2428
|
+
let sponsored;
|
|
927
2429
|
try {
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
2430
|
+
sponsored = await deps.bundler.sponsorUserOp(partial, entryPointAddress);
|
|
2431
|
+
} catch (err2) {
|
|
2432
|
+
const detail = err2 instanceof BundlerClientError && err2.detail && typeof err2.detail === "object" ? ` (rpc code=${err2.detail.code ?? "unknown"})` : "";
|
|
2433
|
+
const safeMsg = sanitizeRpcMessageForLlmContext(
|
|
2434
|
+
err2 instanceof Error ? err2.message : String(err2)
|
|
2435
|
+
);
|
|
2436
|
+
return {
|
|
2437
|
+
kind: "fallback",
|
|
2438
|
+
reason: "paymaster_rejected",
|
|
2439
|
+
message: `pm_sponsorUserOperation rejected${detail}: ${safeMsg}`
|
|
2440
|
+
};
|
|
939
2441
|
}
|
|
940
|
-
|
|
941
|
-
|
|
2442
|
+
const userOpForHash = {
|
|
2443
|
+
sender: accountAddress,
|
|
2444
|
+
nonce,
|
|
2445
|
+
factory: void 0,
|
|
2446
|
+
factoryData: void 0,
|
|
2447
|
+
callData: kernelCallData,
|
|
2448
|
+
callGasLimit: BigInt(sponsored.callGasLimit),
|
|
2449
|
+
verificationGasLimit: BigInt(sponsored.verificationGasLimit),
|
|
2450
|
+
preVerificationGas: BigInt(sponsored.preVerificationGas),
|
|
2451
|
+
maxFeePerGas: BigInt(feeData.maxFeePerGas),
|
|
2452
|
+
maxPriorityFeePerGas: BigInt(feeData.maxPriorityFeePerGas),
|
|
2453
|
+
paymaster: sponsored.paymaster,
|
|
2454
|
+
paymasterVerificationGasLimit: BigInt(sponsored.paymasterVerificationGasLimit),
|
|
2455
|
+
paymasterPostOpGasLimit: BigInt(sponsored.paymasterPostOpGasLimit),
|
|
2456
|
+
paymasterData: sponsored.paymasterData,
|
|
2457
|
+
signature: PLACEHOLDER_SIGNATURE
|
|
2458
|
+
};
|
|
2459
|
+
const userOpHash = getUserOperationHash({
|
|
2460
|
+
userOperation: userOpForHash,
|
|
2461
|
+
entryPointAddress,
|
|
2462
|
+
entryPointVersion: "0.7",
|
|
2463
|
+
chainId
|
|
2464
|
+
});
|
|
2465
|
+
let brokerSig;
|
|
942
2466
|
try {
|
|
943
|
-
const
|
|
944
|
-
|
|
945
|
-
|
|
2467
|
+
const signed = await deps.broker.signUserOp({
|
|
2468
|
+
sessionId: activeId,
|
|
2469
|
+
userOpHash,
|
|
2470
|
+
innerCall: { target: subscriptionAddress, callData: innerCallData },
|
|
2471
|
+
intent: {
|
|
2472
|
+
tool: "muhaven.position.buy",
|
|
2473
|
+
summary: `${shares.toString()} shares of ${sanitizeSymbolForLlmContext(tokenSymbol)}`
|
|
2474
|
+
}
|
|
946
2475
|
});
|
|
947
|
-
|
|
948
|
-
} catch (
|
|
949
|
-
|
|
2476
|
+
brokerSig = signed.signature;
|
|
2477
|
+
} catch (err2) {
|
|
2478
|
+
if (err2 instanceof BrokerClientError && err2.brokerCode) {
|
|
2479
|
+
const code = err2.brokerCode;
|
|
2480
|
+
if (code === "policy_violation") {
|
|
2481
|
+
return {
|
|
2482
|
+
kind: "fallback",
|
|
2483
|
+
reason: "broker_policy_violation",
|
|
2484
|
+
message: "broker rejected sign_userop: policy_violation (innerCall vs snapshot mismatch)"
|
|
2485
|
+
};
|
|
2486
|
+
}
|
|
2487
|
+
if (code === "scope_violation") {
|
|
2488
|
+
return {
|
|
2489
|
+
kind: "fallback",
|
|
2490
|
+
reason: "broker_scope_violation",
|
|
2491
|
+
message: "broker rejected sign_userop: scope_violation (snapshot expired between gate and sign)"
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
if (code === "max_spend_exceeded") {
|
|
2495
|
+
return {
|
|
2496
|
+
kind: "fallback",
|
|
2497
|
+
reason: "broker_max_spend_exceeded",
|
|
2498
|
+
message: "broker rejected sign_userop: max_spend_exceeded (innerCall maxSharesHint over cap)"
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
if (code === "no_active_snapshot") {
|
|
2502
|
+
return {
|
|
2503
|
+
kind: "fallback",
|
|
2504
|
+
reason: "broker_no_active_snapshot_at_sign",
|
|
2505
|
+
message: "broker reported no_active_snapshot at sign time \u2014 likely GC race after our snapshot read"
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
return mapBrokerCallFailure(err2, "sign_userop", "broker_internal");
|
|
2510
|
+
}
|
|
2511
|
+
const signedUserOpWire = {
|
|
2512
|
+
sender: accountAddress,
|
|
2513
|
+
nonce: partial.nonce,
|
|
2514
|
+
callData: kernelCallData,
|
|
2515
|
+
callGasLimit: sponsored.callGasLimit,
|
|
2516
|
+
verificationGasLimit: sponsored.verificationGasLimit,
|
|
2517
|
+
preVerificationGas: sponsored.preVerificationGas,
|
|
2518
|
+
maxFeePerGas: feeData.maxFeePerGas,
|
|
2519
|
+
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
|
|
2520
|
+
paymaster: sponsored.paymaster,
|
|
2521
|
+
paymasterVerificationGasLimit: sponsored.paymasterVerificationGasLimit,
|
|
2522
|
+
paymasterPostOpGasLimit: sponsored.paymasterPostOpGasLimit,
|
|
2523
|
+
paymasterData: sponsored.paymasterData,
|
|
2524
|
+
signature: buildKernelSessionKeySignature({ ecdsaSignature: brokerSig })
|
|
2525
|
+
};
|
|
2526
|
+
let submittedHash;
|
|
2527
|
+
try {
|
|
2528
|
+
submittedHash = await deps.bundler.sendUserOp(signedUserOpWire, entryPointAddress);
|
|
2529
|
+
} catch (err2) {
|
|
2530
|
+
const detail = err2 instanceof BundlerClientError && err2.detail && typeof err2.detail === "object" ? ` (rpc code=${err2.detail.code ?? "unknown"})` : "";
|
|
2531
|
+
return {
|
|
2532
|
+
kind: "fallback",
|
|
2533
|
+
reason: "bundler_submit_rejected",
|
|
2534
|
+
message: `bundler eth_sendUserOperation rejected${detail}: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
2535
|
+
};
|
|
2536
|
+
}
|
|
2537
|
+
if (submittedHash.toLowerCase() !== userOpHash.toLowerCase()) {
|
|
2538
|
+
return {
|
|
2539
|
+
kind: "fallback",
|
|
2540
|
+
reason: "userop_hash_mismatch",
|
|
2541
|
+
message: `bundler reported userOpHash ${submittedHash} but we signed ${userOpHash} \u2014 refusing to wait for receipt`
|
|
2542
|
+
};
|
|
2543
|
+
}
|
|
2544
|
+
try {
|
|
2545
|
+
const receipt = await deps.bundler.waitForReceipt(userOpHash, { timeoutMs: 12e3 });
|
|
2546
|
+
return {
|
|
2547
|
+
kind: "ok",
|
|
2548
|
+
data: {
|
|
2549
|
+
action: "buy",
|
|
2550
|
+
status: "submitted",
|
|
2551
|
+
txHash: receipt.receipt.transactionHash,
|
|
2552
|
+
userOpHash,
|
|
2553
|
+
path: "D"
|
|
2554
|
+
}
|
|
2555
|
+
};
|
|
2556
|
+
} catch (err2) {
|
|
2557
|
+
try {
|
|
2558
|
+
const lateReceipt = await deps.bundler.getReceipt(userOpHash);
|
|
2559
|
+
if (lateReceipt) {
|
|
2560
|
+
return {
|
|
2561
|
+
kind: "ok",
|
|
2562
|
+
data: {
|
|
2563
|
+
action: "buy",
|
|
2564
|
+
status: "submitted",
|
|
2565
|
+
txHash: lateReceipt.receipt.transactionHash,
|
|
2566
|
+
userOpHash,
|
|
2567
|
+
path: "D"
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
}
|
|
2571
|
+
} catch {
|
|
2572
|
+
}
|
|
2573
|
+
return {
|
|
2574
|
+
kind: "fallback",
|
|
2575
|
+
reason: "bundler_receipt_timeout",
|
|
2576
|
+
message: `no receipt for userOp ${userOpHash} within 12s. The userOp may still mine. BEFORE proposing another position.buy for this intent, call muhaven.read.activity to verify whether the prior submit settled \u2014 re-issuing without that check risks double-filling.`,
|
|
2577
|
+
submittedUserOpHash: userOpHash
|
|
2578
|
+
};
|
|
950
2579
|
}
|
|
951
|
-
}
|
|
952
|
-
function buildPositionDeeplink(dashboardBaseUrl, action, params) {
|
|
953
|
-
const base = dashboardBaseUrl.replace(/\/+$/, "");
|
|
954
|
-
const path = action === "buy" || action === "sell" ? "/trade" : action === "claim" ? "/yields" : "/cash";
|
|
955
|
-
const search = new URLSearchParams();
|
|
956
|
-
if (action === "buy" || action === "sell") search.set("mode", action);
|
|
957
|
-
for (const [k, v] of Object.entries(params)) search.set(k, v);
|
|
958
|
-
search.set("from", "mcp");
|
|
959
|
-
return `${base}${path}?${search.toString()}`;
|
|
960
|
-
}
|
|
961
|
-
function resolveDashboardBaseUrl(deps) {
|
|
962
|
-
return deps.dashboardBaseUrl ?? "https://muhaven.app";
|
|
963
|
-
}
|
|
964
|
-
function resolveTokenInCatalog(identifier, catalog) {
|
|
965
|
-
const needle = identifier.toLowerCase();
|
|
966
|
-
return catalog.find(
|
|
967
|
-
(t) => t.address.toLowerCase() === needle || t.symbol.toLowerCase() === needle
|
|
968
|
-
) ?? null;
|
|
969
|
-
}
|
|
970
|
-
function sanitizeSymbolForLlmContext(raw) {
|
|
971
|
-
const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, "?");
|
|
972
|
-
return cleaned.length > 16 ? cleaned.slice(0, 16) : cleaned;
|
|
973
2580
|
}
|
|
974
2581
|
async function positionBuy(input, deps) {
|
|
975
2582
|
let catalog;
|
|
@@ -1034,6 +2641,21 @@ async function positionBuy(input, deps) {
|
|
|
1034
2641
|
const effectiveNotionalDisplay = formatUsd6AsDecimal(effectiveNotionalUsd6);
|
|
1035
2642
|
const navDisplay = formatUsd6AsDecimal(navUsd6);
|
|
1036
2643
|
const sharesStr = shares.toString();
|
|
2644
|
+
let pathDFallbackReason;
|
|
2645
|
+
let pathDSubmittedUserOpHash;
|
|
2646
|
+
const pathD = await attemptPathD(
|
|
2647
|
+
{ shares, tokenAddress: token.address, tokenSymbol: token.symbol },
|
|
2648
|
+
deps
|
|
2649
|
+
);
|
|
2650
|
+
if (pathD.kind === "ok") {
|
|
2651
|
+
return ok(pathD.data);
|
|
2652
|
+
}
|
|
2653
|
+
if (pathD.kind === "fallback") {
|
|
2654
|
+
pathDFallbackReason = pathD.reason;
|
|
2655
|
+
if (pathD.submittedUserOpHash) {
|
|
2656
|
+
pathDSubmittedUserOpHash = pathD.submittedUserOpHash;
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
1037
2659
|
const dashboardUrl = buildPositionDeeplink(resolveDashboardBaseUrl(deps), "buy", {
|
|
1038
2660
|
token: token.symbol,
|
|
1039
2661
|
amount: sharesStr
|
|
@@ -1053,7 +2675,9 @@ ${dashboardUrl}`,
|
|
|
1053
2675
|
// shows the share count instead of the user-stated notional.
|
|
1054
2676
|
amountUsdc: input.amountUsdc,
|
|
1055
2677
|
effectiveNotionalUsd6: effectiveNotionalUsd6.toString(),
|
|
1056
|
-
navUsd6: navUsd6.toString()
|
|
2678
|
+
navUsd6: navUsd6.toString(),
|
|
2679
|
+
...pathDFallbackReason ? { pathDFallbackReason } : {},
|
|
2680
|
+
...pathDSubmittedUserOpHash ? { pathDSubmittedUserOpHash } : {}
|
|
1057
2681
|
}
|
|
1058
2682
|
});
|
|
1059
2683
|
}
|
|
@@ -1404,14 +3028,20 @@ var SERVER_NAME = "@muhaven/mcp";
|
|
|
1404
3028
|
var SERVER_VERSION = resolveServerVersion();
|
|
1405
3029
|
function resolveServerVersion() {
|
|
1406
3030
|
{
|
|
1407
|
-
return "0.2.
|
|
3031
|
+
return "0.2.3";
|
|
1408
3032
|
}
|
|
1409
3033
|
}
|
|
1410
3034
|
function toJsonInputSchema(schema) {
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
3035
|
+
const json = zodToJsonSchema(schema, {
|
|
3036
|
+
target: "jsonSchema7",
|
|
3037
|
+
$refStrategy: "none",
|
|
3038
|
+
removeAdditionalStrategy: "strict"
|
|
3039
|
+
});
|
|
3040
|
+
if ("$schema" in json) {
|
|
3041
|
+
const { $schema: _drop, ...rest } = json;
|
|
3042
|
+
return rest;
|
|
3043
|
+
}
|
|
3044
|
+
return json;
|
|
1415
3045
|
}
|
|
1416
3046
|
async function loadPinnedToolHashes() {
|
|
1417
3047
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
@@ -1480,8 +3110,12 @@ function buildMcpServer(opts) {
|
|
|
1480
3110
|
const result = await entry.handler(parsed, {
|
|
1481
3111
|
backend: opts.backend,
|
|
1482
3112
|
broker: opts.broker,
|
|
3113
|
+
bundler: opts.bundler,
|
|
1483
3114
|
surface: "mcp",
|
|
1484
|
-
dashboardBaseUrl: opts.dashboardBaseUrl
|
|
3115
|
+
dashboardBaseUrl: opts.dashboardBaseUrl,
|
|
3116
|
+
chainId: opts.chainId,
|
|
3117
|
+
subscriptionAddress: opts.subscriptionAddress,
|
|
3118
|
+
entryPointAddress: opts.entryPointAddress
|
|
1485
3119
|
});
|
|
1486
3120
|
return toolJsonResponse(result);
|
|
1487
3121
|
} catch (err2) {
|
|
@@ -1532,6 +3166,17 @@ async function runMcpStdioCli(opts = {}) {
|
|
|
1532
3166
|
timeoutMs: config.requestTimeoutMs,
|
|
1533
3167
|
allowedHosts: config.allowedBackendHosts
|
|
1534
3168
|
});
|
|
3169
|
+
const bundler = config.bundlerUrl ? new BundlerClient({
|
|
3170
|
+
endpoint: config.bundlerUrl,
|
|
3171
|
+
requestTimeoutMs: config.bundlerTimeoutMs,
|
|
3172
|
+
expectedChainId: config.chainId,
|
|
3173
|
+
// Wave 5 Path D 0.2.3 — Origin defaults to the dashboard URL
|
|
3174
|
+
// so ZeroDev's domain-allowlist accepts the MCP server's RPC
|
|
3175
|
+
// traffic. The dashboard URL is the natural match because it's
|
|
3176
|
+
// also the SIWE / passkey origin the project already trusts
|
|
3177
|
+
// for browser-side traffic.
|
|
3178
|
+
originHeader: config.dashboardBaseUrl
|
|
3179
|
+
}) : void 0;
|
|
1535
3180
|
const baseRegistry = selectRegistry(config.readOnly);
|
|
1536
3181
|
const registry = opts.filterRegistry ? opts.filterRegistry(baseRegistry) : baseRegistry;
|
|
1537
3182
|
if (registry.length === 0) {
|
|
@@ -1544,8 +3189,20 @@ async function runMcpStdioCli(opts = {}) {
|
|
|
1544
3189
|
registry,
|
|
1545
3190
|
backend,
|
|
1546
3191
|
broker: config.readOnly ? void 0 : broker,
|
|
1547
|
-
|
|
3192
|
+
bundler: config.readOnly ? void 0 : bundler,
|
|
3193
|
+
dashboardBaseUrl: config.dashboardBaseUrl,
|
|
3194
|
+
chainId: config.chainId,
|
|
3195
|
+
subscriptionAddress: config.subscriptionAddress,
|
|
3196
|
+
entryPointAddress: config.entryPointAddress
|
|
1548
3197
|
});
|
|
3198
|
+
if (bundler && !config.readOnly) {
|
|
3199
|
+
void bundler.assertChainId().catch((err2) => {
|
|
3200
|
+
process.stderr.write(
|
|
3201
|
+
`[muhaven-mcp] bundler chain-id assert failed: ${err2 instanceof Error ? err2.message : String(err2)} \u2014 Path D autonomous-buys will fail until MUHAVEN_BUNDLER_URL + MUHAVEN_CHAIN_ID agree
|
|
3202
|
+
`
|
|
3203
|
+
);
|
|
3204
|
+
});
|
|
3205
|
+
}
|
|
1549
3206
|
const transport = new StdioServerTransport();
|
|
1550
3207
|
await server.connect(transport);
|
|
1551
3208
|
await new Promise((resolve) => {
|
|
@@ -1650,140 +3307,52 @@ var DeviceFlowClient = class {
|
|
|
1650
3307
|
const body2 = await safeJson(res);
|
|
1651
3308
|
throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body: body2 });
|
|
1652
3309
|
}
|
|
1653
|
-
const body = await safeJson(res);
|
|
1654
|
-
if (!body || !body.deviceCode || !body.userCode) {
|
|
1655
|
-
throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
|
|
1656
|
-
}
|
|
1657
|
-
const verificationUri = `${trim(this.options.dashboardBaseUrl)}/link`;
|
|
1658
|
-
const verificationUriComplete = `${verificationUri}?code=${encodeURIComponent(body.userCode)}`;
|
|
1659
|
-
return {
|
|
1660
|
-
deviceCode: body.deviceCode,
|
|
1661
|
-
userCode: body.userCode,
|
|
1662
|
-
verificationUri,
|
|
1663
|
-
verificationUriComplete,
|
|
1664
|
-
expiresInSec: body.expiresInSec ?? 300,
|
|
1665
|
-
pollIntervalSec: body.pollIntervalSec ?? Math.floor(DEFAULT_POLL_INTERVAL_MS / 1e3)
|
|
1666
|
-
};
|
|
1667
|
-
}
|
|
1668
|
-
async pollOnce(deviceCode) {
|
|
1669
|
-
const url = new URL("/api/v1/auth/device/token", this.options.backendBaseUrl);
|
|
1670
|
-
let res;
|
|
1671
|
-
try {
|
|
1672
|
-
res = await this.fetchImpl(url, {
|
|
1673
|
-
method: "POST",
|
|
1674
|
-
headers: { "content-type": "application/json", accept: "application/json" },
|
|
1675
|
-
body: JSON.stringify({ deviceCode })
|
|
1676
|
-
});
|
|
1677
|
-
} catch (err2) {
|
|
1678
|
-
throw new DeviceFlowAbortedError({ code: "network", cause: err2 });
|
|
1679
|
-
}
|
|
1680
|
-
if (res.status === 429) {
|
|
1681
|
-
return { state: "pending" };
|
|
1682
|
-
}
|
|
1683
|
-
const body = await safeJson(res);
|
|
1684
|
-
if (!body || typeof body.state !== "string") {
|
|
1685
|
-
throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
|
|
1686
|
-
}
|
|
1687
|
-
return body;
|
|
1688
|
-
}
|
|
1689
|
-
};
|
|
1690
|
-
function trim(s) {
|
|
1691
|
-
return s.endsWith("/") ? s.slice(0, -1) : s;
|
|
1692
|
-
}
|
|
1693
|
-
async function safeJson(res) {
|
|
1694
|
-
try {
|
|
1695
|
-
return await res.json();
|
|
1696
|
-
} catch {
|
|
1697
|
-
return null;
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
|
|
1701
|
-
// src/broker/protocol.ts
|
|
1702
|
-
var BROKER_PROTOCOL_VERSION = "0.3.0";
|
|
1703
|
-
var HASH_HEX_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
1704
|
-
var JWT_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
1705
|
-
function isHashHex(value) {
|
|
1706
|
-
return typeof value === "string" && HASH_HEX_RE.test(value);
|
|
1707
|
-
}
|
|
1708
|
-
function isJwtShape(value) {
|
|
1709
|
-
return typeof value === "string" && value.length <= 8192 && JWT_RE.test(value);
|
|
1710
|
-
}
|
|
1711
|
-
function parseBrokerRequest(line) {
|
|
1712
|
-
let parsed;
|
|
1713
|
-
try {
|
|
1714
|
-
parsed = JSON.parse(line);
|
|
1715
|
-
} catch {
|
|
1716
|
-
return { type: "error", code: "invalid_request", message: "request is not valid JSON" };
|
|
1717
|
-
}
|
|
1718
|
-
if (typeof parsed !== "object" || parsed === null) {
|
|
1719
|
-
return { type: "error", code: "invalid_request", message: "request must be a JSON object" };
|
|
1720
|
-
}
|
|
1721
|
-
const obj = parsed;
|
|
1722
|
-
switch (obj.type) {
|
|
1723
|
-
case "hello":
|
|
1724
|
-
return { type: "hello" };
|
|
1725
|
-
case "sign_hash": {
|
|
1726
|
-
const hash = obj.hash;
|
|
1727
|
-
if (!isHashHex(hash)) {
|
|
1728
|
-
return {
|
|
1729
|
-
type: "error",
|
|
1730
|
-
code: "invalid_request",
|
|
1731
|
-
message: "sign_hash.hash must be a 0x-prefixed 32-byte hex string"
|
|
1732
|
-
};
|
|
1733
|
-
}
|
|
1734
|
-
const intent = obj.intent;
|
|
1735
|
-
const intentValid = intent === void 0 || typeof intent === "object" && intent !== null && typeof intent.tool === "string";
|
|
1736
|
-
if (!intentValid) {
|
|
1737
|
-
return {
|
|
1738
|
-
type: "error",
|
|
1739
|
-
code: "invalid_request",
|
|
1740
|
-
message: "sign_hash.intent.tool must be a string when provided"
|
|
1741
|
-
};
|
|
1742
|
-
}
|
|
1743
|
-
return {
|
|
1744
|
-
type: "sign_hash",
|
|
1745
|
-
hash,
|
|
1746
|
-
...intent === void 0 ? {} : { intent }
|
|
1747
|
-
};
|
|
3310
|
+
const body = await safeJson(res);
|
|
3311
|
+
if (!body || !body.deviceCode || !body.userCode) {
|
|
3312
|
+
throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
|
|
1748
3313
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
};
|
|
3314
|
+
const verificationUri = `${trim(this.options.dashboardBaseUrl)}/link`;
|
|
3315
|
+
const verificationUriComplete = `${verificationUri}?code=${encodeURIComponent(body.userCode)}`;
|
|
3316
|
+
return {
|
|
3317
|
+
deviceCode: body.deviceCode,
|
|
3318
|
+
userCode: body.userCode,
|
|
3319
|
+
verificationUri,
|
|
3320
|
+
verificationUriComplete,
|
|
3321
|
+
expiresInSec: body.expiresInSec ?? 300,
|
|
3322
|
+
pollIntervalSec: body.pollIntervalSec ?? Math.floor(DEFAULT_POLL_INTERVAL_MS / 1e3)
|
|
3323
|
+
};
|
|
3324
|
+
}
|
|
3325
|
+
async pollOnce(deviceCode) {
|
|
3326
|
+
const url = new URL("/api/v1/auth/device/token", this.options.backendBaseUrl);
|
|
3327
|
+
let res;
|
|
3328
|
+
try {
|
|
3329
|
+
res = await this.fetchImpl(url, {
|
|
3330
|
+
method: "POST",
|
|
3331
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
3332
|
+
body: JSON.stringify({ deviceCode })
|
|
3333
|
+
});
|
|
3334
|
+
} catch (err2) {
|
|
3335
|
+
throw new DeviceFlowAbortedError({ code: "network", cause: err2 });
|
|
1772
3336
|
}
|
|
1773
|
-
|
|
1774
|
-
return {
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
message: `unsupported request type: ${String(obj.type)}`
|
|
1782
|
-
};
|
|
3337
|
+
if (res.status === 429) {
|
|
3338
|
+
return { state: "pending" };
|
|
3339
|
+
}
|
|
3340
|
+
const body = await safeJson(res);
|
|
3341
|
+
if (!body || typeof body.state !== "string") {
|
|
3342
|
+
throw new DeviceFlowAbortedError({ code: "invalid_response", status: res.status, body });
|
|
3343
|
+
}
|
|
3344
|
+
return body;
|
|
1783
3345
|
}
|
|
3346
|
+
};
|
|
3347
|
+
function trim(s) {
|
|
3348
|
+
return s.endsWith("/") ? s.slice(0, -1) : s;
|
|
1784
3349
|
}
|
|
1785
|
-
function
|
|
1786
|
-
|
|
3350
|
+
async function safeJson(res) {
|
|
3351
|
+
try {
|
|
3352
|
+
return await res.json();
|
|
3353
|
+
} catch {
|
|
3354
|
+
return null;
|
|
3355
|
+
}
|
|
1787
3356
|
}
|
|
1788
3357
|
var MissingSessionKeyError = class extends Error {
|
|
1789
3358
|
constructor() {
|
|
@@ -1799,6 +3368,9 @@ var NullSigner = class {
|
|
|
1799
3368
|
async signHash(_hash) {
|
|
1800
3369
|
throw new MissingSessionKeyError();
|
|
1801
3370
|
}
|
|
3371
|
+
async signRawMessage(_hash) {
|
|
3372
|
+
throw new MissingSessionKeyError();
|
|
3373
|
+
}
|
|
1802
3374
|
};
|
|
1803
3375
|
var ViemSigner = class {
|
|
1804
3376
|
account;
|
|
@@ -1811,6 +3383,9 @@ var ViemSigner = class {
|
|
|
1811
3383
|
async signHash(hash) {
|
|
1812
3384
|
return this.account.sign({ hash });
|
|
1813
3385
|
}
|
|
3386
|
+
async signRawMessage(hash) {
|
|
3387
|
+
return this.account.signMessage({ message: { raw: hash } });
|
|
3388
|
+
}
|
|
1814
3389
|
};
|
|
1815
3390
|
var KEYRING_SERVICE = "muhaven.mcp";
|
|
1816
3391
|
var KEYRING_ACCOUNT = "jwt";
|
|
@@ -1967,11 +3542,293 @@ async function openKeystore(options = {}) {
|
|
|
1967
3542
|
}
|
|
1968
3543
|
return { keystore: new OsKeystore(entry), fallbackReason: null };
|
|
1969
3544
|
}
|
|
3545
|
+
var PolicyStoreError = class extends Error {
|
|
3546
|
+
constructor(code, message, cause) {
|
|
3547
|
+
super(message);
|
|
3548
|
+
this.code = code;
|
|
3549
|
+
this.cause = cause;
|
|
3550
|
+
this.name = "PolicyStoreError";
|
|
3551
|
+
}
|
|
3552
|
+
code;
|
|
3553
|
+
cause;
|
|
3554
|
+
};
|
|
3555
|
+
var SESSION_ID_RE2 = /^[A-Za-z0-9_-]{1,128}$/;
|
|
3556
|
+
var UINT256_MAX_LOCAL = (1n << 256n) - 1n;
|
|
3557
|
+
function validateSessionId(sessionId) {
|
|
3558
|
+
if (!SESSION_ID_RE2.test(sessionId)) {
|
|
3559
|
+
throw new PolicyStoreError(
|
|
3560
|
+
"invalid_session_id",
|
|
3561
|
+
`sessionId "${sessionId}" must be 1-128 chars [A-Za-z0-9_-] (path-traversal guard)`
|
|
3562
|
+
);
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
var FilePolicyStore = class {
|
|
3566
|
+
constructor(dir) {
|
|
3567
|
+
this.dir = dir;
|
|
3568
|
+
}
|
|
3569
|
+
dir;
|
|
3570
|
+
static defaultDir() {
|
|
3571
|
+
return join(homedir(), ".muhaven", "policy-snapshots");
|
|
3572
|
+
}
|
|
3573
|
+
snapshotPath(sessionId) {
|
|
3574
|
+
return join(this.dir, `${sessionId}.json`);
|
|
3575
|
+
}
|
|
3576
|
+
async get(sessionId, nowSec) {
|
|
3577
|
+
validateSessionId(sessionId);
|
|
3578
|
+
let raw;
|
|
3579
|
+
try {
|
|
3580
|
+
raw = await readFile(this.snapshotPath(sessionId), "utf8");
|
|
3581
|
+
} catch (err2) {
|
|
3582
|
+
if (err2.code === "ENOENT") return null;
|
|
3583
|
+
throw new PolicyStoreError(
|
|
3584
|
+
"read_failed",
|
|
3585
|
+
`failed to read snapshot ${sessionId}: ${asMessage2(err2)}`,
|
|
3586
|
+
err2
|
|
3587
|
+
);
|
|
3588
|
+
}
|
|
3589
|
+
let parsed;
|
|
3590
|
+
try {
|
|
3591
|
+
const obj = JSON.parse(raw);
|
|
3592
|
+
parsed = coerceFromDisk(obj);
|
|
3593
|
+
} catch (err2) {
|
|
3594
|
+
throw new PolicyStoreError(
|
|
3595
|
+
"malformed_record",
|
|
3596
|
+
`snapshot ${sessionId} is not valid JSON: ${asMessage2(err2)}`,
|
|
3597
|
+
err2
|
|
3598
|
+
);
|
|
3599
|
+
}
|
|
3600
|
+
if (parsed.validUntilSec <= nowSec) return null;
|
|
3601
|
+
return parsed;
|
|
3602
|
+
}
|
|
3603
|
+
async put(snapshot) {
|
|
3604
|
+
validateSessionId(snapshot.sessionId);
|
|
3605
|
+
const dest = this.snapshotPath(snapshot.sessionId);
|
|
3606
|
+
const tmp = `${dest}.tmp-${randomBytes(6).toString("hex")}`;
|
|
3607
|
+
try {
|
|
3608
|
+
await mkdir(this.dir, { recursive: true, mode: 448 });
|
|
3609
|
+
await chmod(this.dir, 448).catch(() => void 0);
|
|
3610
|
+
await writeFile(tmp, JSON.stringify(snapshot), { mode: 384 });
|
|
3611
|
+
await chmod(tmp, 384).catch(() => void 0);
|
|
3612
|
+
await rename(tmp, dest);
|
|
3613
|
+
} catch (err2) {
|
|
3614
|
+
await unlink(tmp).catch(() => void 0);
|
|
3615
|
+
throw new PolicyStoreError(
|
|
3616
|
+
"write_failed",
|
|
3617
|
+
`failed to write snapshot ${snapshot.sessionId}: ${asMessage2(err2)}`,
|
|
3618
|
+
err2
|
|
3619
|
+
);
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
async delete(sessionId) {
|
|
3623
|
+
validateSessionId(sessionId);
|
|
3624
|
+
try {
|
|
3625
|
+
await unlink(this.snapshotPath(sessionId));
|
|
3626
|
+
} catch (err2) {
|
|
3627
|
+
if (err2.code === "ENOENT") return;
|
|
3628
|
+
throw new PolicyStoreError(
|
|
3629
|
+
"delete_failed",
|
|
3630
|
+
`failed to delete snapshot ${sessionId}: ${asMessage2(err2)}`,
|
|
3631
|
+
err2
|
|
3632
|
+
);
|
|
3633
|
+
}
|
|
3634
|
+
}
|
|
3635
|
+
async list() {
|
|
3636
|
+
let entries;
|
|
3637
|
+
try {
|
|
3638
|
+
entries = await readdir(this.dir);
|
|
3639
|
+
} catch (err2) {
|
|
3640
|
+
if (err2.code === "ENOENT") return [];
|
|
3641
|
+
throw new PolicyStoreError(
|
|
3642
|
+
"read_failed",
|
|
3643
|
+
`failed to enumerate snapshot dir: ${asMessage2(err2)}`,
|
|
3644
|
+
err2
|
|
3645
|
+
);
|
|
3646
|
+
}
|
|
3647
|
+
const out = [];
|
|
3648
|
+
for (const entry of entries) {
|
|
3649
|
+
if (!entry.endsWith(".json")) continue;
|
|
3650
|
+
const sessionId = entry.slice(0, -".json".length);
|
|
3651
|
+
if (!SESSION_ID_RE2.test(sessionId)) continue;
|
|
3652
|
+
try {
|
|
3653
|
+
const raw = await readFile(join(this.dir, entry), "utf8");
|
|
3654
|
+
out.push(coerceFromDisk(JSON.parse(raw)));
|
|
3655
|
+
} catch {
|
|
3656
|
+
continue;
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
return out;
|
|
3660
|
+
}
|
|
3661
|
+
async activeSessionId(activeSignerAddress, nowSec) {
|
|
3662
|
+
const all = await this.list();
|
|
3663
|
+
const needle = activeSignerAddress.toLowerCase();
|
|
3664
|
+
const matches = all.filter(
|
|
3665
|
+
(s) => s.validUntilSec > nowSec && s.signerAddress.toLowerCase() === needle
|
|
3666
|
+
);
|
|
3667
|
+
return matches.length === 1 ? matches[0].sessionId : null;
|
|
3668
|
+
}
|
|
3669
|
+
};
|
|
3670
|
+
function coerceFromDisk(obj) {
|
|
3671
|
+
if (typeof obj !== "object" || obj === null) throw new Error("snapshot not an object");
|
|
3672
|
+
const o = obj;
|
|
3673
|
+
if (typeof o.sessionId !== "string" || !SESSION_ID_RE2.test(o.sessionId)) {
|
|
3674
|
+
throw new Error("snapshot.sessionId malformed");
|
|
3675
|
+
}
|
|
3676
|
+
if (o.mode !== "scoped") throw new Error('snapshot.mode must be "scoped"');
|
|
3677
|
+
if (typeof o.signerAddress !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(o.signerAddress)) {
|
|
3678
|
+
throw new Error("snapshot.signerAddress malformed");
|
|
3679
|
+
}
|
|
3680
|
+
if (!Array.isArray(o.targetContracts) || !o.targetContracts.every((t) => typeof t === "string" && /^0x[0-9a-fA-F]{40}$/.test(t))) {
|
|
3681
|
+
throw new Error("snapshot.targetContracts malformed");
|
|
3682
|
+
}
|
|
3683
|
+
if (!Array.isArray(o.selectorCaps) || o.selectorCaps.length === 0) {
|
|
3684
|
+
throw new Error("snapshot.selectorCaps malformed");
|
|
3685
|
+
}
|
|
3686
|
+
const caps = [];
|
|
3687
|
+
for (const c of o.selectorCaps) {
|
|
3688
|
+
if (typeof c !== "object" || c === null) throw new Error("selectorCap not an object");
|
|
3689
|
+
const cap = c;
|
|
3690
|
+
if (typeof cap.selector !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(cap.selector)) {
|
|
3691
|
+
throw new Error("selectorCap.selector malformed");
|
|
3692
|
+
}
|
|
3693
|
+
const indexNull = cap.capArgIndex === null;
|
|
3694
|
+
const amountNull = cap.maxAmount === null;
|
|
3695
|
+
if (indexNull !== amountNull) {
|
|
3696
|
+
throw new Error("selectorCap.capArgIndex/maxAmount must both be null or both non-null");
|
|
3697
|
+
}
|
|
3698
|
+
if (!indexNull) {
|
|
3699
|
+
if (typeof cap.capArgIndex !== "number" || !Number.isInteger(cap.capArgIndex) || cap.capArgIndex < 0 || cap.capArgIndex > 31) {
|
|
3700
|
+
throw new Error("selectorCap.capArgIndex must be an integer in [0, 31]");
|
|
3701
|
+
}
|
|
3702
|
+
if (typeof cap.maxAmount !== "string" || !/^(0|[1-9][0-9]{0,77})$/.test(cap.maxAmount)) {
|
|
3703
|
+
throw new Error("selectorCap.maxAmount malformed (length)");
|
|
3704
|
+
}
|
|
3705
|
+
if (BigInt(cap.maxAmount) > UINT256_MAX_LOCAL) {
|
|
3706
|
+
throw new Error("selectorCap.maxAmount exceeds uint256 max");
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
caps.push({
|
|
3710
|
+
selector: cap.selector.toLowerCase(),
|
|
3711
|
+
capArgIndex: indexNull ? null : cap.capArgIndex,
|
|
3712
|
+
maxAmount: indexNull ? null : cap.maxAmount
|
|
3713
|
+
});
|
|
3714
|
+
}
|
|
3715
|
+
if (typeof o.validUntilSec !== "number" || o.validUntilSec <= 0) {
|
|
3716
|
+
throw new Error("snapshot.validUntilSec malformed");
|
|
3717
|
+
}
|
|
3718
|
+
if (typeof o.mintedAtSec !== "number" || o.mintedAtSec <= 0) {
|
|
3719
|
+
throw new Error("snapshot.mintedAtSec malformed");
|
|
3720
|
+
}
|
|
3721
|
+
if (o.consentActionHash !== void 0) {
|
|
3722
|
+
if (typeof o.consentActionHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(o.consentActionHash)) {
|
|
3723
|
+
throw new Error("snapshot.consentActionHash malformed");
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
if (o.consentTextSha256 !== void 0) {
|
|
3727
|
+
if (typeof o.consentTextSha256 !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(o.consentTextSha256)) {
|
|
3728
|
+
throw new Error("snapshot.consentTextSha256 malformed");
|
|
3729
|
+
}
|
|
3730
|
+
}
|
|
3731
|
+
if (o.permissionId !== void 0) {
|
|
3732
|
+
if (typeof o.permissionId !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(o.permissionId)) {
|
|
3733
|
+
throw new Error("snapshot.permissionId malformed (must be 0x-prefixed 4-byte hex)");
|
|
3734
|
+
}
|
|
3735
|
+
}
|
|
3736
|
+
return {
|
|
3737
|
+
sessionId: o.sessionId,
|
|
3738
|
+
mode: "scoped",
|
|
3739
|
+
signerAddress: o.signerAddress.toLowerCase(),
|
|
3740
|
+
targetContracts: o.targetContracts.map(
|
|
3741
|
+
(t) => t.toLowerCase()
|
|
3742
|
+
),
|
|
3743
|
+
selectorCaps: caps,
|
|
3744
|
+
validUntilSec: o.validUntilSec,
|
|
3745
|
+
mintedAtSec: o.mintedAtSec,
|
|
3746
|
+
...o.consentActionHash === void 0 ? {} : { consentActionHash: o.consentActionHash.toLowerCase() },
|
|
3747
|
+
...o.consentTextSha256 === void 0 ? {} : { consentTextSha256: o.consentTextSha256.toLowerCase() },
|
|
3748
|
+
...o.permissionId === void 0 ? {} : { permissionId: o.permissionId.toLowerCase() }
|
|
3749
|
+
};
|
|
3750
|
+
}
|
|
3751
|
+
function asMessage2(err2) {
|
|
3752
|
+
return err2 instanceof Error ? err2.message : String(err2);
|
|
3753
|
+
}
|
|
3754
|
+
function decodeUint256ArgAt(callDataHex, wordIndex) {
|
|
3755
|
+
if (!Number.isInteger(wordIndex) || wordIndex < 0) {
|
|
3756
|
+
throw new Error(`wordIndex must be a non-negative integer (got ${wordIndex})`);
|
|
3757
|
+
}
|
|
3758
|
+
const requiredLen = 2 + 8 + (wordIndex + 1) * 64;
|
|
3759
|
+
if (callDataHex.length < requiredLen) {
|
|
3760
|
+
throw new Error(
|
|
3761
|
+
`callData length ${callDataHex.length} too short to carry word ${wordIndex} (need \u2265${requiredLen} chars)`
|
|
3762
|
+
);
|
|
3763
|
+
}
|
|
3764
|
+
const wordStart = 2 + 8 + wordIndex * 64;
|
|
3765
|
+
const argHex = callDataHex.slice(wordStart, wordStart + 64);
|
|
3766
|
+
return BigInt(`0x${argHex}`);
|
|
3767
|
+
}
|
|
3768
|
+
function selectorOf(callDataHex) {
|
|
3769
|
+
return callDataHex.slice(0, 10).toLowerCase();
|
|
3770
|
+
}
|
|
3771
|
+
function checkPolicy(input) {
|
|
3772
|
+
const { snapshot, innerCall, activeSigner, nowSec } = input;
|
|
3773
|
+
if (snapshot.validUntilSec <= nowSec) {
|
|
3774
|
+
return {
|
|
3775
|
+
ok: false,
|
|
3776
|
+
code: "scope_violation",
|
|
3777
|
+
message: `snapshot ${snapshot.sessionId} expired at ${snapshot.validUntilSec} (now ${nowSec})`
|
|
3778
|
+
};
|
|
3779
|
+
}
|
|
3780
|
+
if (snapshot.signerAddress.toLowerCase() !== activeSigner.toLowerCase()) {
|
|
3781
|
+
return {
|
|
3782
|
+
ok: false,
|
|
3783
|
+
code: "policy_violation",
|
|
3784
|
+
message: `snapshot ${snapshot.sessionId} bound to signer ${snapshot.signerAddress}, broker active signer is ${activeSigner}`
|
|
3785
|
+
};
|
|
3786
|
+
}
|
|
3787
|
+
const targetLower = innerCall.target.toLowerCase();
|
|
3788
|
+
const targetMatch = snapshot.targetContracts.some((t) => t === targetLower);
|
|
3789
|
+
if (!targetMatch) {
|
|
3790
|
+
return {
|
|
3791
|
+
ok: false,
|
|
3792
|
+
code: "policy_violation",
|
|
3793
|
+
message: `target ${innerCall.target} not in allowlist for session ${snapshot.sessionId}`
|
|
3794
|
+
};
|
|
3795
|
+
}
|
|
3796
|
+
const selector = selectorOf(innerCall.callData);
|
|
3797
|
+
const rule = snapshot.selectorCaps.find((c) => c.selector === selector);
|
|
3798
|
+
if (!rule) {
|
|
3799
|
+
return {
|
|
3800
|
+
ok: false,
|
|
3801
|
+
code: "policy_violation",
|
|
3802
|
+
message: `selector ${selector} not in selectorCaps for session ${snapshot.sessionId}`
|
|
3803
|
+
};
|
|
3804
|
+
}
|
|
3805
|
+
if (rule.capArgIndex !== null && rule.maxAmount !== null) {
|
|
3806
|
+
let argValue;
|
|
3807
|
+
try {
|
|
3808
|
+
argValue = decodeUint256ArgAt(innerCall.callData, rule.capArgIndex);
|
|
3809
|
+
} catch (err2) {
|
|
3810
|
+
return {
|
|
3811
|
+
ok: false,
|
|
3812
|
+
code: "policy_violation",
|
|
3813
|
+
message: `callData decode failed at wordIndex ${rule.capArgIndex}: ${asMessage2(err2)}`
|
|
3814
|
+
};
|
|
3815
|
+
}
|
|
3816
|
+
const cap = BigInt(rule.maxAmount);
|
|
3817
|
+
if (argValue > cap) {
|
|
3818
|
+
return {
|
|
3819
|
+
ok: false,
|
|
3820
|
+
code: "max_spend_exceeded",
|
|
3821
|
+
message: `arg word[${rule.capArgIndex}] = ${argValue} exceeds maxAmount ${cap} for selector ${selector} (session ${snapshot.sessionId})`
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
return { ok: true };
|
|
3826
|
+
}
|
|
1970
3827
|
|
|
1971
3828
|
// src/broker/daemon.ts
|
|
1972
3829
|
var noopLogger = (_e) => {
|
|
1973
3830
|
};
|
|
1974
|
-
async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.floor(Date.now() / 1e3), options = {}) {
|
|
3831
|
+
async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.floor(Date.now() / 1e3), options = {}, policyStore) {
|
|
1975
3832
|
switch (req.type) {
|
|
1976
3833
|
case "hello": {
|
|
1977
3834
|
let hasJwt = false;
|
|
@@ -2044,6 +3901,141 @@ async function handleBrokerRequest(req, signer, keystore, nowSec = () => Math.fl
|
|
|
2044
3901
|
);
|
|
2045
3902
|
}
|
|
2046
3903
|
}
|
|
3904
|
+
case "sign_userop": {
|
|
3905
|
+
if (!policyStore) {
|
|
3906
|
+
return errorResponse(
|
|
3907
|
+
"internal",
|
|
3908
|
+
"broker daemon is not configured with a policy store"
|
|
3909
|
+
);
|
|
3910
|
+
}
|
|
3911
|
+
const now = nowSec();
|
|
3912
|
+
let snapshot;
|
|
3913
|
+
try {
|
|
3914
|
+
snapshot = await policyStore.get(req.sessionId, now);
|
|
3915
|
+
} catch (err2) {
|
|
3916
|
+
return errorResponse(
|
|
3917
|
+
"internal",
|
|
3918
|
+
err2 instanceof Error ? err2.message : "policy store read failed"
|
|
3919
|
+
);
|
|
3920
|
+
}
|
|
3921
|
+
if (!snapshot) {
|
|
3922
|
+
return errorResponse(
|
|
3923
|
+
"no_active_snapshot",
|
|
3924
|
+
`no active snapshot for session ${req.sessionId}`
|
|
3925
|
+
);
|
|
3926
|
+
}
|
|
3927
|
+
const check = checkPolicy({
|
|
3928
|
+
snapshot,
|
|
3929
|
+
innerCall: req.innerCall,
|
|
3930
|
+
activeSigner: signer.address,
|
|
3931
|
+
nowSec: now
|
|
3932
|
+
});
|
|
3933
|
+
if (!check.ok) {
|
|
3934
|
+
return errorResponse(check.code, check.message);
|
|
3935
|
+
}
|
|
3936
|
+
try {
|
|
3937
|
+
const signature = await signer.signRawMessage(req.userOpHash);
|
|
3938
|
+
return {
|
|
3939
|
+
type: "sign_userop",
|
|
3940
|
+
signature,
|
|
3941
|
+
signerAddress: signer.address,
|
|
3942
|
+
sessionId: req.sessionId
|
|
3943
|
+
};
|
|
3944
|
+
} catch (err2) {
|
|
3945
|
+
if (err2 instanceof MissingSessionKeyError) {
|
|
3946
|
+
return errorResponse("session_key_unavailable", err2.message);
|
|
3947
|
+
}
|
|
3948
|
+
throw err2;
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
case "store_policy_snapshot": {
|
|
3952
|
+
if (!policyStore) {
|
|
3953
|
+
return errorResponse(
|
|
3954
|
+
"internal",
|
|
3955
|
+
"broker daemon is not configured with a policy store"
|
|
3956
|
+
);
|
|
3957
|
+
}
|
|
3958
|
+
try {
|
|
3959
|
+
await policyStore.put(req.snapshot);
|
|
3960
|
+
return {
|
|
3961
|
+
type: "store_policy_snapshot",
|
|
3962
|
+
stored: true,
|
|
3963
|
+
sessionId: req.snapshot.sessionId
|
|
3964
|
+
};
|
|
3965
|
+
} catch (err2) {
|
|
3966
|
+
if (err2 instanceof PolicyStoreError) {
|
|
3967
|
+
return errorResponse("internal", err2.message);
|
|
3968
|
+
}
|
|
3969
|
+
return errorResponse(
|
|
3970
|
+
"internal",
|
|
3971
|
+
err2 instanceof Error ? err2.message : "policy store write failed"
|
|
3972
|
+
);
|
|
3973
|
+
}
|
|
3974
|
+
}
|
|
3975
|
+
case "get_policy_snapshot": {
|
|
3976
|
+
if (!policyStore) {
|
|
3977
|
+
return errorResponse(
|
|
3978
|
+
"internal",
|
|
3979
|
+
"broker daemon is not configured with a policy store"
|
|
3980
|
+
);
|
|
3981
|
+
}
|
|
3982
|
+
try {
|
|
3983
|
+
const snapshot = await policyStore.get(req.sessionId, nowSec());
|
|
3984
|
+
return { type: "get_policy_snapshot", snapshot };
|
|
3985
|
+
} catch (err2) {
|
|
3986
|
+
if (err2 instanceof PolicyStoreError) {
|
|
3987
|
+
return errorResponse("internal", err2.message);
|
|
3988
|
+
}
|
|
3989
|
+
return errorResponse(
|
|
3990
|
+
"internal",
|
|
3991
|
+
err2 instanceof Error ? err2.message : "policy store read failed"
|
|
3992
|
+
);
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
case "clear_policy_snapshot": {
|
|
3996
|
+
if (!policyStore) {
|
|
3997
|
+
return errorResponse(
|
|
3998
|
+
"internal",
|
|
3999
|
+
"broker daemon is not configured with a policy store"
|
|
4000
|
+
);
|
|
4001
|
+
}
|
|
4002
|
+
try {
|
|
4003
|
+
await policyStore.delete(req.sessionId);
|
|
4004
|
+
return {
|
|
4005
|
+
type: "clear_policy_snapshot",
|
|
4006
|
+
cleared: true,
|
|
4007
|
+
sessionId: req.sessionId
|
|
4008
|
+
};
|
|
4009
|
+
} catch (err2) {
|
|
4010
|
+
if (err2 instanceof PolicyStoreError) {
|
|
4011
|
+
return errorResponse("internal", err2.message);
|
|
4012
|
+
}
|
|
4013
|
+
return errorResponse(
|
|
4014
|
+
"internal",
|
|
4015
|
+
err2 instanceof Error ? err2.message : "policy store clear failed"
|
|
4016
|
+
);
|
|
4017
|
+
}
|
|
4018
|
+
}
|
|
4019
|
+
case "get_active_session_id": {
|
|
4020
|
+
if (!policyStore) {
|
|
4021
|
+
return errorResponse(
|
|
4022
|
+
"internal",
|
|
4023
|
+
"broker daemon is not configured with a policy store"
|
|
4024
|
+
);
|
|
4025
|
+
}
|
|
4026
|
+
try {
|
|
4027
|
+
const sessionId = await policyStore.activeSessionId(signer.address, nowSec());
|
|
4028
|
+
return { type: "get_active_session_id", sessionId };
|
|
4029
|
+
} catch (err2) {
|
|
4030
|
+
if (err2 instanceof PolicyStoreError) {
|
|
4031
|
+
return errorResponse("internal", err2.message);
|
|
4032
|
+
}
|
|
4033
|
+
return errorResponse(
|
|
4034
|
+
"internal",
|
|
4035
|
+
err2 instanceof Error ? err2.message : "policy store enumerate failed"
|
|
4036
|
+
);
|
|
4037
|
+
}
|
|
4038
|
+
}
|
|
2047
4039
|
}
|
|
2048
4040
|
}
|
|
2049
4041
|
function errorResponse(code, message) {
|
|
@@ -2073,6 +4065,7 @@ var BrokerDaemon = class {
|
|
|
2073
4065
|
log;
|
|
2074
4066
|
config;
|
|
2075
4067
|
keystore;
|
|
4068
|
+
policyStore;
|
|
2076
4069
|
/**
|
|
2077
4070
|
* Whether a session-key private half is actually loaded. `false` =
|
|
2078
4071
|
* daemon booted in read-only posture (no `MUHAVEN_BROKER_SESSION_KEY`
|
|
@@ -2092,6 +4085,7 @@ var BrokerDaemon = class {
|
|
|
2092
4085
|
this.hasSessionKey = false;
|
|
2093
4086
|
}
|
|
2094
4087
|
this.keystore = options.keystore ?? null;
|
|
4088
|
+
this.policyStore = options.policyStore ?? new FilePolicyStore(FilePolicyStore.defaultDir());
|
|
2095
4089
|
this.log = options.logger ?? noopLogger;
|
|
2096
4090
|
this.server = createServer((socket) => this.onConnection(socket));
|
|
2097
4091
|
}
|
|
@@ -2107,6 +4101,7 @@ var BrokerDaemon = class {
|
|
|
2107
4101
|
});
|
|
2108
4102
|
}
|
|
2109
4103
|
}
|
|
4104
|
+
if (this.policyStore.init) await this.policyStore.init();
|
|
2110
4105
|
await prepareEndpoint(this.config.endpoint);
|
|
2111
4106
|
await new Promise((resolve, reject) => {
|
|
2112
4107
|
const onError = (err2) => {
|
|
@@ -2222,7 +4217,8 @@ var BrokerDaemon = class {
|
|
|
2222
4217
|
dashboardBaseUrl: this.config.dashboardBaseUrl
|
|
2223
4218
|
},
|
|
2224
4219
|
pid: process.pid
|
|
2225
|
-
}
|
|
4220
|
+
},
|
|
4221
|
+
this.policyStore
|
|
2226
4222
|
);
|
|
2227
4223
|
socket.end(serializeResponse(res));
|
|
2228
4224
|
} catch (err2) {
|
|
@@ -2238,4 +4234,4 @@ var BrokerDaemon = class {
|
|
|
2238
4234
|
}
|
|
2239
4235
|
};
|
|
2240
4236
|
|
|
2241
|
-
export { BROKER_PROTOCOL_VERSION, BackendClient, BackendError, BrokerClient, BrokerClientError, BrokerDaemon, DeviceFlowAbortedError, DeviceFlowClient, JwtSource, KeystoreError, MissingSessionKeyError, NoJwtAvailableError, NullSigner, SERVER_VERSION, TOOL_DESCRIPTORS, ViemSigner, ZERO_ADDRESS, buildMcpServer, buildToolHashTable, defaultBrokerEndpoint, fullToolRegistry, handleBrokerRequest, hashToolDescriptor, loadBrokerConfig, loadMcpConfig, openKeystore, parseBrokerRequest, registryForReadOnly, runMcpStdioCli, selectRegistry, serializeResponse, verifyDescriptorAgainstPin };
|
|
4237
|
+
export { BROKER_PROTOCOL_VERSION, BackendClient, BackendError, BrokerClient, BrokerClientError, BrokerDaemon, BundlerClient, BundlerClientError, DeviceFlowAbortedError, DeviceFlowClient, JwtSource, KeystoreError, MissingSessionKeyError, NoJwtAvailableError, NullSigner, SERVER_VERSION, TOOL_DESCRIPTORS, ViemSigner, ZERO_ADDRESS, buildMcpServer, buildToolHashTable, defaultBrokerEndpoint, fullToolRegistry, handleBrokerRequest, hashToolDescriptor, loadBrokerConfig, loadMcpConfig, openKeystore, parseBrokerRequest, registryForReadOnly, runMcpStdioCli, selectRegistry, semverGte, serializeResponse, verifyDescriptorAgainstPin };
|