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