@haven_ai/signer 0.8.1-alpha.0 → 0.10.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -154,6 +154,8 @@ function createSigningAuditEntry(tool, payloadHash, context, now = /* @__PURE__
154
154
  };
155
155
  if (context.accountAddress) entry.safe_address = context.accountAddress;
156
156
  if (typeof context.chainId === "number") entry.chain_id = context.chainId;
157
+ if (context.domain !== void 0) entry.domain = context.domain;
158
+ if (context.nonce !== void 0) entry.nonce = context.nonce;
157
159
  return entry;
158
160
  }
159
161
  function hashPayloadForAudit(payload) {
@@ -677,10 +679,237 @@ async function fetchTaskBudgetSignContext(identity, taskBudgetId, fetchImpl = fe
677
679
  }
678
680
  return malformed(`unknown purpose '${String(purpose)}'`);
679
681
  }
682
+ var SIWX_REFUSED = "SIWX_REFUSED";
683
+ var HavenSiwxRefusedError = class extends edge.HavenSigningError {
684
+ next_action = edge.AgentPaymentNextAction.StopAndTellUser;
685
+ step;
686
+ constructor(message) {
687
+ super(message);
688
+ this.code = SIWX_REFUSED;
689
+ this.name = "HavenSiwxRefusedError";
690
+ this.step = signerRefusalStep({
691
+ nextAction: edge.AgentPaymentNextAction.StopAndTellUser,
692
+ nextTool: null,
693
+ nextToolOmittedReason: "check the 402 sign-in-with-x challenge and the URL against the refusal above, then call haven_sign_siwx again with corrected inputs \u2014 a challenge that fails validation is never signed"
694
+ });
695
+ }
696
+ };
697
+ var SIWX_MAX_AGE_SECONDS = 300;
698
+ var SIWX_CLOCK_SKEW_SECONDS = 30;
699
+ var SIWX_VERSION = "1";
700
+ function refuse(message) {
701
+ throw new HavenSiwxRefusedError(message);
702
+ }
703
+ function isPlainObject(value) {
704
+ return typeof value === "object" && value !== null && !Array.isArray(value);
705
+ }
706
+ function stringField(info, name) {
707
+ const value = info[name];
708
+ if (value === void 0) return void 0;
709
+ if (typeof value !== "string") {
710
+ refuse(`The sign-in-with-x challenge field "${name}" must be a string.`);
711
+ }
712
+ return value;
713
+ }
714
+ function assertSingleLine(value, name) {
715
+ if (/[\n\r]/.test(value)) {
716
+ refuse(`The sign-in-with-x challenge field "${name}" contains a line break; EIP-4361 fields are single-line. Refusing \u2014 a line break could smuggle an attacker-chosen line into the signed message.`);
717
+ }
718
+ }
719
+ function validateSiwxChallenge(input) {
720
+ const { url, challenge, chainId } = input;
721
+ const now = input.now ?? /* @__PURE__ */ new Date();
722
+ if (typeof url !== "string" || url.length === 0) {
723
+ refuse("url is required: the URL the agent is calling, so the signature is bound to that origin.");
724
+ }
725
+ let urlObj;
726
+ try {
727
+ urlObj = new URL(url);
728
+ } catch {
729
+ refuse("url is not a valid absolute URL.");
730
+ }
731
+ if (urlObj.protocol !== "https:") {
732
+ refuse(
733
+ `url must be https \u2014 this signer never signs a sign-in bound to a plain-HTTP origin (got '${urlObj.protocol}//').`
734
+ );
735
+ }
736
+ if (!isPlainObject(challenge)) {
737
+ refuse('challenge must be the sign-in-with-x object from the merchant 402 (extensions["sign-in-with-x"]).');
738
+ }
739
+ const hasWrapper = isPlainObject(challenge.info);
740
+ const info = hasWrapper ? challenge.info : challenge;
741
+ const supportedChains = hasWrapper ? challenge.supportedChains : challenge.supportedChains;
742
+ const domain = stringField(info, "domain");
743
+ if (domain === void 0) refuse("The sign-in-with-x challenge carries no domain.");
744
+ assertSingleLine(domain, "domain");
745
+ if (/\s/.test(domain)) {
746
+ refuse("The sign-in-with-x challenge domain is not a valid authority (contains whitespace).");
747
+ }
748
+ if (domain.toLowerCase() !== urlObj.host.toLowerCase()) {
749
+ refuse(
750
+ `The challenge domain '${domain}' does not match the host of the URL being called ('${urlObj.host}'). A sign-in is only valid for the origin that issued it.`
751
+ );
752
+ }
753
+ const uri = stringField(info, "uri");
754
+ if (uri === void 0) refuse("The sign-in-with-x challenge carries no uri.");
755
+ assertSingleLine(uri, "uri");
756
+ let uriObj;
757
+ try {
758
+ uriObj = new URL(uri);
759
+ } catch {
760
+ refuse("The sign-in-with-x challenge uri is not a valid absolute URI.");
761
+ }
762
+ if (uriObj.protocol !== urlObj.protocol || uriObj.host.toLowerCase() !== urlObj.host.toLowerCase()) {
763
+ refuse(
764
+ `The challenge resource uri origin ('${uriObj.protocol}//${uriObj.host}') does not match the origin of the URL being called ('${urlObj.protocol}//${urlObj.host}').`
765
+ );
766
+ }
767
+ const version = stringField(info, "version");
768
+ if (version === void 0) {
769
+ refuse("The sign-in-with-x challenge carries no version; this signer composes CAIP-122 version 1 only.");
770
+ }
771
+ if (version !== SIWX_VERSION) {
772
+ refuse(
773
+ `The sign-in-with-x challenge version is '${version}'; this signer composes version '${SIWX_VERSION}' only. Update @haven_ai/signer if the spec has moved on.`
774
+ );
775
+ }
776
+ const nonce = stringField(info, "nonce");
777
+ if (nonce === void 0) {
778
+ refuse("The sign-in-with-x challenge carries no nonce \u2014 refusing: the nonce is what makes the sign-in single-use.");
779
+ }
780
+ if (!/^[A-Za-z0-9]{8,}$/.test(nonce)) {
781
+ refuse("The sign-in-with-x challenge nonce fails the EIP-4361 grammar (alphanumeric, at least 8 characters).");
782
+ }
783
+ const issuedAt = stringField(info, "issuedAt");
784
+ if (issuedAt === void 0) refuse("The sign-in-with-x challenge carries no issuedAt timestamp.");
785
+ assertSingleLine(issuedAt, "issuedAt");
786
+ if (Number.isNaN(Date.parse(issuedAt))) {
787
+ refuse("The sign-in-with-x challenge issuedAt is not a parseable timestamp.");
788
+ }
789
+ const expirationTime = stringField(info, "expirationTime");
790
+ if (expirationTime === void 0) {
791
+ refuse(
792
+ "The sign-in-with-x challenge carries no absolute expirationTime. A relative expirationSeconds is not accepted by this signer \u2014 only a challenge with an absolute expiry window the signer can bound is signed."
793
+ );
794
+ }
795
+ assertSingleLine(expirationTime, "expirationTime");
796
+ const expiresAtMs = Date.parse(expirationTime);
797
+ if (Number.isNaN(expiresAtMs)) {
798
+ refuse("The sign-in-with-x challenge expirationTime is not a parseable timestamp.");
799
+ }
800
+ if (expiresAtMs < now.getTime() - SIWX_CLOCK_SKEW_SECONDS * 1e3) {
801
+ refuse("The sign-in-with-x challenge has already expired (expirationTime is in the past, beyond the clock-skew tolerance). Nothing was signed.");
802
+ }
803
+ if (expiresAtMs - now.getTime() > (SIWX_MAX_AGE_SECONDS + SIWX_CLOCK_SKEW_SECONDS) * 1e3) {
804
+ refuse(
805
+ `The sign-in-with-x challenge expiry window is longer than the spec's ${SIWX_MAX_AGE_SECONDS}-second max age (beyond the clock-skew tolerance). Refusing to sign a long-lived challenge.`
806
+ );
807
+ }
808
+ const statement = stringField(info, "statement");
809
+ if (statement !== void 0) assertSingleLine(statement, "statement");
810
+ const notBefore = stringField(info, "notBefore");
811
+ if (notBefore !== void 0) {
812
+ assertSingleLine(notBefore, "notBefore");
813
+ if (Number.isNaN(Date.parse(notBefore))) {
814
+ refuse("The sign-in-with-x challenge notBefore is not a parseable timestamp.");
815
+ }
816
+ }
817
+ const requestId = stringField(info, "requestId");
818
+ if (requestId !== void 0) assertSingleLine(requestId, "requestId");
819
+ let resources;
820
+ if (info.resources !== void 0) {
821
+ if (!Array.isArray(info.resources) || info.resources.some((r) => typeof r !== "string")) {
822
+ refuse("The sign-in-with-x challenge resources must be an array of URI strings.");
823
+ }
824
+ for (const resource of info.resources) {
825
+ assertSingleLine(resource, "resources[]");
826
+ try {
827
+ new URL(resource);
828
+ } catch {
829
+ refuse(`The sign-in-with-x challenge resources entry '${resource}' is not a valid absolute URI.`);
830
+ }
831
+ }
832
+ resources = info.resources;
833
+ }
834
+ if (typeof chainId !== "number" || !Number.isInteger(chainId) || chainId <= 0) {
835
+ refuse(
836
+ "This signer credential carries no chain id, so the signer cannot check the challenge against the chain its delegate key pays on. Re-run the connector to refresh the credential."
837
+ );
838
+ }
839
+ const chainIdCaip2 = `eip155:${chainId}`;
840
+ if (!Array.isArray(supportedChains) || supportedChains.length === 0) {
841
+ refuse("The sign-in-with-x challenge carries no supportedChains array.");
842
+ }
843
+ const matched = supportedChains.some(
844
+ (entry) => isPlainObject(entry) && typeof entry.chainId === "string" && entry.chainId.toLowerCase() === chainIdCaip2 && entry.type === "eip191"
845
+ );
846
+ if (!matched) {
847
+ refuse(
848
+ `The challenge's supportedChains does not offer the credential chain ${chainIdCaip2} with an eip191 signature type \u2014 the delegate EOA cannot answer this challenge.`
849
+ );
850
+ }
851
+ return {
852
+ domain,
853
+ uri,
854
+ version,
855
+ nonce,
856
+ issuedAt,
857
+ expirationTime,
858
+ statement,
859
+ notBefore,
860
+ requestId,
861
+ resources,
862
+ chainIdCaip2,
863
+ numericChainId: chainId
864
+ };
865
+ }
866
+ function composeSiwxMessage(fields, address) {
867
+ const suffixLines = [
868
+ `URI: ${fields.uri}`,
869
+ `Version: ${fields.version ?? SIWX_VERSION}`,
870
+ `Chain ID: ${fields.numericChainId}`,
871
+ `Nonce: ${fields.nonce}`,
872
+ `Issued At: ${fields.issuedAt}`
873
+ ];
874
+ if (fields.expirationTime !== void 0) suffixLines.push(`Expiration Time: ${fields.expirationTime}`);
875
+ if (fields.notBefore !== void 0) suffixLines.push(`Not Before: ${fields.notBefore}`);
876
+ if (fields.requestId !== void 0) suffixLines.push(`Request ID: ${fields.requestId}`);
877
+ if (fields.resources !== void 0) {
878
+ suffixLines.push(["Resources:", ...fields.resources.map((r) => `- ${r}`)].join("\n"));
879
+ }
880
+ let head = [`${fields.domain} wants you to sign in with your Ethereum account:`, address].join("\n");
881
+ if (fields.statement === void 0) {
882
+ head += "\n\n";
883
+ } else {
884
+ head = [head, fields.statement].join("\n\n") + "\n";
885
+ }
886
+ return [head, suffixLines.join("\n")].join("\n");
887
+ }
888
+ function buildSiwxPayload(fields, address, signature) {
889
+ return {
890
+ domain: fields.domain,
891
+ address,
892
+ statement: fields.statement,
893
+ uri: fields.uri,
894
+ version: fields.version ?? SIWX_VERSION,
895
+ chainId: fields.chainIdCaip2,
896
+ type: "eip191",
897
+ nonce: fields.nonce,
898
+ issuedAt: fields.issuedAt,
899
+ expirationTime: fields.expirationTime,
900
+ notBefore: fields.notBefore,
901
+ requestId: fields.requestId,
902
+ resources: fields.resources,
903
+ signature
904
+ };
905
+ }
906
+ function encodeSiwxHeader(payload) {
907
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
908
+ }
680
909
 
