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