@haven_ai/signer 0.1.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,614 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var viem = require('viem');
5
+ var accounts = require('viem/accounts');
6
+ var schemes = require('x402/schemes');
7
+ var sdk = require('@haven_ai/sdk');
8
+ var promises = require('fs/promises');
9
+ var mcp_js = require('@modelcontextprotocol/sdk/server/mcp.js');
10
+ var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
11
+ var os = require('os');
12
+ var path = require('path');
13
+ var v3 = require('zod/v3');
14
+
15
+ // src/core.ts
16
+ function createEdgeSigner(delegateKey, options = {}) {
17
+ let delegateAddress;
18
+ try {
19
+ delegateAddress = sdk.addressFromKey(delegateKey);
20
+ } catch (err) {
21
+ throw new sdk.HavenSigningError(
22
+ `Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`
23
+ );
24
+ }
25
+ const x402Bindings = /* @__PURE__ */ new Map();
26
+ function signAndVerify(hash) {
27
+ const signature = sdk.signHash(delegateKey, hash);
28
+ if (!sdk.verifySignature(hash, signature, delegateAddress)) {
29
+ throw new sdk.HavenSigningError(
30
+ "Local signature verification failed \u2014 recovered address does not match the delegate key."
31
+ );
32
+ }
33
+ return signature;
34
+ }
35
+ return {
36
+ delegateAddress,
37
+ signPaymentHash(hash) {
38
+ return signAndVerify(hash);
39
+ },
40
+ signX402FundingHash(hash, expected) {
41
+ assertExpectedBinding(hash, expected, options.x402BindingSigner);
42
+ const signature = signAndVerify(hash);
43
+ const x402Binding = crypto.randomUUID();
44
+ x402Bindings.set(x402Binding, { ...expected });
45
+ return { signature, x402Binding };
46
+ },
47
+ async buildX402PaymentHeader(paymentRequired, x402Binding) {
48
+ const expected = x402Bindings.get(x402Binding);
49
+ if (!expected) {
50
+ throw new sdk.HavenSigningError(
51
+ "x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first."
52
+ );
53
+ }
54
+ const option = sdk.selectStandardPaymentOption(paymentRequired.accepts);
55
+ if (!option) {
56
+ throw new sdk.HavenApiError(
57
+ "No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
58
+ 400
59
+ );
60
+ }
61
+ assertX402MatchesExpected(paymentRequired, option, expected);
62
+ const account = accounts.privateKeyToAccount(delegateKey);
63
+ const requirements = sdk.toStandardPaymentRequirements(paymentRequired, option);
64
+ const header = await schemes.exact.evm.createPaymentHeader(
65
+ account,
66
+ paymentRequired.x402Version,
67
+ requirements
68
+ );
69
+ if (paymentRequired.x402Version < 2) {
70
+ x402Bindings.delete(x402Binding);
71
+ return { paymentHeader: header, accepted: option };
72
+ }
73
+ try {
74
+ const payment = decodeBase64Json(header);
75
+ const wrapped = encodeBase64Json({
76
+ x402Version: paymentRequired.x402Version,
77
+ accepted: option,
78
+ payload: payment.payload
79
+ });
80
+ return { paymentHeader: wrapped, accepted: option };
81
+ } finally {
82
+ x402Bindings.delete(x402Binding);
83
+ }
84
+ }
85
+ };
86
+ }
87
+ function assertX402MatchesExpected(paymentRequired, option, expected) {
88
+ assertExpectedShape(expected);
89
+ const headerResource = option.resource ?? paymentRequired.resource.url;
90
+ if (headerResource !== expected.resourceUrl) {
91
+ throw new sdk.HavenSigningError("x402 payment_required resource does not match the funded intent.");
92
+ }
93
+ if (!sameAddress(option.payTo, expected.merchantTo)) {
94
+ throw new sdk.HavenSigningError("x402 merchant recipient does not match the funded intent.");
95
+ }
96
+ if (sdk.x402AuthorizationAmount(option) !== expected.amount) {
97
+ throw new sdk.HavenSigningError("x402 amount does not match the funded intent.");
98
+ }
99
+ if (!sameAddress(option.asset, expected.asset)) {
100
+ throw new sdk.HavenSigningError("x402 asset does not match the funded intent.");
101
+ }
102
+ if (option.network !== expected.network) {
103
+ throw new sdk.HavenSigningError("x402 network does not match the funded intent.");
104
+ }
105
+ }
106
+ function assertExpectedShape(expected) {
107
+ if (!expected || typeof expected !== "object") {
108
+ throw new sdk.HavenSigningError("x402 expected funding context is required before signing a merchant header.");
109
+ }
110
+ }
111
+ function assertExpectedBinding(payloadHash, expected, trustedSigner) {
112
+ assertExpectedShape(expected);
113
+ if (!trustedSigner) {
114
+ throw new sdk.HavenSigningError(
115
+ "x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding hashes."
116
+ );
117
+ }
118
+ if (expected.payloadHash.toLowerCase() !== payloadHash.toLowerCase()) {
119
+ throw new sdk.HavenSigningError("x402 expected context does not match the funding hash being signed.");
120
+ }
121
+ const message = sdk.buildX402ExpectedMessage({
122
+ paymentId: expected.paymentId,
123
+ payloadHash: expected.payloadHash,
124
+ resourceUrl: expected.resourceUrl,
125
+ merchantTo: expected.merchantTo,
126
+ amount: expected.amount,
127
+ asset: expected.asset,
128
+ network: expected.network
129
+ });
130
+ if (expected.auth?.version !== 1 || expected.auth.message !== message) {
131
+ throw new sdk.HavenSigningError("x402 expected context authentication message is invalid.");
132
+ }
133
+ if (!sameAddress(expected.auth.signer, trustedSigner)) {
134
+ throw new sdk.HavenSigningError("x402 expected context was not signed by the configured Haven signer.");
135
+ }
136
+ if (!sdk.verifySignature(viem.hashMessage(message), expected.auth.signature, trustedSigner)) {
137
+ throw new sdk.HavenSigningError("x402 expected context signature could not be verified.");
138
+ }
139
+ }
140
+ function sameAddress(a, b) {
141
+ return a.toLowerCase() === b.toLowerCase();
142
+ }
143
+ function decodeBase64Json(value) {
144
+ return JSON.parse(Buffer.from(value, "base64").toString("utf8"));
145
+ }
146
+ function encodeBase64Json(value) {
147
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
148
+ }
149
+ async function loadSignerCredentials(path = process.env.HAVEN_CREDENTIALS) {
150
+ if (path) return loadFromFile(path);
151
+ const envKey = stringField(process.env.HAVEN_DELEGATE_KEY);
152
+ if (envKey) {
153
+ return {
154
+ delegateKey: envKey,
155
+ agentId: stringField(process.env.HAVEN_AGENT_ID),
156
+ safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),
157
+ chainId: numberField(process.env.HAVEN_CHAIN_ID),
158
+ network: stringField(process.env.HAVEN_NETWORK),
159
+ x402BindingSigner: stringField(process.env.HAVEN_X402_BINDING_SIGNER)
160
+ };
161
+ }
162
+ throw new Error(
163
+ "No delegate key found. Set HAVEN_DELEGATE_KEY, pass --credentials <path>, or set HAVEN_CREDENTIALS to a Haven agent credential JSON file."
164
+ );
165
+ }
166
+ async function loadFromFile(path) {
167
+ let rawText;
168
+ try {
169
+ rawText = await promises.readFile(path, "utf8");
170
+ } catch (err) {
171
+ throw new Error(
172
+ `Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`
173
+ );
174
+ }
175
+ await warnIfCredentialFilePermissive(path);
176
+ let raw;
177
+ try {
178
+ raw = JSON.parse(rawText);
179
+ } catch {
180
+ throw new Error("Haven credentials must be JSON with a delegate_key field.");
181
+ }
182
+ const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey);
183
+ if (!delegateKey) {
184
+ throw new Error("Haven credentials are missing delegate_key \u2014 the edge signer needs it to sign.");
185
+ }
186
+ const chainId = numberField(raw.chain_id ?? raw.chainId);
187
+ return {
188
+ delegateKey,
189
+ agentId: stringField(raw.agent_id ?? raw.agentId),
190
+ safeAddress: stringField(raw.safe_address ?? raw.safeAddress),
191
+ chainId,
192
+ network: stringField(raw.network),
193
+ x402BindingSigner: stringField(
194
+ raw.x402_binding_signer ?? raw.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER
195
+ ),
196
+ sourcePath: path
197
+ };
198
+ }
199
+ function stringField(value) {
200
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
201
+ }
202
+ function numberField(value) {
203
+ if (typeof value === "number" && Number.isFinite(value)) return value;
204
+ if (typeof value === "string" && value.trim()) {
205
+ const parsed = Number(value);
206
+ if (Number.isFinite(parsed)) return parsed;
207
+ }
208
+ return void 0;
209
+ }
210
+ async function warnIfCredentialFilePermissive(path, log = (message) => process.stderr.write(`${message}
211
+ `), platform = process.platform) {
212
+ if (platform === "win32") return;
213
+ let mode;
214
+ try {
215
+ mode = (await promises.stat(path)).mode;
216
+ } catch {
217
+ return;
218
+ }
219
+ if ((mode & 63) !== 0) {
220
+ const octal = (mode & 511).toString(8).padStart(4, "0");
221
+ log(
222
+ `haven-signer: warning: credential file at ${path} is readable beyond the owner (mode ${octal}). Run: chmod 600 ${path}`
223
+ );
224
+ }
225
+ }
226
+ function defaultSigningAuditPath(credentialsPath) {
227
+ if (credentialsPath) return path.resolve(`${credentialsPath}.signer-audit.jsonl`);
228
+ return path.resolve(os.homedir(), ".haven", "signer-audit.jsonl");
229
+ }
230
+ async function appendSigningAuditEntry(entry, path$1) {
231
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
232
+ await promises.appendFile(path$1, `${JSON.stringify(entry)}
233
+ `, "utf8");
234
+ }
235
+ function createSigningAuditEntry(tool, payloadHash, context, now = /* @__PURE__ */ new Date()) {
236
+ const entry = {
237
+ version: 1,
238
+ timestamp: now.toISOString(),
239
+ tool,
240
+ payload_hash: payloadHash,
241
+ delegate_address: context.delegateAddress
242
+ };
243
+ if (context.safeAddress) entry.safe_address = context.safeAddress;
244
+ if (typeof context.chainId === "number") entry.chain_id = context.chainId;
245
+ return entry;
246
+ }
247
+ function hashPayloadForAudit(payload) {
248
+ return `0x${crypto.createHash("sha256").update(stableStringify(payload)).digest("hex")}`;
249
+ }
250
+ function stableStringify(value) {
251
+ if (value === null || typeof value !== "object") {
252
+ const primitive = JSON.stringify(value);
253
+ return primitive === void 0 ? "undefined" : primitive;
254
+ }
255
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
256
+ const object = value;
257
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(",")}}`;
258
+ }
259
+ var x402ExpectedSchema = v3.z.object({
260
+ payment_id: v3.z.string().min(1),
261
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
262
+ resource_url: v3.z.string().url(),
263
+ merchant_to: v3.z.string().min(1),
264
+ amount: v3.z.string().min(1),
265
+ asset: v3.z.string().min(1),
266
+ network: v3.z.string().min(1),
267
+ auth: v3.z.object({
268
+ version: v3.z.literal(1),
269
+ message: v3.z.string().min(1),
270
+ signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
271
+ signer: v3.z.string().min(1)
272
+ })
273
+ });
274
+ var toolSchemas = {
275
+ haven_sign: {
276
+ // The unsigned hash from haven_pay / haven_x402_authorize (payload_hash).
277
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
278
+ // Pass x402.expected from hosted haven_x402_authorize when this hash funds
279
+ // a standard x402 merchant retry. The signer records it locally and returns
280
+ // an opaque x402_binding for the later header-signing step.
281
+ x402_expected: x402ExpectedSchema.optional()
282
+ },
283
+ haven_x402_sign_header: {
284
+ // The parsed HTTP 402 PaymentRequired from the merchant.
285
+ payment_required: v3.z.unknown(),
286
+ // Opaque binding returned by haven_sign when x402_expected was supplied.
287
+ x402_binding: v3.z.string().min(1)
288
+ }
289
+ };
290
+ var SIGN_DESCRIPTION = [
291
+ "Sign an unsigned Haven payment hash with the delegate key on this machine.",
292
+ "Pass the payload_hash returned by haven_pay or haven_x402_authorize. For x402, also pass",
293
+ "x402_expected from haven_x402_authorize; the signer records it locally and returns",
294
+ "{ signature, x402_binding }. Hand signature to haven_submit, then use x402_binding for",
295
+ "haven_x402_sign_header. The delegate key never leaves this process."
296
+ ].join(" ");
297
+ var X402_SIGN_HEADER_DESCRIPTION = [
298
+ "Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment, using",
299
+ "the delegate key on this machine. Pass the same payment_required you gave haven_x402_authorize",
300
+ "and the x402_binding returned by haven_sign. The signer consumes the recorded funding context",
301
+ "and rejects mismatched amount, merchant, resource, asset, or network before signing. Returns",
302
+ "{ payment_header } to send to the merchant as the X-PAYMENT header on your retry. Do this only",
303
+ "after the funding step (haven_submit) has confirmed."
304
+ ].join(" ");
305
+ var toolDescriptions = {
306
+ haven_sign: SIGN_DESCRIPTION,
307
+ haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION
308
+ };
309
+ function createToolHandlers(signer, options = {}) {
310
+ return {
311
+ haven_sign: async (input) => runTool(async () => {
312
+ const args = parse("haven_sign", input);
313
+ const x402Expected = args.x402_expected ? {
314
+ paymentId: args.x402_expected.payment_id,
315
+ payloadHash: args.x402_expected.payload_hash,
316
+ resourceUrl: args.x402_expected.resource_url,
317
+ merchantTo: args.x402_expected.merchant_to,
318
+ amount: args.x402_expected.amount,
319
+ asset: args.x402_expected.asset,
320
+ network: args.x402_expected.network,
321
+ auth: args.x402_expected.auth
322
+ } : null;
323
+ const result = x402Expected ? signer.signX402FundingHash(args.payload_hash, x402Expected) : null;
324
+ if (!result) {
325
+ const signature = signer.signPaymentHash(args.payload_hash);
326
+ await auditSigning("haven_sign", args.payload_hash);
327
+ return { signature };
328
+ }
329
+ await auditSigning("haven_sign", args.payload_hash);
330
+ return { signature: result.signature, x402_binding: result.x402Binding };
331
+ }),
332
+ haven_x402_sign_header: async (input) => runTool(async () => {
333
+ const args = parse("haven_x402_sign_header", input);
334
+ const result = await signer.buildX402PaymentHeader(
335
+ args.payment_required,
336
+ args.x402_binding
337
+ );
338
+ await auditSigning(
339
+ "haven_x402_sign_header",
340
+ hashPayloadForAudit(args.payment_required)
341
+ );
342
+ return { payment_header: result.paymentHeader, accepted: result.accepted };
343
+ })
344
+ };
345
+ async function auditSigning(tool, payloadHash) {
346
+ if (!options.audit) return;
347
+ const { auditPath, ...context } = options.audit;
348
+ await appendSigningAuditEntry(
349
+ createSigningAuditEntry(tool, payloadHash, {
350
+ ...context,
351
+ delegateAddress: signer.delegateAddress
352
+ }),
353
+ auditPath
354
+ );
355
+ }
356
+ }
357
+ function parse(name, input) {
358
+ return v3.z.object(toolSchemas[name]).parse(input ?? {});
359
+ }
360
+ async function runTool(fn) {
361
+ try {
362
+ return { success: true, data: await fn() };
363
+ } catch (err) {
364
+ return normalizeError(err);
365
+ }
366
+ }
367
+ function normalizeError(err) {
368
+ if (err instanceof v3.z.ZodError) {
369
+ return {
370
+ success: false,
371
+ code: "INVALID_INPUT",
372
+ message: err.errors.map((e) => `${e.path.join(".") || "(root)"}: ${e.message}`).join("; "),
373
+ statusCode: 400
374
+ };
375
+ }
376
+ if (err instanceof sdk.HavenSigningError) {
377
+ return { success: false, code: err.code, message: err.message };
378
+ }
379
+ if (err instanceof sdk.HavenApiError) {
380
+ return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
381
+ }
382
+ if (err instanceof sdk.HavenError) {
383
+ return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
384
+ }
385
+ return {
386
+ success: false,
387
+ code: "UNKNOWN_ERROR",
388
+ message: err instanceof Error ? err.message : String(err)
389
+ };
390
+ }
391
+
392
+ // src/consent.ts
393
+ var SIGNER_ACK_ENV = "HAVEN_SIGNER_ACK";
394
+ function computeSignerConsentHash(input) {
395
+ const identity = [
396
+ input.delegateAddress.toLowerCase(),
397
+ (input.safeAddress ?? "").toLowerCase(),
398
+ input.agentId ?? "",
399
+ input.chainId ?? "",
400
+ input.network ?? ""
401
+ ].join("|");
402
+ const toolCanonical = [...input.toolNames].sort().join(",");
403
+ return crypto.createHash("sha256").update(`${identity}
404
+ ${toolCanonical}`).digest("hex").slice(0, 16);
405
+ }
406
+ function renderSignerConsentBlock(input, hash) {
407
+ const lines = [
408
+ "",
409
+ "------------------------------------------------------------",
410
+ "Haven edge signer - first-launch consent",
411
+ "------------------------------------------------------------",
412
+ "",
413
+ `Delegate address: ${input.delegateAddress}`
414
+ ];
415
+ lines.push(`Haven wallet: ${input.safeAddress ?? "not provided to this signer"}`);
416
+ if (input.agentId) lines.push(`Agent ID: ${input.agentId}`);
417
+ if (typeof input.chainId === "number") lines.push(`Chain ID: ${input.chainId}`);
418
+ if (input.network) lines.push(`Network: ${input.network}`);
419
+ lines.push("");
420
+ lines.push("This local signer holds the delegate key on this machine and signs");
421
+ lines.push("payment payloads or x402 merchant headers for the delegate address above.");
422
+ lines.push("It does not call the Haven API, so it cannot show a live allowance summary.");
423
+ lines.push("On-chain Safe rules remain the real spend gate, and the wallet owner can");
424
+ lines.push("pause or revoke agent authority outside this signer.");
425
+ lines.push("");
426
+ lines.push("Tools this signer will expose to your agent runtime:");
427
+ for (const name of input.toolNames) {
428
+ lines.push(` - ${name}`);
429
+ lines.push(` ${toolDescriptions[name]}`);
430
+ }
431
+ lines.push("");
432
+ lines.push("A local audit entry is appended for every signing operation. Audit entries");
433
+ lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
434
+ lines.push("signature, or x402 payment header.");
435
+ lines.push("");
436
+ lines.push(`Consent hash: ${hash}`);
437
+ lines.push("");
438
+ lines.push("To acknowledge, EITHER:");
439
+ lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`);
440
+ lines.push(" - re-run with --ack to write the acknowledgement next to your");
441
+ lines.push(" credential file (sidecar <credentials>.signer-ack.json).");
442
+ lines.push("");
443
+ lines.push("------------------------------------------------------------");
444
+ lines.push("");
445
+ return lines.join("\n");
446
+ }
447
+ async function ensureSignerConsent(input, options = {}) {
448
+ const env = options.env ?? process.env;
449
+ const out = options.out ?? process.stderr;
450
+ const hash = computeSignerConsentHash(input);
451
+ const envAck = env[SIGNER_ACK_ENV];
452
+ if (typeof envAck === "string" && envAck.length > 0) {
453
+ if (envAck === hash) return { ok: true, hash, reason: "env_var_match" };
454
+ out.write(renderSignerConsentBlock(input, hash));
455
+ out.write(
456
+ `${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.
457
+ Expected: ${hash}
458
+ Got: ${envAck}
459
+ Re-acknowledge with the new hash above, or run with --ack.
460
+
461
+ `
462
+ );
463
+ return { ok: false, hash, reason: "env_var_mismatch" };
464
+ }
465
+ const ackPath = sidecarPath(options.credentialsPath);
466
+ if (ackPath) {
467
+ const stored = await readAckFile(ackPath);
468
+ if (stored?.ack === hash) return { ok: true, hash, reason: "ack_file_match" };
469
+ }
470
+ if (options.writeAck && ackPath) {
471
+ out.write(renderSignerConsentBlock(input, hash));
472
+ await writeAckFile(ackPath, hash);
473
+ out.write(`Wrote acknowledgement to ${ackPath}
474
+
475
+ `);
476
+ return { ok: true, hash, reason: "wrote_ack_file" };
477
+ }
478
+ out.write(renderSignerConsentBlock(input, hash));
479
+ return { ok: false, hash, reason: "no_acknowledgement" };
480
+ }
481
+ function registeredSignerToolNames() {
482
+ return Object.keys(toolSchemas);
483
+ }
484
+ function sidecarPath(credentialsPath) {
485
+ if (!credentialsPath) return null;
486
+ return path.resolve(`${credentialsPath}.signer-ack.json`);
487
+ }
488
+ async function readAckFile(path) {
489
+ try {
490
+ const raw = await promises.readFile(path, "utf8");
491
+ const parsed = JSON.parse(raw);
492
+ return { ack: typeof parsed.ack === "string" ? parsed.ack : void 0 };
493
+ } catch {
494
+ return null;
495
+ }
496
+ }
497
+ async function writeAckFile(path$1, hash) {
498
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
499
+ await promises.writeFile(
500
+ path$1,
501
+ JSON.stringify({ ack: hash, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
502
+ "utf8"
503
+ );
504
+ }
505
+
506
+ // src/server.ts
507
+ var SIGNER_NAME = "@haven_ai/signer";
508
+ var SIGNER_VERSION = "0.1.0-alpha";
509
+ async function resolveEdgeSigner(options = {}) {
510
+ const { signer } = await resolveSignerRuntime(options);
511
+ return signer;
512
+ }
513
+ async function resolveSignerRuntime(options = {}) {
514
+ if (options.delegateKey) {
515
+ return {
516
+ signer: createEdgeSigner(options.delegateKey, {
517
+ x402BindingSigner: options.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER
518
+ })
519
+ };
520
+ }
521
+ const creds = await loadSignerCredentials(options.credentialsPath);
522
+ return {
523
+ signer: createEdgeSigner(creds.delegateKey, {
524
+ x402BindingSigner: options.x402BindingSigner ?? creds.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER
525
+ }),
526
+ credentials: creds
527
+ };
528
+ }
529
+ function buildSignerMcpServer(signer, options = {}) {
530
+ const server = new mcp_js.McpServer({ name: SIGNER_NAME, version: SIGNER_VERSION });
531
+ const credentialsPath = options.credentials?.sourcePath;
532
+ const handlers = createToolHandlers(signer, {
533
+ audit: {
534
+ auditPath: options.auditPath ?? defaultSigningAuditPath(credentialsPath),
535
+ delegateAddress: signer.delegateAddress,
536
+ safeAddress: options.credentials?.safeAddress,
537
+ chainId: options.credentials?.chainId
538
+ }
539
+ });
540
+ const registerTool = server.tool.bind(server);
541
+ for (const name of Object.keys(toolSchemas)) {
542
+ registerTool(
543
+ name,
544
+ toolDescriptions[name],
545
+ toolSchemas[name],
546
+ async (args) => toMcpResult(await handlers[name](args))
547
+ );
548
+ }
549
+ return server;
550
+ }
551
+ async function runSignerStdioServer(options = {}) {
552
+ const { signer, credentials } = await resolveSignerRuntime(options);
553
+ if (!options.skipConsent) {
554
+ const decision = await runSignerConsentGate(signer, credentials, options);
555
+ if (!decision.ok) {
556
+ const err = new Error(
557
+ decision.reason === "env_var_mismatch" ? "Haven edge signer consent acknowledgement does not match the current configuration." : "Haven edge signer requires a one-time consent acknowledgement before starting."
558
+ );
559
+ err.code = "HAVEN_SIGNER_NO_CONSENT";
560
+ throw err;
561
+ }
562
+ }
563
+ const server = buildSignerMcpServer(signer, { credentials, auditPath: options.auditPath });
564
+ await server.connect(new stdio_js.StdioServerTransport());
565
+ }
566
+ async function runSignerConsentGate(signer, credentials, options) {
567
+ return ensureSignerConsent(
568
+ {
569
+ delegateAddress: signer.delegateAddress,
570
+ safeAddress: credentials?.safeAddress,
571
+ agentId: credentials?.agentId,
572
+ chainId: credentials?.chainId,
573
+ network: credentials?.network,
574
+ toolNames: registeredSignerToolNames()
575
+ },
576
+ {
577
+ credentialsPath: options.credentialsPath ?? credentials?.sourcePath,
578
+ writeAck: options.writeAck,
579
+ env: options.consentEnv,
580
+ out: options.consentOut
581
+ }
582
+ );
583
+ }
584
+ function toMcpResult(payload) {
585
+ return {
586
+ isError: !payload.success,
587
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
588
+ };
589
+ }
590
+
591
+ exports.SIGNER_ACK_ENV = SIGNER_ACK_ENV;
592
+ exports.SIGNER_NAME = SIGNER_NAME;
593
+ exports.SIGNER_VERSION = SIGNER_VERSION;
594
+ exports.appendSigningAuditEntry = appendSigningAuditEntry;
595
+ exports.assertX402MatchesExpected = assertX402MatchesExpected;
596
+ exports.buildSignerMcpServer = buildSignerMcpServer;
597
+ exports.computeSignerConsentHash = computeSignerConsentHash;
598
+ exports.createEdgeSigner = createEdgeSigner;
599
+ exports.createSigningAuditEntry = createSigningAuditEntry;
600
+ exports.createToolHandlers = createToolHandlers;
601
+ exports.defaultSigningAuditPath = defaultSigningAuditPath;
602
+ exports.ensureSignerConsent = ensureSignerConsent;
603
+ exports.hashPayloadForAudit = hashPayloadForAudit;
604
+ exports.loadSignerCredentials = loadSignerCredentials;
605
+ exports.renderSignerConsentBlock = renderSignerConsentBlock;
606
+ exports.resolveEdgeSigner = resolveEdgeSigner;
607
+ exports.resolveSignerRuntime = resolveSignerRuntime;
608
+ exports.runSignerConsentGate = runSignerConsentGate;
609
+ exports.runSignerStdioServer = runSignerStdioServer;
610
+ exports.toolDescriptions = toolDescriptions;
611
+ exports.toolSchemas = toolSchemas;
612
+ exports.warnIfCredentialFilePermissive = warnIfCredentialFilePermissive;
613
+ //# sourceMappingURL=index.cjs.map
614
+ //# sourceMappingURL=index.cjs.map