681
910
  // src/tools.ts
682
911
  var SIGNER_NAME = "@haven_ai/signer";
683
- var SIGNER_VERSION = "0.8.1-alpha.0";
912
+ var SIGNER_VERSION = "0.10.0-alpha.0";
684
913
  var UNSUPPORTED_ARGUMENT_MARKER = "HavenSignerUnsupportedArgument:";
685
914
  var USEROP_BINDING_MISMATCH = "USEROP_BINDING_MISMATCH";
686
915
  var HavenUserOpBindingRefusedError = class extends edge.HavenSigningError {
@@ -843,6 +1072,18 @@ var toolSchemas = {
843
1072
  typed_data: v3.z.record(v3.z.string(), v3.z.unknown()).optional(),
844
1073
  // #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.
845
1074
  typed_data_b64: v3.z.string().min(1).max(262144).optional()
1075
+ },
1076
+ haven_sign_siwx: {
1077
+ // #3728: the https URL the agent is calling — the challenge's domain and
1078
+ // resource uri are pinned to THIS origin before anything is signed.
1079
+ url: v3.z.string().min(1),
1080
+ // The merchant's sign-in-with-x challenge. Accepted as EITHER the 402
1081
+ // extension object (payment_required.extensions['sign-in-with-x'] —
1082
+ // { info, supportedChains, schema? }) or the flattened info object the
1083
+ // x402 reference client builds ({ ...info, chainId, type }). Validated
1084
+ // field by field in siwx.ts; the signer composes the EIP-4361 message
1085
+ // itself and never signs a caller-supplied message.
1086
+ challenge: v3.z.record(v3.z.string(), v3.z.unknown())
846
1087
  }
847
1088
  // #3101: keys survive on the type (see the hosted server's contracts.ts).
848
1089
  };
