@haven_ai/signer 0.3.0-alpha.0 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,26 +1,141 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var mcp_js = require('@modelcontextprotocol/sdk/server/mcp.js');
5
- var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
6
4
  var crypto = require('crypto');
7
5
  var promises = require('fs/promises');
8
- var os = require('os');
9
6
  var path = require('path');
10
- var sdk = require('@haven_ai/sdk');
7
+ var edge = require('@haven_ai/sdk/edge');
11
8
  var viem = require('viem');
12
- var accounts = require('viem/accounts');
13
- var schemes = require('x402/schemes');
14
9
  var v3 = require('zod/v3');
10
+ var zod = require('zod');
11
+ var os = require('os');
12
+ var mcp_js = require('@modelcontextprotocol/sdk/server/mcp.js');
13
+ var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
14
+ var accounts = require('viem/accounts');
15
+
16
+ var SIGNER_HOSTED_HANDOFF_SHAPES = {
17
+ haven_get_payment_status: { payment_id: zod.z.string().min(1) }
18
+ };
19
+ function target(shape) {
20
+ const schema = zod.z.object(shape).strict();
21
+ return {
22
+ role: "hosted",
23
+ validate: (input) => {
24
+ const r = schema.safeParse(input ?? {});
25
+ return r.success ? null : r.error.errors.map((e) => `${e.path.join(".") || "(root)"}: ${e.message}`).join("; ");
26
+ }
27
+ };
28
+ }
29
+ var SIGNER_NEXT_STEP_TARGETS = {
30
+ haven_get_payment_status: target(SIGNER_HOSTED_HANDOFF_SHAPES.haven_get_payment_status)
31
+ };
32
+ var nextStep = edge.createNextStepBuilder(SIGNER_NEXT_STEP_TARGETS);
33
+ function signerRefusalStep(input) {
34
+ return nextStep({ ...input, safeToContinue: false, reason: "" });
35
+ }
36
+ function nextStepWireFields(step) {
37
+ return {
38
+ ...step.next_tool ? { next_tool: step.next_tool } : {},
39
+ ...step.next_tool_server ? { next_tool_server: step.next_tool_server } : {},
40
+ ...step.next_tool_name ? { next_tool_name: step.next_tool_name } : {},
41
+ ...step.next_tool_server_role ? { next_tool_server_role: step.next_tool_server_role } : {},
42
+ ...step.next_arguments ? { next_arguments: step.next_arguments } : {},
43
+ ...step.next_tool_omitted_reason ? { next_tool_omitted_reason: step.next_tool_omitted_reason } : {}
44
+ };
45
+ }
46
+
47
+ // src/bare-hash.ts
48
+ var BARE_HASH_REFUSED = "BARE_HASH_REFUSED";
49
+ var HavenBareHashRefusedError = class extends edge.HavenSigningError {
50
+ next_action = edge.AgentPaymentNextAction.StopAndTellUser;
51
+ step;
52
+ constructor() {
53
+ super(
54
+ "Refusing to sign a bare payload_hash. A hash carries no shape, amount, merchant or binding, so this signer cannot tell a Haven payment from a transfer out of the delegate wallet or a delegation of its authority \u2014 and the only rail that ever validated a raw hash signature is retired. Call this tool with { payment_id } (the signer fetches and verifies the Haven-signed context itself), or with typed_data / typed_data_b64 (the account validates that EIP-712 payload), or with x402_expected for an x402 funding leg."
55
+ );
56
+ this.code = BARE_HASH_REFUSED;
57
+ this.name = "HavenBareHashRefusedError";
58
+ this.step = signerRefusalStep({
59
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
60
+ nextTool: null,
61
+ nextToolOmittedReason: "call haven_sign again with payment_id (preferred), typed_data / typed_data_b64, or x402_expected \u2014 a bare payload_hash is never signed"
62
+ });
63
+ }
64
+ };
65
+ var OWNER_ONLY_MODE = 384;
66
+ var defaultLog = (message) => process.stderr.write(`${message}
67
+ `);
68
+ async function permissiveMode(path, platform = process.platform, stats, follow = "nofollow") {
69
+ if (platform === "win32") return null;
70
+ let info;
71
+ try {
72
+ info = stats ?? (follow === "follow" ? await promises.stat(path) : await promises.lstat(path));
73
+ } catch {
74
+ return null;
75
+ }
76
+ if ((info.mode & 63) === 0) return null;
77
+ return { octal: (info.mode & 511).toString(8).padStart(4, "0"), regular: info.isFile() };
78
+ }
79
+ async function warnIfFilePermissive(kind, path, log = defaultLog, platform = process.platform) {
80
+ const found = await permissiveMode(path, platform, void 0, "follow");
81
+ if (found === null) return;
82
+ log(
83
+ `haven-signer: warning: ${kind} at ${path} is readable beyond the owner (mode ${found.octal}). Run: chmod 600 ${path}`
84
+ );
85
+ }
86
+ async function tightenIfFilePermissive(kind, path, log = defaultLog, platform = process.platform, stats) {
87
+ if (platform === "win32") return "skipped";
88
+ let info = stats ?? null;
89
+ if (!info) {
90
+ try {
91
+ info = await promises.lstat(path);
92
+ } catch {
93
+ return "owner-only";
94
+ }
95
+ }
96
+ if (!info.isFile()) {
97
+ log(
98
+ `haven-signer: warning: ${kind} at ${path} is not a regular file (a symlink or similar); audit rows are being written through it and it was not tightened. Remove it: rm ${path}`
99
+ );
100
+ return "warned";
101
+ }
102
+ const found = await permissiveMode(path, platform, info);
103
+ if (found === null) return "owner-only";
104
+ {
105
+ try {
106
+ await promises.chmod(path, OWNER_ONLY_MODE);
107
+ log(
108
+ `haven-signer: ${kind} at ${path} was readable beyond the owner (mode ${found.octal}); tightened to 0600.`
109
+ );
110
+ return "tightened";
111
+ } catch {
112
+ }
113
+ }
114
+ log(
115
+ `haven-signer: warning: ${kind} at ${path} is readable beyond the owner (mode ${found.octal}) and could not be tightened. Run: chmod 600 ${path}`
116
+ );
117
+ return "warned";
118
+ }
15
119
 
120
+ // src/audit.ts
121
+ var AUDIT_ROTATE_BYTES = 8 * 1024 * 1024;
16
122
  function defaultSigningAuditPath(credentialsPath) {
17
123
  if (credentialsPath) return path.resolve(`${credentialsPath}.signer-audit.jsonl`);
18
124
  return path.resolve(os.homedir(), ".haven", "signer-audit.jsonl");
19
125
  }
