@haven_ai/signer 0.1.18-alpha.0 → 0.1.20-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 +810 -604
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +811 -605
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +239 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +113 -4
- package/dist/index.d.ts +113 -4
- package/dist/index.js +237 -33
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -7,11 +7,11 @@ var crypto = require('crypto');
|
|
|
7
7
|
var promises = require('fs/promises');
|
|
8
8
|
var os = require('os');
|
|
9
9
|
var path = require('path');
|
|
10
|
-
var sdk = require('@haven_ai/sdk');
|
|
11
|
-
var v3 = require('zod/v3');
|
|
12
10
|
var viem = require('viem');
|
|
13
11
|
var accounts = require('viem/accounts');
|
|
14
12
|
var schemes = require('x402/schemes');
|
|
13
|
+
var sdk = require('@haven_ai/sdk');
|
|
14
|
+
var v3 = require('zod/v3');
|
|
15
15
|
|
|
16
16
|
function defaultSigningAuditPath(credentialsPath) {
|
|
17
17
|
if (credentialsPath) return path.resolve(`${credentialsPath}.signer-audit.jsonl`);
|
|
@@ -46,684 +46,867 @@ 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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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 bindingVersionSchema = v3.z.number().int().positive();
|
|
60
|
-
var sweepExpectedAuthSchema = v3.z.object({
|
|
61
|
-
version: bindingVersionSchema,
|
|
62
|
-
message: v3.z.string().min(1),
|
|
63
|
-
signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
|
|
64
|
-
signer: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "signer must be a 0x address")
|
|
65
|
-
});
|
|
66
|
-
var x402ExpectedSchema = v3.z.object({
|
|
67
|
-
payment_id: v3.z.string().min(1),
|
|
68
|
-
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
|
|
69
|
-
resource_url: v3.z.string().url(),
|
|
70
|
-
merchant_to: v3.z.string().min(1),
|
|
71
|
-
amount: v3.z.string().min(1),
|
|
72
|
-
asset: v3.z.string().min(1),
|
|
73
|
-
network: v3.z.string().min(1),
|
|
74
|
-
// Required: expires_at is folded into the Haven-signed binding message, so the
|
|
75
|
-
// signer must receive the exact same value to reconstruct a matching message.
|
|
76
|
-
// Omitting it used to fail downstream with a cryptic "authentication message is
|
|
77
|
-
// invalid" — making it required surfaces a clear INVALID_INPUT at the boundary.
|
|
78
|
-
expires_at: v3.z.string().min(1),
|
|
79
|
-
// #1138: present on a delegation-rail (v2) context. It commits to the EIP-712
|
|
80
|
-
// typed data the account validates; the signer refuses to raw-sign the bare
|
|
81
|
-
// hash when it is present, and refuses to sign typed data when it is absent.
|
|
82
|
-
typed_data_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "typed_data_hash must be a 0x-prefixed hex string").optional(),
|
|
83
|
-
auth: v3.z.object({
|
|
84
|
-
// Open at the boundary, enforced in the signer — see bindingVersionSchema.
|
|
85
|
-
version: bindingVersionSchema,
|
|
86
|
-
message: v3.z.string().min(1),
|
|
87
|
-
signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
|
|
88
|
-
signer: v3.z.string().min(1)
|
|
89
|
-
})
|
|
90
|
-
});
|
|
91
|
-
var toolSchemas = {
|
|
92
|
-
haven_sign_sweep_delegate: {
|
|
93
|
-
// The authorization fields prepared by Haven's POST /sweep/prepare. Passed
|
|
94
|
-
// through verbatim from the hosted haven_sweep_delegate tool — the signer
|
|
95
|
-
// re-derives the binding message from these exact values.
|
|
96
|
-
authorization: sweepAuthorizationSchema,
|
|
97
|
-
// Haven's signature over the authorization context (the binding).
|
|
98
|
-
expected_auth: sweepExpectedAuthSchema
|
|
99
|
-
},
|
|
100
|
-
haven_sign: {
|
|
101
|
-
// The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).
|
|
102
|
-
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
|
|
103
|
-
// Pass x402.expected from hosted haven_pay_x402_quote when this hash funds
|
|
104
|
-
// a standard x402 merchant retry. The signer records it locally and returns
|
|
105
|
-
// an opaque x402_binding for the later header-signing step.
|
|
106
|
-
x402_expected: x402ExpectedSchema.optional(),
|
|
107
|
-
// #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
|
|
108
|
-
// (not z.unknown()) so MCP clients embed it as JSON rather than a string.
|
|
109
|
-
typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional()
|
|
110
|
-
},
|
|
111
|
-
haven_x402_sign_header: {
|
|
112
|
-
// The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object
|
|
113
|
-
// (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients
|
|
114
|
-
// embed it as JSON rather than serialising the object to a string.
|
|
115
|
-
payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
|
|
116
|
-
// Opaque binding returned by haven_sign when x402_expected was supplied.
|
|
117
|
-
x402_binding: v3.z.string().min(1)
|
|
118
|
-
},
|
|
119
|
-
haven_sign_x402: {
|
|
120
|
-
// One-shot x402 signing: funding hash + merchant header in one local call.
|
|
121
|
-
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
|
|
122
|
-
x402_expected: x402ExpectedSchema,
|
|
123
|
-
payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
|
|
124
|
-
// #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
|
|
125
|
-
// (not z.unknown()) so MCP clients embed it as JSON rather than a string.
|
|
126
|
-
typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional()
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
var SIGN_DESCRIPTION = [
|
|
130
|
-
"Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves",
|
|
131
|
-
"this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.",
|
|
132
|
-
"For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally",
|
|
133
|
-
"and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that",
|
|
134
|
-
"window closes. DELEGATION-RAIL accounts: when the hosted result carries typed_data, pass it too \u2014",
|
|
135
|
-
"the account validates that EIP-712 payload, not payload_hash, and signing is refused without it.",
|
|
136
|
-
"Next: call mcp__haven__haven_submit with signature, then pass x402_binding",
|
|
137
|
-
"to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and",
|
|
138
|
-
"relay the returned signature via mcp__haven__haven_submit."
|
|
139
|
-
].join(" ");
|
|
140
|
-
var X402_SIGN_HEADER_DESCRIPTION = [
|
|
141
|
-
"Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment.",
|
|
142
|
-
"The delegate key stays local \u2014 only the signed header crosses any boundary.",
|
|
143
|
-
"Pass the payment_required from the original merchant 402 response and the x402_binding",
|
|
144
|
-
"returned by haven_sign. The signer validates the merchant, amount, resource, asset, and",
|
|
145
|
-
"network against the recorded funding context before signing, checks expires_at when present,",
|
|
146
|
-
"and rejects mismatches or expired payment windows.",
|
|
147
|
-
"Returns { payment_header, accepted }. Set X-PAYMENT: <payment_header> on your retry to the",
|
|
148
|
-
"merchant. Only call after haven_submit has confirmed the funding step (nextAction=none or",
|
|
149
|
-
"the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
|
|
150
|
-
].join(" ");
|
|
151
|
-
var SIGN_X402_DESCRIPTION = [
|
|
152
|
-
"One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009",
|
|
153
|
-
"X-PAYMENT header in a single local call (equivalent to haven_sign followed by",
|
|
154
|
-
"haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool",
|
|
155
|
-
"result pass payload_hash, x402_expected (the nested x402.expected object \u2014 passing the whole x402",
|
|
156
|
-
"object is also accepted and unwrapped for you), and payment_required (verbatim). On a",
|
|
157
|
-
"delegation-rail account the result also carries typed_data \u2014 pass that verbatim too; the signer",
|
|
158
|
-
"signs it instead of payload_hash and refuses the bare hash when the context commits to typed data.",
|
|
159
|
-
"Returns",
|
|
160
|
-
"{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to",
|
|
161
|
-
"mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before",
|
|
162
|
-
"funding confirms), so its short validity window starts here \u2014 call mcp__haven__haven_settle_mcp_tool promptly,",
|
|
163
|
-
"and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.",
|
|
164
|
-
"Next: call mcp__haven__haven_settle_mcp_tool."
|
|
165
|
-
].join(" ");
|
|
166
|
-
var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
|
|
167
|
-
"Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
|
|
168
|
-
"wallet back to your Haven wallet. The delegate key never leaves this process and this tool",
|
|
169
|
-
"never broadcasts \u2014 it returns only an EIP-3009 signature that Haven's relayer submits and",
|
|
170
|
-
"pays gas for. Pass the authorization and expected_auth returned by the hosted",
|
|
171
|
-
"haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it",
|
|
172
|
-
"pays out to your own Safe before signing, then returns { signature } to hand back to",
|
|
173
|
-
"mcp__haven__haven_sweep_delegate to complete recovery."
|
|
174
|
-
].join(" ");
|
|
175
|
-
var toolDescriptions = {
|
|
176
|
-
haven_sign: SIGN_DESCRIPTION,
|
|
177
|
-
haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
|
|
178
|
-
haven_sign_x402: SIGN_X402_DESCRIPTION,
|
|
179
|
-
haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
|
|
180
|
-
};
|
|
181
|
-
async function signFundingLeg(signer, expected, payloadHash, typedData) {
|
|
182
|
-
if (!expected.typedDataHash) {
|
|
183
|
-
return signer.signX402FundingHash(payloadHash, expected);
|
|
184
|
-
}
|
|
185
|
-
if (!typedData) {
|
|
49
|
+
function createEdgeSigner(delegateKey, options = {}) {
|
|
50
|
+
let delegateAddress;
|
|
51
|
+
try {
|
|
52
|
+
delegateAddress = sdk.addressFromKey(delegateKey);
|
|
53
|
+
} catch (err) {
|
|
186
54
|
throw new sdk.HavenSigningError(
|
|
187
|
-
|
|
55
|
+
`Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`
|
|
188
56
|
);
|
|
189
57
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
asset: raw.asset,
|
|
201
|
-
network: raw.network,
|
|
202
|
-
expiresAt: raw.expires_at,
|
|
203
|
-
auth: raw.auth
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
function createToolHandlers(signer, options = {}) {
|
|
58
|
+
const x402Bindings = /* @__PURE__ */ new Map();
|
|
59
|
+
function signAndVerify(hash) {
|
|
60
|
+
const signature = sdk.signHash(delegateKey, hash);
|
|
61
|
+
if (!sdk.verifySignature(hash, signature, delegateAddress)) {
|
|
62
|
+
throw new sdk.HavenSigningError(
|
|
63
|
+
"Local signature verification failed \u2014 recovered address does not match the delegate key."
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return signature;
|
|
67
|
+
}
|
|
207
68
|
return {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
69
|
+
delegateAddress,
|
|
70
|
+
signPaymentHash(hash) {
|
|
71
|
+
return signAndVerify(hash);
|
|
72
|
+
},
|
|
73
|
+
async signDelegationTypedData(typedData) {
|
|
74
|
+
const account = accounts.privateKeyToAccount(delegateKey);
|
|
75
|
+
return account.signTypedData(typedData);
|
|
76
|
+
},
|
|
77
|
+
signX402FundingHash(hash, expected) {
|
|
78
|
+
assertExpectedBinding(hash, expected, options.x402BindingSigner, "hash");
|
|
79
|
+
const signature = signAndVerify(hash);
|
|
80
|
+
const x402Binding = crypto.randomUUID();
|
|
81
|
+
x402Bindings.set(x402Binding, { ...expected });
|
|
82
|
+
return { signature, x402Binding };
|
|
83
|
+
},
|
|
84
|
+
async signX402FundingTypedData(typedData, expected) {
|
|
85
|
+
assertExpectedBinding(expected.payloadHash, expected, options.x402BindingSigner, "typed-data");
|
|
86
|
+
const digest = viem.hashTypedData(typedData);
|
|
87
|
+
if (digest.toLowerCase() !== expected.typedDataHash?.toLowerCase()) {
|
|
88
|
+
throw new sdk.HavenSigningError(
|
|
89
|
+
"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."
|
|
90
|
+
);
|
|
216
91
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
haven_x402_sign_header: async (input) => runTool(async () => {
|
|
221
|
-
const args = parse("haven_x402_sign_header", coercePaymentRequired(input));
|
|
222
|
-
const result = await signer.buildX402PaymentHeader(
|
|
223
|
-
args.payment_required,
|
|
224
|
-
args.x402_binding
|
|
225
|
-
);
|
|
226
|
-
await auditSigning(
|
|
227
|
-
"haven_x402_sign_header",
|
|
228
|
-
hashPayloadForAudit(args.payment_required)
|
|
229
|
-
);
|
|
230
|
-
return { payment_header: result.paymentHeader, accepted: result.accepted };
|
|
231
|
-
}),
|
|
232
|
-
haven_sign_x402: async (input) => runTool(async () => {
|
|
233
|
-
const args = parse("haven_sign_x402", coerceX402Expected(coercePaymentRequired(input)));
|
|
234
|
-
const funding = await signFundingLeg(
|
|
235
|
-
signer,
|
|
236
|
-
toExpectedX402(args.x402_expected),
|
|
237
|
-
args.payload_hash,
|
|
238
|
-
args.typed_data
|
|
92
|
+
const account = accounts.privateKeyToAccount(delegateKey);
|
|
93
|
+
const signature = await account.signTypedData(
|
|
94
|
+
typedData
|
|
239
95
|
);
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
|
|
96
|
+
const x402Binding = crypto.randomUUID();
|
|
97
|
+
x402Bindings.set(x402Binding, { ...expected });
|
|
98
|
+
return { signature, x402Binding };
|
|
99
|
+
},
|
|
100
|
+
async buildX402PaymentHeader(paymentRequired, x402Binding) {
|
|
101
|
+
const expected = x402Bindings.get(x402Binding);
|
|
102
|
+
if (!expected) {
|
|
103
|
+
throw new sdk.HavenSigningError(
|
|
104
|
+
"x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first."
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
assertX402PaymentWindowOpen(expected);
|
|
109
|
+
} catch (err) {
|
|
110
|
+
x402Bindings.delete(x402Binding);
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
const option = sdk.selectStandardPaymentOption(paymentRequired.accepts);
|
|
114
|
+
if (!option) {
|
|
115
|
+
throw new sdk.HavenApiError(
|
|
116
|
+
"No compatible payment option found in x402 requirements. Haven supports standard x402 exact payments on Base USDC.",
|
|
117
|
+
400
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
assertX402MatchesExpected(paymentRequired, option, expected);
|
|
121
|
+
const account = accounts.privateKeyToAccount(delegateKey);
|
|
122
|
+
const requirements = sdk.toStandardPaymentRequirements(paymentRequired, option);
|
|
123
|
+
const header = await schemes.exact.evm.createPaymentHeader(
|
|
124
|
+
account,
|
|
125
|
+
paymentRequired.x402Version,
|
|
126
|
+
requirements
|
|
243
127
|
);
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
128
|
+
if (paymentRequired.x402Version < 2) {
|
|
129
|
+
x402Bindings.delete(x402Binding);
|
|
130
|
+
return { paymentHeader: header, accepted: option };
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const payment = sdk.decodeBase64Json(header);
|
|
134
|
+
const wrapped = sdk.encodeBase64Json({
|
|
135
|
+
x402Version: paymentRequired.x402Version,
|
|
136
|
+
accepted: option,
|
|
137
|
+
payload: payment.payload
|
|
138
|
+
});
|
|
139
|
+
return { paymentHeader: wrapped, accepted: option };
|
|
140
|
+
} finally {
|
|
141
|
+
x402Bindings.delete(x402Binding);
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
async signSweepAuthorization({
|
|
145
|
+
authorization,
|
|
146
|
+
expectedAuth,
|
|
147
|
+
expectedSafe
|
|
148
|
+
}) {
|
|
149
|
+
assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner);
|
|
150
|
+
if (!sameAddress(authorization.from, delegateAddress)) {
|
|
151
|
+
throw new sdk.HavenSigningError(
|
|
152
|
+
"Sweep authorization `from` does not match this delegate address."
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {
|
|
156
|
+
throw new sdk.HavenSigningError(
|
|
157
|
+
"Sweep authorization `to` does not match the Safe in the local credential."
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
const typedData = sdk.buildSweepTypedData(authorization);
|
|
161
|
+
const viemTypedData = {
|
|
162
|
+
domain: {
|
|
163
|
+
...typedData.domain,
|
|
164
|
+
verifyingContract: typedData.domain.verifyingContract
|
|
165
|
+
},
|
|
166
|
+
types: typedData.types,
|
|
167
|
+
primaryType: typedData.primaryType,
|
|
168
|
+
message: {
|
|
169
|
+
...typedData.message,
|
|
170
|
+
from: typedData.message.from,
|
|
171
|
+
to: typedData.message.to,
|
|
172
|
+
nonce: typedData.message.nonce
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const account = accounts.privateKeyToAccount(delegateKey);
|
|
176
|
+
const signature = await account.signTypedData(viemTypedData);
|
|
177
|
+
const recovered = await viem.recoverTypedDataAddress({ ...viemTypedData, signature });
|
|
178
|
+
if (!sameAddress(recovered, delegateAddress)) {
|
|
179
|
+
throw new sdk.HavenSigningError(
|
|
180
|
+
"Local sweep signature verification failed \u2014 recovered address does not match the delegate key."
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return { signature };
|
|
184
|
+
}
|
|
267
185
|
};
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
auditPath
|
|
186
|
+
}
|
|
187
|
+
function assertSweepBinding(authorization, expectedAuth, trustedSigner) {
|
|
188
|
+
if (!expectedAuth || typeof expectedAuth !== "object") {
|
|
189
|
+
throw new sdk.HavenSigningError("Sweep authorization binding is required before signing.");
|
|
190
|
+
}
|
|
191
|
+
if (!trustedSigner) {
|
|
192
|
+
throw new sdk.HavenSigningError(
|
|
193
|
+
"Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations."
|
|
277
194
|
);
|
|
278
195
|
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
if (typeof value === "string") {
|
|
288
|
-
try {
|
|
289
|
-
value = JSON.parse(value);
|
|
290
|
-
} catch {
|
|
291
|
-
return input;
|
|
292
|
-
}
|
|
196
|
+
assertSupportedBindingVersion(
|
|
197
|
+
expectedAuth.version,
|
|
198
|
+
SUPPORTED_SWEEP_BINDING_VERSIONS,
|
|
199
|
+
"sweep authorization binding"
|
|
200
|
+
);
|
|
201
|
+
const message = sdk.buildSweepAuthorizationMessage(authorization);
|
|
202
|
+
if (expectedAuth.message !== message) {
|
|
203
|
+
throw new sdk.HavenSigningError("Sweep authorization binding does not match the authorization being signed.");
|
|
293
204
|
}
|
|
294
|
-
if (!
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
205
|
+
if (!sameAddress(expectedAuth.signer, trustedSigner)) {
|
|
206
|
+
throw new sdk.HavenSigningError("Sweep authorization binding was not signed by the configured Haven signer.");
|
|
207
|
+
}
|
|
208
|
+
if (!sdk.verifySignature(viem.hashMessage(message), expectedAuth.signature, trustedSigner)) {
|
|
209
|
+
throw new sdk.HavenSigningError("Sweep authorization binding signature could not be verified.");
|
|
298
210
|
}
|
|
299
|
-
if (value !== record.x402_expected) return { ...record, x402_expected: value };
|
|
300
|
-
return input;
|
|
301
211
|
}
|
|
302
|
-
function
|
|
303
|
-
|
|
304
|
-
const
|
|
305
|
-
if (
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
212
|
+
function assertX402MatchesExpected(paymentRequired, option, expected) {
|
|
213
|
+
assertExpectedShape(expected);
|
|
214
|
+
const headerResource = option.resource ?? paymentRequired.resource.url;
|
|
215
|
+
if (headerResource !== expected.resourceUrl) {
|
|
216
|
+
throw new sdk.HavenSigningError("x402 payment_required resource does not match the funded intent.");
|
|
217
|
+
}
|
|
218
|
+
if (!sameAddress(option.payTo, expected.merchantTo)) {
|
|
219
|
+
throw new sdk.HavenSigningError("x402 merchant recipient does not match the funded intent.");
|
|
220
|
+
}
|
|
221
|
+
if (sdk.x402AuthorizationAmount(option) !== expected.amount) {
|
|
222
|
+
throw new sdk.HavenSigningError("x402 amount does not match the funded intent.");
|
|
223
|
+
}
|
|
224
|
+
if (!sameAddress(option.asset, expected.asset)) {
|
|
225
|
+
throw new sdk.HavenSigningError("x402 asset does not match the funded intent.");
|
|
226
|
+
}
|
|
227
|
+
if (option.network !== expected.network) {
|
|
228
|
+
throw new sdk.HavenSigningError("x402 network does not match the funded intent.");
|
|
310
229
|
}
|
|
311
230
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
} catch (err) {
|
|
316
|
-
return normalizeError(err);
|
|
231
|
+
function assertExpectedShape(expected) {
|
|
232
|
+
if (!expected || typeof expected !== "object") {
|
|
233
|
+
throw new sdk.HavenSigningError("x402 expected funding context is required before signing a merchant header.");
|
|
317
234
|
}
|
|
318
235
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
}
|
|
236
|
+
var SUPPORTED_X402_EXPECTED_VERSIONS = [1, 2];
|
|
237
|
+
var SUPPORTED_SWEEP_BINDING_VERSIONS = [1];
|
|
238
|
+
function assertSupportedBindingVersion(received, supported, context) {
|
|
239
|
+
if (supported.includes(received)) return;
|
|
240
|
+
const highest = Math.max(...supported);
|
|
241
|
+
const ceiling = received > highest ? `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 (\`npx @haven_ai/connect@alpha\`), which reinstalls the pinned MCP runtime.` : `Unsupported ${context} version ${received}: this signer supports ${supported.join(", ")}.`;
|
|
242
|
+
throw new sdk.HavenSigningError(
|
|
243
|
+
`${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 authorised.`
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
function assertExpectedBinding(payloadHash, expected, trustedSigner, mode = "hash") {
|
|
247
|
+
assertExpectedShape(expected);
|
|
248
|
+
if (!trustedSigner) {
|
|
249
|
+
throw new sdk.HavenSigningError(
|
|
250
|
+
"x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding hashes."
|
|
251
|
+
);
|
|
327
252
|
}
|
|
328
|
-
if (
|
|
329
|
-
|
|
253
|
+
if (expected.auth) {
|
|
254
|
+
assertSupportedBindingVersion(
|
|
255
|
+
expected.auth.version,
|
|
256
|
+
SUPPORTED_X402_EXPECTED_VERSIONS,
|
|
257
|
+
"x402 expected context"
|
|
258
|
+
);
|
|
330
259
|
}
|
|
331
|
-
if (
|
|
332
|
-
|
|
260
|
+
if (expected.payloadHash.toLowerCase() !== payloadHash.toLowerCase()) {
|
|
261
|
+
throw new sdk.HavenSigningError("x402 expected context does not match the funding hash being signed.");
|
|
333
262
|
}
|
|
334
|
-
if (
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
message: err.message,
|
|
339
|
-
statusCode: err.statusCode,
|
|
340
|
-
paymentId: err.paymentId,
|
|
341
|
-
...err.code === sdk.AgentPaymentFailureCode.PaymentWindowExpired ? {
|
|
342
|
-
next_action: sdk.AgentPaymentNextAction.PaymentWindowExpired,
|
|
343
|
-
retry_with_new_quote: true,
|
|
344
|
-
suggested_tool: "haven_pay_mcp_tool"
|
|
345
|
-
} : {}
|
|
346
|
-
};
|
|
263
|
+
if (mode === "hash" && expected.typedDataHash) {
|
|
264
|
+
throw new sdk.HavenSigningError(
|
|
265
|
+
"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."
|
|
266
|
+
);
|
|
347
267
|
}
|
|
268
|
+
if (mode === "typed-data" && !expected.typedDataHash) {
|
|
269
|
+
throw new sdk.HavenSigningError(
|
|
270
|
+
"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."
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
const message = sdk.buildX402ExpectedMessage({
|
|
274
|
+
paymentId: expected.paymentId,
|
|
275
|
+
payloadHash: expected.payloadHash,
|
|
276
|
+
resourceUrl: expected.resourceUrl,
|
|
277
|
+
merchantTo: expected.merchantTo,
|
|
278
|
+
amount: expected.amount,
|
|
279
|
+
asset: expected.asset,
|
|
280
|
+
network: expected.network,
|
|
281
|
+
expiresAt: expected.expiresAt,
|
|
282
|
+
typedDataHash: expected.typedDataHash
|
|
283
|
+
});
|
|
284
|
+
const expectedVersion = expected.typedDataHash ? 2 : 1;
|
|
285
|
+
if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {
|
|
286
|
+
throw new sdk.HavenSigningError("x402 expected context authentication message is invalid.");
|
|
287
|
+
}
|
|
288
|
+
if (!sameAddress(expected.auth.signer, trustedSigner)) {
|
|
289
|
+
throw new sdk.HavenSigningError("x402 expected context was not signed by the configured Haven signer.");
|
|
290
|
+
}
|
|
291
|
+
if (!sdk.verifySignature(viem.hashMessage(message), expected.auth.signature, trustedSigner)) {
|
|
292
|
+
throw new sdk.HavenSigningError("x402 expected context signature could not be verified.");
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function assertX402PaymentWindowOpen(expected) {
|
|
296
|
+
if (!expected.expiresAt) return;
|
|
297
|
+
const expiresAtMs = Date.parse(expected.expiresAt);
|
|
298
|
+
if (Number.isNaN(expiresAtMs)) {
|
|
299
|
+
throw new sdk.HavenSigningError("x402 expected context expiresAt is not a valid ISO timestamp.");
|
|
300
|
+
}
|
|
301
|
+
if (expiresAtMs <= Date.now()) {
|
|
302
|
+
throw new sdk.HavenError(
|
|
303
|
+
"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.",
|
|
304
|
+
sdk.AgentPaymentFailureCode.PaymentWindowExpired,
|
|
305
|
+
410,
|
|
306
|
+
expected.paymentId
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function sameAddress(a, b) {
|
|
311
|
+
return a.toLowerCase() === b.toLowerCase();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// src/capabilities.ts
|
|
315
|
+
var SIGNER_CAPABILITY_KEY = "haven/signer-compatibility";
|
|
316
|
+
function signerCompatibility() {
|
|
348
317
|
return {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
message: err instanceof Error ? err.message : String(err)
|
|
318
|
+
x402_expected_context_versions: [...SUPPORTED_X402_EXPECTED_VERSIONS],
|
|
319
|
+
sweep_binding_versions: [...SUPPORTED_SWEEP_BINDING_VERSIONS]
|
|
352
320
|
};
|
|
353
321
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
var SIGNER_ACK_ENV = "HAVEN_SIGNER_ACK";
|
|
357
|
-
function computeSignerConsentHash(input) {
|
|
358
|
-
const identity = [
|
|
359
|
-
input.delegateAddress.toLowerCase(),
|
|
360
|
-
(input.safeAddress ?? "").toLowerCase(),
|
|
361
|
-
input.agentId ?? "",
|
|
362
|
-
input.chainId ?? "",
|
|
363
|
-
input.network ?? ""
|
|
364
|
-
].join("|");
|
|
365
|
-
const toolCanonical = [...input.toolNames].sort().join(",");
|
|
366
|
-
return crypto.createHash("sha256").update(`${identity}
|
|
367
|
-
${toolCanonical}`).digest("hex").slice(0, 16);
|
|
322
|
+
function signerCapabilityAdvertisement() {
|
|
323
|
+
return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } };
|
|
368
324
|
}
|
|
369
|
-
function
|
|
370
|
-
const
|
|
325
|
+
function signerInstructions() {
|
|
326
|
+
const compatibility = signerCompatibility();
|
|
327
|
+
return [
|
|
328
|
+
"Haven edge signer: sign-only tools bound to the local delegate key. It never emits the",
|
|
329
|
+
"key. Its one network capability is an authenticated READ of a signing context from",
|
|
330
|
+
"Haven by payment_id \u2014 pass payment_id to haven_sign / haven_sign_x402 (preferred for",
|
|
331
|
+
"delegation-rail x402) instead of relaying bulky typed-data payloads yourself.",
|
|
371
332
|
"",
|
|
372
|
-
"
|
|
373
|
-
|
|
374
|
-
"
|
|
333
|
+
"Version compatibility (check this BEFORE signing, not after):",
|
|
334
|
+
`- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(", ")}`,
|
|
335
|
+
`- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(", ")}`,
|
|
375
336
|
"",
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
337
|
+
"Haven quote and prepare results report the expected-context version they will emit",
|
|
338
|
+
"(signer_compatibility.x402_expected_context_version). If that version is not in the list",
|
|
339
|
+
"above, this signer is out of date: STOP before signing, and tell the user to update",
|
|
340
|
+
"@haven_ai/signer by rerunning `npx @haven_ai/connect@alpha`, which reinstalls the pinned",
|
|
341
|
+
"MCP runtime. Do not edit the version field to a supported value \u2014 it is part of the",
|
|
342
|
+
"Haven-signed binding message, so changing it invalidates the signature."
|
|
343
|
+
].join("\n");
|
|
344
|
+
}
|
|
345
|
+
async function loadHavenIdentity(credentialsPath) {
|
|
346
|
+
if (!credentialsPath) return null;
|
|
347
|
+
try {
|
|
348
|
+
const raw = JSON.parse(
|
|
349
|
+
await promises.readFile(path.join(path.dirname(credentialsPath), "identity.json"), "utf8")
|
|
350
|
+
);
|
|
351
|
+
const apiKey = typeof raw.api_key === "string" ? raw.api_key : void 0;
|
|
352
|
+
const apiUrl = typeof raw.api_url === "string" ? raw.api_url : void 0;
|
|
353
|
+
if (!apiKey || !apiUrl) return null;
|
|
354
|
+
return { apiKey, apiUrl: apiUrl.replace(/\/+$/, "") };
|
|
355
|
+
} catch {
|
|
356
|
+
return null;
|
|
393
357
|
}
|
|
394
|
-
lines.push("");
|
|
395
|
-
lines.push("A local audit entry is appended for every signing operation. Audit entries");
|
|
396
|
-
lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
|
|
397
|
-
lines.push("signature, or x402 payment header.");
|
|
398
|
-
lines.push("");
|
|
399
|
-
lines.push(`Consent hash: ${hash}`);
|
|
400
|
-
lines.push("");
|
|
401
|
-
lines.push("To acknowledge, EITHER:");
|
|
402
|
-
lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`);
|
|
403
|
-
lines.push(" - re-run with --ack to write the acknowledgement next to your");
|
|
404
|
-
lines.push(" credential file (sidecar <credentials>.signer-ack.json).");
|
|
405
|
-
lines.push("");
|
|
406
|
-
lines.push("------------------------------------------------------------");
|
|
407
|
-
lines.push("");
|
|
408
|
-
return lines.join("\n");
|
|
409
358
|
}
|
|
410
|
-
async function
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
Expected: ${hash}
|
|
421
|
-
Got: ${envAck}
|
|
422
|
-
Re-acknowledge with the new hash above, or run with --ack.
|
|
423
|
-
|
|
424
|
-
`
|
|
359
|
+
async function fetchX402SignContext(identity, paymentId, fetchImpl = fetch) {
|
|
360
|
+
let response;
|
|
361
|
+
try {
|
|
362
|
+
response = await fetchImpl(
|
|
363
|
+
`${identity.apiUrl}/x402/${encodeURIComponent(paymentId)}/sign-context`,
|
|
364
|
+
{ headers: { Authorization: `Bearer ${identity.apiKey}` } }
|
|
365
|
+
);
|
|
366
|
+
} catch (err) {
|
|
367
|
+
throw new sdk.HavenSigningError(
|
|
368
|
+
`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.`
|
|
425
369
|
);
|
|
426
|
-
return { ok: false, hash, reason: "env_var_mismatch" };
|
|
427
370
|
}
|
|
428
|
-
const
|
|
429
|
-
if (
|
|
430
|
-
const
|
|
431
|
-
|
|
371
|
+
const body = await response.json().catch(() => ({}));
|
|
372
|
+
if (!response.ok) {
|
|
373
|
+
const detail = typeof body.error === "string" ? body.error : `HTTP ${response.status}`;
|
|
374
|
+
throw new sdk.HavenSigningError(
|
|
375
|
+
`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." : "")
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
const signData = body.sign_data;
|
|
379
|
+
const x402Expected = body.x402_expected;
|
|
380
|
+
if (!signData || typeof signData.hash !== "string" || !signData.typed_data || typeof signData.typed_data !== "object" || !x402Expected) {
|
|
381
|
+
throw new sdk.HavenSigningError(
|
|
382
|
+
"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."
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
return {
|
|
386
|
+
paymentId: String(body.payment_id ?? paymentId),
|
|
387
|
+
payloadHash: signData.hash,
|
|
388
|
+
typedData: signData.typed_data,
|
|
389
|
+
x402Expected
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/tools.ts
|
|
394
|
+
var sweepAuthorizationSchema = v3.z.object({
|
|
395
|
+
from: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "from must be a 0x address"),
|
|
396
|
+
to: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "to must be a 0x address"),
|
|
397
|
+
value: v3.z.string().regex(/^[0-9]+$/, "value must be a decimal atomic amount"),
|
|
398
|
+
validAfter: v3.z.string().regex(/^[0-9]+$/, "validAfter must be a decimal unix time"),
|
|
399
|
+
validBefore: v3.z.string().regex(/^[0-9]+$/, "validBefore must be a decimal unix time"),
|
|
400
|
+
nonce: v3.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "nonce must be a 0x-prefixed 32-byte hex string"),
|
|
401
|
+
token: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "token must be a 0x address"),
|
|
402
|
+
chainId: v3.z.number().int().positive()
|
|
403
|
+
});
|
|
404
|
+
var bindingVersionSchema = v3.z.number().int().positive();
|
|
405
|
+
var sweepExpectedAuthSchema = v3.z.object({
|
|
406
|
+
version: bindingVersionSchema,
|
|
407
|
+
message: v3.z.string().min(1),
|
|
408
|
+
signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
|
|
409
|
+
signer: v3.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "signer must be a 0x address")
|
|
410
|
+
});
|
|
411
|
+
var x402ExpectedShape = {
|
|
412
|
+
payment_id: v3.z.string().min(1),
|
|
413
|
+
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string"),
|
|
414
|
+
resource_url: v3.z.string().url(),
|
|
415
|
+
merchant_to: v3.z.string().min(1),
|
|
416
|
+
amount: v3.z.string().min(1),
|
|
417
|
+
asset: v3.z.string().min(1),
|
|
418
|
+
network: v3.z.string().min(1),
|
|
419
|
+
// Required: expires_at is folded into the Haven-signed binding message, so the
|
|
420
|
+
// signer must receive the exact same value to reconstruct a matching message.
|
|
421
|
+
// Omitting it used to fail downstream with a cryptic "authentication message is
|
|
422
|
+
// invalid" — making it required surfaces a clear INVALID_INPUT at the boundary.
|
|
423
|
+
expires_at: v3.z.string().min(1),
|
|
424
|
+
// #1138: present on a delegation-rail (v2) context. It commits to the EIP-712
|
|
425
|
+
// typed data the account validates; the signer refuses to raw-sign the bare
|
|
426
|
+
// hash when it is present, and refuses to sign typed data when it is absent.
|
|
427
|
+
typed_data_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "typed_data_hash must be a 0x-prefixed hex string").optional(),
|
|
428
|
+
auth: v3.z.object({
|
|
429
|
+
// Open at the boundary, enforced in the signer — see bindingVersionSchema.
|
|
430
|
+
version: bindingVersionSchema,
|
|
431
|
+
message: v3.z.string().min(1),
|
|
432
|
+
signature: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "signature must be a 0x-prefixed hex string"),
|
|
433
|
+
signer: v3.z.string().min(1)
|
|
434
|
+
})
|
|
435
|
+
};
|
|
436
|
+
var x402ExpectedSchema = v3.z.object(x402ExpectedShape);
|
|
437
|
+
var toolSchemas = {
|
|
438
|
+
haven_sign_sweep_delegate: {
|
|
439
|
+
// The authorization fields prepared by Haven's POST /sweep/prepare. Passed
|
|
440
|
+
// through verbatim from the hosted haven_sweep_delegate tool — the signer
|
|
441
|
+
// re-derives the binding message from these exact values.
|
|
442
|
+
authorization: sweepAuthorizationSchema,
|
|
443
|
+
// Haven's signature over the authorization context (the binding).
|
|
444
|
+
expected_auth: sweepExpectedAuthSchema
|
|
445
|
+
},
|
|
446
|
+
haven_sign: {
|
|
447
|
+
// #1263: THE preferred x402 input — the signer fetches the exact signing
|
|
448
|
+
// payload + expected context from Haven itself (authenticated with the
|
|
449
|
+
// locally-stored agent credential), so no bulky bytes ever cross the
|
|
450
|
+
// model. Pass payment_id ALONE for a delegation-rail x402 funding intent.
|
|
451
|
+
payment_id: v3.z.string().min(1).optional(),
|
|
452
|
+
// The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).
|
|
453
|
+
// Optional when payment_id is supplied (the fetch carries it).
|
|
454
|
+
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string").optional(),
|
|
455
|
+
// Pass x402.expected from hosted haven_pay_x402_quote when this hash funds
|
|
456
|
+
// a standard x402 merchant retry. The signer records it locally and returns
|
|
457
|
+
// an opaque x402_binding for the later header-signing step.
|
|
458
|
+
x402_expected: x402ExpectedSchema.optional(),
|
|
459
|
+
// #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
|
|
460
|
+
// (not z.unknown()) so MCP clients embed it as JSON rather than a string.
|
|
461
|
+
typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
|
|
462
|
+
// #1255: the same payload as ONE opaque base64 string, exactly as returned
|
|
463
|
+
// by the hosted tools. Preferred over typed_data when both are present —
|
|
464
|
+
// an agent re-emitting multi-KB nested JSON between tool calls is the
|
|
465
|
+
// failure mode this field removes (a truncated/reshaped payload fails the
|
|
466
|
+
// digest check and the payment refuses, correctly but pointlessly).
|
|
467
|
+
// Bounded: a realistic redemption payload is ~10KB encoded; 256KB is
|
|
468
|
+
// generous headroom while keeping the offline signer from materializing
|
|
469
|
+
// arbitrarily large caller input.
|
|
470
|
+
typed_data_b64: v3.z.string().min(1).max(262144).optional()
|
|
471
|
+
},
|
|
472
|
+
haven_x402_sign_header: {
|
|
473
|
+
// The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object
|
|
474
|
+
// (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients
|
|
475
|
+
// embed it as JSON rather than serialising the object to a string.
|
|
476
|
+
payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
|
|
477
|
+
// Opaque binding returned by haven_sign when x402_expected was supplied.
|
|
478
|
+
x402_binding: v3.z.string().min(1)
|
|
479
|
+
},
|
|
480
|
+
haven_sign_x402: {
|
|
481
|
+
// #1263: preferred — pass payment_id (plus payment_required) and the
|
|
482
|
+
// signer fetches the exact signing payload + expected context itself.
|
|
483
|
+
payment_id: v3.z.string().min(1).optional(),
|
|
484
|
+
// One-shot x402 signing: funding hash + merchant header in one local call.
|
|
485
|
+
// Both optional when payment_id is supplied (the fetch carries them).
|
|
486
|
+
payload_hash: v3.z.string().regex(/^0x[0-9a-fA-F]+$/, "payload_hash must be a 0x-prefixed hex string").optional(),
|
|
487
|
+
x402_expected: x402ExpectedSchema.optional(),
|
|
488
|
+
payment_required: v3.z.record(v3.z.string(), v3.z.unknown()),
|
|
489
|
+
// #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed
|
|
490
|
+
// (not z.unknown()) so MCP clients embed it as JSON rather than a string.
|
|
491
|
+
typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
|
|
492
|
+
// #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.
|
|
493
|
+
typed_data_b64: v3.z.string().min(1).max(262144).optional()
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
var SIGN_DESCRIPTION = [
|
|
497
|
+
"Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves",
|
|
498
|
+
"this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.",
|
|
499
|
+
"For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally",
|
|
500
|
+
"and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that",
|
|
501
|
+
"window closes. DELEGATION-RAIL x402 accounts (#1263): pass payment_id ALONE (preferred) \u2014 this",
|
|
502
|
+
"signer fetches the exact signing payload and expected context from Haven itself, so nothing",
|
|
503
|
+
"bulky ever crosses your context. Fallback: pass typed_data_b64 through UNCHANGED (never re-type",
|
|
504
|
+
"the nested typed_data JSON); the account validates that EIP-712 payload, not payload_hash.",
|
|
505
|
+
"Next: call mcp__haven__haven_submit with signature, then pass x402_binding",
|
|
506
|
+
"to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and",
|
|
507
|
+
"relay the returned signature via mcp__haven__haven_submit."
|
|
508
|
+
].join(" ");
|
|
509
|
+
var X402_SIGN_HEADER_DESCRIPTION = [
|
|
510
|
+
"Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment.",
|
|
511
|
+
"The delegate key stays local \u2014 only the signed header crosses any boundary.",
|
|
512
|
+
"Pass the payment_required from the original merchant 402 response and the x402_binding",
|
|
513
|
+
"returned by haven_sign. The signer validates the merchant, amount, resource, asset, and",
|
|
514
|
+
"network against the recorded funding context before signing, checks expires_at when present,",
|
|
515
|
+
"and rejects mismatches or expired payment windows.",
|
|
516
|
+
"Returns { payment_header, accepted }. Set X-PAYMENT: <payment_header> on your retry to the",
|
|
517
|
+
"merchant. Only call after haven_submit has confirmed the funding step (nextAction=none or",
|
|
518
|
+
"the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
|
|
519
|
+
].join(" ");
|
|
520
|
+
var SIGN_X402_DESCRIPTION = [
|
|
521
|
+
"One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009",
|
|
522
|
+
"X-PAYMENT header in a single local call (equivalent to haven_sign followed by",
|
|
523
|
+
"haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool",
|
|
524
|
+
"result pass payment_id and payment_required \u2014 PREFERRED (#1263): this signer fetches the exact",
|
|
525
|
+
"signing payload and expected context from Haven itself, so nothing bulky crosses your context.",
|
|
526
|
+
"Fallback for older backends: pass payload_hash, x402_expected (the nested x402.expected object \u2014",
|
|
527
|
+
"passing the whole x402 object is also accepted and unwrapped for you), and typed_data_b64",
|
|
528
|
+
"through UNCHANGED; the signer",
|
|
529
|
+
"signs the typed data instead of payload_hash and refuses the bare hash when the context commits to typed data.",
|
|
530
|
+
"Returns",
|
|
531
|
+
"{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to",
|
|
532
|
+
"mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before",
|
|
533
|
+
"funding confirms), so its short validity window starts here \u2014 call mcp__haven__haven_settle_mcp_tool promptly,",
|
|
534
|
+
"and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.",
|
|
535
|
+
"Next: call mcp__haven__haven_settle_mcp_tool."
|
|
536
|
+
].join(" ");
|
|
537
|
+
var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
|
|
538
|
+
"Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
|
|
539
|
+
"wallet back to your Haven wallet. The delegate key never leaves this process and this tool",
|
|
540
|
+
"never broadcasts \u2014 it returns only an EIP-3009 signature that Haven's relayer submits and",
|
|
541
|
+
"pays gas for. Pass the authorization and expected_auth returned by the hosted",
|
|
542
|
+
"haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it",
|
|
543
|
+
"pays out to your own Safe before signing, then returns { signature } to hand back to",
|
|
544
|
+
"mcp__haven__haven_sweep_delegate to complete recovery."
|
|
545
|
+
].join(" ");
|
|
546
|
+
var toolDescriptions = {
|
|
547
|
+
haven_sign: SIGN_DESCRIPTION,
|
|
548
|
+
haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
|
|
549
|
+
haven_sign_x402: SIGN_X402_DESCRIPTION,
|
|
550
|
+
haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
|
|
551
|
+
};
|
|
552
|
+
async function signFundingLeg(signer, expected, payloadHash, typedData) {
|
|
553
|
+
if (!expected.typedDataHash) {
|
|
554
|
+
return signer.signX402FundingHash(payloadHash, expected);
|
|
432
555
|
}
|
|
433
|
-
if (
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
`);
|
|
439
|
-
return { ok: true, hash, reason: "wrote_ack_file" };
|
|
556
|
+
if (!typedData) {
|
|
557
|
+
throw new sdk.HavenSigningError(
|
|
558
|
+
"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."
|
|
559
|
+
);
|
|
440
560
|
}
|
|
441
|
-
|
|
442
|
-
return { ok: false, hash, reason: "no_acknowledgement" };
|
|
443
|
-
}
|
|
444
|
-
function registeredSignerToolNames() {
|
|
445
|
-
return Object.keys(toolSchemas);
|
|
561
|
+
return signer.signX402FundingTypedData(typedData, expected);
|
|
446
562
|
}
|
|
447
|
-
function
|
|
448
|
-
|
|
449
|
-
|
|
563
|
+
function toExpectedX402(raw) {
|
|
564
|
+
return {
|
|
565
|
+
paymentId: raw.payment_id,
|
|
566
|
+
payloadHash: raw.payload_hash,
|
|
567
|
+
typedDataHash: raw.typed_data_hash,
|
|
568
|
+
resourceUrl: raw.resource_url,
|
|
569
|
+
merchantTo: raw.merchant_to,
|
|
570
|
+
amount: raw.amount,
|
|
571
|
+
asset: raw.asset,
|
|
572
|
+
network: raw.network,
|
|
573
|
+
expiresAt: raw.expires_at,
|
|
574
|
+
auth: raw.auth
|
|
575
|
+
};
|
|
450
576
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
return null;
|
|
577
|
+
function parseFetchedExpected(fetched) {
|
|
578
|
+
const parsed = v3.z.object(x402ExpectedShape).safeParse(fetched.x402Expected);
|
|
579
|
+
if (!parsed.success) {
|
|
580
|
+
throw new sdk.HavenSigningError(
|
|
581
|
+
`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"}`
|
|
582
|
+
);
|
|
458
583
|
}
|
|
584
|
+
return parsed.data;
|
|
459
585
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
await promises.writeFile(
|
|
463
|
-
path$1,
|
|
464
|
-
JSON.stringify({ ack: hash, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
|
|
465
|
-
"utf8"
|
|
466
|
-
);
|
|
467
|
-
}
|
|
468
|
-
function createEdgeSigner(delegateKey, options = {}) {
|
|
469
|
-
let delegateAddress;
|
|
586
|
+
function resolveTypedData(args) {
|
|
587
|
+
if (!args.typed_data_b64) return args.typed_data;
|
|
470
588
|
try {
|
|
471
|
-
|
|
589
|
+
const decoded = JSON.parse(
|
|
590
|
+
Buffer.from(args.typed_data_b64, "base64").toString("utf8")
|
|
591
|
+
);
|
|
592
|
+
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) {
|
|
593
|
+
throw new Error("decoded value is not an object");
|
|
594
|
+
}
|
|
595
|
+
return decoded;
|
|
472
596
|
} catch (err) {
|
|
473
597
|
throw new sdk.HavenSigningError(
|
|
474
|
-
`
|
|
598
|
+
`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)}`
|
|
475
599
|
);
|
|
476
600
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
if (!
|
|
601
|
+
}
|
|
602
|
+
function createToolHandlers(signer, options = {}) {
|
|
603
|
+
async function resolveSignContext(args) {
|
|
604
|
+
if (!args.payment_id) return null;
|
|
605
|
+
const identity = await options.signContext?.loadIdentity() ?? null;
|
|
606
|
+
if (!identity) {
|
|
481
607
|
throw new sdk.HavenSigningError(
|
|
482
|
-
"
|
|
608
|
+
"payment_id signing needs the agent identity (identity.json next to the signer credentials), which this signer could not load. Re-run `npx @haven_ai/connect@alpha` to restore it, or pass typed_data_b64 from the quote result instead."
|
|
483
609
|
);
|
|
484
610
|
}
|
|
485
|
-
|
|
611
|
+
const ctx = await fetchX402SignContext(
|
|
612
|
+
identity,
|
|
613
|
+
args.payment_id,
|
|
614
|
+
options.signContext?.fetchImpl
|
|
615
|
+
);
|
|
616
|
+
if (args.payload_hash && args.payload_hash.toLowerCase() !== ctx.payloadHash.toLowerCase()) {
|
|
617
|
+
throw new sdk.HavenSigningError(
|
|
618
|
+
`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.`
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
return ctx;
|
|
486
622
|
}
|
|
487
623
|
return {
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
const signature = signAndVerify(hash);
|
|
495
|
-
const x402Binding = crypto.randomUUID();
|
|
496
|
-
x402Bindings.set(x402Binding, { ...expected });
|
|
497
|
-
return { signature, x402Binding };
|
|
498
|
-
},
|
|
499
|
-
async signX402FundingTypedData(typedData, expected) {
|
|
500
|
-
assertExpectedBinding(expected.payloadHash, expected, options.x402BindingSigner, "typed-data");
|
|
501
|
-
const digest = viem.hashTypedData(typedData);
|
|
502
|
-
if (digest.toLowerCase() !== expected.typedDataHash?.toLowerCase()) {
|
|
503
|
-
throw new sdk.HavenSigningError(
|
|
504
|
-
"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."
|
|
505
|
-
);
|
|
506
|
-
}
|
|
507
|
-
const account = accounts.privateKeyToAccount(delegateKey);
|
|
508
|
-
const signature = await account.signTypedData(
|
|
509
|
-
typedData
|
|
510
|
-
);
|
|
511
|
-
const x402Binding = crypto.randomUUID();
|
|
512
|
-
x402Bindings.set(x402Binding, { ...expected });
|
|
513
|
-
return { signature, x402Binding };
|
|
514
|
-
},
|
|
515
|
-
async buildX402PaymentHeader(paymentRequired, x402Binding) {
|
|
516
|
-
const expected = x402Bindings.get(x402Binding);
|
|
517
|
-
if (!expected) {
|
|
624
|
+
haven_sign: async (input) => runTool(async () => {
|
|
625
|
+
const args = parse("haven_sign", coerceX402Expected(input));
|
|
626
|
+
const fetched = await resolveSignContext(args);
|
|
627
|
+
const typedData = fetched?.typedData ?? resolveTypedData(args);
|
|
628
|
+
const payloadHash = fetched?.payloadHash ?? args.payload_hash;
|
|
629
|
+
if (!payloadHash) {
|
|
518
630
|
throw new sdk.HavenSigningError(
|
|
519
|
-
"
|
|
631
|
+
"Pass payment_id (preferred for delegation-rail x402) or payload_hash."
|
|
520
632
|
);
|
|
521
633
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
634
|
+
const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected;
|
|
635
|
+
const x402Expected = expectedRaw ? toExpectedX402(expectedRaw) : null;
|
|
636
|
+
const result = x402Expected ? await signFundingLeg(signer, x402Expected, payloadHash, typedData) : null;
|
|
637
|
+
if (!result) {
|
|
638
|
+
if (typedData) {
|
|
639
|
+
const signature2 = await signer.signDelegationTypedData(typedData);
|
|
640
|
+
await auditSigning("haven_sign", payloadHash);
|
|
641
|
+
return { signature: signature2 };
|
|
642
|
+
}
|
|
643
|
+
const signature = signer.signPaymentHash(payloadHash);
|
|
644
|
+
await auditSigning("haven_sign", payloadHash);
|
|
645
|
+
return { signature };
|
|
534
646
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
647
|
+
await auditSigning("haven_sign", payloadHash);
|
|
648
|
+
return { signature: result.signature, x402_binding: result.x402Binding };
|
|
649
|
+
}),
|
|
650
|
+
haven_x402_sign_header: async (input) => runTool(async () => {
|
|
651
|
+
const args = parse("haven_x402_sign_header", coercePaymentRequired(input));
|
|
652
|
+
const result = await signer.buildX402PaymentHeader(
|
|
653
|
+
args.payment_required,
|
|
654
|
+
args.x402_binding
|
|
542
655
|
);
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
} finally {
|
|
556
|
-
x402Bindings.delete(x402Binding);
|
|
557
|
-
}
|
|
558
|
-
},
|
|
559
|
-
async signSweepAuthorization({
|
|
560
|
-
authorization,
|
|
561
|
-
expectedAuth,
|
|
562
|
-
expectedSafe
|
|
563
|
-
}) {
|
|
564
|
-
assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner);
|
|
565
|
-
if (!sameAddress(authorization.from, delegateAddress)) {
|
|
566
|
-
throw new sdk.HavenSigningError(
|
|
567
|
-
"Sweep authorization `from` does not match this delegate address."
|
|
568
|
-
);
|
|
569
|
-
}
|
|
570
|
-
if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {
|
|
656
|
+
await auditSigning(
|
|
657
|
+
"haven_x402_sign_header",
|
|
658
|
+
hashPayloadForAudit(args.payment_required)
|
|
659
|
+
);
|
|
660
|
+
return { payment_header: result.paymentHeader, accepted: result.accepted };
|
|
661
|
+
}),
|
|
662
|
+
haven_sign_x402: async (input) => runTool(async () => {
|
|
663
|
+
const args = parse("haven_sign_x402", coerceX402Expected(coercePaymentRequired(input)));
|
|
664
|
+
const fetched = await resolveSignContext(args);
|
|
665
|
+
const payloadHash = fetched?.payloadHash ?? args.payload_hash;
|
|
666
|
+
const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected;
|
|
667
|
+
if (!payloadHash || !expectedRaw) {
|
|
571
668
|
throw new sdk.HavenSigningError(
|
|
572
|
-
"
|
|
669
|
+
"Pass payment_id (preferred \u2014 the signer fetches the signing context itself) or payload_hash + x402_expected from the quote result."
|
|
573
670
|
);
|
|
574
671
|
}
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
672
|
+
const funding = await signFundingLeg(
|
|
673
|
+
signer,
|
|
674
|
+
toExpectedX402(expectedRaw),
|
|
675
|
+
payloadHash,
|
|
676
|
+
fetched?.typedData ?? resolveTypedData(args)
|
|
677
|
+
);
|
|
678
|
+
const header = await signer.buildX402PaymentHeader(
|
|
679
|
+
args.payment_required,
|
|
680
|
+
funding.x402Binding
|
|
681
|
+
);
|
|
682
|
+
await auditSigning("haven_sign_x402", payloadHash);
|
|
683
|
+
await auditSigning("haven_sign_x402", hashPayloadForAudit(args.payment_required));
|
|
684
|
+
return {
|
|
685
|
+
signature: funding.signature,
|
|
686
|
+
x402_binding: funding.x402Binding,
|
|
687
|
+
payment_header: header.paymentHeader,
|
|
688
|
+
accepted: header.accepted
|
|
589
689
|
};
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
690
|
+
}),
|
|
691
|
+
haven_sign_sweep_delegate: async (input) => runTool(async () => {
|
|
692
|
+
const args = parse("haven_sign_sweep_delegate", input);
|
|
693
|
+
const result = await signer.signSweepAuthorization({
|
|
694
|
+
authorization: args.authorization,
|
|
695
|
+
expectedAuth: args.expected_auth,
|
|
696
|
+
// Cross-check `to` against the Safe in the local credential when present.
|
|
697
|
+
expectedSafe: options.audit?.safeAddress
|
|
698
|
+
});
|
|
699
|
+
await auditSigning(
|
|
700
|
+
"haven_sign_sweep_delegate",
|
|
701
|
+
hashPayloadForAudit(args.authorization)
|
|
702
|
+
);
|
|
703
|
+
return { signature: result.signature };
|
|
704
|
+
})
|
|
600
705
|
};
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
706
|
+
async function auditSigning(tool, payloadHash) {
|
|
707
|
+
if (!options.audit) return;
|
|
708
|
+
const { auditPath, ...context } = options.audit;
|
|
709
|
+
await appendSigningAuditEntry(
|
|
710
|
+
createSigningAuditEntry(tool, payloadHash, {
|
|
711
|
+
...context,
|
|
712
|
+
delegateAddress: signer.delegateAddress
|
|
713
|
+
}),
|
|
714
|
+
auditPath
|
|
609
715
|
);
|
|
610
716
|
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
717
|
+
}
|
|
718
|
+
function parse(name, input) {
|
|
719
|
+
return v3.z.object(toolSchemas[name]).parse(input ?? {});
|
|
720
|
+
}
|
|
721
|
+
function coerceX402Expected(input) {
|
|
722
|
+
if (!input || typeof input !== "object") return input;
|
|
723
|
+
const record = input;
|
|
724
|
+
let value = record.x402_expected;
|
|
725
|
+
if (typeof value === "string") {
|
|
726
|
+
try {
|
|
727
|
+
value = JSON.parse(value);
|
|
728
|
+
} catch {
|
|
729
|
+
return input;
|
|
730
|
+
}
|
|
622
731
|
}
|
|
623
|
-
if (!
|
|
624
|
-
|
|
732
|
+
if (!value || typeof value !== "object") return input;
|
|
733
|
+
const obj = value;
|
|
734
|
+
if (obj.auth === void 0 && obj.expected && typeof obj.expected === "object") {
|
|
735
|
+
return { ...record, x402_expected: obj.expected };
|
|
625
736
|
}
|
|
737
|
+
if (value !== record.x402_expected) return { ...record, x402_expected: value };
|
|
738
|
+
return input;
|
|
626
739
|
}
|
|
627
|
-
function
|
|
628
|
-
|
|
629
|
-
const
|
|
630
|
-
if (
|
|
631
|
-
|
|
740
|
+
function coercePaymentRequired(input) {
|
|
741
|
+
if (!input || typeof input !== "object") return input;
|
|
742
|
+
const record = input;
|
|
743
|
+
if (typeof record.payment_required !== "string") return input;
|
|
744
|
+
try {
|
|
745
|
+
return { ...record, payment_required: JSON.parse(record.payment_required) };
|
|
746
|
+
} catch {
|
|
747
|
+
return input;
|
|
632
748
|
}
|
|
633
|
-
|
|
634
|
-
|
|
749
|
+
}
|
|
750
|
+
async function runTool(fn) {
|
|
751
|
+
try {
|
|
752
|
+
return { success: true, data: await fn() };
|
|
753
|
+
} catch (err) {
|
|
754
|
+
return normalizeError(err);
|
|
635
755
|
}
|
|
636
|
-
|
|
637
|
-
|
|
756
|
+
}
|
|
757
|
+
function normalizeError(err) {
|
|
758
|
+
if (err instanceof v3.z.ZodError) {
|
|
759
|
+
return {
|
|
760
|
+
success: false,
|
|
761
|
+
code: "INVALID_INPUT",
|
|
762
|
+
message: err.errors.map((e) => `${e.path.join(".") || "(root)"}: ${e.message}`).join("; "),
|
|
763
|
+
statusCode: 400
|
|
764
|
+
};
|
|
638
765
|
}
|
|
639
|
-
if (
|
|
640
|
-
|
|
766
|
+
if (err instanceof sdk.HavenSigningError) {
|
|
767
|
+
return { success: false, code: err.code, message: err.message };
|
|
641
768
|
}
|
|
642
|
-
if (
|
|
643
|
-
|
|
769
|
+
if (err instanceof sdk.HavenApiError) {
|
|
770
|
+
return { success: false, code: err.code, message: err.message, statusCode: err.statusCode };
|
|
644
771
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
772
|
+
if (err instanceof sdk.HavenError) {
|
|
773
|
+
return {
|
|
774
|
+
success: false,
|
|
775
|
+
code: err.code,
|
|
776
|
+
message: err.message,
|
|
777
|
+
statusCode: err.statusCode,
|
|
778
|
+
paymentId: err.paymentId,
|
|
779
|
+
...err.code === sdk.AgentPaymentFailureCode.PaymentWindowExpired ? {
|
|
780
|
+
next_action: sdk.AgentPaymentNextAction.PaymentWindowExpired,
|
|
781
|
+
retry_with_new_quote: true,
|
|
782
|
+
suggested_tool: "haven_pay_mcp_tool"
|
|
783
|
+
} : {}
|
|
784
|
+
};
|
|
649
785
|
}
|
|
786
|
+
return {
|
|
787
|
+
success: false,
|
|
788
|
+
code: "UNKNOWN_ERROR",
|
|
789
|
+
message: err instanceof Error ? err.message : String(err)
|
|
790
|
+
};
|
|
650
791
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
const
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
792
|
+
|
|
793
|
+
// src/consent.ts
|
|
794
|
+
var SIGNER_ACK_ENV = "HAVEN_SIGNER_ACK";
|
|
795
|
+
var SIGNER_CONSENT_SURFACE_VERSION = 2;
|
|
796
|
+
function computeSignerConsentHash(input) {
|
|
797
|
+
const identity = [
|
|
798
|
+
input.delegateAddress.toLowerCase(),
|
|
799
|
+
(input.safeAddress ?? "").toLowerCase(),
|
|
800
|
+
input.agentId ?? "",
|
|
801
|
+
input.chainId ?? "",
|
|
802
|
+
input.network ?? ""
|
|
803
|
+
].join("|");
|
|
804
|
+
const toolCanonical = [...input.toolNames].sort().join(",");
|
|
805
|
+
return crypto.createHash("sha256").update(`${identity}
|
|
806
|
+
${toolCanonical}
|
|
807
|
+
surface:v${SIGNER_CONSENT_SURFACE_VERSION}`).digest("hex").slice(0, 16);
|
|
660
808
|
}
|
|
661
|
-
function
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
809
|
+
function renderSignerConsentBlock(input, hash) {
|
|
810
|
+
const lines = [
|
|
811
|
+
"",
|
|
812
|
+
"------------------------------------------------------------",
|
|
813
|
+
"Haven edge signer - first-launch consent",
|
|
814
|
+
"------------------------------------------------------------",
|
|
815
|
+
"",
|
|
816
|
+
`Delegate address: ${input.delegateAddress}`
|
|
817
|
+
];
|
|
818
|
+
lines.push(`Haven wallet: ${input.safeAddress ?? "not provided to this signer"}`);
|
|
819
|
+
if (input.agentId) lines.push(`Agent ID: ${input.agentId}`);
|
|
820
|
+
if (typeof input.chainId === "number") lines.push(`Chain ID: ${input.chainId}`);
|
|
821
|
+
if (input.network) lines.push(`Network: ${input.network}`);
|
|
822
|
+
lines.push("");
|
|
823
|
+
lines.push("This local signer holds the delegate key on this machine and signs");
|
|
824
|
+
lines.push("payment payloads or x402 merchant headers for the delegate address above.");
|
|
825
|
+
lines.push("Its one network use is a read-only fetch of a pending payment's signing");
|
|
826
|
+
lines.push("payload from Haven, authenticated with the agent credential stored next to");
|
|
827
|
+
lines.push("this signer's key file - it never sends the key, a signature, or anything");
|
|
828
|
+
lines.push("else outbound, and it cannot show a live allowance summary.");
|
|
829
|
+
lines.push("On-chain Safe rules remain the real spend gate, and the wallet owner can");
|
|
830
|
+
lines.push("pause or revoke agent authority outside this signer.");
|
|
831
|
+
lines.push("");
|
|
832
|
+
lines.push("Tools this signer will expose to your agent runtime:");
|
|
833
|
+
for (const name of input.toolNames) {
|
|
834
|
+
lines.push(` - ${name}`);
|
|
835
|
+
lines.push(` ${toolDescriptions[name]}`);
|
|
682
836
|
}
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
837
|
+
lines.push("");
|
|
838
|
+
lines.push("A local audit entry is appended for every signing operation. Audit entries");
|
|
839
|
+
lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
|
|
840
|
+
lines.push("signature, or x402 payment header.");
|
|
841
|
+
lines.push("");
|
|
842
|
+
lines.push(`Consent hash: ${hash}`);
|
|
843
|
+
lines.push("");
|
|
844
|
+
lines.push("To acknowledge, EITHER:");
|
|
845
|
+
lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`);
|
|
846
|
+
lines.push(" - re-run with --ack to write the acknowledgement next to your");
|
|
847
|
+
lines.push(" credential file (sidecar <credentials>.signer-ack.json).");
|
|
848
|
+
lines.push("");
|
|
849
|
+
lines.push("------------------------------------------------------------");
|
|
850
|
+
lines.push("");
|
|
851
|
+
return lines.join("\n");
|
|
852
|
+
}
|
|
853
|
+
async function ensureSignerConsent(input, options = {}) {
|
|
854
|
+
const env = options.env ?? process.env;
|
|
855
|
+
const out = options.out ?? process.stderr;
|
|
856
|
+
const hash = computeSignerConsentHash(input);
|
|
857
|
+
const envAck = env[SIGNER_ACK_ENV];
|
|
858
|
+
if (typeof envAck === "string" && envAck.length > 0) {
|
|
859
|
+
if (envAck === hash) return { ok: true, hash, reason: "env_var_match" };
|
|
860
|
+
out.write(renderSignerConsentBlock(input, hash));
|
|
861
|
+
out.write(
|
|
862
|
+
`${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.
|
|
863
|
+
Expected: ${hash}
|
|
864
|
+
Got: ${envAck}
|
|
865
|
+
Re-acknowledge with the new hash above, or run with --ack.
|
|
866
|
+
|
|
867
|
+
`
|
|
686
868
|
);
|
|
869
|
+
return { ok: false, hash, reason: "env_var_mismatch" };
|
|
687
870
|
}
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
merchantTo: expected.merchantTo,
|
|
693
|
-
amount: expected.amount,
|
|
694
|
-
asset: expected.asset,
|
|
695
|
-
network: expected.network,
|
|
696
|
-
expiresAt: expected.expiresAt,
|
|
697
|
-
typedDataHash: expected.typedDataHash
|
|
698
|
-
});
|
|
699
|
-
const expectedVersion = expected.typedDataHash ? 2 : 1;
|
|
700
|
-
if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {
|
|
701
|
-
throw new sdk.HavenSigningError("x402 expected context authentication message is invalid.");
|
|
702
|
-
}
|
|
703
|
-
if (!sameAddress(expected.auth.signer, trustedSigner)) {
|
|
704
|
-
throw new sdk.HavenSigningError("x402 expected context was not signed by the configured Haven signer.");
|
|
871
|
+
const ackPath = sidecarPath(options.credentialsPath);
|
|
872
|
+
if (ackPath) {
|
|
873
|
+
const stored = await readAckFile(ackPath);
|
|
874
|
+
if (stored?.ack === hash) return { ok: true, hash, reason: "ack_file_match" };
|
|
705
875
|
}
|
|
706
|
-
if (
|
|
707
|
-
|
|
876
|
+
if (options.writeAck && ackPath) {
|
|
877
|
+
out.write(renderSignerConsentBlock(input, hash));
|
|
878
|
+
await writeAckFile(ackPath, hash);
|
|
879
|
+
out.write(`Wrote acknowledgement to ${ackPath}
|
|
880
|
+
|
|
881
|
+
`);
|
|
882
|
+
return { ok: true, hash, reason: "wrote_ack_file" };
|
|
708
883
|
}
|
|
884
|
+
out.write(renderSignerConsentBlock(input, hash));
|
|
885
|
+
return { ok: false, hash, reason: "no_acknowledgement" };
|
|
709
886
|
}
|
|
710
|
-
function
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
887
|
+
function registeredSignerToolNames() {
|
|
888
|
+
return Object.keys(toolSchemas);
|
|
889
|
+
}
|
|
890
|
+
function sidecarPath(credentialsPath) {
|
|
891
|
+
if (!credentialsPath) return null;
|
|
892
|
+
return path.resolve(`${credentialsPath}.signer-ack.json`);
|
|
893
|
+
}
|
|
894
|
+
async function readAckFile(path) {
|
|
895
|
+
try {
|
|
896
|
+
const raw = await promises.readFile(path, "utf8");
|
|
897
|
+
const parsed = JSON.parse(raw);
|
|
898
|
+
return { ack: typeof parsed.ack === "string" ? parsed.ack : void 0 };
|
|
899
|
+
} catch {
|
|
900
|
+
return null;
|
|
723
901
|
}
|
|
724
902
|
}
|
|
725
|
-
function
|
|
726
|
-
|
|
903
|
+
async function writeAckFile(path$1, hash) {
|
|
904
|
+
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
905
|
+
await promises.writeFile(
|
|
906
|
+
path$1,
|
|
907
|
+
JSON.stringify({ ack: hash, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
|
|
908
|
+
"utf8"
|
|
909
|
+
);
|
|
727
910
|
}
|
|
728
911
|
async function loadSignerCredentials(path = process.env.HAVEN_CREDENTIALS) {
|
|
729
912
|
if (path) return loadFromFile(path);
|
|
@@ -815,8 +998,9 @@ async function warnIfCredentialFilePermissive(path, log = (message) => process.s
|
|
|
815
998
|
|
|
816
999
|
// src/server.ts
|
|
817
1000
|
var SIGNER_NAME = "@haven_ai/signer";
|
|
818
|
-
var SIGNER_VERSION = "0.1.
|
|
1001
|
+
var SIGNER_VERSION = "0.1.20-alpha.0";
|
|
819
1002
|
async function resolveSignerRuntime(options = {}) {
|
|
1003
|
+
assertSupportedNodeVersion(options.nodeVersion);
|
|
820
1004
|
if (options.delegateKey) {
|
|
821
1005
|
return {
|
|
822
1006
|
signer: createEdgeSigner(options.delegateKey, {
|
|
@@ -833,7 +1017,13 @@ async function resolveSignerRuntime(options = {}) {
|
|
|
833
1017
|
};
|
|
834
1018
|
}
|
|
835
1019
|
function buildSignerMcpServer(signer, options = {}) {
|
|
836
|
-
const server = new mcp_js.McpServer(
|
|
1020
|
+
const server = new mcp_js.McpServer(
|
|
1021
|
+
{ name: SIGNER_NAME, version: SIGNER_VERSION },
|
|
1022
|
+
{
|
|
1023
|
+
capabilities: signerCapabilityAdvertisement(),
|
|
1024
|
+
instructions: signerInstructions()
|
|
1025
|
+
}
|
|
1026
|
+
);
|
|
837
1027
|
const credentialsPath = options.credentials?.sourcePath;
|
|
838
1028
|
const handlers = createToolHandlers(signer, {
|
|
839
1029
|
audit: {
|
|
@@ -841,6 +1031,14 @@ function buildSignerMcpServer(signer, options = {}) {
|
|
|
841
1031
|
delegateAddress: signer.delegateAddress,
|
|
842
1032
|
safeAddress: options.credentials?.safeAddress,
|
|
843
1033
|
chainId: options.credentials?.chainId
|
|
1034
|
+
},
|
|
1035
|
+
// #1263: the payment_id signing path — the ONLY network call this server
|
|
1036
|
+
// can make, an authenticated read of a signing context from Haven, using
|
|
1037
|
+
// the agent identity the connector stores next to the signer credential.
|
|
1038
|
+
// The signer CORE stays network-free; fetched bytes still pass the same
|
|
1039
|
+
// binding verification + digest re-derivation as tool-argument bytes.
|
|
1040
|
+
signContext: {
|
|
1041
|
+
loadIdentity: () => loadHavenIdentity(credentialsPath)
|
|
844
1042
|
}
|
|
845
1043
|
});
|
|
846
1044
|
const registerTool = server.tool.bind(server);
|
|
@@ -854,6 +1052,14 @@ function buildSignerMcpServer(signer, options = {}) {
|
|
|
854
1052
|
}
|
|
855
1053
|
return server;
|
|
856
1054
|
}
|
|
1055
|
+
function assertSupportedNodeVersion(nodeVersion = process.versions.node) {
|
|
1056
|
+
if (sdk.isSupportedNodeVersion(nodeVersion)) return;
|
|
1057
|
+
const err = new Error(
|
|
1058
|
+
sdk.unsupportedNodeVersionMessage({ subject: "The Haven signer", nodeVersion })
|
|
1059
|
+
);
|
|
1060
|
+
err.code = "HAVEN_SIGNER_UNSUPPORTED_NODE";
|
|
1061
|
+
throw err;
|
|
1062
|
+
}
|
|
857
1063
|
async function runSignerStdioServer(options = {}) {
|
|
858
1064
|
const { signer, credentials } = await resolveSignerRuntime(options);
|
|
859
1065
|
if (!options.skipConsent) {
|