@@ -881,8 +1122,10 @@ var X402_SIGN_HEADER_DESCRIPTION = [
881
1122
  "do not call this tool. The signer validates the merchant, amount, resource, asset, and",
882
1123
  "network against the recorded funding context before signing, checks expires_at when present,",
883
1124
  "and rejects mismatches or expired payment windows.",
884
- "Returns { payment_header, accepted }. On your retry set BOTH PAYMENT-SIGNATURE (x402 v2) and",
885
- "X-PAYMENT (v1) to <payment_header>; a strict v2 merchant reads only the first.",
1125
+ "Returns { payment_header, retry_headers, accepted }. On your retry set EVERY header named in",
1126
+ "retry_headers to <payment_header> \u2014 the names come from the same rule the wire uses (both",
1127
+ "PAYMENT-SIGNATURE (x402 v2) and X-PAYMENT (v1) on the EIP-3009 bridge; a strict v2 merchant reads",
1128
+ "only the first).",
886
1129
  "Only call after haven_submit has confirmed the funding step (nextAction=none or",
887
1130
  "the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool."
888
1131
  ].join(" ");
@@ -908,8 +1151,8 @@ var SIGN_X402_DESCRIPTION = [
908
1151
  "haven_sign, not to this one. payment_header IS the header to use.",
909
1152
  "Next: for a paid MCP tool, call mcp__haven__haven_settle_mcp_tool. For a direct plain-HTTP x402",
910
1153
  "merchant (the haven_pay_x402_quote path), relay signature via mcp__haven__haven_submit and then",
911
- "retry the original merchant URL YOURSELF, setting BOTH PAYMENT-SIGNATURE (x402 v2) and",
912
- "X-PAYMENT (v1) to payment_header \u2014 Haven never contacts that merchant."
1154
+ "retry the original merchant URL YOURSELF, setting EVERY header the result names in",
1155
+ "retry_headers to payment_header \u2014 Haven never sends that merchant the paid request."
913
1156
  ].join(" ");