20
- async function appendSigningAuditEntry(entry, path$1) {
126
+ async function appendSigningAuditEntry(entry, path$1, options = {}) {
21
127
  await promises.mkdir(path.dirname(path$1), { recursive: true });
128
+ const rotateAt = options.rotateAtBytes ?? AUDIT_ROTATE_BYTES;
129
+ const existing = await promises.lstat(path$1).catch(() => null);
130
+ if (existing) {
131
+ await tightenIfFilePermissive("audit sidecar", path$1, options.log, options.platform, existing);
132
+ if (existing.size >= rotateAt) {
133
+ await promises.rename(path$1, `${path$1}.1`).catch(() => {
134
+ });
135
+ }
136
+ }
22
137
  await promises.appendFile(path$1, `${JSON.stringify(entry)}
23
- `, "utf8");
138
+ `, { encoding: "utf8", mode: OWNER_ONLY_MODE });
24
139
  }
25
140
  function createSigningAuditEntry(tool, payloadHash, context, now = /* @__PURE__ */ new Date()) {
26
141
  const entry = {
@@ -46,1181 +161,1452 @@ function stableStringify(value) {
46
161
  const object = value;
47
162
  return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(",")}}`;
48
163
  }
49
- var DELEGATION_MANAGER = "0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3";
50
- var CAVEAT_ENFORCERS = {
51
- erc20TransferAmount: "0xf100b0819427117EcF76Ed94B358B1A5b5C6D2Fc",
52
- allowedCalldata: "0xc2b0d624c1c4319760C96503BA27C347F3260f55",
53
- timestamp: "0x1046bb45C8d673d4ea75321280DB34899413c069"};
54
- var MAX_SETTLEMENT_WINDOW_SECONDS = 600;
55
- function isSettlementChildTypedData(value) {
56
- const td = value;
57
- return !!td && td.primaryType === "Delegation" && typeof td.domain?.verifyingContract === "string" && Array.isArray(td.message?.caveats);
58
- }
59
- function same(a, b) {
60
- return !!a && !!b && a.toLowerCase() === b.toLowerCase();
61
- }
62
- function hex(value) {
63
- return value.startsWith("0x") ? value.slice(2).toLowerCase() : value.toLowerCase();
64
- }
65
- function slice(terms, start, end) {
66
- const body = hex(terms);
67
- return end === void 0 ? body.slice(start * 2) : body.slice(start * 2, end * 2);
164
+ var DIRECT_RELAY_FALLBACK = "call haven_sign with payload_hash and typed_data_b64 from the haven_send / haven_pay result, passed through unchanged";
165
+ var HavenSignContextError = class extends edge.HavenSigningError {
166
+ /**
167
+ * #3001 / #3010 review: the recovery path, when signing OTHER bytes is
168
+ * actually a remedy — a transport failure (timeout, unreachable) or a
169
+ * body this signer could not read. `typed_data_b64` is NOT in the default
170
+ * quote result since #1272: obtain it by re-running the SAME quote tool
171
+ * with the SAME idempotency_key plus `include_signing_payload: true`.
172
+ * Absent on a backend REFUSAL (an expired, executed or unsignable intent
173
+ * cannot be rescued by re-signing its bytes) — with one #3271 exception: a
174
+ * 404 from the DIRECT fetch (an older backend with no direct route), where
175
+ * the `haven_send` / `haven_pay` result's relay fields still work.
176
+ */
177
+ fallback;
178
+ /**
179
+ * #3001: `AgentPaymentNextAction` values the signer already emits — the
180
+ * version-mismatch refusal's `stop_and_tell_user` for the classes where
181
+ * retrying the same call cannot help, and `payment_window_expired` (with
182
+ * `retry_with_new_quote`) for the x402 fetch's 410 / `expired`, exactly as
183
+ * the plain `HavenError` branch already does for that code. On the direct
184
+ * fetch (#3271) only `error_code: 'expired'` means an expired window, with
185
+ * no `retry_with_new_quote`; a bare 410 there is a retired-rail tombstone.
186
+ */
187
+ next_action;
188
+ /**
189
+ * #3103 (epic #3105, decisions 1 and 3): the typed next step beside the
190
+ * action. A refusal Haven made (`SIGN_CONTEXT_REFUSED`, not expired) names
191
+ * the hosted status read with the payment id — except a 404 from the direct
192
+ * fetch (#3271), which names none and points at the `typed_data_b64`
193
+ * relay; a transport failure or a
194
+ * malformed body names no tool — the remedy is re-running the SAME quote
195
+ * tool with `include_signing_payload: true` (x402), or the payment
196
+ * result's `typed_data_b64` relay (direct, #3271) — and an expired window names
197
+ * none either (which quote tool depends on the flow). Never null: a step
198
+ * with no tool carries `next_tool_omitted_reason`. Additive: the class is
199
+ * not exported from the package index — the published surface is the
200
+ * `ToolFailure` envelope `tools.ts` builds from these fields — and every
201
+ * constructor call site is in this file.
202
+ */
203
+ next_tool;
204
+ next_tool_server;
205
+ next_tool_name;
206
+ next_tool_server_role;
207
+ next_arguments;
208
+ next_tool_omitted_reason;
209
+ retry_with_new_quote;
210
+ /** Present only for `SIGN_CONTEXT_REFUSED` (the backend's HTTP status). */
211
+ http_status;
212
+ /** Present only for `SIGN_CONTEXT_REFUSED`: the backend's own `error_code`. */
213
+ backend_error_code;
214
+ /**
215
+ * #3303: on a 426 `client_outdated` refusal, the backend's update hint —
216
+ * this signer is below the minimum the deployment set, and
217
+ * `client_update.upgrade_command` is what updates it.
218
+ */
219
+ client_update;
220
+ constructor(message, code, refusal, paymentId, flow = "x402") {
221
+ super(message);
222
+ this.code = code;
223
+ this.name = "HavenSignContextError";
224
+ let step;
225
+ if (code === "SIGN_CONTEXT_REFUSED") {
226
+ this.http_status = refusal?.httpStatus;
227
+ this.backend_error_code = refusal?.errorCode;
228
+ if (refusal?.errorCode === "client_outdated") {
229
+ this.client_update = refusal.clientUpdate;
230
+ this.next_action = edge.AgentPaymentNextAction.StopAndTellUser;
231
+ step = signerRefusalStep({
232
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
233
+ nextTool: null,
234
+ nextToolOmittedReason: `this signer is below the minimum version Haven accepts \u2014 tell the user to run ${refusal.clientUpdate?.upgrade_command ?? "the connector again"}, restart the agent runtime, then retry the same haven_sign / haven_sign_x402 call`
235
+ });
236
+ } else if (flow === "direct" && refusal?.httpStatus === 404) {
237
+ this.fallback = "typed_data_b64";
238
+ this.next_action = edge.AgentPaymentNextAction.StopAndTellUser;
239
+ step = signerRefusalStep({
240
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
241
+ nextTool: null,
242
+ nextToolOmittedReason: DIRECT_RELAY_FALLBACK
243
+ });
244
+ } else if (flow === "direct" && refusal?.errorCode === "expired") {
245
+ this.next_action = edge.AgentPaymentNextAction.PaymentWindowExpired;
246
+ step = signerRefusalStep({
247
+ nextAction: edge.AgentPaymentNextAction.PaymentWindowExpired,
248
+ nextTool: null,
249
+ nextToolOmittedReason: "call haven_send / haven_pay again with the same idempotency_key \u2014 the expired payment frees it"
250
+ });
251
+ } else if (flow === "x402" && (refusal?.httpStatus === 410 || refusal?.errorCode === "expired")) {
252
+ this.next_action = edge.AgentPaymentNextAction.PaymentWindowExpired;
253
+ this.retry_with_new_quote = true;
254
+ step = signerRefusalStep({
255
+ nextAction: edge.AgentPaymentNextAction.PaymentWindowExpired,
256
+ nextTool: null,
257
+ nextToolOmittedReason: "re-run the hosted quote tool you called with the same idempotency_key; which one depends on the flow"
258
+ });
259
+ } else {
260
+ this.next_action = edge.AgentPaymentNextAction.StopAndTellUser;
261
+ step = signerRefusalStep({
262
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
263
+ nextTool: "haven_get_payment_status",
264
+ nextArguments: { payment_id: paymentId }
265
+ });
266
+ }
267
+ } else {
268
+ this.fallback = "typed_data_b64";
269
+ this.next_action = edge.AgentPaymentNextAction.StopAndTellUser;
270
+ step = signerRefusalStep({
271
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
272
+ nextTool: null,
273
+ nextToolOmittedReason: flow === "direct" ? DIRECT_RELAY_FALLBACK : "re-run the SAME hosted quote tool with the same idempotency_key and include_signing_payload: true, then pass its typed_data_b64 to this signer"
274
+ });
275
+ }
276
+ Object.assign(this, nextStepWireFields(step));
277
+ }
278
+ };
279
+ async function loadHavenIdentity(credentialsPath) {
280
+ if (!credentialsPath) return null;
281
+ try {
282
+ const raw = JSON.parse(
283
+ await promises.readFile(path.join(path.dirname(credentialsPath), "identity.json"), "utf8")
284
+ );
285
+ const apiKey = typeof raw.api_key === "string" ? raw.api_key : void 0;
286
+ const apiUrl = typeof raw.api_url === "string" ? raw.api_url : void 0;
287
+ if (!apiKey || !apiUrl) return null;
288
+ return { apiKey, apiUrl: apiUrl.replace(/\/+$/, "") };
289
+ } catch {
290
+ return null;
291
+ }
68
292
  }
69
- function findCaveat(caveats, enforcer) {
70
- return caveats.find((c) => same(c.enforcer, enforcer));
293
+ var SIGN_CONTEXT_TIMEOUT_MS = 15e3;
294
+ function signContextHeaders(identity, clientIdentity) {
295
+ return {
296
+ Authorization: `Bearer ${identity.apiKey}`,
297
+ ...clientIdentity ? { [edge.HAVEN_CLIENT_HEADER]: clientIdentity } : {}
298
+ };
71
299
  }
72
- function refuse(what, detail) {
73
- throw new sdk.HavenSigningError(
74
- `Refusing to sign the x402 settlement child: ${what}. ${detail} The signature on this child is what lets a merchant pull from the treasury, so it is verified locally against the Haven-signed expected context rather than trusted.`
75
- );
300
+ function refusalOf(status, body) {
301
+ return {
302
+ httpStatus: status,
303
+ errorCode: typeof body.error_code === "string" ? body.error_code : void 0,
304
+ clientUpdate: edge.readClientUpdate(body.client_update)
305
+ };
76
306
  }
77
- function chainIdForNetwork(network) {
78
- if (!network) return void 0;
79
- const caip = /^eip155:(\d+)$/.exec(network);
80
- if (caip) return Number(caip[1]);
81
- if (network === "base") return 8453;
82
- if (network === "base-sepolia") return 84532;
83
- return void 0;
84
- }
85
- function verifySettlementChild(typedData, expected, now = Date.now()) {
86
- if (typedData.primaryType !== "Delegation") {
87
- refuse("it is not a Delegation payload", `primaryType was '${typedData.primaryType}'.`);
88
- }
89
- if (!same(typedData.domain?.verifyingContract, DELEGATION_MANAGER)) {
90
- refuse(
91
- "the EIP-712 domain names an unknown DelegationManager",
92
- `Expected ${DELEGATION_MANAGER}, got ${typedData.domain?.verifyingContract}.`
307
+ async function fetchX402SignContext(identity, paymentId, fetchImpl = fetch, timeoutMs = SIGN_CONTEXT_TIMEOUT_MS, clientIdentity) {
308
+ let response;
309
+ try {
310
+ response = await fetchImpl(
311
+ `${identity.apiUrl}/x402/${encodeURIComponent(paymentId)}/sign-context`,
312
+ {
313
+ headers: signContextHeaders(identity, clientIdentity),
314
+ signal: AbortSignal.timeout(timeoutMs)
315
+ }
93
316
  );
94
- }
95
- const domainChain = Number(typedData.domain?.chainId);
96
- if (!Number.isFinite(domainChain) || domainChain !== expected.chainId) {
97
- refuse(
98
- "it is scoped to the wrong chain",
99
- `The expected context says chain ${expected.chainId}; the child says ${typedData.domain?.chainId}.`
317
+ } catch (err) {
318
+ const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
319
+ throw new HavenSignContextError(
320
+ timedOut ? `Haven did not answer the signing-context fetch for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the quote result instead.` : `Could not reach Haven to fetch the signing context for ${paymentId}: ${err instanceof Error ? err.message : String(err)}. Retry, or pass typed_data_b64 from the quote result instead.`,
321
+ timedOut ? "SIGN_CONTEXT_TIMEOUT" : "SIGN_CONTEXT_UNREACHABLE",
322
+ void 0,
323
+ paymentId
100
324
  );
101
325
  }
102
- const caveats = typedData.message?.caveats ?? [];
103
- if (caveats.length === 0) {
104
- refuse("it carries no caveats at all", "An unconstrained delegation is not a payment.");
326
+ let body;
327
+ try {
328
+ body = await response.json();
329
+ } catch (err) {
330
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
331
+ throw new HavenSignContextError(
332
+ `Haven did not finish sending the signing context for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the quote result instead.`,
333
+ "SIGN_CONTEXT_TIMEOUT",
334
+ void 0,
335
+ paymentId
336
+ );
337
+ }
338
+ body = {};
105
339
  }
106
- const transfer = findCaveat(caveats, CAVEAT_ENFORCERS.erc20TransferAmount);
107
- if (!transfer) {
108
- refuse(
109
- "it has no ERC-20 transfer-amount caveat",
110
- "Without it the delegation is not bounded to an amount."
340
+ if (!response.ok) {
341
+ const detail = typeof body.error === "string" ? body.error : `HTTP ${response.status}`;
342
+ throw new HavenSignContextError(
343
+ `Haven refused the signing-context fetch for ${paymentId}: ${detail}` + (response.status === 404 ? " \u2014 check the payment_id came from this agent\u2019s own quote." : response.status === 410 ? " Re-run the quote with the same idempotency key, then sign the fresh payment_id." : ""),
344
+ "SIGN_CONTEXT_REFUSED",
345
+ refusalOf(response.status, body),
346
+ paymentId
111
347
  );
112
348
  }
113
- const token = `0x${slice(transfer.terms, 0, 20)}`;
114
- if (!same(token, expected.asset)) {
115
- refuse("it spends a different token", `Expected ${expected.asset}, child pins ${token}.`);
116
- }
117
- const amount = BigInt(`0x${slice(transfer.terms, 20, 52)}`);
118
- if (amount !== BigInt(expected.amount)) {
119
- refuse(
120
- "the amount does not match",
121
- `The expected context says ${expected.amount}; the child allows ${amount.toString()}.`
349
+ const signData = body.sign_data;
350
+ const x402Expected = body.x402_expected;
351
+ if (!signData || typeof signData.hash !== "string" || !signData.typed_data || typeof signData.typed_data !== "object" || !x402Expected) {
352
+ throw new HavenSignContextError(
353
+ "The Haven sign-context response is missing sign_data.typed_data or x402_expected \u2014 the backend may predate #1263. Pass typed_data_b64 from the quote result instead.",
354
+ "SIGN_CONTEXT_MALFORMED",
355
+ void 0,
356
+ paymentId
122
357
  );
123
358
  }
124
- const calldata = findCaveat(caveats, CAVEAT_ENFORCERS.allowedCalldata);
125
- if (!calldata) {
126
- refuse(
127
- "it has no payee pin",
128
- "Without an allowed-calldata caveat the merchant could redeem it to any address."
359
+ const paymentRequired = body.payment_required;
360
+ return {
361
+ paymentId: String(body.payment_id ?? paymentId),
362
+ payloadHash: signData.hash,
363
+ typedData: signData.typed_data,
364
+ x402Expected,
365
+ paymentRequired: paymentRequired && typeof paymentRequired === "object" && !Array.isArray(paymentRequired) ? paymentRequired : null,
366
+ clientUpdate: edge.readClientUpdate(body.client_update)
367
+ };
368
+ }
369
+ var SUPPORTED_DIRECT_SIGN_CONTEXT_VERSIONS = [edge.DIRECT_SIGN_CONTEXT_VERSION];
370
+ async function fetchDirectSignContext(identity, paymentId, fetchImpl = fetch, timeoutMs = SIGN_CONTEXT_TIMEOUT_MS, clientIdentity) {
371
+ let response;
372
+ try {
373
+ response = await fetchImpl(
374
+ `${identity.apiUrl}/payments/${encodeURIComponent(paymentId)}/sign-context`,
375
+ {
376
+ headers: signContextHeaders(identity, clientIdentity),
377
+ signal: AbortSignal.timeout(timeoutMs)
378
+ }
129
379
  );
130
- }
131
- const startIndex = BigInt(`0x${slice(calldata.terms, 0, 32)}`);
132
- if (startIndex !== 4n) {
133
- refuse(
134
- "the payee pin points at the wrong calldata offset",
135
- `Expected offset 4 (the transfer's \`to\` word), got ${startIndex.toString()}.`
380
+ } catch (err) {
381
+ const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
382
+ throw new HavenSignContextError(
383
+ timedOut ? `Haven did not answer the direct-payment signing-context fetch for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the payment result instead.` : `Could not reach Haven to fetch the direct-payment signing context for ${paymentId}: ${err instanceof Error ? err.message : String(err)}. Retry, or pass typed_data_b64 from the payment result instead.`,
384
+ timedOut ? "SIGN_CONTEXT_TIMEOUT" : "SIGN_CONTEXT_UNREACHABLE",
385
+ void 0,
386
+ paymentId,
387
+ "direct"
136
388
  );
137
389
  }
138
- const paddedPayee = slice(calldata.terms, 32, 64);
139
- if (paddedPayee.slice(0, 24) !== "0".repeat(24)) {
140
- refuse("the pinned payee is not a plain address", "Its 32-byte word is not a padded address.");
390
+ let body;
391
+ try {
392
+ body = await response.json();
393
+ } catch (err) {
394
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
395
+ throw new HavenSignContextError(
396
+ `Haven did not finish sending the direct-payment signing context for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the payment result instead.`,
397
+ "SIGN_CONTEXT_TIMEOUT",
398
+ void 0,
399
+ paymentId,
400
+ "direct"
401
+ );
402
+ }
403
+ body = {};
141
404
  }
142
- const payee = `0x${paddedPayee.slice(24)}`;
143
- if (!same(payee, expected.merchantTo)) {
144
- refuse(
145
- "it pays a different address than Haven declared",
146
- `The expected context says ${expected.merchantTo}; the child pins ${payee}.`
405
+ if (!response.ok) {
406
+ const detail = typeof body.error === "string" ? body.error : `HTTP ${response.status}`;
407
+ throw new HavenSignContextError(
408
+ `Haven refused the direct-payment signing-context fetch for ${paymentId}: ${detail}` + (response.status === 404 ? " \u2014 either the payment_id is not from this agent\u2019s own POST /payments call, or this Haven backend predates #3271. Pass payload_hash and typed_data_b64 from the haven_send / haven_pay result, unchanged, instead." : body.error_code === "expired" ? " The payment window has expired; call haven_send / haven_pay again with the same idempotency_key." : ""),
409
+ "SIGN_CONTEXT_REFUSED",
410
+ refusalOf(response.status, body),
411
+ paymentId,
412
+ "direct"
147
413
  );
148
414
  }
149
- const timestamp = findCaveat(caveats, CAVEAT_ENFORCERS.timestamp);
150
- if (!timestamp) {
151
- refuse("it never expires", "A settlement child without a timestamp caveat is open-ended.");
152
- }
153
- const beforeThreshold = Number(BigInt(`0x${slice(timestamp.terms, 16, 32)}`));
154
- if (beforeThreshold <= 0) {
155
- refuse("its expiry is unset", "The timestamp caveat has no upper bound.");
156
- }
157
- const nowSec = Math.floor(now / 1e3);
158
- if (beforeThreshold <= nowSec) {
159
- refuse("it has already expired", `Expiry ${beforeThreshold} is not in the future.`);
160
- }
161
- if (beforeThreshold > nowSec + MAX_SETTLEMENT_WINDOW_SECONDS) {
162
- refuse(
163
- "its window is longer than a settlement may live",
164
- `Expiry is ${beforeThreshold - nowSec}s out; the ceiling is ${MAX_SETTLEMENT_WINDOW_SECONDS}s.`
415
+ const signData = body.sign_data;
416
+ const version = body.direct_sign_context_version;
417
+ if (!signData || typeof signData.hash !== "string" || !signData.typed_data || typeof signData.typed_data !== "object" || signData.signature_scheme !== "eip712_userop" || typeof version !== "number" || !SUPPORTED_DIRECT_SIGN_CONTEXT_VERSIONS.includes(version)) {
418
+ throw new HavenSignContextError(
419
+ typeof version === "number" && !SUPPORTED_DIRECT_SIGN_CONTEXT_VERSIONS.includes(version) ? `The Haven direct-payment sign-context response is version ${version}, which this signer does not support (supported: ${SUPPORTED_DIRECT_SIGN_CONTEXT_VERSIONS.join(", ")}). Update @haven_ai/signer.` : "The Haven direct-payment sign-context response is missing sign_data.typed_data, or its signature_scheme is not 'eip712_userop' \u2014 the backend may predate #3271. Pass typed_data_b64 from the payment result instead.",
420
+ "SIGN_CONTEXT_MALFORMED",
421
+ void 0,
422
+ paymentId,
423
+ "direct"
165
424
  );
166
425
  }
167
- if (expected.expiresAt) {
168
- const declared = Math.floor(Date.parse(expected.expiresAt) / 1e3);
169
- if (Number.isFinite(declared) && beforeThreshold > declared) {
170
- refuse(
171
- "it outlives the payment window Haven declared",
172
- `The expected context expires at ${expected.expiresAt}; the child lives to ${beforeThreshold}.`
173
- );
174
- }
175
- }
426
+ return {
427
+ paymentId: String(body.payment_id ?? paymentId),
428
+ payloadHash: signData.hash,
429
+ typedData: signData.typed_data,
430
+ status: typeof body.status === "string" ? body.status : "pending_signature",
431
+ expiresAt: typeof body.expires_at === "string" ? body.expires_at : void 0,
432
+ clientUpdate: edge.readClientUpdate(body.client_update)
433
+ };
176
434
  }
177
- function createEdgeSigner(delegateKey, options = {}) {
178
- let delegateAddress;
179
- try {
180
- delegateAddress = sdk.addressFromKey(delegateKey);
181
- } catch (err) {
182
- throw new sdk.HavenSigningError(
183
- `Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`
184
- );
435
+
436
+ // src/tools.ts
437
+ var USEROP_BINDING_MISMATCH = "USEROP_BINDING_MISMATCH";
438
+ var HavenUserOpBindingRefusedError = class extends edge.HavenSigningError {
439
+ next_action = edge.AgentPaymentNextAction.StopAndTellUser;
440
+ step;
441
+ /** `message`: the SDK's `HavenUserOpBindingError.message` verbatim — it already names the mismatch and the remedy. */
442
+ constructor(message) {
443
+ super(message);
444
+ this.code = USEROP_BINDING_MISMATCH;
445
+ this.name = "HavenUserOpBindingRefusedError";
446
+ this.step = signerRefusalStep({
447
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
448
+ nextTool: null,
449
+ nextToolOmittedReason: "call haven_sign again with payment_id alone (preferred), or with typed_data copied unchanged from the payment result"
450
+ });
185
451
  }
186
- const x402Bindings = /* @__PURE__ */ new Map();
187
- const retiredX402Bindings = /* @__PURE__ */ new Map();
188
- const RETIRED_BINDING_MEMORY = 64;
189
- function retireX402Binding(id, reason) {
190
- retiredX402Bindings.set(id, reason);
191
- if (retiredX402Bindings.size > RETIRED_BINDING_MEMORY) {
192
- const oldest = retiredX402Bindings.keys().next();
193
- if (!oldest.done) retiredX402Bindings.delete(oldest.value);
194
- }
452
+ };
453
+ var HavenTypedDataNotAllowedError = class extends edge.HavenTypedDataRefusedError {
454
+ next_action = edge.AgentPaymentNextAction.StopAndTellUser;
455
+ step;
456
+ constructor(message) {
457
+ super(message);
458
+ this.name = "HavenTypedDataNotAllowedError";
459
+ this.step = signerRefusalStep({
460
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
461
+ nextTool: null,
462
+ nextToolOmittedReason: "sign only Haven-prepared payloads: call haven_sign with payment_id (preferred), or pass typed_data / typed_data_b64 copied unchanged from a haven_send / haven_pay result, or x402_expected from a Haven quote"
463
+ });
195
464
  }
196
- function signAndVerify(hash) {
197
- const signature = sdk.signHash(delegateKey, hash);
198
- if (!sdk.verifySignature(hash, signature, delegateAddress)) {
199
- throw new sdk.HavenSigningError(
200
- "Local signature verification failed \u2014 recovered address does not match the delegate key."
201
- );
465
+ };
466
+ function assertBoundDirectPaymentUserOp(typedData, delegateAddress) {
467
+ try {
468
+ edge.assertBoundDirectPaymentUserOp(typedData, delegateAddress);
469
+ } catch (err) {
470
+ if (err instanceof edge.HavenTypedDataRefusedError && !(err instanceof HavenTypedDataNotAllowedError)) {
471
+ throw new HavenTypedDataNotAllowedError(err.message);
202
472
  }
203
- return signature;
473
+ throw err;
204
474
  }
205
- return {
206
- delegateAddress,
207
- signPaymentHash(hash) {
208
- return signAndVerify(hash);
209
- },
210
- async signDelegationTypedData(typedData) {
211
- const account = accounts.privateKeyToAccount(delegateKey);
212
- return account.signTypedData(typedData);
213
- },
214
- signX402FundingHash(hash, expected) {
215
- assertExpectedBinding(hash, expected, options.x402BindingSigner, "hash");
216
- assertPayerMatchesDelegate(expected, delegateAddress, options.agentId);
217
- const signature = signAndVerify(hash);
218
- const x402Binding = crypto.randomUUID();
219
- x402Bindings.set(x402Binding, { ...expected });
220
- return { signature, x402Binding };
221
- },
222
- async signX402FundingTypedData(typedData, expected) {
223
- assertExpectedBinding(expected.payloadHash, expected, options.x402BindingSigner, "typed-data");
224
- assertPayerMatchesDelegate(expected, delegateAddress, options.agentId);
225
- const digest = viem.hashTypedData(typedData);
226
- if (digest.toLowerCase() !== expected.typedDataHash?.toLowerCase()) {
227
- throw new sdk.HavenSigningError(
228
- "x402 typed data does not match the digest Haven committed to in the expected context. Refusing to sign \u2014 the payload was altered in transit or Haven declared a different one. The most common cause is the typed data being truncated or reshaped while being copied between tool calls (#1255): re-run the hosted quote and pass its typed_data_b64 string through UNCHANGED instead of re-emitting the nested JSON."
229
- );
230
- }
231
- if (isSettlementChildTypedData(typedData)) {
232
- const settlementChainId = chainIdForNetwork(expected.network);
233
- if (settlementChainId === void 0) {
234
- throw new sdk.HavenSigningError(
235
- `Refusing to sign the x402 settlement child: this signer cannot map the network '${expected.network}' to a chain id, so it cannot check which chain the child is scoped to. Update @haven_ai/signer.`
236
- );
237
- }
238
- verifySettlementChild(typedData, {
239
- merchantTo: expected.merchantTo,
240
- amount: expected.amount,
241
- asset: expected.asset,
242
- // From the SIGNED network, not the payload's own claim. Passing
243
- // Number(typedData.domain.chainId) here made the check compare a
244
- // value to itself — vacuous, and precisely the "declared one thing,
245
- // signed another" class this file exists to catch (#1455 review).
246
- chainId: settlementChainId,
247
- expiresAt: expected.expiresAt
248
- });
249
- }
250
- const account = accounts.privateKeyToAccount(delegateKey);
251
- const signature = await account.signTypedData(
252
- typedData
253
- );
254
- const x402Binding = crypto.randomUUID();
255
- x402Bindings.set(x402Binding, { ...expected });
256
- return { signature, x402Binding };
257
- },
258
- async buildX402PaymentHeader(paymentRequired, x402Binding) {
259
- const expected = x402Bindings.get(x402Binding);
260
- if (!expected) {
261
- const retired = retiredX402Bindings.get(x402Binding);
262
- if (retired === "header_built") {
263
- throw new sdk.HavenSigningError(
264
- "This x402 binding was already used to build a merchant header. Bindings are single-use. If you called haven_sign_x402, it already returned the payment_header \u2014 retry the merchant with THAT header instead of building another; haven_x402_sign_header is the follow-up to haven_sign, not to haven_sign_x402. If you no longer have the header, re-run the quote tool with the same idempotency_key."
265
- );
266
- }
267
- if (retired === "window_expired") {
268
- throw new sdk.HavenSigningError(
269
- "This x402 binding was retired because its payment window closed before a merchant header could be built \u2014 no header exists to retry with. Re-run the quote tool with the same idempotency_key to get a fresh window, then sign again."
475
+ }
476
+ var sweepAuthorizationSchema = v3.z.object({
477
+ from: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "from must be a 0x address"),
478
+ to: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "to must be a 0x address"),
479
+ value: v3.z.string().regex(/^[0-9]+$/, "value must be a decimal atomic amount"),
480
+ validAfter: v3.z.string().regex(/^[0-9]+$/, "validAfter must be a decimal unix time"),
481
+ validBefore: v3.z.string().regex(/^[0-9]+$/, "validBefore must be a decimal unix time"),
482
+ nonce: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "nonce must be a 0x-prefixed 32-byte hex string"),
483
+ token: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "token must be a 0x address"),
484
+ chainId: v3.z.number().int().positive()
485
+ });
486
+ var bindingVersionSchema = v3.z.number().int().positive();
487
+ var sweepExpectedAuthSchema = v3.z.object({
488
+ version: bindingVersionSchema,
489
+ message: v3.z.string().min(1),
490
+ signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
491
+ signer: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "signer must be a 0x address")
492
+ });
493
+ var x402ExpectedShape = {
494
+ payment_id: v3.z.string().min(1),
495
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "payload_hash must be a 0x-prefixed 32-byte hex string"),
496
+ resource_url: v3.z.string().url(),
497
+ merchant_to: v3.z.string().min(1),
498
+ amount: v3.z.string().min(1),
499
+ asset: v3.z.string().min(1),
500
+ network: v3.z.string().min(1),
501
+ // Required: expires_at is folded into the Haven-signed binding message, so the
502
+ // signer must receive the exact same value to reconstruct a matching message.
503
+ // Omitting it used to fail downstream with a cryptic "authentication message is
504
+ // invalid" — making it required surfaces a clear INVALID_INPUT at the boundary.
505
+ expires_at: v3.z.string().min(1),
506
+ // #1138: present on a delegation-rail (v2) context. It commits to the EIP-712
507
+ // typed data the account validates; the signer refuses to raw-sign the bare
508
+ // hash when it is present, and refuses to sign typed data when it is absent.
509
+ typed_data_hash: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "typed_data_hash must be a 0x-prefixed 32-byte hex string").optional(),
510
+ // #1690: present on a v3 context. The delegate this quote was created FOR —
511
+ // the signer refuses to sign when it is not its own. Inside the Haven-signed
512
+ // message, so stripping it here would only break the binding signature.
513
+ payer_delegate: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "payer_delegate must be a 0x-prefixed address").optional(),
514
+ payer_agent_id: v3.z.string().min(1).optional(),
515
+ auth: v3.z.object({
516
+ // Open at the boundary, enforced in the signer — see bindingVersionSchema.
517
+ version: bindingVersionSchema,
518
+ message: v3.z.string().min(1),
519
+ signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
520
+ signer: v3.z.string().min(1)
521
+ })
522
+ };
523
+ var x402ExpectedSchema = v3.z.object(x402ExpectedShape);
524
+ var toolSchemas = {
525
+ haven_sign_sweep_delegate: {
526
+ // The authorization fields prepared by Haven's POST /sweep/prepare. Passed
527
+ // through verbatim from the hosted haven_sweep_delegate tool — the signer
528
+ // re-derives the binding message from these exact values.
529
+ authorization: sweepAuthorizationSchema,
530
+ // Haven's signature over the authorization context (the binding).
531
+ expected_auth: sweepExpectedAuthSchema
532
+ },
533
+ haven_sign: {
534
+ // #1263: THE preferred x402 input — the signer fetches the exact signing
535
+ // payload + expected context from Haven itself (authenticated with the
536
+ // locally-stored agent credential), so no bulky bytes ever cross the
537
+ // model. Pass payment_id ALONE for a delegation-rail x402 funding intent.
538
+ payment_id: v3.z.string().min(1).optional(),
539
+ // The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).
540
+ // Optional when payment_id is supplied (the fetch carries it).
541
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "payload_hash must be a 0x-prefixed 32-byte hex string").optional(),
542
+ // Pass x402.expected from hosted haven_pay_x402_quote when this hash funds
543
+ // a standard x402 merchant retry. The signer records it locally and returns
544
+ // an opaque x402_binding for the later header-signing step.
545
+ x402_expected: x402ExpectedSchema.optional(),
546
+ // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
547
+ // (not z.unknown()) so MCP clients embed it as JSON rather than a string.
548
+ typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
549
+ // #1255: the same payload as ONE opaque base64 string, exactly as returned
550
+ // by the hosted tools. Preferred over typed_data when both are present —
551
+ // an agent re-emitting multi-KB nested JSON between tool calls is the
552
+ // failure mode this field removes (a truncated/reshaped payload fails the
553
+ // digest check and the payment refuses, correctly but pointlessly).
554
+ // Bounded: a realistic redemption payload is ~10KB encoded; 256KB is
555
+ // generous headroom while keeping the offline signer from materializing
556
+ // arbitrarily large caller input.
557
+ typed_data_b64: v3.z.string().min(1).max(262144).optional()
558
+ },
559
+ haven_x402_sign_header: {
560
+ // The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object
561
+ // (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients
562
+ // embed it as JSON rather than serialising the object to a string.
563
+ payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
564
+ // Opaque binding returned by haven_sign when x402_expected was supplied.
565
+ x402_binding: v3.z.string().min(1)
566
+ },
567
+ haven_sign_x402: {
568
+ // #1263: preferred — pass payment_id (plus payment_required) and the
569
+ // signer fetches the exact signing payload + expected context itself.
570
+ payment_id: v3.z.string().min(1).optional(),
571
+ // One-shot x402 signing: funding hash + merchant header in one local call.
572
+ // Both optional when payment_id is supplied (the fetch carries them).
573
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "payload_hash must be a 0x-prefixed 32-byte hex string").optional(),
574
+ x402_expected: x402ExpectedSchema.optional(),
575
+ // #1355: optional when payment_id is supplied — the signer's context fetch
576
+ // carries the stored 402 PaymentRequired, so `{ payment_id }` alone is the
577
+ // preferred call. Still required (via the runtime check in the handler)
578
+ // for the quote-based fallback path without a payment_id.
579
+ payment_required: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
580
+ // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
581
+ // (not z.unknown()) so MCP clients embed it as JSON rather than a string.
582
+ typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
583
+ // #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.
584
+ typed_data_b64: v3.z.string().min(1).max(262144).optional()
585
+ }
586
+ // #3101: keys survive on the type (see the hosted server's contracts.ts).
587
+ };
588
+ var SIGN_DESCRIPTION = [
589
+ "Sign an unsigned Haven payment with the local delegate key. The delegate key never leaves",
590
+ "this process. Pass payment_id (preferred), or the payload_hash from haven_pay / haven_pay_x402_quote",
591
+ "TOGETHER WITH typed_data / typed_data_b64 or x402_expected \u2014 never a payload_hash alone.",
592
+ "For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally",
593
+ "and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that",
594
+ "window closes. DELEGATION-RAIL x402 accounts (#1263): pass payment_id ALONE (preferred) \u2014 this",
595
+ "signer fetches the exact signing payload and expected context from Haven itself, so nothing",
596
+ "bulky ever crosses your context. DIRECT payments (#3271, haven_send / haven_pay): payment_id",
597
+ "ALONE also works here \u2014 the signer fetches the exact PackedUserOperation typed data and its",
598
+ "payload_hash from Haven and checks them against each other before signing, so a payload corrupted",
599
+ "in transit is refused (USEROP_BINDING_MISMATCH) instead of producing a bad signature. Fallback for",
600
+ "either flow: pass typed_data_b64 through UNCHANGED (never re-type the nested typed_data JSON); the",
601
+ "account validates that EIP-712 payload, not payload_hash. On a direct payment the same binding",
602
+ "check runs on the relayed payload too. This tool signs ONLY Haven-prepared payloads (#3272): a",
603
+ "direct-payment UserOp from your own account that redeems a delegation granted to it, or an x402",
604
+ "intent against a Haven-signed context \u2014 never an arbitrary typed_data payload, however it is shaped.",
605
+ "Next: call mcp__haven__haven_submit with signature, then pass x402_binding",
606
+ "to mcp__haven-signer__haven_x402_sign_header. A bare payload_hash with no payment_id, typed_data",
607
+ "or x402_expected is REFUSED (BARE_HASH_REFUSED): a hash carries nothing this signer can verify."
608
+ ].join(" ");
609
+ var X402_SIGN_HEADER_DESCRIPTION = [
610
+ "Build and sign the EIP-3009 merchant payment header for the merchant leg of an x402 payment.",
611
+ "The delegate key stays local \u2014 only the signed header crosses any boundary.",
612
+ "Pass the payment_required from the original merchant 402 response and the x402_binding",
613
+ "returned by haven_sign. It must be haven_sign \u2014 NOT haven_sign_x402, which is a",
614
+ "one-shot that builds the header itself and spends its own binding doing so. If you called",
615
+ "haven_sign_x402, its result already carries payment_header; retry the merchant with that and",
616
+ "do not call this tool. The signer validates the merchant, amount, resource, asset, and",
617
+ "network against the recorded funding context before signing, checks expires_at when present,",
618
+ "and rejects mismatches or expired payment windows.",
619
+ "Returns { payment_header, accepted }. On your retry set BOTH PAYMENT-SIGNATURE (x402 v2) and",
620
+ "X-PAYMENT (v1) to <payment_header>; a strict v2 merchant reads only the first.",
621
+ "Only call after haven_submit has confirmed the funding step (nextAction=none or",
622
+ "the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
623
+ ].join(" ");
624
+ var SIGN_X402_DESCRIPTION = [
625
+ "One-shot x402 signing for the fast 3-call flow: sign the funding payload AND build the EIP-3009",
626
+ "merchant payment header in a single local call (equivalent to haven_sign followed by",
627
+ "haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool",
628
+ "result pass JUST payment_id \u2014 PREFERRED (#1263, #1355): this signer fetches the exact signing",
629
+ "payload, expected context, and merchant payment_required from Haven itself, so nothing bulky",
630
+ "crosses your context. If the signer reports the context carried no payment_required (older",
631
+ "backend), re-call with payment_id plus payment_required verbatim from the pay result.",
632
+ "Fallback for older backends: pass payload_hash, x402_expected (the nested x402.expected object \u2014",
633
+ "passing the whole x402 object is also accepted and unwrapped for you), and typed_data_b64",
634
+ "through UNCHANGED; the signer",
635
+ "signs the typed data instead of payload_hash and refuses the bare hash when the context commits to typed data.",
636
+ "Returns",
637
+ "{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to",
638
+ "mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before",
639
+ "funding confirms), so its short validity window starts here \u2014 call mcp__haven__haven_settle_mcp_tool promptly,",
640
+ "and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.",
641
+ "The returned x402_binding is ALREADY SPENT \u2014 this tool consumed it building payment_header \u2014",
642
+ "so never pass it to mcp__haven-signer__haven_x402_sign_header; that tool is the follow-up to",
643
+ "haven_sign, not to this one. payment_header IS the header to use.",
644
+ "Next: for a paid MCP tool, call mcp__haven__haven_settle_mcp_tool. For a direct plain-HTTP x402",
645
+ "merchant (the haven_pay_x402_quote path), relay signature via mcp__haven__haven_submit and then",
646
+ "retry the original merchant URL YOURSELF, setting BOTH PAYMENT-SIGNATURE (x402 v2) and",
647
+ "X-PAYMENT (v1) to payment_header \u2014 Haven never contacts that merchant."
648
+ ].join(" ");
649
+ var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
650
+ "Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
651
+ "wallet back to the agent's account (Haven wallet). The delegate key never leaves this process and this",
652
+ "tool never broadcasts \u2014 it returns only an EIP-3009 signature that Haven's relayer submits and",
653
+ "pays gas for. Pass the authorization and expected_auth returned by the hosted",
654
+ "haven_sweep_delegate tool. The signer verifies Haven authored the authorization; the",
655
+ "destination is checked against the agent's account (Haven wallet) from the local credential",
656
+ "when the credential carries one, and otherwise rests on Haven's binding signature. Then it",
657
+ "returns { signature } to hand back to mcp__haven__haven_sweep_delegate to complete recovery."
658
+ ].join(" ");
659
+ var toolDescriptions = {
660
+ haven_sign: SIGN_DESCRIPTION,
661
+ haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
662
+ haven_sign_x402: SIGN_X402_DESCRIPTION,
663
+ haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
664
+ };
665
+ async function signFundingLeg(signer, expected, typedData) {
666
+ try {
667
+ return await signer.signX402FundingTypedData(typedData, expected);
668
+ } catch (err) {
669
+ if (err instanceof edge.HavenTypedDataRefusedError && !(err instanceof HavenTypedDataNotAllowedError)) {
670
+ throw new HavenTypedDataNotAllowedError(err.message);
671
+ }
672
+ if (err instanceof edge.HavenUserOpBindingError) {
673
+ throw new HavenUserOpBindingRefusedError(err.message);
674
+ }
675
+ throw err;
676
+ }
677
+ }
678
+ function toExpectedX402(raw) {
679
+ return {
680
+ paymentId: raw.payment_id,
681
+ payloadHash: raw.payload_hash,
682
+ typedDataHash: raw.typed_data_hash,
683
+ payerDelegate: raw.payer_delegate,
684
+ payerAgentId: raw.payer_agent_id,
685
+ resourceUrl: raw.resource_url,
686
+ merchantTo: raw.merchant_to,
687
+ amount: raw.amount,
688
+ asset: raw.asset,
689
+ network: raw.network,
690
+ expiresAt: raw.expires_at,
691
+ auth: raw.auth
692
+ };
693
+ }
694
+ function parseFetchedExpected(fetched) {
695
+ const parsed = v3.z.object(x402ExpectedShape).safeParse(fetched.x402Expected);
696
+ if (!parsed.success) {
697
+ throw new edge.HavenSigningError(
698
+ `The Haven sign-context response carried a malformed x402_expected \u2014 the backend may predate #1263. Pass payload_hash + x402_expected from the quote result instead. Underlying: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`
699
+ );
700
+ }
701
+ return parsed.data;
702
+ }
703
+ function clientUpdateField(resolved) {
704
+ return resolved?.ctx.clientUpdate ? { client_update: resolved.ctx.clientUpdate } : {};
705
+ }
706
+ function resolveTypedData(args) {
707
+ if (!args.typed_data_b64) return args.typed_data;
708
+ try {
709
+ const decoded = JSON.parse(
710
+ Buffer.from(args.typed_data_b64, "base64").toString("utf8")
711
+ );
712
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) {
713
+ throw new Error("decoded value is not an object");
714
+ }
715
+ return decoded;
716
+ } catch (err) {
717
+ throw new edge.HavenSigningError(
718
+ `typed_data_b64 did not decode to a JSON object. Pass the exact string returned by the hosted Haven tool, unchanged \u2014 do not re-encode, trim, or reformat it. Underlying error: ${err instanceof Error ? err.message : String(err)}`
719
+ );
720
+ }
721
+ }
722
+ function createToolHandlers(signer, options = {}) {
723
+ function checkPayloadHashMatch(suppliedHash, fetchedHash, paymentId) {
724
+ if (suppliedHash && suppliedHash.toLowerCase() !== fetchedHash.toLowerCase()) {
725
+ throw new edge.HavenSigningError(
726
+ `The supplied payload_hash does not match the signing context Haven serves for payment ${paymentId}. Pass payment_id alone, or check which quote the hash came from.`
727
+ );
728
+ }
729
+ }
730
+ async function resolveSignContext(args, opts) {
731
+ if (!args.payment_id) return null;
732
+ const identity = await options.signContext?.loadIdentity() ?? null;
733
+ if (!identity) {
734
+ throw new edge.HavenSigningError(
735
+ `payment_id signing needs the agent identity (identity.json next to the signer credentials), which this signer could not load. Re-run \`${edge.connectorRerunCommand()}\` to restore it, or pass typed_data_b64 from the quote result instead.`
736
+ );
737
+ }
738
+ try {
739
+ const ctx = await fetchX402SignContext(
740
+ identity,
741
+ args.payment_id,
742
+ options.signContext?.fetchImpl,
743
+ void 0,
744
+ options.signContext?.clientIdentity
745
+ );
746
+ checkPayloadHashMatch(args.payload_hash, ctx.payloadHash, args.payment_id);
747
+ return { kind: "x402", ctx };
748
+ } catch (err) {
749
+ if (opts.allowDirectFallback && err instanceof HavenSignContextError && err.http_status === 409 && err.backend_error_code === "sign_context_unavailable") {
750
+ let ctx;
751
+ try {
752
+ ctx = await fetchDirectSignContext(
753
+ identity,
754
+ args.payment_id,
755
+ options.signContext?.fetchImpl,
756
+ void 0,
757
+ options.signContext?.clientIdentity
270
758
  );
759
+ } catch (directErr) {
760
+ if (directErr instanceof HavenSignContextError && directErr.http_status === 409 && directErr.backend_error_code === "sign_context_unavailable") {
761
+ throw err;
762
+ }
763
+ throw directErr;
271
764
  }
272
- throw new sdk.HavenSigningError(
273
- "x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first (haven_sign returns a binding this tool can use). A binding is also lost when the signer process restarts, since bindings live in memory only \u2014 re-sign to mint a fresh one."
274
- );
275
- }
276
- try {
277
- assertX402PaymentWindowOpen(expected);
278
- } catch (err) {
279
- x402Bindings.delete(x402Binding);
280
- retireX402Binding(x402Binding, "window_expired");
281
- throw err;
765
+ checkPayloadHashMatch(args.payload_hash, ctx.payloadHash, args.payment_id);
766
+ return { kind: "direct", ctx };
282
767
  }
283
- const option = sdk.selectStandardPaymentOption(paymentRequired.accepts);
284
- if (!option) {
285
- throw new sdk.HavenApiError(
286
- "No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
287
- 400
768
+ throw err;
769
+ }
770
+ }
771
+ return {
772
+ haven_sign: async (input) => runTool(async () => {
773
+ const args = parse("haven_sign", coerceX402Expected(input));
774
+ const resolved = await resolveSignContext(args, { allowDirectFallback: true });
775
+ const typedData = resolved?.ctx.typedData ?? resolveTypedData(args);
776
+ const payloadHash = resolved?.ctx.payloadHash ?? args.payload_hash;
777
+ if (!payloadHash) {
778
+ throw new edge.HavenSigningError(
779
+ "Pass payment_id (preferred for delegation-rail x402 or direct payments) or payload_hash."
288
780
  );
289
781
  }
290
- assertX402MatchesExpected(paymentRequired, option, expected);
291
- const account = accounts.privateKeyToAccount(delegateKey);
292
- const requirements = sdk.toStandardPaymentRequirements(paymentRequired, option);
293
- const header = await schemes.exact.evm.createPaymentHeader(
294
- account,
295
- paymentRequired.x402Version,
296
- requirements
297
- );
298
- if (paymentRequired.x402Version < 2) {
299
- x402Bindings.delete(x402Binding);
300
- retireX402Binding(x402Binding, "header_built");
301
- return { paymentHeader: header, accepted: option };
302
- }
303
- try {
304
- const payment = sdk.decodeBase64Json(header);
305
- const wrapped = sdk.encodeBase64Json(
306
- sdk.x402V2PaymentEnvelope(paymentRequired, option, payment.payload)
307
- );
308
- return { paymentHeader: wrapped, accepted: option };
309
- } finally {
310
- x402Bindings.delete(x402Binding);
311
- retireX402Binding(x402Binding, "header_built");
782
+ const expectedRaw = resolved?.kind === "x402" ? parseFetchedExpected(resolved.ctx) : resolved?.kind === "direct" ? null : args.x402_expected;
783
+ const x402Expected = expectedRaw ? toExpectedX402(expectedRaw) : null;
784
+ const result = x402Expected ? await signFundingLeg(signer, x402Expected, typedData) : null;
785
+ if (!result) {
786
+ if (typedData) {
787
+ if (edge.isSettlementChildTypedData(typedData)) {
788
+ throw new edge.HavenSigningError(
789
+ "Refusing to sign a delegation payload with no expected context. This typed data is a DELEGATION \u2014 signing it grants a third party authority to move funds \u2014 so it is only ever signed against a Haven-signed context that the caveats are verified against. Call this tool with { payment_id } instead (the signer then fetches and verifies the context itself), or use haven_sign_x402."
790
+ );
791
+ }
792
+ if (resolved?.kind !== "direct" && !edge.isPackedUserOperationTypedData(typedData)) {
793
+ throw new HavenTypedDataNotAllowedError(
794
+ "This signer signs only Haven-prepared payloads: a direct-payment PackedUserOperation from your own account that redeems a delegation granted to it, or a Haven-signed x402 context. Call haven_sign with payment_id (preferred), or pass x402_expected for an x402 funding leg."
795
+ );
796
+ }
797
+ try {
798
+ edge.assertUserOpTypedDataBinding(typedData, payloadHash);
799
+ } catch (err) {
800
+ if (err instanceof edge.HavenUserOpBindingError) {
801
+ throw new HavenUserOpBindingRefusedError(err.message);
802
+ }
803
+ throw err;
804
+ }
805
+ assertBoundDirectPaymentUserOp(typedData, signer.delegateAddress);
806
+ const signature = await signer.signDelegationTypedData(typedData);
807
+ await auditSigning("haven_sign", viem.hashTypedData(typedData));
808
+ return { signature, ...clientUpdateField(resolved) };
809
+ }
810
+ throw new HavenBareHashRefusedError();
312
811
  }
313
- },
314
- async signSweepAuthorization({
315
- authorization,
316
- expectedAuth,
317
- expectedSafe
318
- }) {
319
- assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner);
320
- if (!sameAddress(authorization.from, delegateAddress)) {
321
- throw new sdk.HavenSigningError(
322
- "Sweep authorization `from` does not match this delegate address."
812
+ await auditSigning("haven_sign", viem.hashTypedData(typedData));
813
+ return { signature: result.signature, x402_binding: result.x402Binding, ...clientUpdateField(resolved) };
814
+ }),
815
+ haven_x402_sign_header: async (input) => runTool(async () => {
816
+ const args = parse("haven_x402_sign_header", coercePaymentRequired(input));
817
+ const result = await signer.buildX402PaymentHeader(
818
+ args.payment_required,
819
+ args.x402_binding
820
+ );
821
+ await auditSigning(
822
+ "haven_x402_sign_header",
823
+ hashPayloadForAudit(args.payment_required)
824
+ );
825
+ return { payment_header: result.paymentHeader, accepted: result.accepted };
826
+ }),
827
+ haven_sign_x402: async (input) => runTool(async () => {
828
+ const args = parse("haven_sign_x402", coerceX402Expected(coercePaymentRequired(input)));
829
+ const resolved = await resolveSignContext(args, { allowDirectFallback: false });
830
+ const fetched = resolved?.kind === "x402" ? resolved.ctx : void 0;
831
+ const payloadHash = fetched?.payloadHash ?? args.payload_hash;
832
+ const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected;
833
+ if (!payloadHash || !expectedRaw) {
834
+ throw new edge.HavenSigningError(
835
+ "Pass payment_id (preferred \u2014 the signer fetches the signing context itself) or payload_hash + x402_expected from the quote result."
323
836
  );
324
837
  }
325
- if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {
326
- throw new sdk.HavenSigningError(
327
- "Sweep authorization `to` does not match the Safe in the local credential."
838
+ const fundingTypedData = fetched?.typedData ?? resolveTypedData(args);
839
+ const funding = await signFundingLeg(signer, toExpectedX402(expectedRaw), fundingTypedData);
840
+ const paymentRequired = fetched?.paymentRequired ?? args.payment_required;
841
+ if (!paymentRequired) {
842
+ throw new edge.HavenSigningError(
843
+ fetched ? "The Haven sign-context for this payment_id carried no payment_required (backend predates #1355). Pass payment_required from the pay result explicitly, verbatim." : "payment_required is required on the quote-based path (no payment_id to fetch it by). Pass it verbatim from the quote result."
328
844
  );
329
845
  }
330
- const typedData = sdk.buildSweepTypedData(authorization);
331
- const viemTypedData = {
332
- domain: {
333
- ...typedData.domain,
334
- verifyingContract: typedData.domain.verifyingContract
335
- },
336
- types: typedData.types,
337
- primaryType: typedData.primaryType,
338
- message: {
339
- ...typedData.message,
340
- from: typedData.message.from,
341
- to: typedData.message.to,
342
- nonce: typedData.message.nonce
343
- }
846
+ const header = await signer.buildX402PaymentHeader(
847
+ paymentRequired,
848
+ funding.x402Binding
849
+ );
850
+ await auditSigning(
851
+ "haven_sign_x402",
852
+ viem.hashTypedData(fundingTypedData)
853
+ );
854
+ await auditSigning("haven_sign_x402", hashPayloadForAudit(paymentRequired));
855
+ return {
856
+ signature: funding.signature,
857
+ x402_binding: funding.x402Binding,
858
+ payment_header: header.paymentHeader,
859
+ accepted: header.accepted,
860
+ ...clientUpdateField(resolved)
344
861
  };
345
- const account = accounts.privateKeyToAccount(delegateKey);
346
- const signature = await account.signTypedData(viemTypedData);
347
- const recovered = await viem.recoverTypedDataAddress({ ...viemTypedData, signature });
348
- if (!sameAddress(recovered, delegateAddress)) {
349
- throw new sdk.HavenSigningError(
350
- "Local sweep signature verification failed \u2014 recovered address does not match the delegate key."
351
- );
352
- }
353
- return { signature };
354
- }
862
+ }),
863
+ haven_sign_sweep_delegate: async (input) => runTool(async () => {
864
+ const args = parse("haven_sign_sweep_delegate", input);
865
+ const result = await signer.signSweepAuthorization({
866
+ authorization: args.authorization,
867
+ expectedAuth: args.expected_auth,
868
+ // Cross-check `to` against the agent's account (Haven wallet) from the
869
+ // local credential, when the credential carries one.
870
+ expectedSafe: options.audit?.accountAddress
871
+ });
872
+ await auditSigning(
873
+ "haven_sign_sweep_delegate",
874
+ hashPayloadForAudit(args.authorization)
875
+ );
876
+ return { signature: result.signature };
877
+ })
355
878
  };
356
- }
357
- function assertSweepBinding(authorization, expectedAuth, trustedSigner) {
358
- if (!expectedAuth || typeof expectedAuth !== "object") {
359
- throw new sdk.HavenSigningError("Sweep authorization binding is required before signing.");
360
- }
361
- if (!trustedSigner) {
362
- throw new sdk.HavenSigningError(
363
- "Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations."
364
- );
365
- }
366
- assertSupportedBindingVersion(
367
- expectedAuth.version,
368
- SUPPORTED_SWEEP_BINDING_VERSIONS,
369
- "sweep authorization binding"
370
- );
371
- const message = sdk.buildSweepAuthorizationMessage(authorization);
372
- if (expectedAuth.message !== message) {
373
- throw new sdk.HavenSigningError("Sweep authorization binding does not match the authorization being signed.");
374
- }
375
- if (!sameAddress(expectedAuth.signer, trustedSigner)) {
376
- throw new sdk.HavenSigningError("Sweep authorization binding was not signed by the configured Haven signer.");
377
- }
378
- if (!sdk.verifySignature(viem.hashMessage(message), expectedAuth.signature, trustedSigner)) {
379
- throw new sdk.HavenSigningError("Sweep authorization binding signature could not be verified.");
879
+ async function auditSigning(tool, payloadHash) {
880
+ if (!options.audit) return;
881
+ const { auditPath, ...context } = options.audit;
882
+ try {
883
+ await appendSigningAuditEntry(
884
+ createSigningAuditEntry(tool, payloadHash, {
885
+ ...context,
886
+ delegateAddress: signer.delegateAddress
887
+ }),
888
+ auditPath
889
+ );
890
+ } catch (err) {
891
+ const message = err instanceof Error ? err.message : String(err);
892
+ process.stderr.write(`haven-signer: warning: audit entry for ${tool} could not be written to ${auditPath}: ${message}
893
+ `);
894
+ }
380
895
  }
381
896
  }
382
- function assertX402MatchesExpected(paymentRequired, option, expected) {
383
- assertExpectedShape(expected);
384
- const headerResource = option.resource ?? paymentRequired.resource.url;
385
- if (headerResource !== expected.resourceUrl) {
386
- throw new sdk.HavenSigningError("x402 payment_required resource does not match the funded intent.");
387
- }
388
- if (!sameAddress(option.payTo, expected.merchantTo)) {
389
- throw new sdk.HavenSigningError("x402 merchant recipient does not match the funded intent.");
390
- }
391
- if (sdk.x402AuthorizationAmount(option) !== expected.amount) {
392
- throw new sdk.HavenSigningError("x402 amount does not match the funded intent.");
393
- }
394
- if (!sameAddress(option.asset, expected.asset)) {
395
- throw new sdk.HavenSigningError("x402 asset does not match the funded intent.");
897
+ function parse(name, input) {
898
+ return v3.z.object(toolSchemas[name]).parse(input ?? {});
899
+ }
900
+ function coerceX402Expected(input) {
901
+ if (!input || typeof input !== "object") return input;
902
+ const record = input;
903
+ let value = record.x402_expected;
904
+ if (typeof value === "string") {
905
+ try {
906
+ value = JSON.parse(value);
907
+ } catch {
908
+ return input;
909
+ }
396
910
  }
397
- if (option.network !== expected.network) {
398
- throw new sdk.HavenSigningError("x402 network does not match the funded intent.");
911
+ if (!value || typeof value !== "object") return input;
912
+ const obj = value;
913
+ if (obj.auth === void 0 && obj.expected && typeof obj.expected === "object") {
914
+ return { ...record, x402_expected: obj.expected };
399
915
  }
916
+ if (value !== record.x402_expected) return { ...record, x402_expected: value };
917
+ return input;
400
918
  }
401
- function assertExpectedShape(expected) {
402
- if (!expected || typeof expected !== "object") {
403
- throw new sdk.HavenSigningError("x402 expected funding context is required before signing a merchant header.");
919
+ function coercePaymentRequired(input) {
920
+ if (!input || typeof input !== "object") return input;
921
+ const record = input;
922
+ if (typeof record.payment_required !== "string") return input;
923
+ try {
924
+ return { ...record, payment_required: JSON.parse(record.payment_required) };
925
+ } catch {
926
+ return input;
404
927
  }
405
928
  }
406
- var SUPPORTED_X402_EXPECTED_VERSIONS = [1, 2, 3];
407
- var SUPPORTED_SWEEP_BINDING_VERSIONS = [1];
408
- function assertSupportedBindingVersion(received, supported, context) {
409
- if (supported.includes(received)) return;
410
- const highest = Math.max(...supported);
411
- const outOfDate = received > highest;
412
- const code = context === "x402 expected context" ? sdk.SignerRefusalCode.UnsupportedExpectedContextVersion : sdk.SignerRefusalCode.UnsupportedSweepBindingVersion;
413
- const ceiling = outOfDate ? `This signer is out of date: it supports ${context} versions up to ${highest}, and Haven sent version ${received}. Update @haven_ai/signer \u2014 rerun the Haven connector (\`${sdk.connectorRerunCommand()}\`), which reinstalls the pinned MCP runtime.` : `Unsupported ${context} version ${received}: this signer supports ${supported.join(", ")}.`;
414
- const fallback = outOfDate ? sdk.SIGNER_UPDATE_FALLBACK : `This ${context} version (${received}) is older than what this signer enforces (${supported.join(", ")}) \u2014 updating @haven_ai/signer will not restore it. Nothing was signed or spent; stop and tell the user rather than retrying.`;
415
- throw new sdk.HavenUnsupportedSignerVersionError(
416
- `${ceiling} Nothing was signed. Do not rewrite the version field to a supported value: it is part of the Haven-signed binding message, so changing it invalidates the signature and would misrepresent what Haven declared.`,
417
- code,
418
- supported,
419
- received,
420
- fallback
421
- );
422
- }
423
- function assertExpectedBinding(payloadHash, expected, trustedSigner, mode = "hash") {
424
- assertExpectedShape(expected);
425
- if (!trustedSigner) {
426
- throw new sdk.HavenSigningError(
427
- "x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding hashes."
428
- );
929
+ async function runTool(fn) {
930
+ try {
931
+ return { success: true, data: await fn() };
932
+ } catch (err) {
933
+ return normalizeError(err);
429
934
  }
430
- if (expected.auth) {
431
- assertSupportedBindingVersion(
432
- expected.auth.version,
433
- SUPPORTED_X402_EXPECTED_VERSIONS,
434
- "x402 expected context"
435
- );
935
+ }
936
+ function normalizeError(err) {
937
+ if (err instanceof v3.z.ZodError) {
938
+ return {
939
+ success: false,
940
+ code: "INVALID_INPUT",
941
+ message: err.errors.map((e) => `${e.path.join(".") || "(root)"}: ${e.message}`).join("; "),
942
+ statusCode: 400
943
+ };
436
944
  }
437
- if (expected.payloadHash.toLowerCase() !== payloadHash.toLowerCase()) {
438
- throw new sdk.HavenSigningError("x402 expected context does not match the funding hash being signed.");
945
+ if (err instanceof edge.HavenUnsupportedSignerVersionError) {
946
+ return {
947
+ success: false,
948
+ code: err.code,
949
+ message: err.message,
950
+ supported_versions: [...err.supportedVersions],
951
+ received_version: err.receivedVersion,
952
+ fallback: err.fallback,
953
+ next_action: edge.AgentPaymentNextAction.StopAndTellUser,
954
+ // #3103: no tool can fix a version skew from inside the call.
955
+ ...nextStepWireFields(signerRefusalStep({
956
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
957
+ nextTool: null,
958
+ nextToolOmittedReason: "update @haven_ai/signer by re-running the connector, then repeat the same call"
959
+ }))
960
+ };
439
961
  }
440
- if (mode === "hash" && expected.typedDataHash) {
441
- throw new sdk.HavenSigningError(
442
- "This x402 funding intent commits to EIP-712 typed data, so its bare hash must not be raw-signed \u2014 the account would reject that signature on-chain. Sign sign_data.typed_data instead."
443
- );
962
+ if (err instanceof HavenBareHashRefusedError) {
963
+ return {
964
+ success: false,
965
+ code: err.code,
966
+ message: err.message,
967
+ next_action: err.next_action,
968
+ ...nextStepWireFields(err.step)
969
+ };
444
970
  }
445
- if (mode === "typed-data" && !expected.typedDataHash) {
446
- throw new sdk.HavenSigningError(
447
- "Refusing to sign typed data under an expected context that does not commit to it. Haven must return a v2 x402 expected context (with typedDataHash) for a delegation-rail intent."
448
- );
971
+ if (err instanceof HavenUserOpBindingRefusedError) {
972
+ return {
973
+ success: false,
974
+ code: err.code,
975
+ message: err.message,
976
+ next_action: err.next_action,
977
+ ...nextStepWireFields(err.step)
978
+ };
449
979
  }
450
- const message = sdk.buildX402ExpectedMessage({
451
- paymentId: expected.paymentId,
452
- payloadHash: expected.payloadHash,
453
- resourceUrl: expected.resourceUrl,
454
- merchantTo: expected.merchantTo,
455
- amount: expected.amount,
456
- asset: expected.asset,
457
- network: expected.network,
458
- expiresAt: expected.expiresAt,
459
- typedDataHash: expected.typedDataHash,
460
- payerDelegate: expected.payerDelegate,
461
- payerAgentId: expected.payerAgentId
462
- });
463
- const expectedVersion = expected.payerDelegate ? 3 : expected.typedDataHash ? 2 : 1;
464
- if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {
465
- throw new sdk.HavenSigningError("x402 expected context authentication message is invalid.");
980
+ if (err instanceof HavenTypedDataNotAllowedError) {
981
+ return {
982
+ success: false,
983
+ code: err.code,
984
+ message: err.message,
985
+ next_action: err.next_action,
986
+ ...nextStepWireFields(err.step)
987
+ };
466
988
  }
467
- if (!sameAddress(expected.auth.signer, trustedSigner)) {
468
- throw new sdk.HavenSigningError("x402 expected context was not signed by the configured Haven signer.");
989
+ if (err instanceof HavenSignContextError) {
990
+ return {
991
+ success: false,
992
+ code: err.code,
993
+ message: err.message,
994
+ next_action: err.next_action,
995
+ ...err.fallback !== void 0 ? { fallback: err.fallback } : {},
996
+ ...err.retry_with_new_quote ? { retry_with_new_quote: true } : {},
997
+ ...err.http_status !== void 0 ? { http_status: err.http_status } : {},
998
+ ...err.backend_error_code !== void 0 ? { backend_error_code: err.backend_error_code } : {},
999
+ ...err.client_update ? { client_update: err.client_update } : {},
1000
+ // #3103: the typed step the error decided beside its action.
1001
+ ...err.next_tool ? { next_tool: err.next_tool } : {},
1002
+ ...err.next_tool_server ? { next_tool_server: err.next_tool_server } : {},
1003
+ ...err.next_tool_name ? { next_tool_name: err.next_tool_name } : {},
1004
+ ...err.next_tool_server_role ? { next_tool_server_role: err.next_tool_server_role } : {},
1005
+ ...err.next_arguments ? { next_arguments: err.next_arguments } : {},
1006
+ ...err.next_tool_omitted_reason ? { next_tool_omitted_reason: err.next_tool_omitted_reason } : {}
1007
+ };
469
1008
  }
470
- if (!sdk.verifySignature(viem.hashMessage(message), expected.auth.signature, trustedSigner)) {
471
- throw new sdk.HavenSigningError("x402 expected context signature could not be verified.");
1009
+ if (err instanceof edge.HavenSigningError) {
1010
+ return { success: false, code: err.code, message: err.message };
472
1011
  }
473
- }
474
- function assertPayerMatchesDelegate(expected, delegateAddress, localAgentId) {
475
- if (!expected.payerDelegate) return;
476
- if (sameAddress(expected.payerDelegate, delegateAddress)) return;
477
- const quoteAgent = expected.payerAgentId ?? "unknown";
478
- const localAgent = localAgentId ?? "unknown";
479
- throw new sdk.HavenSigningError(
480
- `This quote belongs to a DIFFERENT agent: the quote was created for agent ${quoteAgent} (delegate ${expected.payerDelegate}), but this signer holds agent ${localAgent} (delegate ${delegateAddress}). A long-lived host is holding stale credentials \u2014 its session authenticates as the old agent while the signer on disk belongs to the new one. Nothing was signed. Restart the host so it re-reads its wiring, then re-quote.`
481
- );
482
- }
483
- function assertX402PaymentWindowOpen(expected) {
484
- if (!expected.expiresAt) return;
485
- const expiresAtMs = Date.parse(expected.expiresAt);
486
- if (Number.isNaN(expiresAtMs)) {
487
- throw new sdk.HavenSigningError("x402 expected context expiresAt is not a valid ISO timestamp.");
1012
+ if (err instanceof edge.HavenApiError) {
1013
+ return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
488
1014
  }
489
- if (expiresAtMs <= Date.now()) {
490
- throw new sdk.HavenError(
491
- "The x402 payment window expired before the merchant header could be signed. Re-quote with haven_pay_mcp_tool using the same idempotency_key before trying again.",
492
- sdk.AgentPaymentFailureCode.PaymentWindowExpired,
493
- 410,
494
- expected.paymentId
495
- );
1015
+ if (err instanceof edge.HavenError) {
1016
+ return {
1017
+ success: false,
1018
+ code: err.code,
1019
+ message: err.message,
1020
+ statusCode: err.statusCode,
1021
+ paymentId: err.paymentId,
1022
+ ...err.code === edge.AgentPaymentFailureCode.PaymentWindowExpired ? {
1023
+ next_action: edge.AgentPaymentNextAction.PaymentWindowExpired,
1024
+ retry_with_new_quote: true,
1025
+ suggested_tool: "haven_pay_mcp_tool",
1026
+ // #3103: same omission as the hosted window-expired helper.
1027
+ ...nextStepWireFields(signerRefusalStep({
1028
+ nextAction: edge.AgentPaymentNextAction.PaymentWindowExpired,
1029
+ nextTool: null,
1030
+ nextToolOmittedReason: "re-run the hosted quote tool you called with the same idempotency_key; which one depends on the flow (suggested_tool names the MCP one)"
1031
+ }))
1032
+ } : {}
1033
+ };
496
1034
  }
497
- }
498
- function sameAddress(a, b) {
499
- return a.toLowerCase() === b.toLowerCase();
500
- }
501
-
502
- // src/capabilities.ts
503
- var SIGNER_CAPABILITY_KEY = "haven/signer-compatibility";
504
- function signerCompatibility() {
505
1035
  return {
506
- x402_expected_context_versions: [...SUPPORTED_X402_EXPECTED_VERSIONS],
507
- sweep_binding_versions: [...SUPPORTED_SWEEP_BINDING_VERSIONS]
1036
+ success: false,
1037
+ code: "UNKNOWN_ERROR",
1038
+ message: err instanceof Error ? err.message : String(err)
508
1039
  };
509
1040
  }
510
- function signerCapabilityAdvertisement() {
511
- return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } };
1041
+
1042
+ // src/consent.ts
1043
+ var toolSummaries = {
1044
+ haven_sign: "signs one Haven-prepared payment (a direct-payment UserOp from your own account whose only call redeems a delegation made to it, or an x402 funding intent against a Haven-signed context)",
1045
+ haven_x402_sign_header: "builds and signs the EIP-3009 merchant payment header for an x402 payment",
1046
+ haven_sign_x402: "the two above in one call: funding payload + merchant header",
1047
+ haven_sign_sweep_delegate: "signs a Haven-prepared gasless sweep of stranded funds back to your own account"
1048
+ };
1049
+ var CONNECTOR_DOCTOR_HINT = [
1050
+ "Wired by the Haven connector (Claude Desktop, Codex, ...)? Diagnose and repair with: npx @haven_ai/connect --doctor",
1051
+ " (the doctor shows this as a failed 'Signer stdio handshake' check; the connector's setup outcome reports it as",
1052
+ " local_signer_ack_required; the repair is the connector's --ack-local-tools)."
1053
+ ].join("\n");
1054
+ var SIGNER_ACK_ENV = "HAVEN_SIGNER_ACK";
1055
+ var SIGNER_CONSENT_SURFACE_VERSION = 2;
1056
+ function computeSignerConsentHash(input) {
1057
+ const identity = [
1058
+ input.delegateAddress.toLowerCase(),
1059
+ (input.accountAddress ?? "").toLowerCase(),
1060
+ input.agentId ?? "",
1061
+ input.chainId ?? "",
1062
+ input.network ?? ""
1063
+ ].join("|");
1064
+ const toolCanonical = [...input.toolNames].sort().join(",");
1065
+ return crypto.createHash("sha256").update(`${identity}
1066
+ ${toolCanonical}
1067
+ surface:v${SIGNER_CONSENT_SURFACE_VERSION}`).digest("hex").slice(0, 16);
512
1068
  }
513
- function signerInstructions() {
514
- const compatibility = signerCompatibility();
515
- return [
516
- "Haven edge signer: sign-only tools bound to the local delegate key. It never emits the",
517
- "key. Its one network capability is an authenticated READ of a signing context from",
518
- "Haven by payment_id \u2014 pass payment_id to haven_sign / haven_sign_x402 (preferred for",
519
- "delegation-rail x402) instead of relaying bulky typed-data payloads yourself.",
520
- "",
521
- "Version compatibility (check this BEFORE signing, not after):",
522
- `- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(", ")}`,
523
- `- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(", ")}`,
1069
+ function renderSignerConsentBlock(input, hash) {
1070
+ const lines = [
524
1071
  "",
525
- "Haven quote and prepare results report the expected-context version they will emit",
526
- "(signer_compatibility.x402_expected_context_version). If that version is not in the list",
527
- "above, this signer is out of date: STOP before signing, and tell the user to update",
528
- `@haven_ai/signer by rerunning \`${sdk.connectorRerunCommand()}\`, which reinstalls the pinned`,
529
- "MCP runtime. Do not edit the version field to a supported value \u2014 it is part of the",
530
- "Haven-signed binding message, so changing it invalidates the signature.",
1072
+ "------------------------------------------------------------",
1073
+ "Haven edge signer - first-launch consent",
1074
+ "------------------------------------------------------------",
531
1075
  "",
532
- "A version-mismatch refusal from haven_sign / haven_sign_x402 / haven_sign_sweep_delegate is",
533
- "machine-readable, not just prose: it carries code, supported_versions, received_version, and",
534
- "fallback fields alongside the message, so you can branch on it directly."
535
- ].join("\n");
536
- }
537
- var HavenSignContextError = class extends sdk.HavenSigningError {
538
- /**
539
- * #3001 / #3010 review: the recovery path, when signing OTHER bytes is
540
- * actually a remedy — a transport failure (timeout, unreachable) or a
541
- * body this signer could not read. `typed_data_b64` is NOT in the default
542
- * quote result since #1272: obtain it by re-running the SAME quote tool
543
- * with the SAME idempotency_key plus `include_signing_payload: true`.
544
- * Absent on a backend REFUSAL: an expired, executed or unsignable intent
545
- * cannot be rescued by re-signing its bytes.
546
- */
547
- fallback;
548
- /**
549
- * #3001: `AgentPaymentNextAction` values the signer already emits — the
550
- * version-mismatch refusal's `stop_and_tell_user` for the classes where
551
- * retrying the same call cannot help, and `payment_window_expired` (with
552
- * `retry_with_new_quote`) for the backend's 410 `expired`, exactly as the
553
- * plain `HavenError` branch already does for that code.
554
- */
555
- next_action;
556
- retry_with_new_quote;
557
- /** Present only for `SIGN_CONTEXT_REFUSED` (the backend's HTTP status). */
558
- http_status;
559
- /** Present only for `SIGN_CONTEXT_REFUSED`: the backend's own `error_code`. */
560
- backend_error_code;
561
- constructor(message, code, refusal) {
562
- super(message);
563
- this.code = code;
564
- this.name = "HavenSignContextError";
565
- if (code === "SIGN_CONTEXT_REFUSED") {
566
- this.http_status = refusal?.httpStatus;
567
- this.backend_error_code = refusal?.errorCode;
568
- if (refusal?.httpStatus === 410 || refusal?.errorCode === "expired") {
569
- this.next_action = sdk.AgentPaymentNextAction.PaymentWindowExpired;
570
- this.retry_with_new_quote = true;
571
- } else {
572
- this.next_action = sdk.AgentPaymentNextAction.StopAndTellUser;
573
- }
574
- } else {
575
- this.fallback = "typed_data_b64";
576
- this.next_action = sdk.AgentPaymentNextAction.StopAndTellUser;
577
- }
578
- }
579
- };
580
- async function loadHavenIdentity(credentialsPath) {
581
- if (!credentialsPath) return null;
582
- try {
583
- const raw = JSON.parse(
584
- await promises.readFile(path.join(path.dirname(credentialsPath), "identity.json"), "utf8")
585
- );
586
- const apiKey = typeof raw.api_key === "string" ? raw.api_key : void 0;
587
- const apiUrl = typeof raw.api_url === "string" ? raw.api_url : void 0;
588
- if (!apiKey || !apiUrl) return null;
589
- return { apiKey, apiUrl: apiUrl.replace(/\/+$/, "") };
590
- } catch {
591
- return null;
1076
+ `Delegate address: ${input.delegateAddress}`
1077
+ ];
1078
+ lines.push(`Haven wallet: ${input.accountAddress ?? "not provided to this signer"}`);
1079
+ if (input.agentId) lines.push(`Agent ID: ${input.agentId}`);
1080
+ if (typeof input.chainId === "number") lines.push(`Chain ID: ${input.chainId}`);
1081
+ if (input.network) lines.push(`Network: ${input.network}`);
1082
+ lines.push("");
1083
+ lines.push("This local signer holds the delegate key on this machine and signs");
1084
+ lines.push("payment payloads or x402 merchant headers for the delegate address above.");
1085
+ lines.push("Its one network use is a read-only fetch of a pending payment's signing");
1086
+ lines.push("payload from Haven, authenticated with the agent credential stored next to");
1087
+ lines.push("this signer's key file - it never sends the key, a signature, or anything");
1088
+ lines.push("else outbound, and it cannot show a live allowance summary.");
1089
+ lines.push("The agent's signed budget delegation is the real spend gate, and the wallet");
1090
+ lines.push("owner can pause or revoke agent authority outside this signer.");
1091
+ lines.push("");
1092
+ lines.push("Tools this signer will expose to your agent runtime (one line each; the");
1093
+ lines.push("full agent-facing descriptions are what the runtime sees):");
1094
+ for (const name of input.toolNames) {
1095
+ lines.push(` - ${name}: ${toolSummaries[name]}`);
592
1096
  }
1097
+ lines.push("");
1098
+ lines.push("A local audit entry is appended for every signing operation. Audit entries");
1099
+ lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
1100
+ lines.push("signature, or x402 payment header.");
1101
+ lines.push("");
1102
+ lines.push(`Consent hash: ${hash}`);
1103
+ lines.push("");
1104
+ lines.push("To acknowledge, EITHER:");
1105
+ lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`);
1106
+ lines.push(" - re-run with --ack to write the acknowledgement next to your");
1107
+ lines.push(" credential file (sidecar <credentials>.signer-ack.json).");
1108
+ lines.push("");
1109
+ lines.push(CONNECTOR_DOCTOR_HINT);
1110
+ lines.push("");
1111
+ lines.push("------------------------------------------------------------");
1112
+ lines.push("");
1113
+ return lines.join("\n");
593
1114
  }
594
- var SIGN_CONTEXT_TIMEOUT_MS = 15e3;
595
- async function fetchX402SignContext(identity, paymentId, fetchImpl = fetch, timeoutMs = SIGN_CONTEXT_TIMEOUT_MS) {
596
- let response;
597
- try {
598
- response = await fetchImpl(
599
- `${identity.apiUrl}/x402/${encodeURIComponent(paymentId)}/sign-context`,
600
- {
601
- headers: { Authorization: `Bearer ${identity.apiKey}` },
602
- signal: AbortSignal.timeout(timeoutMs)
603
- }
604
- );
605
- } catch (err) {
606
- const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
607
- throw new HavenSignContextError(
608
- timedOut ? `Haven did not answer the signing-context fetch for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the quote result instead.` : `Could not reach Haven to fetch the signing context for ${paymentId}: ${err instanceof Error ? err.message : String(err)}. Retry, or pass typed_data_b64 from the quote result instead.`,
609
- timedOut ? "SIGN_CONTEXT_TIMEOUT" : "SIGN_CONTEXT_UNREACHABLE"
610
- );
611
- }
612
- let body;
613
- try {
614
- body = await response.json();
615
- } catch (err) {
616
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
617
- throw new HavenSignContextError(
618
- `Haven did not finish sending the signing context for ${paymentId} within ${timeoutMs} ms. Retry, or pass typed_data_b64 from the quote result instead.`,
619
- "SIGN_CONTEXT_TIMEOUT"
620
- );
621
- }
622
- body = {};
623
- }
624
- if (!response.ok) {
625
- const detail = typeof body.error === "string" ? body.error : `HTTP ${response.status}`;
626
- throw new HavenSignContextError(
627
- `Haven refused the signing-context fetch for ${paymentId}: ${detail}` + (response.status === 404 ? " \u2014 check the payment_id came from this agent\u2019s own quote." : response.status === 410 ? " Re-run the quote with the same idempotency key, then sign the fresh payment_id." : ""),
628
- "SIGN_CONTEXT_REFUSED",
629
- { httpStatus: response.status, errorCode: typeof body.error_code === "string" ? body.error_code : void 0 }
1115
+ async function ensureSignerConsent(input, options = {}) {
1116
+ const env = options.env ?? process.env;
1117
+ const out = options.out ?? process.stderr;
1118
+ const hash = computeSignerConsentHash(input);
1119
+ const envAck = env[SIGNER_ACK_ENV];
1120
+ if (typeof envAck === "string" && envAck.length > 0) {
1121
+ if (envAck === hash) return { ok: true, hash, reason: "env_var_match" };
1122
+ out.write(renderSignerConsentBlock(input, hash));
1123
+ out.write(
1124
+ `${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.
1125
+ Expected: ${hash}
1126
+ Got: ${envAck}
1127
+ Re-acknowledge with the new hash above, or run with --ack.
1128
+
1129
+ `
630
1130
  );
1131
+ return { ok: false, hash, reason: "env_var_mismatch" };
631
1132
  }
632
- const signData = body.sign_data;
633
- const x402Expected = body.x402_expected;
634
- if (!signData || typeof signData.hash !== "string" || !signData.typed_data || typeof signData.typed_data !== "object" || !x402Expected) {
635
- throw new HavenSignContextError(
636
- "The Haven sign-context response is missing sign_data.typed_data or x402_expected \u2014 the backend may predate #1263. Pass typed_data_b64 from the quote result instead.",
637
- "SIGN_CONTEXT_MALFORMED"
638
- );
1133
+ const ackPath = sidecarPath(options.credentialsPath);
1134
+ if (ackPath) {
1135
+ const stored = await readAckFile(ackPath);
1136
+ if (stored?.ack === hash) return { ok: true, hash, reason: "ack_file_match" };
639
1137
  }
640
- const paymentRequired = body.payment_required;
641
- return {
642
- paymentId: String(body.payment_id ?? paymentId),
643
- payloadHash: signData.hash,
644
- typedData: signData.typed_data,
645
- x402Expected,
646
- paymentRequired: paymentRequired && typeof paymentRequired === "object" && !Array.isArray(paymentRequired) ? paymentRequired : null
647
- };
648
- }
1138
+ if (options.writeAck && ackPath) {
1139
+ out.write(renderSignerConsentBlock(input, hash));
1140
+ await writeAckFile(ackPath, hash);
1141
+ out.write(`Wrote acknowledgement to ${ackPath}
649
1142
 
650
- // src/tools.ts
651
- var sweepAuthorizationSchema = v3.z.object({
652
- from: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "from must be a 0x address"),
653
- to: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "to must be a 0x address"),
654
- value: v3.z.string().regex(/^[0-9]+$/, "value must be a decimal atomic amount"),
655
- validAfter: v3.z.string().regex(/^[0-9]+$/, "validAfter must be a decimal unix time"),
656
- validBefore: v3.z.string().regex(/^[0-9]+$/, "validBefore must be a decimal unix time"),
657
- nonce: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "nonce must be a 0x-prefixed 32-byte hex string"),
658
- token: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "token must be a 0x address"),
659
- chainId: v3.z.number().int().positive()
660
- });
661
- var bindingVersionSchema = v3.z.number().int().positive();
662
- var sweepExpectedAuthSchema = v3.z.object({
663
- version: bindingVersionSchema,
664
- message: v3.z.string().min(1),
665
- signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
666
- signer: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "signer must be a 0x address")
667
- });
668
- var x402ExpectedShape = {
669
- payment_id: v3.z.string().min(1),
670
- payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
671
- resource_url: v3.z.string().url(),
672
- merchant_to: v3.z.string().min(1),
673
- amount: v3.z.string().min(1),
674
- asset: v3.z.string().min(1),
675
- network: v3.z.string().min(1),
676
- // Required: expires_at is folded into the Haven-signed binding message, so the
677
- // signer must receive the exact same value to reconstruct a matching message.
678
- // Omitting it used to fail downstream with a cryptic "authentication message is
679
- // invalid" — making it required surfaces a clear INVALID_INPUT at the boundary.
680
- expires_at: v3.z.string().min(1),
681
- // #1138: present on a delegation-rail (v2) context. It commits to the EIP-712
682
- // typed data the account validates; the signer refuses to raw-sign the bare
683
- // hash when it is present, and refuses to sign typed data when it is absent.
684
- typed_data_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "typed_data_hash must be a 0x-prefixed hex string").optional(),
685
- // #1690: present on a v3 context. The delegate this quote was created FOR —
686
- // the signer refuses to sign when it is not its own. Inside the Haven-signed
687
- // message, so stripping it here would only break the binding signature.
688
- payer_delegate: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "payer_delegate must be a 0x-prefixed address").optional(),
689
- payer_agent_id: v3.z.string().min(1).optional(),
690
- auth: v3.z.object({
691
- // Open at the boundary, enforced in the signer — see bindingVersionSchema.
692
- version: bindingVersionSchema,
693
- message: v3.z.string().min(1),
694
- signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
695
- signer: v3.z.string().min(1)
696
- })
697
- };
698
- var x402ExpectedSchema = v3.z.object(x402ExpectedShape);
699
- var toolSchemas = {
700
- haven_sign_sweep_delegate: {
701
- // The authorization fields prepared by Haven's POST /sweep/prepare. Passed
702
- // through verbatim from the hosted haven_sweep_delegate tool — the signer
703
- // re-derives the binding message from these exact values.
704
- authorization: sweepAuthorizationSchema,
705
- // Haven's signature over the authorization context (the binding).
706
- expected_auth: sweepExpectedAuthSchema
707
- },
708
- haven_sign: {
709
- // #1263: THE preferred x402 input — the signer fetches the exact signing
710
- // payload + expected context from Haven itself (authenticated with the
711
- // locally-stored agent credential), so no bulky bytes ever cross the
712
- // model. Pass payment_id ALONE for a delegation-rail x402 funding intent.
713
- payment_id: v3.z.string().min(1).optional(),
714
- // The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).
715
- // Optional when payment_id is supplied (the fetch carries it).
716
- payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string").optional(),
717
- // Pass x402.expected from hosted haven_pay_x402_quote when this hash funds
718
- // a standard x402 merchant retry. The signer records it locally and returns
719
- // an opaque x402_binding for the later header-signing step.
720
- x402_expected: x402ExpectedSchema.optional(),
721
- // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
722
- // (not z.unknown()) so MCP clients embed it as JSON rather than a string.
723
- typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
724
- // #1255: the same payload as ONE opaque base64 string, exactly as returned
725
- // by the hosted tools. Preferred over typed_data when both are present —
726
- // an agent re-emitting multi-KB nested JSON between tool calls is the
727
- // failure mode this field removes (a truncated/reshaped payload fails the
728
- // digest check and the payment refuses, correctly but pointlessly).
729
- // Bounded: a realistic redemption payload is ~10KB encoded; 256KB is
730
- // generous headroom while keeping the offline signer from materializing
731
- // arbitrarily large caller input.
732
- typed_data_b64: v3.z.string().min(1).max(262144).optional()
733
- },
734
- haven_x402_sign_header: {
735
- // The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object
736
- // (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients
737
- // embed it as JSON rather than serialising the object to a string.
738
- payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
739
- // Opaque binding returned by haven_sign when x402_expected was supplied.
740
- x402_binding: v3.z.string().min(1)
741
- },
742
- haven_sign_x402: {
743
- // #1263: preferred — pass payment_id (plus payment_required) and the
744
- // signer fetches the exact signing payload + expected context itself.
745
- payment_id: v3.z.string().min(1).optional(),
746
- // One-shot x402 signing: funding hash + merchant header in one local call.
747
- // Both optional when payment_id is supplied (the fetch carries them).
748
- payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string").optional(),
749
- x402_expected: x402ExpectedSchema.optional(),
750
- // #1355: optional when payment_id is supplied — the signer's context fetch
751
- // carries the stored 402 PaymentRequired, so `{ payment_id }` alone is the
752
- // preferred call. Still required (via the runtime check in the handler)
753
- // for the quote-based fallback path without a payment_id.
754
- payment_required: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
755
- // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
756
- // (not z.unknown()) so MCP clients embed it as JSON rather than a string.
757
- typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
758
- // #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.
759
- typed_data_b64: v3.z.string().min(1).max(262144).optional()
760
- }
761
- };
762
- var SIGN_DESCRIPTION = [
763
- "Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves",
764
- "this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.",
765
- "For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally",
766
- "and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that",
767
- "window closes. DELEGATION-RAIL x402 accounts (#1263): pass payment_id ALONE (preferred) \u2014 this",
768
- "signer fetches the exact signing payload and expected context from Haven itself, so nothing",
769
- "bulky ever crosses your context. Fallback: pass typed_data_b64 through UNCHANGED (never re-type",
770
- "the nested typed_data JSON); the account validates that EIP-712 payload, not payload_hash.",
771
- "Next: call mcp__haven__haven_submit with signature, then pass x402_binding",
772
- "to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and",
773
- "relay the returned signature via mcp__haven__haven_submit."
774
- ].join(" ");
775
- var X402_SIGN_HEADER_DESCRIPTION = [
776
- "Build and sign the EIP-3009 merchant payment header for the merchant leg of an x402 payment.",
777
- "The delegate key stays local \u2014 only the signed header crosses any boundary.",
778
- "Pass the payment_required from the original merchant 402 response and the x402_binding",
779
- "returned by haven_sign. It must be haven_sign \u2014 NOT haven_sign_x402, which is a",
780
- "one-shot that builds the header itself and spends its own binding doing so. If you called",
781
- "haven_sign_x402, its result already carries payment_header; retry the merchant with that and",
782
- "do not call this tool. The signer validates the merchant, amount, resource, asset, and",
783
- "network against the recorded funding context before signing, checks expires_at when present,",
784
- "and rejects mismatches or expired payment windows.",
785
- "Returns { payment_header, accepted }. On your retry set BOTH PAYMENT-SIGNATURE (x402 v2) and",
786
- "X-PAYMENT (v1) to <payment_header>; a strict v2 merchant reads only the first.",
787
- "Only call after haven_submit has confirmed the funding step (nextAction=none or",
788
- "the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
789
- ].join(" ");
790
- var SIGN_X402_DESCRIPTION = [
791
- "One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009",
792
- "merchant payment header in a single local call (equivalent to haven_sign followed by",
793
- "haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool",
794
- "result pass JUST payment_id \u2014 PREFERRED (#1263, #1355): this signer fetches the exact signing",
795
- "payload, expected context, and merchant payment_required from Haven itself, so nothing bulky",
796
- "crosses your context. If the signer reports the context carried no payment_required (older",
797
- "backend), re-call with payment_id plus payment_required verbatim from the pay result.",
798
- "Fallback for older backends: pass payload_hash, x402_expected (the nested x402.expected object \u2014",
799
- "passing the whole x402 object is also accepted and unwrapped for you), and typed_data_b64",
800
- "through UNCHANGED; the signer",
801
- "signs the typed data instead of payload_hash and refuses the bare hash when the context commits to typed data.",
802
- "Returns",
803
- "{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to",
804
- "mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before",
805
- "funding confirms), so its short validity window starts here \u2014 call mcp__haven__haven_settle_mcp_tool promptly,",
806
- "and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.",
807
- "The returned x402_binding is ALREADY SPENT \u2014 this tool consumed it building payment_header \u2014",
808
- "so never pass it to mcp__haven-signer__haven_x402_sign_header; that tool is the follow-up to",
809
- "haven_sign, not to this one. payment_header IS the header to use.",
810
- "Next: for a paid MCP tool, call mcp__haven__haven_settle_mcp_tool. For a direct plain-HTTP x402",
811
- "merchant (the haven_pay_x402_quote path), relay signature via mcp__haven__haven_submit and then",
812
- "retry the original merchant URL YOURSELF, setting BOTH PAYMENT-SIGNATURE (x402 v2) and",
813
- "X-PAYMENT (v1) to payment_header \u2014 Haven never contacts that merchant."
814
- ].join(" ");
815
- var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
816
- "Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
817
- "wallet back to your Haven wallet. The delegate key never leaves this process and this tool",
818
- "never broadcasts \u2014 it returns only an EIP-3009 signature that Haven's relayer submits and",
819
- "pays gas for. Pass the authorization and expected_auth returned by the hosted",
820
- "haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it",
821
- "pays out to your own Safe before signing, then returns { signature } to hand back to",
822
- "mcp__haven__haven_sweep_delegate to complete recovery."
823
- ].join(" ");
824
- var toolDescriptions = {
825
- haven_sign: SIGN_DESCRIPTION,
826
- haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
827
- haven_sign_x402: SIGN_X402_DESCRIPTION,
828
- haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
829
- };
830
- async function signFundingLeg(signer, expected, payloadHash, typedData) {
831
- if (!expected.typedDataHash) {
832
- return signer.signX402FundingHash(payloadHash, expected);
1143
+ `);
1144
+ return { ok: true, hash, reason: "wrote_ack_file" };
833
1145
  }
834
- if (!typedData) {
835
- throw new sdk.HavenSigningError(
836
- "This x402 funding intent is on the delegation rail: it commits to EIP-712 typed data, which was not supplied. Pass typed_data_b64 from haven_pay_mcp_tool / haven_pay_x402_quote through unchanged (or typed_data verbatim) \u2014 the bare payload_hash is not what the account validates."
837
- );
1146
+ out.write(renderSignerConsentBlock(input, hash));
1147
+ return { ok: false, hash, reason: "no_acknowledgement" };
1148
+ }
1149
+ function registeredSignerToolNames() {
1150
+ return Object.keys(toolSchemas);
1151
+ }
1152
+ function sidecarPath(credentialsPath) {
1153
+ if (!credentialsPath) return null;
1154
+ return path.resolve(`${credentialsPath}.signer-ack.json`);
1155
+ }
1156
+ async function readAckFile(path) {
1157
+ try {
1158
+ const raw = await promises.readFile(path, "utf8");
1159
+ const parsed = JSON.parse(raw);
1160
+ return { ack: typeof parsed.ack === "string" ? parsed.ack : void 0 };
1161
+ } catch {
1162
+ return null;
838
1163
  }
839
- return signer.signX402FundingTypedData(typedData, expected);
840
1164
  }
841
- function toExpectedX402(raw) {
842
- return {
843
- paymentId: raw.payment_id,
844
- payloadHash: raw.payload_hash,
845
- typedDataHash: raw.typed_data_hash,
846
- payerDelegate: raw.payer_delegate,
847
- payerAgentId: raw.payer_agent_id,
848
- resourceUrl: raw.resource_url,
849
- merchantTo: raw.merchant_to,
850
- amount: raw.amount,
851
- asset: raw.asset,
852
- network: raw.network,
853
- expiresAt: raw.expires_at,
854
- auth: raw.auth
855
- };
1165
+ async function writeAckFile(path$1, hash) {
1166
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
1167
+ await promises.writeFile(
1168
+ path$1,
1169
+ JSON.stringify({ ack: hash, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
1170
+ "utf8"
1171
+ );
856
1172
  }
857
- function parseFetchedExpected(fetched) {
858
- const parsed = v3.z.object(x402ExpectedShape).safeParse(fetched.x402Expected);
859
- if (!parsed.success) {
860
- throw new sdk.HavenSigningError(
861
- `The Haven sign-context response carried a malformed x402_expected \u2014 the backend may predate #1263. Pass payload_hash + x402_expected from the quote result instead. Underlying: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`
862
- );
1173
+
1174
+ // src/cli-args.ts
1175
+ var CONNECTOR_DOCTOR_COMMAND = "npx @haven_ai/connect --doctor";
1176
+ function parseSignerArgs(argv) {
1177
+ const options = {};
1178
+ for (let i = 0; i < argv.length; i += 1) {
1179
+ const arg = argv[i];
1180
+ if (arg === "--credentials" || arg === "--credentials-path") {
1181
+ options.credentialsPath = argv[i + 1];
1182
+ i += 1;
1183
+ } else if (arg === "--ack") {
1184
+ options.writeAck = true;
1185
+ } else if (arg === "--help" || arg === "-h") {
1186
+ return { kind: "help", text: helpText() };
1187
+ } else {
1188
+ return {
1189
+ kind: "unknown-option",
1190
+ option: arg,
1191
+ text: `haven-signer: unknown option ${arg}. Run with --help for the options this signer takes` + (arg === "--ack-local-tools" ? ` \u2014 --ack-local-tools belongs to the connector (${CONNECTOR_DOCTOR_COMMAND}), not the signer.` : ".")
1192
+ };
1193
+ }
863
1194
  }
864
- return parsed.data;
1195
+ return { kind: "run", options };
1196
+ }
1197
+ function helpText() {
1198
+ const tools = registeredSignerToolNames();
1199
+ return [
1200
+ "Haven edge signer (local, holds the delegate key)",
1201
+ "",
1202
+ "Runs a local stdio MCP server exposing sign-only tools:",
1203
+ ...tools.map((name) => ` - ${name}`),
1204
+ "Pair it with the hosted, keyless Haven MCP server: the hosted server",
1205
+ "constructs and relays, this one signs.",
1206
+ "",
1207
+ "Usage:",
1208
+ " npx @haven_ai/signer --credentials /path/to/agent.json",
1209
+ "",
1210
+ "Options:",
1211
+ " --credentials <path> Haven credential JSON (delegate_key is read from it).",
1212
+ " Alias: --credentials-path. Also supported: HAVEN_CREDENTIALS,",
1213
+ " or HAVEN_DELEGATE_KEY.",
1214
+ " --ack Acknowledge the first-launch consent block and write",
1215
+ " a signer sidecar acknowledgement next to the credential.",
1216
+ " --help, -h This text. Any other option is refused (exit 2).",
1217
+ "",
1218
+ "Consent:",
1219
+ " On first launch the signer prints the sign-only tool list and delegate",
1220
+ " address, then refuses to start unless acknowledged. Its only Haven API call",
1221
+ " is a read-only fetch of the signing payload for one pending payment, so it",
1222
+ " cannot show a live allowance summary.",
1223
+ " Acknowledge with EITHER --ack OR HAVEN_SIGNER_ACK=<hash> in your environment.",
1224
+ "",
1225
+ "Connector-wired (the usual case)?",
1226
+ ` Diagnose and repair with: ${CONNECTOR_DOCTOR_COMMAND}`,
1227
+ " (an unacknowledged signer shows there as a failed 'Signer stdio handshake'",
1228
+ " check, and in the connector's setup outcome as local_signer_ack_required;",
1229
+ " the repair is the connector's --ack-local-tools, not a signer flag).",
1230
+ ""
1231
+ ].join("\n");
865
1232
  }
866
- function resolveTypedData(args) {
867
- if (!args.typed_data_b64) return args.typed_data;
1233
+ function createEdgeSigner(delegateKey, options = {}) {
1234
+ let delegateAddress;
868
1235
  try {
869
- const decoded = JSON.parse(
870
- Buffer.from(args.typed_data_b64, "base64").toString("utf8")
871
- );
872
- if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) {
873
- throw new Error("decoded value is not an object");
874
- }
875
- return decoded;
1236
+ delegateAddress = edge.addressFromKey(delegateKey);
876
1237
  } catch (err) {
877
- throw new sdk.HavenSigningError(
878
- `typed_data_b64 did not decode to a JSON object. Pass the exact string returned by the hosted Haven tool, unchanged \u2014 do not re-encode, trim, or reformat it. Underlying error: ${err instanceof Error ? err.message : String(err)}`
1238
+ throw new edge.HavenSigningError(
1239
+ `Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`
879
1240
  );
880
1241
  }
881
- }
882
- function createToolHandlers(signer, options = {}) {
883
- async function resolveSignContext(args) {
884
- if (!args.payment_id) return null;
885
- const identity = await options.signContext?.loadIdentity() ?? null;
886
- if (!identity) {
887
- throw new sdk.HavenSigningError(
888
- `payment_id signing needs the agent identity (identity.json next to the signer credentials), which this signer could not load. Re-run \`${sdk.connectorRerunCommand()}\` to restore it, or pass typed_data_b64 from the quote result instead.`
889
- );
890
- }
891
- const ctx = await fetchX402SignContext(
892
- identity,
893
- args.payment_id,
894
- options.signContext?.fetchImpl
895
- );
896
- if (args.payload_hash && args.payload_hash.toLowerCase() !== ctx.payloadHash.toLowerCase()) {
897
- throw new sdk.HavenSigningError(
898
- `The supplied payload_hash does not match the signing context Haven serves for payment ${args.payment_id}. Pass payment_id alone, or check which quote the hash came from.`
899
- );
1242
+ const x402Bindings = /* @__PURE__ */ new Map();
1243
+ const retiredX402Bindings = /* @__PURE__ */ new Map();
1244
+ const RETIRED_BINDING_MEMORY = 64;
1245
+ function retireX402Binding(id, reason) {
1246
+ retiredX402Bindings.set(id, reason);
1247
+ if (retiredX402Bindings.size > RETIRED_BINDING_MEMORY) {
1248
+ const oldest = retiredX402Bindings.keys().next();
1249
+ if (!oldest.done) retiredX402Bindings.delete(oldest.value);
900
1250
  }
901
- return ctx;
902
1251
  }
903
1252
  return {
904
- haven_sign: async (input) => runTool(async () => {
905
- const args = parse("haven_sign", coerceX402Expected(input));
906
- const fetched = await resolveSignContext(args);
907
- const typedData = fetched?.typedData ?? resolveTypedData(args);
908
- const payloadHash = fetched?.payloadHash ?? args.payload_hash;
909
- if (!payloadHash) {
910
- throw new sdk.HavenSigningError(
911
- "Pass payment_id (preferred for delegation-rail x402) or payload_hash."
1253
+ delegateAddress,
1254
+ async signDelegationTypedData(typedData) {
1255
+ const account = accounts.privateKeyToAccount(delegateKey);
1256
+ return account.signTypedData(typedData);
1257
+ },
1258
+ async signX402FundingTypedData(typedData, expected) {
1259
+ if (expected?.auth) {
1260
+ assertSupportedBindingVersion(
1261
+ expected.auth.version,
1262
+ SUPPORTED_X402_EXPECTED_VERSIONS,
1263
+ "x402 expected context"
912
1264
  );
913
1265
  }
914
- const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected;
915
- const x402Expected = expectedRaw ? toExpectedX402(expectedRaw) : null;
916
- const result = x402Expected ? await signFundingLeg(signer, x402Expected, payloadHash, typedData) : null;
917
- if (!result) {
918
- if (typedData) {
919
- if (isSettlementChildTypedData(typedData)) {
920
- throw new sdk.HavenSigningError(
921
- "Refusing to sign a delegation payload with no expected context. This typed data is a DELEGATION \u2014 signing it grants a third party authority to move funds \u2014 so it is only ever signed against a Haven-signed context that the caveats are verified against. Call this tool with { payment_id } instead (the signer then fetches and verifies the context itself), or use haven_sign_x402."
922
- );
923
- }
924
- const signature2 = await signer.signDelegationTypedData(typedData);
925
- await auditSigning("haven_sign", payloadHash);
926
- return { signature: signature2 };
1266
+ if (!typedData) {
1267
+ throw new edge.HavenSigningError(
1268
+ "This x402 funding intent is on the delegation rail: it commits to EIP-712 typed data, which was not supplied. Pass typed_data_b64 from haven_pay_mcp_tool / haven_pay_x402_quote through unchanged (or typed_data verbatim) \u2014 a bare payload_hash is not what the account validates."
1269
+ );
1270
+ }
1271
+ const digest = viem.hashTypedData(typedData);
1272
+ assertExpectedBinding(digest, expected, options.x402BindingSigner);
1273
+ assertPayerMatchesDelegate(expected, delegateAddress, options.agentId);
1274
+ if (edge.isSettlementChildTypedData(typedData)) {
1275
+ const settlementChainId = edge.chainIdForNetwork(expected.network);
1276
+ if (settlementChainId === void 0) {
1277
+ throw new edge.HavenSigningError(
1278
+ `Refusing to sign the x402 settlement child: this signer cannot map the network '${expected.network}' to a chain id, so it cannot check which chain the child is scoped to. Update @haven_ai/signer.`
1279
+ );
927
1280
  }
928
- const signature = signer.signPaymentHash(payloadHash);
929
- await auditSigning("haven_sign", payloadHash);
930
- return { signature };
1281
+ edge.assertOwnSettlementChild(typedData, {
1282
+ merchantTo: expected.merchantTo,
1283
+ amount: expected.amount,
1284
+ asset: expected.asset,
1285
+ // From the SIGNED network, not the payload's own claim. Passing
1286
+ // Number(typedData.domain.chainId) here made the check compare a
1287
+ // value to itself — vacuous, and precisely the "declared one thing,
1288
+ // signed another" class this file exists to catch (#1455 review).
1289
+ chainId: settlementChainId,
1290
+ expiresAt: expected.expiresAt
1291
+ }, delegateAddress);
1292
+ } else if (edge.isPackedUserOperationTypedData(typedData)) {
1293
+ edge.assertUserOpTypedDataBinding(typedData, expected.payloadHash);
1294
+ edge.assertBoundDirectPaymentUserOp(typedData, delegateAddress);
1295
+ edge.assertFundingLegPaysDelegate(typedData, {
1296
+ delegateAddress,
1297
+ asset: expected.asset,
1298
+ amount: expected.amount
1299
+ });
1300
+ } else {
1301
+ throw new edge.HavenTypedDataRefusedError(
1302
+ `This signer's x402 arm signs only a funding-leg PackedUserOperation or an erc7710 settlement Delegation; this typed data is '${String(
1303
+ typedData.primaryType
1304
+ )}'. Refusing, even though its digest is bound by the expected context.`
1305
+ );
931
1306
  }
932
- await auditSigning("haven_sign", payloadHash);
933
- return { signature: result.signature, x402_binding: result.x402Binding };
934
- }),
935
- haven_x402_sign_header: async (input) => runTool(async () => {
936
- const args = parse("haven_x402_sign_header", coercePaymentRequired(input));
937
- const result = await signer.buildX402PaymentHeader(
938
- args.payment_required,
939
- args.x402_binding
940
- );
941
- await auditSigning(
942
- "haven_x402_sign_header",
943
- hashPayloadForAudit(args.payment_required)
1307
+ const account = accounts.privateKeyToAccount(delegateKey);
1308
+ const signature = await account.signTypedData(
1309
+ typedData
944
1310
  );
945
- return { payment_header: result.paymentHeader, accepted: result.accepted };
946
- }),
947
- haven_sign_x402: async (input) => runTool(async () => {
948
- const args = parse("haven_sign_x402", coerceX402Expected(coercePaymentRequired(input)));
949
- const fetched = await resolveSignContext(args);
950
- const payloadHash = fetched?.payloadHash ?? args.payload_hash;
951
- const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected;
952
- if (!payloadHash || !expectedRaw) {
953
- throw new sdk.HavenSigningError(
954
- "Pass payment_id (preferred \u2014 the signer fetches the signing context itself) or payload_hash + x402_expected from the quote result."
1311
+ const x402Binding = crypto.randomUUID();
1312
+ x402Bindings.set(x402Binding, { ...expected });
1313
+ return { signature, x402Binding };
1314
+ },
1315
+ async buildX402PaymentHeader(paymentRequired, x402Binding) {
1316
+ const expected = x402Bindings.get(x402Binding);
1317
+ if (!expected) {
1318
+ const retired = retiredX402Bindings.get(x402Binding);
1319
+ if (retired === "header_built") {
1320
+ throw new edge.HavenSigningError(
1321
+ "This x402 binding was already used to build a merchant header. Bindings are single-use. If you called haven_sign_x402, it already returned the payment_header \u2014 retry the merchant with THAT header instead of building another; haven_x402_sign_header is the follow-up to haven_sign, not to haven_sign_x402. If you no longer have the header, re-run the quote tool with the same idempotency_key."
1322
+ );
1323
+ }
1324
+ if (retired === "window_expired") {
1325
+ throw new edge.HavenSigningError(
1326
+ "This x402 binding was retired because its payment window closed before a merchant header could be built \u2014 no header exists to retry with. Re-run the quote tool with the same idempotency_key to get a fresh window, then sign again."
1327
+ );
1328
+ }
1329
+ throw new edge.HavenSigningError(
1330
+ "x402 funding binding is required before signing a merchant header. Sign the hosted funding payload with x402_expected first (haven_sign returns a binding this tool can use). A binding is also lost when the signer process restarts, since bindings live in memory only \u2014 re-sign to mint a fresh one."
955
1331
  );
956
1332
  }
957
- const funding = await signFundingLeg(
958
- signer,
959
- toExpectedX402(expectedRaw),
960
- payloadHash,
961
- fetched?.typedData ?? resolveTypedData(args)
962
- );
963
- const paymentRequired = fetched?.paymentRequired ?? args.payment_required;
964
- if (!paymentRequired) {
965
- throw new sdk.HavenSigningError(
966
- fetched ? "The Haven sign-context for this payment_id carried no payment_required (backend predates #1355). Pass payment_required from the pay result explicitly, verbatim." : "payment_required is required on the quote-based path (no payment_id to fetch it by). Pass it verbatim from the quote result."
1333
+ const assertWindowOpenOrRetire = () => {
1334
+ try {
1335
+ assertX402PaymentWindowOpen(expected);
1336
+ } catch (err) {
1337
+ x402Bindings.delete(x402Binding);
1338
+ retireX402Binding(x402Binding, "window_expired");
1339
+ throw err;
1340
+ }
1341
+ };
1342
+ assertWindowOpenOrRetire();
1343
+ const option = edge.selectStandardPaymentOption(paymentRequired.accepts);
1344
+ if (!option) {
1345
+ throw new edge.HavenApiError(
1346
+ "No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
1347
+ 400
967
1348
  );
968
1349
  }
969
- const header = await signer.buildX402PaymentHeader(
970
- paymentRequired,
971
- funding.x402Binding
1350
+ assertX402MatchesExpected(paymentRequired, option, expected);
1351
+ const account = accounts.privateKeyToAccount(delegateKey);
1352
+ const requirements = edge.toStandardPaymentRequirements(paymentRequired, option);
1353
+ const { exact } = await loadX402Schemes();
1354
+ assertWindowOpenOrRetire();
1355
+ const header = await exact.evm.createPaymentHeader(
1356
+ account,
1357
+ paymentRequired.x402Version,
1358
+ requirements
972
1359
  );
973
- await auditSigning("haven_sign_x402", payloadHash);
974
- await auditSigning("haven_sign_x402", hashPayloadForAudit(paymentRequired));
975
- return {
976
- signature: funding.signature,
977
- x402_binding: funding.x402Binding,
978
- payment_header: header.paymentHeader,
979
- accepted: header.accepted
1360
+ if (paymentRequired.x402Version < 2) {
1361
+ x402Bindings.delete(x402Binding);
1362
+ retireX402Binding(x402Binding, "header_built");
1363
+ return { paymentHeader: header, accepted: option };
1364
+ }
1365
+ try {
1366
+ const payment = edge.decodeBase64Json(header);
1367
+ const wrapped = edge.encodeBase64Json(
1368
+ edge.x402V2PaymentEnvelope(paymentRequired, option, payment.payload)
1369
+ );
1370
+ return { paymentHeader: wrapped, accepted: option };
1371
+ } finally {
1372
+ x402Bindings.delete(x402Binding);
1373
+ retireX402Binding(x402Binding, "header_built");
1374
+ }
1375
+ },
1376
+ async signSweepAuthorization({
1377
+ authorization,
1378
+ expectedAuth,
1379
+ expectedSafe
1380
+ }) {
1381
+ assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner);
1382
+ if (!sameAddress(authorization.from, delegateAddress)) {
1383
+ throw new edge.HavenSigningError(
1384
+ "Sweep authorization `from` does not match this delegate address."
1385
+ );
1386
+ }
1387
+ if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {
1388
+ throw new edge.HavenSigningError(
1389
+ "Sweep authorization `to` does not match the agent's account (Haven wallet) in the local credential."
1390
+ );
1391
+ }
1392
+ const typedData = edge.buildSweepTypedData(authorization);
1393
+ const viemTypedData = {
1394
+ domain: {
1395
+ ...typedData.domain,
1396
+ verifyingContract: typedData.domain.verifyingContract
1397
+ },
1398
+ types: typedData.types,
1399
+ primaryType: typedData.primaryType,
1400
+ message: {
1401
+ ...typedData.message,
1402
+ from: typedData.message.from,
1403
+ to: typedData.message.to,
1404
+ nonce: typedData.message.nonce
1405
+ }
980
1406
  };
981
- }),
982
- haven_sign_sweep_delegate: async (input) => runTool(async () => {
983
- const args = parse("haven_sign_sweep_delegate", input);
984
- const result = await signer.signSweepAuthorization({
985
- authorization: args.authorization,
986
- expectedAuth: args.expected_auth,
987
- // Cross-check `to` against the Safe in the local credential when present.
988
- expectedSafe: options.audit?.accountAddress
989
- });
990
- await auditSigning(
991
- "haven_sign_sweep_delegate",
992
- hashPayloadForAudit(args.authorization)
993
- );
994
- return { signature: result.signature };
995
- })
1407
+ const account = accounts.privateKeyToAccount(delegateKey);
1408
+ const signature = await account.signTypedData(viemTypedData);
1409
+ const recovered = await viem.recoverTypedDataAddress({ ...viemTypedData, signature });
1410
+ if (!sameAddress(recovered, delegateAddress)) {
1411
+ throw new edge.HavenSigningError(
1412
+ "Local sweep signature verification failed \u2014 recovered address does not match the delegate key."
1413
+ );
1414
+ }
1415
+ return { signature };
1416
+ }
996
1417
  };
997
- async function auditSigning(tool, payloadHash) {
998
- if (!options.audit) return;
999
- const { auditPath, ...context } = options.audit;
1000
- await appendSigningAuditEntry(
1001
- createSigningAuditEntry(tool, payloadHash, {
1002
- ...context,
1003
- delegateAddress: signer.delegateAddress
1004
- }),
1005
- auditPath
1418
+ }
1419
+ function assertSweepBinding(authorization, expectedAuth, trustedSigner) {
1420
+ if (!expectedAuth || typeof expectedAuth !== "object") {
1421
+ throw new edge.HavenSigningError("Sweep authorization binding is required before signing.");
1422
+ }
1423
+ if (!trustedSigner) {
1424
+ throw new edge.HavenSigningError(
1425
+ "Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations."
1006
1426
  );
1007
1427
  }
1008
- }
1009
- function parse(name, input) {
1010
- return v3.z.object(toolSchemas[name]).parse(input ?? {});
1011
- }
1012
- function coerceX402Expected(input) {
1013
- if (!input || typeof input !== "object") return input;
1014
- const record = input;
1015
- let value = record.x402_expected;
1016
- if (typeof value === "string") {
1017
- try {
1018
- value = JSON.parse(value);
1019
- } catch {
1020
- return input;
1021
- }
1428
+ assertSupportedBindingVersion(
1429
+ expectedAuth.version,
1430
+ SUPPORTED_SWEEP_BINDING_VERSIONS,
1431
+ "sweep authorization binding"
1432
+ );
1433
+ const message = edge.buildSweepAuthorizationMessage(authorization);
1434
+ if (expectedAuth.message !== message) {
1435
+ throw new edge.HavenSigningError("Sweep authorization binding does not match the authorization being signed.");
1022
1436
  }
1023
- if (!value || typeof value !== "object") return input;
1024
- const obj = value;
1025
- if (obj.auth === void 0 && obj.expected && typeof obj.expected === "object") {
1026
- return { ...record, x402_expected: obj.expected };
1437
+ if (!sameAddress(expectedAuth.signer, trustedSigner)) {
1438
+ throw new edge.HavenSigningError("Sweep authorization binding was not signed by the configured Haven signer.");
1439
+ }
1440
+ if (!edge.verifySignature(viem.hashMessage(message), expectedAuth.signature, trustedSigner)) {
1441
+ throw new edge.HavenSigningError("Sweep authorization binding signature could not be verified.");
1027
1442
  }
1028
- if (value !== record.x402_expected) return { ...record, x402_expected: value };
1029
- return input;
1030
1443
  }
1031
- function coercePaymentRequired(input) {
1032
- if (!input || typeof input !== "object") return input;
1033
- const record = input;
1034
- if (typeof record.payment_required !== "string") return input;
1035
- try {
1036
- return { ...record, payment_required: JSON.parse(record.payment_required) };
1037
- } catch {
1038
- return input;
1444
+ function assertX402MatchesExpected(paymentRequired, option, expected) {
1445
+ assertExpectedShape(expected);
1446
+ const headerResource = option.resource ?? paymentRequired.resource.url;
1447
+ if (headerResource !== expected.resourceUrl) {
1448
+ throw new edge.HavenSigningError("x402 payment_required resource does not match the funded intent.");
1449
+ }
1450
+ if (!sameAddress(option.payTo, expected.merchantTo)) {
1451
+ throw new edge.HavenSigningError("x402 merchant recipient does not match the funded intent.");
1452
+ }
1453
+ if (edge.x402AuthorizationAmount(option) !== expected.amount) {
1454
+ throw new edge.HavenSigningError("x402 amount does not match the funded intent.");
1455
+ }
1456
+ if (!sameAddress(option.asset, expected.asset)) {
1457
+ throw new edge.HavenSigningError("x402 asset does not match the funded intent.");
1458
+ }
1459
+ if (option.network !== expected.network) {
1460
+ throw new edge.HavenSigningError("x402 network does not match the funded intent.");
1039
1461
  }
1040
1462
  }
1041
- async function runTool(fn) {
1042
- try {
1043
- return { success: true, data: await fn() };
1044
- } catch (err) {
1045
- return normalizeError(err);
1463
+ function assertExpectedShape(expected) {
1464
+ if (!expected || typeof expected !== "object") {
1465
+ throw new edge.HavenSigningError("x402 expected funding context is required before signing a merchant header.");
1046
1466
  }
1047
1467
  }
1048
- function normalizeError(err) {
1049
- if (err instanceof v3.z.ZodError) {
1050
- return {
1051
- success: false,
1052
- code: "INVALID_INPUT",
1053
- message: err.errors.map((e) => `${e.path.join(".") || "(root)"}: ${e.message}`).join("; "),
1054
- statusCode: 400
1055
- };
1468
+ var SUPPORTED_X402_EXPECTED_VERSIONS = [2, 3];
1469
+ var SUPPORTED_SWEEP_BINDING_VERSIONS = [1];
1470
+ function assertSupportedBindingVersion(received, supported, context) {
1471
+ if (supported.includes(received)) return;
1472
+ const highest = Math.max(...supported);
1473
+ const outOfDate = received > highest;
1474
+ const code = context === "x402 expected context" ? edge.SignerRefusalCode.UnsupportedExpectedContextVersion : edge.SignerRefusalCode.UnsupportedSweepBindingVersion;
1475
+ const ceiling = outOfDate ? `This signer is out of date: it supports ${context} versions up to ${highest}, and Haven sent version ${received}. Update @haven_ai/signer \u2014 rerun the Haven connector (\`${edge.connectorRerunCommand()}\`), which reinstalls the pinned MCP runtime.` : `Unsupported ${context} version ${received}: this signer supports ${supported.join(", ")}.`;
1476
+ const fallback = outOfDate ? edge.SIGNER_UPDATE_FALLBACK : `This ${context} version (${received}) is older than what this signer enforces (${supported.join(", ")}) \u2014 updating @haven_ai/signer will not restore it. Nothing was signed or spent; stop and tell the user rather than retrying.`;
1477
+ throw new edge.HavenUnsupportedSignerVersionError(
1478
+ `${ceiling} Nothing was signed. Do not rewrite the version field to a supported value: it is part of the Haven-signed binding message, so changing it invalidates the signature and would misrepresent what Haven declared.`,
1479
+ code,
1480
+ supported,
1481
+ received,
1482
+ fallback
1483
+ );
1484
+ }
1485
+ function assertExpectedBinding(typedDataDigest, expected, trustedSigner) {
1486
+ assertExpectedShape(expected);
1487
+ if (!trustedSigner) {
1488
+ throw new edge.HavenSigningError(
1489
+ "x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding payloads."
1490
+ );
1056
1491
  }
1057
- if (err instanceof sdk.HavenUnsupportedSignerVersionError) {
1058
- return {
1059
- success: false,
1060
- code: err.code,
1061
- message: err.message,
1062
- supported_versions: [...err.supportedVersions],
1063
- received_version: err.receivedVersion,
1064
- fallback: err.fallback,
1065
- next_action: sdk.AgentPaymentNextAction.StopAndTellUser
1066
- };
1492
+ if (expected.auth) {
1493
+ assertSupportedBindingVersion(
1494
+ expected.auth.version,
1495
+ SUPPORTED_X402_EXPECTED_VERSIONS,
1496
+ "x402 expected context"
1497
+ );
1067
1498
  }
1068
- if (err instanceof HavenSignContextError) {
1069
- return {
1070
- success: false,
1071
- code: err.code,
1072
- message: err.message,
1073
- next_action: err.next_action,
1074
- ...err.fallback !== void 0 ? { fallback: err.fallback } : {},
1075
- ...err.retry_with_new_quote ? { retry_with_new_quote: true } : {},
1076
- ...err.http_status !== void 0 ? { http_status: err.http_status } : {},
1077
- ...err.backend_error_code !== void 0 ? { backend_error_code: err.backend_error_code } : {}
1078
- };
1499
+ if (!expected.typedDataHash) {
1500
+ throw new edge.HavenSigningError(
1501
+ "Refusing to sign typed data under an expected context that does not commit to it. Haven must return a v2/v3 x402 expected context (with typedDataHash) for a delegation-rail intent."
1502
+ );
1079
1503
  }
1080
- if (err instanceof sdk.HavenSigningError) {
1081
- return { success: false, code: err.code, message: err.message };
1504
+ if (expected.typedDataHash.toLowerCase() !== typedDataDigest.toLowerCase()) {
1505
+ throw new edge.HavenSigningError(
1506
+ "x402 typed data does not match the digest Haven committed to in the expected context. Refusing to sign \u2014 the payload was altered in transit or Haven declared a different one. The most common cause is the typed data being truncated or reshaped while being copied between tool calls (#1255): re-run the hosted quote and pass its typed_data_b64 string through UNCHANGED instead of re-emitting the nested JSON."
1507
+ );
1082
1508
  }
1083
- if (err instanceof sdk.HavenApiError) {
1084
- return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
1509
+ const message = edge.buildX402ExpectedMessage({
1510
+ paymentId: expected.paymentId,
1511
+ payloadHash: expected.payloadHash,
1512
+ resourceUrl: expected.resourceUrl,
1513
+ merchantTo: expected.merchantTo,
1514
+ amount: expected.amount,
1515
+ asset: expected.asset,
1516
+ network: expected.network,
1517
+ expiresAt: expected.expiresAt,
1518
+ typedDataHash: expected.typedDataHash,
1519
+ payerDelegate: expected.payerDelegate,
1520
+ payerAgentId: expected.payerAgentId
1521
+ });
1522
+ const expectedVersion = expected.payerDelegate ? 3 : 2;
1523
+ if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {
1524
+ throw new edge.HavenSigningError("x402 expected context authentication message is invalid.");
1085
1525
  }
1086
- if (err instanceof sdk.HavenError) {
1087
- return {
1088
- success: false,
1089
- code: err.code,
1090
- message: err.message,
1091
- statusCode: err.statusCode,
1092
- paymentId: err.paymentId,
1093
- ...err.code === sdk.AgentPaymentFailureCode.PaymentWindowExpired ? {
1094
- next_action: sdk.AgentPaymentNextAction.PaymentWindowExpired,
1095
- retry_with_new_quote: true,
1096
- suggested_tool: "haven_pay_mcp_tool"
1097
- } : {}
1098
- };
1526
+ if (!sameAddress(expected.auth.signer, trustedSigner)) {
1527
+ throw new edge.HavenSigningError("x402 expected context was not signed by the configured Haven signer.");
1099
1528
  }
1100
- return {
1101
- success: false,
1102
- code: "UNKNOWN_ERROR",
1103
- message: err instanceof Error ? err.message : String(err)
1104
- };
1105
- }
1106
-
1107
- // src/consent.ts
1108
- var SIGNER_ACK_ENV = "HAVEN_SIGNER_ACK";
1109
- var SIGNER_CONSENT_SURFACE_VERSION = 2;
1110
- function computeSignerConsentHash(input) {
1111
- const identity = [
1112
- input.delegateAddress.toLowerCase(),
1113
- (input.accountAddress ?? "").toLowerCase(),
1114
- input.agentId ?? "",
1115
- input.chainId ?? "",
1116
- input.network ?? ""
1117
- ].join("|");
1118
- const toolCanonical = [...input.toolNames].sort().join(",");
1119
- return crypto.createHash("sha256").update(`${identity}
1120
- ${toolCanonical}
1121
- surface:v${SIGNER_CONSENT_SURFACE_VERSION}`).digest("hex").slice(0, 16);
1122
- }
1123
- function renderSignerConsentBlock(input, hash) {
1124
- const lines = [
1125
- "",
1126
- "------------------------------------------------------------",
1127
- "Haven edge signer - first-launch consent",
1128
- "------------------------------------------------------------",
1129
- "",
1130
- `Delegate address: ${input.delegateAddress}`
1131
- ];
1132
- lines.push(`Haven wallet: ${input.accountAddress ?? "not provided to this signer"}`);
1133
- if (input.agentId) lines.push(`Agent ID: ${input.agentId}`);
1134
- if (typeof input.chainId === "number") lines.push(`Chain ID: ${input.chainId}`);
1135
- if (input.network) lines.push(`Network: ${input.network}`);
1136
- lines.push("");
1137
- lines.push("This local signer holds the delegate key on this machine and signs");
1138
- lines.push("payment payloads or x402 merchant headers for the delegate address above.");
1139
- lines.push("Its one network use is a read-only fetch of a pending payment's signing");
1140
- lines.push("payload from Haven, authenticated with the agent credential stored next to");
1141
- lines.push("this signer's key file - it never sends the key, a signature, or anything");
1142
- lines.push("else outbound, and it cannot show a live allowance summary.");
1143
- lines.push("On-chain Safe rules remain the real spend gate, and the wallet owner can");
1144
- lines.push("pause or revoke agent authority outside this signer.");
1145
- lines.push("");
1146
- lines.push("Tools this signer will expose to your agent runtime:");
1147
- for (const name of input.toolNames) {
1148
- lines.push(` - ${name}`);
1149
- lines.push(` ${toolDescriptions[name]}`);
1529
+ if (!edge.verifySignature(viem.hashMessage(message), expected.auth.signature, trustedSigner)) {
1530
+ throw new edge.HavenSigningError("x402 expected context signature could not be verified.");
1150
1531
  }
1151
- lines.push("");
1152
- lines.push("A local audit entry is appended for every signing operation. Audit entries");
1153
- lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
1154
- lines.push("signature, or x402 payment header.");
1155
- lines.push("");
1156
- lines.push(`Consent hash: ${hash}`);
1157
- lines.push("");
1158
- lines.push("To acknowledge, EITHER:");
1159
- lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`);
1160
- lines.push(" - re-run with --ack to write the acknowledgement next to your");
1161
- lines.push(" credential file (sidecar <credentials>.signer-ack.json).");
1162
- lines.push("");
1163
- lines.push("------------------------------------------------------------");
1164
- lines.push("");
1165
- return lines.join("\n");
1166
1532
  }
1167
- async function ensureSignerConsent(input, options = {}) {
1168
- const env = options.env ?? process.env;
1169
- const out = options.out ?? process.stderr;
1170
- const hash = computeSignerConsentHash(input);
1171
- const envAck = env[SIGNER_ACK_ENV];
1172
- if (typeof envAck === "string" && envAck.length > 0) {
1173
- if (envAck === hash) return { ok: true, hash, reason: "env_var_match" };
1174
- out.write(renderSignerConsentBlock(input, hash));
1175
- out.write(
1176
- `${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.
1177
- Expected: ${hash}
1178
- Got: ${envAck}
1179
- Re-acknowledge with the new hash above, or run with --ack.
1180
-
1181
- `
1533
+ function assertPayerMatchesDelegate(expected, delegateAddress, localAgentId) {
1534
+ if (!expected.payerDelegate) return;
1535
+ if (sameAddress(expected.payerDelegate, delegateAddress)) return;
1536
+ const quoteAgent = expected.payerAgentId ?? "unknown";
1537
+ const localAgent = localAgentId ?? "unknown";
1538
+ throw new edge.HavenSigningError(
1539
+ `This quote belongs to a DIFFERENT agent: the quote was created for agent ${quoteAgent} (delegate ${expected.payerDelegate}), but this signer holds agent ${localAgent} (delegate ${delegateAddress}). A long-lived host is holding stale credentials \u2014 its session authenticates as the old agent while the signer on disk belongs to the new one. Nothing was signed. Restart the host so it re-reads its wiring, then re-quote.`
1540
+ );
1541
+ }
1542
+ async function loadX402Schemes() {
1543
+ try {
1544
+ return await import('x402/schemes');
1545
+ } catch (err) {
1546
+ throw new edge.HavenSigningError(
1547
+ `The x402 scheme module could not be loaded, so no merchant header was built (nothing was sent to the merchant): ${err instanceof Error ? err.message : String(err)}. The signer's runtime install is incomplete \u2014 run: npx @haven_ai/connect --doctor`
1182
1548
  );
1183
- return { ok: false, hash, reason: "env_var_mismatch" };
1184
1549
  }
1185
- const ackPath = sidecarPath(options.credentialsPath);
1186
- if (ackPath) {
1187
- const stored = await readAckFile(ackPath);
1188
- if (stored?.ack === hash) return { ok: true, hash, reason: "ack_file_match" };
1550
+ }
1551
+ function assertX402PaymentWindowOpen(expected) {
1552
+ if (!expected.expiresAt) return;
1553
+ const expiresAtMs = Date.parse(expected.expiresAt);
1554
+ if (Number.isNaN(expiresAtMs)) {
1555
+ throw new edge.HavenSigningError("x402 expected context expiresAt is not a valid ISO timestamp.");
1189
1556
  }
1190
- if (options.writeAck && ackPath) {
1191
- out.write(renderSignerConsentBlock(input, hash));
1192
- await writeAckFile(ackPath, hash);
1193
- out.write(`Wrote acknowledgement to ${ackPath}
1194
-
1195
- `);
1196
- return { ok: true, hash, reason: "wrote_ack_file" };
1557
+ if (expiresAtMs <= Date.now()) {
1558
+ throw new edge.HavenError(
1559
+ "The x402 payment window expired before the merchant header could be signed. Re-quote with haven_pay_mcp_tool using the same idempotency_key before trying again.",
1560
+ edge.AgentPaymentFailureCode.PaymentWindowExpired,
1561
+ 410,
1562
+ expected.paymentId
1563
+ );
1197
1564
  }
1198
- out.write(renderSignerConsentBlock(input, hash));
1199
- return { ok: false, hash, reason: "no_acknowledgement" };
1200
1565
  }
1201
- function registeredSignerToolNames() {
1202
- return Object.keys(toolSchemas);
1566
+ function sameAddress(a, b) {
1567
+ return a.toLowerCase() === b.toLowerCase();
1203
1568
  }
1204
- function sidecarPath(credentialsPath) {
1205
- if (!credentialsPath) return null;
1206
- return path.resolve(`${credentialsPath}.signer-ack.json`);
1569
+
1570
+ // src/capabilities.ts
1571
+ var SIGNER_CAPABILITY_KEY = "haven/signer-compatibility";
1572
+ function signerCompatibility() {
1573
+ return {
1574
+ x402_expected_context_versions: [...SUPPORTED_X402_EXPECTED_VERSIONS],
1575
+ sweep_binding_versions: [...SUPPORTED_SWEEP_BINDING_VERSIONS],
1576
+ direct_sign_context_versions: [...SUPPORTED_DIRECT_SIGN_CONTEXT_VERSIONS]
1577
+ };
1207
1578
  }
1208
- async function readAckFile(path) {
1209
- try {
1210
- const raw = await promises.readFile(path, "utf8");
1211
- const parsed = JSON.parse(raw);
1212
- return { ack: typeof parsed.ack === "string" ? parsed.ack : void 0 };
1213
- } catch {
1214
- return null;
1215
- }
1579
+ function signerCapabilityAdvertisement() {
1580
+ return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } };
1216
1581
  }
1217
- async function writeAckFile(path$1, hash) {
1218
- await promises.mkdir(path.dirname(path$1), { recursive: true });
1219
- await promises.writeFile(
1220
- path$1,
1221
- JSON.stringify({ ack: hash, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
1222
- "utf8"
1223
- );
1582
+ function signerInstructions() {
1583
+ const compatibility = signerCompatibility();
1584
+ return [
1585
+ "Haven edge signer: sign-only tools bound to the local delegate key. It never emits the",
1586
+ "key. Its one network capability is an authenticated READ of a signing context from",
1587
+ "Haven by payment_id \u2014 pass payment_id to haven_sign (preferred for both a direct payment,",
1588
+ "#3271, and delegation-rail x402) or haven_sign_x402 (x402 only) instead of relaying bulky",
1589
+ "typed-data payloads yourself.",
1590
+ "",
1591
+ "Version compatibility (check this BEFORE signing, not after):",
1592
+ `- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(", ")}`,
1593
+ `- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(", ")}`,
1594
+ `- direct-payment (haven_send / haven_pay) sign-context versions supported: ${compatibility.direct_sign_context_versions.join(", ")} \u2014 pass payment_id alone to haven_sign; this signer fetches the exact bytes`,
1595
+ "",
1596
+ "Haven quote and prepare results report the expected-context version they will emit",
1597
+ "(signer_compatibility.x402_expected_context_version). If that version is not in the list",
1598
+ "above, this signer is out of date: STOP before signing, and tell the user to update",
1599
+ `@haven_ai/signer by rerunning \`${edge.connectorRerunCommand()}\`, which reinstalls the pinned`,
1600
+ "MCP runtime. Do not edit the version field to a supported value \u2014 it is part of the",
1601
+ "Haven-signed binding message, so changing it invalidates the signature.",
1602
+ "",
1603
+ "A version-mismatch refusal from haven_sign / haven_sign_x402 / haven_sign_sweep_delegate is",
1604
+ "machine-readable, not just prose: it carries code, supported_versions, received_version, and",
1605
+ "fallback fields alongside the message, so you can branch on it directly. Every signer",
1606
+ "refusal also carries the next-step family: next_tool_name + next_tool_server_role when a",
1607
+ "hosted tool follows (resolve the role against your own server names), else",
1608
+ "next_tool_omitted_reason saying why not."
1609
+ ].join("\n");
1224
1610
  }
1225
1611
  async function loadSignerCredentials(path = process.env.HAVEN_CREDENTIALS) {
1226
1612
  if (path) return loadFromFile(path);
@@ -1318,24 +1704,12 @@ function invalidChainIdError(label) {
1318
1704
  }
1319
1705
  async function warnIfCredentialFilePermissive(path, log = (message) => process.stderr.write(`${message}
1320
1706
  `), platform = process.platform) {
1321
- if (platform === "win32") return;
1322
- let mode;
1323
- try {
1324
- mode = (await promises.stat(path)).mode;
1325
- } catch {
1326
- return;
1327
- }
1328
- if ((mode & 63) !== 0) {
1329
- const octal = (mode & 511).toString(8).padStart(4, "0");
1330
- log(
1331
- `haven-signer: warning: credential file at ${path} is readable beyond the owner (mode ${octal}). Run: chmod 600 ${path}`
1332
- );
1333
- }
1707
+ await warnIfFilePermissive("credential file", path, log, platform);
1334
1708
  }
1335
1709
 
1336
1710
  // src/server.ts
1337
1711
  var SIGNER_NAME = "@haven_ai/signer";
1338
- var SIGNER_VERSION = "0.3.0-alpha.0";
1712
+ var SIGNER_VERSION = "0.5.0-alpha.1";
1339
1713
  async function resolveSignerRuntime(options = {}) {
1340
1714
  assertSupportedNodeVersion(options.nodeVersion);
1341
1715
  if (options.delegateKey) {
@@ -1373,13 +1747,17 @@ function buildSignerMcpServer(signer, options = {}) {
1373
1747
  accountAddress: options.credentials?.accountAddress,
1374
1748
  chainId: options.credentials?.chainId
1375
1749
  },
1376
- // #1263: the payment_id signing path — the ONLY network call this server
1377
- // can make, an authenticated read of a signing context from Haven, using
1750
+ // #1263: the payment_id signing path — the ONLY network path this server
1751
+ // has: up to two authenticated reads of a signing context from Haven (x402,
1752
+ // then direct for haven_sign, #3271), using
1378
1753
  // the agent identity the connector stores next to the signer credential.
1379
1754
  // The signer CORE stays network-free; fetched bytes still pass the same
1380
1755
  // binding verification + digest re-derivation as tool-argument bytes.
1381
1756
  signContext: {
1382
- loadIdentity: () => loadHavenIdentity(credentialsPath)
1757
+ loadIdentity: () => loadHavenIdentity(credentialsPath),
1758
+ // #3303: the backend refuses a signer below a minimum it has set, at
1759
+ // sign-context — the one place this signer meets it.
1760
+ clientIdentity: edge.havenClientIdentity(SIGNER_NAME, SIGNER_VERSION)
1383
1761
  }
1384
1762
  });
1385
1763
  const registerTool = server.tool.bind(server);
@@ -1394,9 +1772,9 @@ function buildSignerMcpServer(signer, options = {}) {
1394
1772
  return server;
1395
1773
  }
1396
1774
  function assertSupportedNodeVersion(nodeVersion = process.versions.node) {
1397
- if (sdk.isSupportedNodeVersion(nodeVersion)) return;
1775
+ if (edge.isSupportedNodeVersion(nodeVersion)) return;
1398
1776
  const err = new Error(
1399
- sdk.unsupportedNodeVersionMessage({ subject: "The Haven signer", nodeVersion })
1777
+ edge.unsupportedNodeVersionMessage({ subject: "The Haven signer", nodeVersion })
1400
1778
  );
1401
1779
  err.code = "HAVEN_SIGNER_UNSUPPORTED_NODE";
1402
1780
  throw err;
@@ -1407,7 +1785,7 @@ async function runSignerStdioServer(options = {}) {
1407
1785
  const decision = await runSignerConsentGate(signer, credentials, options);
1408
1786
  if (!decision.ok) {
1409
1787
  const err = new Error(
1410
- 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."
1788
+ (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.") + " See the consent block above; if the Haven connector wired this signer, run: npx @haven_ai/connect --doctor"
1411
1789
  );
1412
1790
  err.code = "HAVEN_SIGNER_NO_CONSENT";
1413
1791
  throw err;
@@ -1442,49 +1820,18 @@ function toMcpResult(payload) {
1442
1820
  }
1443
1821
 
1444
1822
  // src/cli.ts
1445
- function parseArgs(argv) {
1446
- const options = {};
1447
- for (let i = 0; i < argv.length; i += 1) {
1448
- const arg = argv[i];
1449
- if (arg === "--credentials" || arg === "--credentials-path") {
1450
- options.credentialsPath = argv[i + 1];
1451
- i += 1;
1452
- } else if (arg === "--ack") {
1453
- options.writeAck = true;
1454
- } else if (arg === "--help" || arg === "-h") {
1455
- process.stdout.write(
1456
- [
1457
- "Haven edge signer (local, holds the delegate key)",
1458
- "",
1459
- "Runs a local stdio MCP server exposing sign-only tools (haven_sign,",
1460
- "haven_x402_sign_header). Pair it with the hosted, keyless Haven MCP",
1461
- "server: the hosted server constructs and relays, this one signs.",
1462
- "",
1463
- "Usage:",
1464
- " npx @haven_ai/signer --credentials /path/to/agent.json",
1465
- "",
1466
- "Options:",
1467
- " --credentials <path> Haven credential JSON (delegate_key is read from it).",
1468
- " Also supported: HAVEN_CREDENTIALS, or HAVEN_DELEGATE_KEY.",
1469
- " --ack Acknowledge the first-launch consent block and write",
1470
- " a signer sidecar acknowledgement next to the credential.",
1471
- "",
1472
- "Consent:",
1473
- " On first launch the signer prints the sign-only tool list and delegate",
1474
- " address, then refuses to start unless acknowledged. Its only Haven API call",
1475
- " is a read-only fetch of the signing payload for one pending payment, so it",
1476
- " cannot show a live allowance summary.",
1477
- " Acknowledge with EITHER --ack OR HAVEN_SIGNER_ACK=<hash> in your environment.",
1478
- ""
1479
- ].join("\n")
1480
- );
1481
- process.exit(0);
1482
- }
1483
- }
1484
- return options;
1485
- }
1486
1823
  async function main() {
1487
- await runSignerStdioServer(parseArgs(process.argv.slice(2)));
1824
+ const decision = parseSignerArgs(process.argv.slice(2));
1825
+ if (decision.kind === "help") {
1826
+ process.stdout.write(decision.text);
1827
+ process.exit(0);
1828
+ }
1829
+ if (decision.kind === "unknown-option") {
1830
+ process.stderr.write(`${decision.text}
1831
+ `);
1832
+ process.exit(2);
1833
+ }
1834
+ await runSignerStdioServer(decision.options);
1488
1835
  }
1489
1836
  main().catch((err) => {
1490
1837
  process.stderr.write(`${err instanceof Error ? err.message : String(err)}