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