914
1157
  var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
915
1158
  "Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate",
@@ -921,8 +1164,28 @@ var SIGN_SWEEP_DELEGATE_DESCRIPTION = [
921
1164
  "when the credential carries one, and otherwise rests on Haven's binding signature. Then it",
922
1165
  "returns { signature } to hand back to mcp__haven__haven_sweep_delegate to complete recovery."
923
1166
  ].join(" ");
1167
+ var SIGN_SIWX_DESCRIPTION = [
1168
+ "Answer a merchant x402 Sign-In-With-X (SIWX) sign-in challenge with the local delegate key (#3728).",
1169
+ "Use it when a merchant 402 carries a sign-in-with-x extension, or when the merchant documents a",
1170
+ "sign-in route (CAIP-122): pass url \u2014 the FINAL URL the header will be sent to, i.e. after any",
1171
+ "redirects, not the originally requested one \u2014 and challenge, the sign-in-with-x object from the",
1172
+ "402 (extensions['sign-in-with-x'], or the flattened info object). NEVER follow a redirect with",
1173
+ "the SIGN-IN-WITH-X header (or a resulting session token) attached: re-sign for the final origin.",
1174
+ "This signer composes the EIP-4361 message ITSELF from the validated challenge fields and the",
1175
+ "delegate address read from the key \u2014 it never signs a caller-supplied message, and an address",
1176
+ "inside the challenge cannot change whose wallet signs in. It refuses (SIWX_REFUSED) unless the",
1177
+ "challenge domain matches the URL host, its resource uri origin matches the URL origin, the URL is",
1178
+ "https, the nonce is well-formed, the expiry window is at most 5 minutes (plus a small clock-skew",
1179
+ "tolerance), and supportedChains offers the credential chain with an eip191 signature type. This",
1180
+ "tool MOVES NO FUNDS and grants no spend authority: it only proves the delegate wallet is the one",
1181
+ "that paid the merchant. Returns { sign_in_with_x_header } \u2014 retry the merchant request with the",
1182
+ "SIGN-IN-WITH-X header set to that value. The merchant then recognises the delegate wallet as a",
1183
+ "paying customer (a session it mints typically outlives the 5-minute signature; what the session",
1184
+ "reaches is merchant-defined)."
1185
+ ].join(" ");
924
1186
  var toolDescriptions = {
925
1187
  haven_sign: SIGN_DESCRIPTION,
1188
+ haven_sign_siwx: SIGN_SIWX_DESCRIPTION,
926
1189
  haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,
927
1190
  haven_sign_x402: SIGN_X402_DESCRIPTION,
928
1191
  haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION
@@ -1250,7 +1513,13 @@ function createToolHandlers(signer, options = {}) {
1250
1513
  "haven_x402_sign_header",
1251
1514
  hashPayloadForAudit(args.payment_required)
1252
1515
  );
1253
- return { payment_header: result.paymentHeader, accepted: result.accepted };
1516
+ return {
1517
+ payment_header: result.paymentHeader,
1518
+ accepted: result.accepted,
1519
+ // #3727: the ready-made retry headers beside the prose — the names
1520
+ // come from the SDK's live rule, never re-derived here.
1521
+ retry_headers: edge.x402RetryHeadersFor(result.paymentHeader)
1522
+ };
1254
1523
  }),
