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