@haven_ai/signer 0.1.14-alpha.0 → 0.1.15-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -46,6 +46,22 @@ function stableStringify(value) {
46
46
  const object = value;
47
47
  return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(",")}}`;
48
48
  }
49
+ var sweepAuthorizationSchema = v3.z.object({
50
+ from: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "from must be a 0x address"),
51
+ to: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "to must be a 0x address"),
52
+ value: v3.z.string().regex(/^[0-9]+$/, "value must be a decimal atomic amount"),
53
+ validAfter: v3.z.string().regex(/^[0-9]+$/, "validAfter must be a decimal unix time"),
54
+ validBefore: v3.z.string().regex(/^[0-9]+$/, "validBefore must be a decimal unix time"),
55
+ nonce: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "nonce must be a 0x-prefixed 32-byte hex string"),
56
+ token: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "token must be a 0x address"),
57
+ chainId: v3.z.number().int().positive()
58
+ });
59
+ var sweepExpectedAuthSchema = v3.z.object({
60
+ version: v3.z.literal(1),
61
+ message: v3.z.string().min(1),
62
+ signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
63
+ signer: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "signer must be a 0x address")
64
+ });
49
65
  var x402ExpectedSchema = v3.z.object({
50
66
  payment_id: v3.z.string().min(1),
51
67
  payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
@@ -54,6 +70,7 @@ var x402ExpectedSchema = v3.z.object({
54
70
  amount: v3.z.string().min(1),
55
71
  asset: v3.z.string().min(1),
56
72
  network: v3.z.string().min(1),
73
+ expires_at: v3.z.string().min(1).optional(),
57
74
  auth: v3.z.object({
58
75
  version: v3.z.literal(1),
59
76
  message: v3.z.string().min(1),
@@ -62,11 +79,18 @@ var x402ExpectedSchema = v3.z.object({
62
79
  })
63
80
  });
64
81
  var toolSchemas = {
65
- haven_sweep_delegate: {},
82
+ haven_sign_sweep_delegate: {
83
+ // The authorization fields prepared by Haven's POST /sweep/prepare. Passed
84
+ // through verbatim from the hosted haven_sweep_delegate tool — the signer
85
+ // re-derives the binding message from these exact values.
86
+ authorization: sweepAuthorizationSchema,
87
+ // Haven's signature over the authorization context (the binding).
88
+ expected_auth: sweepExpectedAuthSchema
89
+ },
66
90
  haven_sign: {
67
- // The unsigned hash from haven_pay / haven_x402_authorize (payload_hash).
91
+ // The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).
68
92
  payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
69
- // Pass x402.expected from hosted haven_x402_authorize when this hash funds
93
+ // Pass x402.expected from hosted haven_pay_x402_quote when this hash funds
70
94
  // a standard x402 merchant retry. The signer records it locally and returns
71
95
  // an opaque x402_binding for the later header-signing step.
72
96
  x402_expected: x402ExpectedSchema.optional()
@@ -78,67 +102,79 @@ var toolSchemas = {
78
102
  payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
79
103
  // Opaque binding returned by haven_sign when x402_expected was supplied.
80
104
  x402_binding: v3.z.string().min(1)
105
+ },
106
+ haven_sign_x402: {
107
+ // One-shot x402 signing: funding hash + merchant header in one local call.
108
+ payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
109
+ x402_expected: x402ExpectedSchema,
110
+ payment_required: v3.z.record(v3.z.string(), v3.z.unknown())
81
111
  }
82
112
  };
83
113
  var SIGN_DESCRIPTION = [
84
114
  "Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves",
85
115
  "this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.",
86
116
  "For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally",
87
- "and returns { signature, x402_binding }. Hand signature to haven_submit, then pass x402_binding",
88
- "to haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and",
89
- "relay the returned signature via haven_submit."
117
+ "and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that",
118
+ "window closes. Next: call mcp__haven__haven_submit with signature, then pass x402_binding",
119
+ "to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and",
120
+ "relay the returned signature via mcp__haven__haven_submit."
90
121
  ].join(" ");
91
122
  var X402_SIGN_HEADER_DESCRIPTION = [
92
123
  "Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment.",
93
124
  "The delegate key stays local \u2014 only the signed header crosses any boundary.",
94
125
  "Pass the payment_required from the original merchant 402 response and the x402_binding",
95
126
  "returned by haven_sign. The signer validates the merchant, amount, resource, asset, and",
96
- "network against the recorded funding context before signing, and rejects mismatches.",
127
+ "network against the recorded funding context before signing, checks expires_at when present,",
128
+ "and rejects mismatches or expired payment windows.",
97
129
  "Returns { payment_header, accepted }. Set X-PAYMENT: <payment_header> on your retry to the",
98
130
  "merchant. Only call after haven_submit has confirmed the funding step (nextAction=none or",
99
- "the funding tx has a confirmed status)."
131
+ "the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
132
+ ].join(" ");
133
+ var SIGN_X402_DESCRIPTION = [
134
+ "One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009",
135
+ "X-PAYMENT header in a single local call (equivalent to haven_sign followed by",
136
+ "haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool",
137
+ "result pass payload_hash, x402_expected (the nested x402.expected object, not a top-level field),",
138
+ "and payment_required (verbatim). Returns",
139
+ "{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to",
140
+ "mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before",
141
+ "funding confirms), so its short validity window starts here \u2014 call mcp__haven__haven_settle_mcp_tool promptly,",
142
+ "and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.",
143
+ "Next: call mcp__haven__haven_settle_mcp_tool."
100
144
  ].join(" ");
101
- var SWEEP_DELEGATE_DESCRIPTION = [
102
- "Sweep stranded USDC and/or ETH from the delegate wallet back to the originating Safe.",
103
- "Use when a payment failed or expired after funding, leaving funds on the delegate EOA.",
104
- "Signs ERC-20 transfer and native ETH transfer transactions locally with the delegate key.",
105
- "Only supported on Base (chainId 8453). Returns tx hashes and recovered amounts.",
106
- "Returns an empty transfers list when nothing is stranded."
145
+ var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
146
+ "Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
147
+ "wallet back to your Haven wallet. The delegate key never leaves this process and this tool",
148
+ "never broadcasts \u2014 it returns only an EIP-3009 signature that Haven's relayer submits and",
149
+ "pays gas for. Pass the authorization and expected_auth returned by the hosted",
150
+ "haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it",
151
+ "pays out to your own Safe before signing, then returns { signature } to hand back to",
152
+ "mcp__haven__haven_sweep_delegate to complete recovery."
107
153
  ].join(" ");
108
154
  var toolDescriptions = {
109
- haven_sweep_delegate: SWEEP_DELEGATE_DESCRIPTION,
110
155
  haven_sign: SIGN_DESCRIPTION,
111
- haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION
156
+ haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
157
+ haven_sign_x402: SIGN_X402_DESCRIPTION,
158
+ haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
112
159
  };
160
+ function toExpectedX402(raw) {
161
+ return {
162
+ paymentId: raw.payment_id,
163
+ payloadHash: raw.payload_hash,
164
+ resourceUrl: raw.resource_url,
165
+ merchantTo: raw.merchant_to,
166
+ amount: raw.amount,
167
+ asset: raw.asset,
168
+ network: raw.network,
169
+ expiresAt: raw.expires_at,
170
+ auth: raw.auth
171
+ };
172
+ }
113
173
  function createToolHandlers(signer, options = {}) {
114
174
  return {
115
- haven_sweep_delegate: async () => runTool(async () => {
116
- const safeAddress = options.audit?.safeAddress;
117
- const chainId = options.audit?.chainId;
118
- if (!safeAddress) {
119
- throw new Error(
120
- "Sweep requires a Safe address \u2014 ensure credentials include safe_address."
121
- );
122
- }
123
- if (typeof chainId !== "number") {
124
- throw new Error(
125
- "Sweep requires a chainId \u2014 ensure credentials include chain_id."
126
- );
127
- }
128
- return signer.sweepDelegate({ safeAddress, chainId });
129
- }),
130
175
  haven_sign: async (input) => runTool(async () => {
131
176
  const args = parse("haven_sign", input);
132
- const x402Expected = args.x402_expected ? {
133
- paymentId: args.x402_expected.payment_id,
134
- payloadHash: args.x402_expected.payload_hash,
135
- resourceUrl: args.x402_expected.resource_url,
136
- merchantTo: args.x402_expected.merchant_to,
137
- amount: args.x402_expected.amount,
138
- asset: args.x402_expected.asset,
139
- network: args.x402_expected.network,
140
- auth: args.x402_expected.auth
141
- } : null;
177
+ const x402Expected = args.x402_expected ? toExpectedX402(args.x402_expected) : null;
142
178
  const result = x402Expected ? signer.signX402FundingHash(args.payload_hash, x402Expected) : null;
143
179
  if (!result) {
144
180
  const signature = signer.signPaymentHash(args.payload_hash);
@@ -159,6 +195,36 @@ function createToolHandlers(signer, options = {}) {
159
195
  hashPayloadForAudit(args.payment_required)
160
196
  );
161
197
  return { payment_header: result.paymentHeader, accepted: result.accepted };
198
+ }),
199
+ haven_sign_x402: async (input) => runTool(async () => {
200
+ const args = parse("haven_sign_x402", coercePaymentRequired(input));
201
+ const funding = signer.signX402FundingHash(args.payload_hash, toExpectedX402(args.x402_expected));
202
+ const header = await signer.buildX402PaymentHeader(
203
+ args.payment_required,
204
+ funding.x402Binding
205
+ );
206
+ await auditSigning("haven_sign_x402", args.payload_hash);
207
+ await auditSigning("haven_sign_x402", hashPayloadForAudit(args.payment_required));
208
+ return {
209
+ signature: funding.signature,
210
+ x402_binding: funding.x402Binding,
211
+ payment_header: header.paymentHeader,
212
+ accepted: header.accepted
213
+ };
214
+ }),
215
+ haven_sign_sweep_delegate: async (input) => runTool(async () => {
216
+ const args = parse("haven_sign_sweep_delegate", input);
217
+ const result = await signer.signSweepAuthorization({
218
+ authorization: args.authorization,
219
+ expectedAuth: args.expected_auth,
220
+ // Cross-check `to` against the Safe in the local credential when present.
221
+ expectedSafe: options.audit?.safeAddress
222
+ });
223
+ await auditSigning(
224
+ "haven_sign_sweep_delegate",
225
+ hashPayloadForAudit(args.authorization)
226
+ );
227
+ return { signature: result.signature };
162
228
  })
163
229
  };
164
230
  async function auditSigning(tool, payloadHash) {
@@ -209,7 +275,18 @@ function normalizeError(err) {
209
275
  return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
210
276
  }
211
277
  if (err instanceof sdk.HavenError) {
212
- return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
278
+ return {
279
+ success: false,
280
+ code: err.code,
281
+ message: err.message,
282
+ statusCode: err.statusCode,
283
+ paymentId: err.paymentId,
284
+ ...err.code === sdk.AgentPaymentFailureCode.PaymentWindowExpired ? {
285
+ next_action: sdk.AgentPaymentNextAction.PaymentWindowExpired,
286
+ retry_with_new_quote: true,
287
+ suggested_tool: "haven_pay_mcp_tool"
288
+ } : {}
289
+ };
213
290
  }
214
291
  return {
215
292
  success: false,
@@ -331,42 +408,6 @@ async function writeAckFile(path$1, hash) {
331
408
  "utf8"
332
409
  );
333
410
  }
334
- var BASE_CHAIN_ID = 8453;
335
- var BASE_RPC_URL = "https://mainnet.base.org";
336
- var BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
337
- var BASE_EXPLORER_TX = "https://basescan.org/tx";
338
- var BASE_CHAIN = {
339
- id: BASE_CHAIN_ID,
340
- name: "Base",
341
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
342
- rpcUrls: { default: { http: [BASE_RPC_URL] } }
343
- };
344
- var ERC20_ABI = [
345
- {
346
- name: "balanceOf",
347
- type: "function",
348
- inputs: [{ name: "account", type: "address" }],
349
- outputs: [{ name: "", type: "uint256" }],
350
- stateMutability: "view"
351
- },
352
- {
353
- name: "transfer",
354
- type: "function",
355
- inputs: [
356
- { name: "to", type: "address" },
357
- { name: "amount", type: "uint256" }
358
- ],
359
- outputs: [{ name: "", type: "bool" }],
360
- stateMutability: "nonpayable"
361
- }
362
- ];
363
- function formatTokenAmount(atomic, decimals) {
364
- const divisor = 10n ** BigInt(decimals);
365
- const whole = atomic / divisor;
366
- const frac = atomic % divisor;
367
- if (frac === 0n) return whole.toString();
368
- return `${whole}.${frac.toString().padStart(decimals, "0").replace(/0+$/, "")}`;
369
- }
370
411
  function createEdgeSigner(delegateKey, options = {}) {
371
412
  let delegateAddress;
372
413
  try {
@@ -405,6 +446,12 @@ function createEdgeSigner(delegateKey, options = {}) {
405
446
  "x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first."
406
447
  );
407
448
  }
449
+ try {
450
+ assertX402PaymentWindowOpen(expected);
451
+ } catch (err) {
452
+ x402Bindings.delete(x402Binding);
453
+ throw err;
454
+ }
408
455
  const option = sdk.selectStandardPaymentOption(paymentRequired.accepts);
409
456
  if (!option) {
410
457
  throw new sdk.HavenApiError(
@@ -436,64 +483,69 @@ function createEdgeSigner(delegateKey, options = {}) {
436
483
  x402Bindings.delete(x402Binding);
437
484
  }
438
485
  },
439
- async sweepDelegate({ safeAddress, chainId }) {
440
- if (chainId !== BASE_CHAIN_ID) {
441
- throw new sdk.HavenApiError(
442
- `Sweep is only supported on Base (chainId ${BASE_CHAIN_ID}). Got chainId ${chainId}.`,
443
- 422
486
+ async signSweepAuthorization({
487
+ authorization,
488
+ expectedAuth,
489
+ expectedSafe
490
+ }) {
491
+ assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner);
492
+ if (!sameAddress(authorization.from, delegateAddress)) {
493
+ throw new sdk.HavenSigningError(
494
+ "Sweep authorization `from` does not match this delegate address."
444
495
  );
445
496
  }
446
- const account = accounts.privateKeyToAccount(delegateKey);
447
- const publicClient = viem.createPublicClient({ chain: BASE_CHAIN, transport: viem.http(BASE_RPC_URL) });
448
- const walletClient = viem.createWalletClient({ account, chain: BASE_CHAIN, transport: viem.http(BASE_RPC_URL) });
449
- const transfers = [];
450
- const usdcBalance = await publicClient.readContract({
451
- address: BASE_USDC_ADDRESS,
452
- abi: ERC20_ABI,
453
- functionName: "balanceOf",
454
- args: [account.address]
455
- });
456
- if (usdcBalance > 0n) {
457
- const hash = await walletClient.writeContract({
458
- address: BASE_USDC_ADDRESS,
459
- abi: ERC20_ABI,
460
- functionName: "transfer",
461
- args: [safeAddress, usdcBalance]
462
- });
463
- await publicClient.waitForTransactionReceipt({ hash });
464
- transfers.push({
465
- asset: "USDC",
466
- amount: formatTokenAmount(usdcBalance, 6),
467
- amountAtomic: usdcBalance.toString(),
468
- txHash: hash,
469
- explorerUrl: `${BASE_EXPLORER_TX}/${hash}`
470
- });
497
+ if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {
498
+ throw new sdk.HavenSigningError(
499
+ "Sweep authorization `to` does not match the Safe in the local credential."
500
+ );
471
501
  }
472
- const ethBalance = await publicClient.getBalance({ address: account.address });
473
- if (ethBalance > 0n) {
474
- const gasPrice = await publicClient.getGasPrice() ?? 1000000n;
475
- const gasLimit = 21000n;
476
- const gasCost = gasPrice * gasLimit;
477
- const toSend = ethBalance > gasCost ? ethBalance - gasCost : 0n;
478
- if (toSend > 0n) {
479
- const hash = await walletClient.sendTransaction({
480
- to: safeAddress,
481
- value: toSend
482
- });
483
- await publicClient.waitForTransactionReceipt({ hash });
484
- transfers.push({
485
- asset: "ETH",
486
- amount: formatTokenAmount(toSend, 18),
487
- amountAtomic: toSend.toString(),
488
- txHash: hash,
489
- explorerUrl: `${BASE_EXPLORER_TX}/${hash}`
490
- });
502
+ const typedData = sdk.buildSweepTypedData(authorization);
503
+ const viemTypedData = {
504
+ domain: {
505
+ ...typedData.domain,
506
+ verifyingContract: typedData.domain.verifyingContract
507
+ },
508
+ types: typedData.types,
509
+ primaryType: typedData.primaryType,
510
+ message: {
511
+ ...typedData.message,
512
+ from: typedData.message.from,
513
+ to: typedData.message.to,
514
+ nonce: typedData.message.nonce
491
515
  }
516
+ };
517
+ const account = accounts.privateKeyToAccount(delegateKey);
518
+ const signature = await account.signTypedData(viemTypedData);
519
+ const recovered = await viem.recoverTypedDataAddress({ ...viemTypedData, signature });
520
+ if (!sameAddress(recovered, delegateAddress)) {
521
+ throw new sdk.HavenSigningError(
522
+ "Local sweep signature verification failed \u2014 recovered address does not match the delegate key."
523
+ );
492
524
  }
493
- return { fromAddress: account.address, toAddress: safeAddress, chainId, transfers };
525
+ return { signature };
494
526
  }
495
527
  };
496
528
  }
529
+ function assertSweepBinding(authorization, expectedAuth, trustedSigner) {
530
+ if (!expectedAuth || typeof expectedAuth !== "object") {
531
+ throw new sdk.HavenSigningError("Sweep authorization binding is required before signing.");
532
+ }
533
+ if (!trustedSigner) {
534
+ throw new sdk.HavenSigningError(
535
+ "Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations."
536
+ );
537
+ }
538
+ const message = sdk.buildSweepAuthorizationMessage(authorization);
539
+ if (expectedAuth.version !== 1 || expectedAuth.message !== message) {
540
+ throw new sdk.HavenSigningError("Sweep authorization binding does not match the authorization being signed.");
541
+ }
542
+ if (!sameAddress(expectedAuth.signer, trustedSigner)) {
543
+ throw new sdk.HavenSigningError("Sweep authorization binding was not signed by the configured Haven signer.");
544
+ }
545
+ if (!sdk.verifySignature(viem.hashMessage(message), expectedAuth.signature, trustedSigner)) {
546
+ throw new sdk.HavenSigningError("Sweep authorization binding signature could not be verified.");
547
+ }
548
+ }
497
549
  function assertX402MatchesExpected(paymentRequired, option, expected) {
498
550
  assertExpectedShape(expected);
499
551
  const headerResource = option.resource ?? paymentRequired.resource.url;
@@ -535,7 +587,8 @@ function assertExpectedBinding(payloadHash, expected, trustedSigner) {
535
587
  merchantTo: expected.merchantTo,
536
588
  amount: expected.amount,
537
589
  asset: expected.asset,
538
- network: expected.network
590
+ network: expected.network,
591
+ expiresAt: expected.expiresAt
539
592
  });
540
593
  if (expected.auth?.version !== 1 || expected.auth.message !== message) {
541
594
  throw new sdk.HavenSigningError("x402 expected context authentication message is invalid.");
@@ -547,6 +600,21 @@ function assertExpectedBinding(payloadHash, expected, trustedSigner) {
547
600
  throw new sdk.HavenSigningError("x402 expected context signature could not be verified.");
548
601
  }
549
602
  }
603
+ function assertX402PaymentWindowOpen(expected) {
604
+ if (!expected.expiresAt) return;
605
+ const expiresAtMs = Date.parse(expected.expiresAt);
606
+ if (Number.isNaN(expiresAtMs)) {
607
+ throw new sdk.HavenSigningError("x402 expected context expiresAt is not a valid ISO timestamp.");
608
+ }
609
+ if (expiresAtMs <= Date.now()) {
610
+ throw new sdk.HavenError(
611
+ "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.",
612
+ sdk.AgentPaymentFailureCode.PaymentWindowExpired,
613
+ 410,
614
+ expected.paymentId
615
+ );
616
+ }
617
+ }
550
618
  function sameAddress(a, b) {
551
619
  return a.toLowerCase() === b.toLowerCase();
552
620
  }
@@ -640,7 +708,7 @@ async function warnIfCredentialFilePermissive(path, log = (message) => process.s
640
708
 
641
709
  // src/server.ts
642
710
  var SIGNER_NAME = "@haven_ai/signer";
643
- var SIGNER_VERSION = "0.1.14-alpha.0";
711
+ var SIGNER_VERSION = "0.1.15-alpha.0";
644
712
  async function resolveSignerRuntime(options = {}) {
645
713
  if (options.delegateKey) {
646
714
  return {