1255
1524
  haven_sign_x402: async (input) => runTool(async () => {
1256
1525
  const args = parseStrictFor("haven_sign_x402", coerceX402Expected(coercePaymentRequired(input)));
@@ -1285,6 +1554,9 @@ function createToolHandlers(signer, options = {}) {
1285
1554
  x402_binding: funding.x402Binding,
1286
1555
  payment_header: header.paymentHeader,
1287
1556
  accepted: header.accepted,
1557
+ // #3727: the ready-made retry headers beside the prose — the names
1558
+ // come from the SDK's live rule, never re-derived here.
1559
+ retry_headers: edge.x402RetryHeadersFor(header.paymentHeader),
1288
1560
  ...clientUpdateField(resolved)
1289
1561
  };
1290
1562
  }),
@@ -1302,15 +1574,35 @@ function createToolHandlers(signer, options = {}) {
1302
1574
  hashPayloadForAudit(args.authorization)
1303
1575
  );
1304
1576
  return { signature: result.signature };
1577
+ }),
1578
+ haven_sign_siwx: async (input) => runTool(async () => {
1579
+ const args = parseStrictFor("haven_sign_siwx", input);
1580
+ const chainId = options.audit?.chainId;
1581
+ const fields = validateSiwxChallenge({
1582
+ url: args.url,
1583
+ challenge: args.challenge,
1584
+ chainId
1585
+ });
1586
+ const message = composeSiwxMessage(fields, signer.delegateAddress);
1587
+ const signature = await signer.signSiwxMessage(message);
1588
+ const header = encodeSiwxHeader(
1589
+ buildSiwxPayload(fields, signer.delegateAddress, signature)
1590
+ );
1591
+ await auditSigning("haven_sign_siwx", hashPayloadForAudit(message), {
1592
+ domain: fields.domain,
1593
+ nonce: fields.nonce
1594
+ });
1595
+ return { sign_in_with_x_header: header };
1305
1596
  })
1306
1597
  };
1307
- async function auditSigning(tool, payloadHash) {
1598
+ async function auditSigning(tool, payloadHash, extra = {}) {
1308
1599
  if (!options.audit) return;
1309
1600
  const { auditPath, ...context } = options.audit;
1310
1601
  try {
1311
1602
  await appendSigningAuditEntry(
1312
1603
  createSigningAuditEntry(tool, payloadHash, {
1313
1604
  ...context,
1605
+ ...extra,
1314
1606
  delegateAddress: signer.delegateAddress
1315
1607
  }),
1316
1608
  auditPath
@@ -1465,6 +1757,15 @@ function normalizeError(err) {
1465
1757
  ...err.next_tool_omitted_reason ? { next_tool_omitted_reason: err.next_tool_omitted_reason } : {}
1466
1758
  };
1467
1759
  }
1760
+ if (err instanceof HavenSiwxRefusedError) {
1761
+ return {
1762
+ success: false,
1763
+ code: err.code,
1764
+ message: err.message,
1765
+ next_action: err.next_action,
1766
+ ...nextStepWireFields(err.step)
1767
+ };
1768
+ }
1468
1769
  if (err instanceof edge.HavenSigningError) {
1469
1770
  return { success: false, code: err.code, message: err.message };
1470
1771
  }
@@ -1501,6 +1802,7 @@ function normalizeError(err) {
1501
1802
  // src/consent.ts
1502
1803
  var toolSummaries = {
1503
1804
  haven_sign: "signs a Haven-prepared payment, task-budget or sub-budget open or close (a UserOp from your own account redeeming a delegation made to it, directly or via a task-budget child; a sub-budget child narrowing your budget for another agent of yours; or an x402 funding intent against a Haven-signed context)",
1805
+ haven_sign_siwx: "signs a merchant x402 Sign-In-With-X sign-in challenge as the delegate wallet \u2014 proves the wallet paid that merchant, moves no funds and grants no spend authority",
1504
1806
  haven_x402_sign_header: "builds and signs the EIP-3009 merchant payment header for an x402 payment",
1505
1807
  haven_sign_x402: "the two above in one call: funding payload + merchant header",
1506
1808
  haven_sign_sweep_delegate: "signs a Haven-prepared gasless sweep of stranded funds back to your own account"
@@ -1540,13 +1842,16 @@ function renderSignerConsentBlock(input, hash) {
1540
1842
  if (input.network) lines.push(`Network: ${input.network}`);
1541
1843
  lines.push("");
1542
1844
  lines.push("This local signer holds the delegate key on this machine and signs");
1543
- lines.push("payment payloads or x402 merchant headers for the delegate address above.");
1845
+ lines.push("payment payloads, x402 merchant headers, or x402 Sign-In-With-X sign-in");
1846
+ lines.push("challenges for the delegate address above. A sign-in challenge proves to a");
1847
+ lines.push("merchant that this wallet paid it before; it moves no funds and grants no");
1848
+ lines.push("spend authority.");
1544
1849
  lines.push("Its one network use is a read-only fetch of a pending payment's signing");
1545
1850
  lines.push("payload from Haven, authenticated with the agent credential stored next to");
1546
1851
  lines.push("this signer's key file - it never sends the key, a signature, or anything");
1547
1852
  lines.push("else outbound, and it cannot show a live allowance summary.");
1548
1853
  lines.push("The agent's signed budget delegation is the real spend gate, and the wallet");
1549
- lines.push("owner can pause or revoke agent authority outside this signer.");
1854
+ lines.push("owner can stop the agent's budget or remove the agent outside this signer.");
1550
1855
  lines.push("");
1551
1856
  lines.push("Tools this signer will expose to your agent runtime (one line each; the");
1552
1857
  lines.push("full agent-facing descriptions are what the runtime sees):");
@@ -1556,7 +1861,7 @@ function renderSignerConsentBlock(input, hash) {
1556
1861
  lines.push("");
1557
1862
  lines.push("A local audit entry is appended for every signing operation. Audit entries");
1558
1863
  lines.push("record timestamp, tool, payload hash, and delegate address; never the key,");
1559
- lines.push("signature, or x402 payment header.");
1864
+ lines.push("signature, x402 payment header, or sign-in message.");
1560
1865
  lines.push("");
1561
1866
  lines.push(`Consent hash: ${hash}`);
1562
1867
  lines.push("");
@@ -1811,11 +2116,14 @@ function createEdgeSigner(delegateKey, options = {}) {
1811
2116
  const requirements = edge.toStandardPaymentRequirements(paymentRequired, option);
1812
2117
  const { exact } = await loadX402Schemes();
1813
2118
  assertWindowOpenOrRetire();
1814
- const header = await exact.evm.createPaymentHeader(
1815
- account,
2119
+ const unsigned = exact.evm.preparePaymentHeader(
2120
+ account.address,
1816
2121
  paymentRequired.x402Version,
1817
2122
  requirements
1818
2123
  );
2124
+ unsigned.payload.authorization.nonce = edge.deriveX402PaymentNonce(expected.paymentId);
2125
+ const signed = await exact.evm.signPaymentHeader(account, requirements, unsigned);
2126
+ const header = exact.evm.encodePayment(signed);
1819
2127
  if (paymentRequired.x402Version < 2) {
1820
2128
  x402Bindings.delete(x402Binding);
1821
2129
  retireX402Binding(x402Binding, "header_built");
@@ -1872,6 +2180,10 @@ function createEdgeSigner(delegateKey, options = {}) {
1872
2180
  );
1873
2181
  }
1874
2182
  return { signature };
2183
+ },
2184
+ async signSiwxMessage(message) {
2185
+ const account = accounts.privateKeyToAccount(delegateKey);
2186
+ return account.signMessage({ message });
1875
2187
  }
1876
2188
  };
1877
2189
  }
@@ -2040,7 +2352,13 @@ function signerCompatibility() {
2040
2352
  function signerCapabilityAdvertisement() {
2041
2353
  return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } };
2042
2354
  }
2043
- function signerInstructions() {
2355
+ function signerIdentityLines(identity) {
2356
+ if (!identity?.agentId && !identity?.delegateAddress) return [];
2357
+ const agent = identity.agentId ? `agent id ${identity.agentId}` : "no recorded agent id";
2358
+ const delegate = identity.delegateAddress ? ` and delegate address ${identity.delegateAddress}` : "";
2359
+ return [`This signer is bound to ${agent}${delegate}.`];
2360
+ }
2361
+ function signerInstructions(identity) {
2044
2362
  const compatibility = signerCompatibility();
2045
2363
  return [
2046
2364
  "Haven edge signer: sign-only tools bound to the local delegate key. It never emits the",
@@ -2049,6 +2367,16 @@ function signerInstructions() {
2049
2367
  "#3271, and delegation-rail x402) or haven_sign_x402 (x402 only) instead of relaying bulky",
2050
2368
  "typed-data payloads yourself.",
2051
2369
  "",
2370
+ ...signerIdentityLines(identity),
2371
+ "When more than one Haven pair is configured, you act as ONE agent per task: if the",
2372
+ "user has not said which (in the request, or a project-level choice they stated), ask",
2373
+ "before any payment tool. Sign only through the signer of the hosted server you called:",
2374
+ "haven-<slug> with haven-signer-<slug>, bare haven with haven-signer, Codex haven with",
2375
+ "haven_signer. Before signing, compare the identity this signer states with",
2376
+ "haven_get_agent (its id and delegateAddress) from that hosted server \u2014 the delegate",
2377
+ "address alone when this signer has no recorded agent id. If they differ, stop and sign",
2378
+ "nothing \u2014 switch to the signer whose identity matches.",
2379
+ "",
2052
2380
  "Version compatibility (check this BEFORE signing, not after):",
2053
2381
  `- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(", ")}`,
2054
2382
  `- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(", ")}`,
@@ -2067,28 +2395,36 @@ function signerInstructions() {
2067
2395
  "machine-readable, not just prose: it carries code, supported_versions, received_version, and",
2068
2396
  "fallback fields alongside the message, so you can branch on it directly. Every signer",
2069
2397
  "refusal also carries the next-step family: next_tool_name + next_tool_server_role when a",
2070
- "hosted tool follows (resolve the role against your own server names), else",
2398
+ "hosted tool follows (resolve the role against your own server names \u2014 with several",
2399
+ "Haven pairs, the hosted server of THIS signer's pair), else",
2071
2400
  "next_tool_omitted_reason saying why not.",
2072
2401
  "",
2073
2402
  "An undeclared top-level argument is refused, not stripped: haven_sign answers",
2074
2403
  "UNSUPPORTED_ARGUMENT with unknown_arguments, signer_version and fallback (the update",
2075
2404
  "command) instead of dropping the key and answering the generic signing error \u2014 if you see",
2076
2405
  "that refusal, this signer predates the argument form you sent. Update the signer; nothing",
2077
- "was signed, fetched or audited."
2406
+ "was signed, fetched or audited.",
2407
+ "",
2408
+ "Sign-In-With-X (#3728): when a merchant 402 carries a sign-in-with-x extension (or the",
2409
+ "merchant documents a CAIP-122 sign-in route), call haven_sign_siwx with { url, challenge }.",
2410
+ "The signer composes the EIP-4361 message itself from the validated challenge and signs it with",
2411
+ "the delegate key \u2014 it returns { sign_in_with_x_header }; retry the merchant with the",
2412
+ "SIGN-IN-WITH-X header set to that value. This proves the delegate wallet paid the merchant; it",
2413
+ "moves no funds and cannot approve any payment."
2078
2414
  ].join("\n");
2079
2415
  }
2080
2416
  async function loadSignerCredentials(path = process.env.HAVEN_CREDENTIALS) {
2081
2417
  if (path) return loadFromFile(path);
2082
- const envKey = stringField(process.env.HAVEN_DELEGATE_KEY);
2418
+ const envKey = stringField2(process.env.HAVEN_DELEGATE_KEY);
2083
2419
  if (envKey) {
2084
2420
  const accountAddress = readAccountAddressEnv(process.env);
2085
2421
  return {
2086
2422
  delegateKey: envKey,
2087
- agentId: stringField(process.env.HAVEN_AGENT_ID),
2423
+ agentId: stringField2(process.env.HAVEN_AGENT_ID),
2088
2424
  accountAddress,
2089
2425
  chainId: chainIdField(process.env.HAVEN_CHAIN_ID, "HAVEN_CHAIN_ID"),
2090
- network: stringField(process.env.HAVEN_NETWORK),
2091
- x402BindingSigner: stringField(process.env.HAVEN_X402_BINDING_SIGNER)
2426
+ network: stringField2(process.env.HAVEN_NETWORK),
2427
+ x402BindingSigner: stringField2(process.env.HAVEN_X402_BINDING_SIGNER)
2092
2428
  };
2093
2429
  }
2094
2430
  throw new Error(
@@ -2111,30 +2447,30 @@ async function loadFromFile(path) {
2111
2447
  } catch {
2112
2448
  throw new Error("Haven credentials must be JSON with a delegate_key field.");
2113
2449
  }
2114
- const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey);
2450
+ const delegateKey = stringField2(raw.delegate_key ?? raw.delegateKey);
2115
2451
  if (!delegateKey) {
2116
2452
  throw new Error("Haven credentials are missing delegate_key \u2014 the edge signer needs it to sign.");
2117
2453
  }
2118
2454
  const accountAddress = readAccountAddressField(raw);
2119
2455
  return {
2120
2456
  delegateKey,
2121
- agentId: stringField(raw.agent_id ?? raw.agentId),
2457
+ agentId: stringField2(raw.agent_id ?? raw.agentId),
2122
2458
  accountAddress,
2123
2459
  chainId: chainIdField(raw.chain_id ?? raw.chainId, "chain_id"),
2124
- network: stringField(raw.network),
2125
- x402BindingSigner: stringField(
2460
+ network: stringField2(raw.network),
2461
+ x402BindingSigner: stringField2(
2126
2462
  raw.x402_binding_signer ?? raw.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER
2127
2463
  ),
2128
2464
  sourcePath: path
2129
2465
  };
2130
2466
  }
2131
2467
  function readAccountAddressField(raw) {
2132
- return stringField(raw.account_address ?? raw.safe_address ?? raw.safeAddress);
2468
+ return stringField2(raw.account_address ?? raw.safe_address ?? raw.safeAddress);
2133
2469
  }
2134
2470
  function readAccountAddressEnv(env) {
2135
- const current = stringField(env.HAVEN_ACCOUNT_ADDRESS);
2471
+ const current = stringField2(env.HAVEN_ACCOUNT_ADDRESS);
2136
2472
  for (const name of ["HAVEN_WALLET_ADDRESS", "HAVEN_SAFE_ADDRESS"]) {
2137
- const retired = stringField(env[name]);
2473
+ const retired = stringField2(env[name]);
2138
2474
  if (!retired) continue;
2139
2475
  if (!current) {
2140
2476
  throw new Error(
@@ -2149,7 +2485,7 @@ function readAccountAddressEnv(env) {
2149
2485
  }
2150
2486
  return current;
2151
2487
  }
2152
- function stringField(value) {
2488
+ function stringField2(value) {
2153
2489
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
2154
2490
  }
2155
2491
  function chainIdField(value, label) {
@@ -2203,7 +2539,12 @@ function buildSignerMcpServer(signer, options = {}) {
2203
2539
  { name: SIGNER_NAME, version: SIGNER_VERSION },
2204
2540
  {
2205
2541
  capabilities: signerCapabilityAdvertisement(),
2206
- instructions: signerInstructions()
2542
+ // #3738: the identity line lets a model holding several Haven pairs
2543
+ // confirm this signer belongs to the hosted server it called.
2544
+ instructions: signerInstructions({
2545
+ agentId: options.credentials?.agentId,
2546
+ delegateAddress: signer.delegateAddress
2547
+ })
2207
2548
  }
2208
2549
  );
2209
2550
  const credentialsPath = options.credentials?.sourcePath;